sha
stringlengths
40
40
author
stringclasses
155 values
date
stringlengths
19
19
commit_message
stringlengths
24
9.22k
git_diff
stringlengths
110
332k
type
stringclasses
9 values
2dc76d0d8087bdd882cf3e0aa8dc4e4cd643e9b9
Shelley Vohr
2023-02-01 18:12:19
build: fixup release_dependency_versions action (#37036)
diff --git a/.github/workflows/release_dependency_versions.yml b/.github/workflows/release_dependency_versions.yml index 62c48fc797..c6dd4cd350 100644 --- a/.github/workflows/release_dependency_versions.yml +++ b/.github/workflows/release_dependency_versions.yml @@ -7,9 +7,6 @@ on: env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} -permissions: # added using https://github.com/step-security/secure-workflows - contents: read - jobs: trigger_chromedriver: runs-on: ubuntu-latest @@ -17,10 +14,10 @@ jobs: - uses: actions/checkout@93ea575cb5d8a053eaa0ac8fa3b40d7e05a33cc8 # tag: v3 - name: Trigger New chromedriver Release run: | - if [[ ${{ github.event.release.tag_name }} =~ ^v[0-9]+\.0\.0$ ]]; then + if [[ ${{ github.event.release.tag_name }} =~ ^v\d+\.\d+\.\d+$ ]]; then gh api /repos/:owner/chromedriver/actions/workflows/release.yml/dispatches --input - <<< '{"ref":"main","inputs":{"version":"${{ github.event.release.tag_name }}"}}' else - echo "Not releasing for version ${{ github.event.release.tag_name }}: requires major version change" + echo "Not releasing for version ${{ github.event.release.tag_name }}" fi trigger_mksnapshot: @@ -29,4 +26,8 @@ jobs: - uses: actions/checkout@93ea575cb5d8a053eaa0ac8fa3b40d7e05a33cc8 # tag: v3 - name: Trigger New mksnapshot Release run: | - gh api /repos/:owner/mksnapshot/actions/workflows/release.yml/dispatches --input - <<< '{"ref":"main","inputs":{"version":"${{ github.event.release.tag_name }}"}}' + if [[ ${{ github.event.release.tag_name }} =~ ^v\d+\.\d+\.\d+$ ]]; then + gh api /repos/:owner/mksnapshot/actions/workflows/release.yml/dispatches --input - <<< '{"ref":"main","inputs":{"version":"${{ github.event.release.tag_name }}"}}' + else + echo "Not releasing for version ${{ github.event.release.tag_name }}" + fi
build
2fd04a78a1e774a32e9db926d07de686fd03fb79
Keeley Hammond
2024-07-25 13:02:02
fix: revert BrowserWindow unresponsive handling refactor (#43034) * Revert "refactor: JSify BrowserWindow unresponsive handling (#37902)" This reverts commit 67ba30402bcbf6942fa0846927f2d088cf0a749d. * chore: remove BrowserWindow::SetTitleBarOverlay --------- Co-authored-by: Shelley Vohr <[email protected]>
diff --git a/lib/browser/api/browser-window.ts b/lib/browser/api/browser-window.ts index adffaf8fa4..13ec3ef264 100644 --- a/lib/browser/api/browser-window.ts +++ b/lib/browser/api/browser-window.ts @@ -36,29 +36,6 @@ BrowserWindow.prototype._init = function (this: BWT) { app.emit('browser-window-focus', event, this); }); - let unresponsiveEvent: NodeJS.Timeout | null = null; - const emitUnresponsiveEvent = () => { - unresponsiveEvent = null; - if (!this.isDestroyed() && this.isEnabled()) { this.emit('unresponsive'); } - }; - this.webContents.on('unresponsive', () => { - if (!unresponsiveEvent) { unresponsiveEvent = setTimeout(emitUnresponsiveEvent, 50); } - }); - this.webContents.on('responsive', () => { - if (unresponsiveEvent) { - clearTimeout(unresponsiveEvent); - unresponsiveEvent = null; - } - this.emit('responsive'); - }); - this.on('close', () => { - if (!unresponsiveEvent) { unresponsiveEvent = setTimeout(emitUnresponsiveEvent, 5000); } - }); - this.webContents.on('destroyed', () => { - if (unresponsiveEvent) clearTimeout(unresponsiveEvent); - unresponsiveEvent = null; - }); - // Subscribe to visibilityState changes and pass to renderer process. let isVisible = this.isVisible() && !this.isMinimized(); const visibilityChanged = () => { diff --git a/shell/browser/api/electron_api_browser_window.cc b/shell/browser/api/electron_api_browser_window.cc index cd757612af..12e769015e 100644 --- a/shell/browser/api/electron_api_browser_window.cc +++ b/shell/browser/api/electron_api_browser_window.cc @@ -106,6 +106,19 @@ BrowserWindow::~BrowserWindow() { void BrowserWindow::BeforeUnloadDialogCancelled() { WindowList::WindowCloseCancelled(window()); + // Cancel unresponsive event when window close is cancelled. + window_unresponsive_closure_.Cancel(); +} + +void BrowserWindow::OnRendererUnresponsive(content::RenderProcessHost*) { + // Schedule the unresponsive shortly later, since we may receive the + // responsive event soon. This could happen after the whole application had + // blocked for a while. + // Also notice that when closing this event would be ignored because we have + // explicitly started a close timeout counter. This is on purpose because we + // don't want the unresponsive event to be sent too early when user is closing + // the window. + ScheduleUnresponsiveEvent(50); } void BrowserWindow::WebContentsDestroyed() { @@ -113,6 +126,11 @@ void BrowserWindow::WebContentsDestroyed() { CloseImmediately(); } +void BrowserWindow::OnRendererResponsive(content::RenderProcessHost*) { + window_unresponsive_closure_.Cancel(); + Emit("responsive"); +} + void BrowserWindow::OnSetContentBounds(const gfx::Rect& rect) { // window.resizeTo(...) // window.moveTo(...) @@ -148,6 +166,13 @@ void BrowserWindow::OnCloseButtonClicked(bool* prevent_default) { // first, and when the web page is closed the window will also be closed. *prevent_default = true; + // Assume the window is not responding if it doesn't cancel the close and is + // not closed in 5s, in this way we can quickly show the unresponsive + // dialog when the window is busy executing some script without waiting for + // the unresponsive timeout. + if (window_unresponsive_closure_.IsCancelled()) + ScheduleUnresponsiveEvent(5000); + // Already closed by renderer. if (!web_contents() || !api_web_contents_) return; @@ -214,6 +239,9 @@ void BrowserWindow::CloseImmediately() { } BaseWindow::CloseImmediately(); + + // Do not sent "unresponsive" event after window is closed. + window_unresponsive_closure_.Cancel(); } void BrowserWindow::Focus() { @@ -264,6 +292,24 @@ v8::Local<v8::Value> BrowserWindow::GetWebContents(v8::Isolate* isolate) { return v8::Local<v8::Value>::New(isolate, web_contents_); } +void BrowserWindow::ScheduleUnresponsiveEvent(int ms) { + if (!window_unresponsive_closure_.IsCancelled()) + return; + + window_unresponsive_closure_.Reset(base::BindRepeating( + &BrowserWindow::NotifyWindowUnresponsive, GetWeakPtr())); + base::SingleThreadTaskRunner::GetCurrentDefault()->PostDelayedTask( + FROM_HERE, window_unresponsive_closure_.callback(), + base::Milliseconds(ms)); +} + +void BrowserWindow::NotifyWindowUnresponsive() { + window_unresponsive_closure_.Cancel(); + if (!window_->IsClosed() && window_->IsEnabled()) { + Emit("unresponsive"); + } +} + void BrowserWindow::OnWindowShow() { web_contents()->WasShown(); BaseWindow::OnWindowShow(); diff --git a/shell/browser/api/electron_api_browser_window.h b/shell/browser/api/electron_api_browser_window.h index 2ad029bc03..2fc835cdcc 100644 --- a/shell/browser/api/electron_api_browser_window.h +++ b/shell/browser/api/electron_api_browser_window.h @@ -43,6 +43,9 @@ class BrowserWindow : public BaseWindow, // content::WebContentsObserver: void BeforeUnloadDialogCancelled() override; + void OnRendererUnresponsive(content::RenderProcessHost*) override; + void OnRendererResponsive( + content::RenderProcessHost* render_process_host) override; void WebContentsDestroyed() override; // ExtendedWebContentsObserver: @@ -77,6 +80,16 @@ class BrowserWindow : public BaseWindow, private: // Helpers. + // Schedule a notification unresponsive event. + void ScheduleUnresponsiveEvent(int ms); + + // Dispatch unresponsive event to observers. + void NotifyWindowUnresponsive(); + + // Closure that would be called when window is unresponsive when closing, + // it should be cancelled when we can prove that the window is responsive. + base::CancelableRepeatingClosure window_unresponsive_closure_; + v8::Global<v8::Value> web_contents_; v8::Global<v8::Value> web_contents_view_; base::WeakPtr<api::WebContents> api_web_contents_;
fix
a595044989d94a1691343b666faa128ac4058b3f
github-actions[bot]
2023-06-20 14:15:00
build: update appveyor image to latest version - e-116.0.5833.0. (#38803) build: update appveyor image to latest version Co-authored-by: jkleinsc <[email protected]>
diff --git a/appveyor-woa.yml b/appveyor-woa.yml index 594fdebc53..cad8ec6335 100644 --- a/appveyor-woa.yml +++ b/appveyor-woa.yml @@ -29,7 +29,7 @@ version: 1.0.{build} build_cloud: electronhq-16-core -image: e-116.0.5829.0 +image: e-116.0.5833.0 environment: GIT_CACHE_PATH: C:\Users\appveyor\libcc_cache ELECTRON_OUT_DIR: Default diff --git a/appveyor.yml b/appveyor.yml index a939096cb7..e180d250f2 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -29,7 +29,7 @@ version: 1.0.{build} build_cloud: electronhq-16-core -image: e-116.0.5829.0 +image: e-116.0.5833.0 environment: GIT_CACHE_PATH: C:\Users\appveyor\libcc_cache ELECTRON_OUT_DIR: Default
build
229c2a8f50605289d2eb616ff113ac65144037b9
Shelley Vohr
2024-12-03 23:03:43
chore: make version parsing more tolerant (#44918) * chore: make version parsing more tolerant * Update .github/workflows/issue-opened.yml Co-authored-by: Niklas Wenzel <[email protected]> --------- Co-authored-by: Niklas Wenzel <[email protected]>
diff --git a/.github/workflows/issue-opened.yml b/.github/workflows/issue-opened.yml index ad2a03c780..69c51b0d80 100644 --- a/.github/workflows/issue-opened.yml +++ b/.github/workflows/issue-opened.yml @@ -61,7 +61,7 @@ jobs: // for now check for comma or space separated version. const versions = electronVersion.split(/, | /); for (const version of versions) { - const major = semver.parse(version)?.major; + const major = semver.coerce(version, { loose: true })?.major; if (major) { const versionLabel = `${major}-x-y`; let labelExists = false;
chore
8650682c5b6e94357c36c0e538eba1eb1ee4de05
Keeley Hammond
2024-06-14 09:11:30
build: revert removal of CIPD patch from depot tools (#42500) Revert "build: remove the CIPD patch from depot tools (#42484)" This reverts commit a0a8bd2222176cec3b4131100937ffda2cf4df7c.
diff --git a/.circleci/config/base.yml b/.circleci/config/base.yml index 7c0266603a..5b9e62f6bf 100644 --- a/.circleci/config/base.yml +++ b/.circleci/config/base.yml @@ -253,6 +253,25 @@ step-depot-tools-get: &step-depot-tools-get sed -i '' '/ninjalog_uploader_wrapper.py/d' ./depot_tools/autoninja else sed -i '/ninjalog_uploader_wrapper.py/d' ./depot_tools/autoninja + # Remove swift-format dep from cipd on macOS until we send a patch upstream. + cd depot_tools + cat > gclient.diff \<< 'EOF' + diff --git a/gclient.py b/gclient.py + index c305c248..e6e0fbdc 100755 + --- a/gclient.py + +++ b/gclient.py + @@ -783,7 +783,8 @@ class Dependency(gclient_utils.WorkItem, DependencySettings): + not condition or "non_git_source" not in condition): + continue + cipd_root = self.GetCipdRoot() + - for package in dep_value.get('packages', []): + + packages = dep_value.get('packages', []) + + for package in (x for x in packages if "infra/3pp/tools/swift-format" not in x.get('package')): + deps_to_add.append( + CipdDependency(parent=self, + name=name, + EOF + git apply --3way gclient.diff fi # Ensure depot_tools does not update. test -d depot_tools && cd depot_tools diff --git a/.github/actions/checkout/action.yml b/.github/actions/checkout/action.yml index af876a8f7e..241e93c67b 100644 --- a/.github/actions/checkout/action.yml +++ b/.github/actions/checkout/action.yml @@ -21,7 +21,12 @@ runs: shell: bash run: | git clone --depth=1 https://chromium.googlesource.com/chromium/tools/depot_tools.git + sed -i '/ninjalog_uploader_wrapper.py/d' ./depot_tools/autoninja + # Remove swift-format dep from cipd on macOS until we send a patch upstream. + cd depot_tools + git apply --3way ../src/electron/.github/workflows/config/gclient.diff + # Ensure depot_tools does not update. test -d depot_tools && cd depot_tools touch .disable_auto_update diff --git a/.github/workflows/config/gclient.diff b/.github/workflows/config/gclient.diff new file mode 100644 index 0000000000..4a035b8c99 --- /dev/null +++ b/.github/workflows/config/gclient.diff @@ -0,0 +1,14 @@ +diff --git a/gclient.py b/gclient.py +index 59e2b4c5197928bdba1ef69bdbe637d7dfe471c1..b4bae5e48c83c84bd867187afaf40eed16e69851 100755 +--- a/gclient.py ++++ b/gclient.py +@@ -783,7 +783,8 @@ class Dependency(gclient_utils.WorkItem, DependencySettings): + not condition or "non_git_source" not in condition): + continue + cipd_root = self.GetCipdRoot() +- for package in dep_value.get('packages', []): ++ packages = dep_value.get('packages', []) ++ for package in (x for x in packages if "infra/3pp/tools/swift-format" not in x.get('package')): + deps_to_add.append( + CipdDependency(parent=self, + name=name, diff --git a/.github/workflows/pipeline-segment-electron-build.yml b/.github/workflows/pipeline-segment-electron-build.yml index 7caf63e95e..85cf23fa41 100644 --- a/.github/workflows/pipeline-segment-electron-build.yml +++ b/.github/workflows/pipeline-segment-electron-build.yml @@ -112,6 +112,9 @@ jobs: # Ensure depot_tools does not update. test -d depot_tools && cd depot_tools + if [ "`uname`" = "Linux" ]; then + git apply --3way ../src/electron/.github/workflows/config/gclient.diff + fi touch .disable_auto_update - name: Add Depot Tools to PATH run: echo "$(pwd)/depot_tools" >> $GITHUB_PATH diff --git a/.github/workflows/pipeline-segment-electron-test.yml b/.github/workflows/pipeline-segment-electron-test.yml index 0f28524887..be824b2ce0 100644 --- a/.github/workflows/pipeline-segment-electron-test.yml +++ b/.github/workflows/pipeline-segment-electron-test.yml @@ -70,6 +70,9 @@ jobs: sed -i '' '/ninjalog_uploader_wrapper.py/d' ./depot_tools/autoninja else sed -i '/ninjalog_uploader_wrapper.py/d' ./depot_tools/autoninja + # Remove swift-format dep from cipd on macOS until we send a patch upstream. + cd depot_tools + git apply --3way ../src/electron/.github/workflows/config/gclient.diff fi # Ensure depot_tools does not update. test -d depot_tools && cd depot_tools diff --git a/.github/workflows/pipeline-segment-node-nan-test.yml b/.github/workflows/pipeline-segment-node-nan-test.yml index 72301752b9..f7d96719e4 100644 --- a/.github/workflows/pipeline-segment-node-nan-test.yml +++ b/.github/workflows/pipeline-segment-node-nan-test.yml @@ -64,6 +64,8 @@ jobs: run: | git clone --depth=1 https://chromium.googlesource.com/chromium/tools/depot_tools.git sed -i '/ninjalog_uploader_wrapper.py/d' ./depot_tools/autoninja + cd depot_tools + git apply --3way ../src/electron/.github/workflows/config/gclient.diff # Ensure depot_tools does not update. test -d depot_tools && cd depot_tools touch .disable_auto_update @@ -127,6 +129,8 @@ jobs: run: | git clone --depth=1 https://chromium.googlesource.com/chromium/tools/depot_tools.git sed -i '/ninjalog_uploader_wrapper.py/d' ./depot_tools/autoninja + cd depot_tools + git apply --3way ../src/electron/.github/workflows/config/gclient.diff # Ensure depot_tools does not update. test -d depot_tools && cd depot_tools touch .disable_auto_update
build
df524c6ecafb44f214fffc307ddaf21487eb3b25
Charles Kerr
2024-07-24 18:24:07
chore: use v8::Local<>, not v8::Handle<> (#43019) v8::Handle is an alias for v8::Local that "is kept around for historical reasons" and is disabled when V8_IMMINENT_DEPRECATION_WARNING is defined
diff --git a/shell/browser/api/electron_api_base_window.cc b/shell/browser/api/electron_api_base_window.cc index ce2d5c3ee9..337c928889 100644 --- a/shell/browser/api/electron_api_base_window.cc +++ b/shell/browser/api/electron_api_base_window.cc @@ -50,7 +50,7 @@ namespace gin { template <> struct Converter<electron::TaskbarHost::ThumbarButton> { static bool FromV8(v8::Isolate* isolate, - v8::Handle<v8::Value> val, + v8::Local<v8::Value> val, electron::TaskbarHost::ThumbarButton* out) { gin::Dictionary dict(isolate); if (!gin::ConvertFromV8(isolate, val, &dict)) diff --git a/shell/browser/native_window.cc b/shell/browser/native_window.cc index 5e5a6977d5..bb1d82fd82 100644 --- a/shell/browser/native_window.cc +++ b/shell/browser/native_window.cc @@ -47,7 +47,7 @@ namespace gin { template <> struct Converter<electron::NativeWindow::TitleBarStyle> { static bool FromV8(v8::Isolate* isolate, - v8::Handle<v8::Value> val, + v8::Local<v8::Value> val, electron::NativeWindow::TitleBarStyle* out) { using TitleBarStyle = electron::NativeWindow::TitleBarStyle; std::string title_bar_style; diff --git a/shell/browser/native_window_mac.mm b/shell/browser/native_window_mac.mm index 06036607dd..fd94b01353 100644 --- a/shell/browser/native_window_mac.mm +++ b/shell/browser/native_window_mac.mm @@ -93,7 +93,7 @@ namespace gin { template <> struct Converter<electron::NativeWindowMac::VisualEffectState> { static bool FromV8(v8::Isolate* isolate, - v8::Handle<v8::Value> val, + v8::Local<v8::Value> val, electron::NativeWindowMac::VisualEffectState* out) { using VisualEffectState = electron::NativeWindowMac::VisualEffectState; std::string visual_effect_state; diff --git a/shell/common/api/electron_api_shell.cc b/shell/common/api/electron_api_shell.cc index 6881ca7849..e1348bd7e1 100644 --- a/shell/common/api/electron_api_shell.cc +++ b/shell/common/api/electron_api_shell.cc @@ -24,7 +24,7 @@ namespace gin { template <> struct Converter<base::win::ShortcutOperation> { static bool FromV8(v8::Isolate* isolate, - v8::Handle<v8::Value> val, + v8::Local<v8::Value> val, base::win::ShortcutOperation* out) { std::string operation; if (!ConvertFromV8(isolate, val, &operation)) diff --git a/shell/common/gin_converters/blink_converter.cc b/shell/common/gin_converters/blink_converter.cc index 7e9c609785..715cea3348 100644 --- a/shell/common/gin_converters/blink_converter.cc +++ b/shell/common/gin_converters/blink_converter.cc @@ -51,7 +51,7 @@ namespace gin { template <> struct Converter<char16_t> { static bool FromV8(v8::Isolate* isolate, - v8::Handle<v8::Value> val, + v8::Local<v8::Value> val, char16_t* out) { std::u16string code = base::UTF8ToUTF16(gin::V8ToString(isolate, val)); if (code.length() != 1) @@ -108,7 +108,7 @@ struct Converter<char16_t> { bool Converter<blink::WebInputEvent::Type>::FromV8( v8::Isolate* isolate, - v8::Handle<v8::Value> val, + v8::Local<v8::Value> val, blink::WebInputEvent::Type* out) { std::string type = gin::V8ToString(isolate, val); #define CASE_TYPE(event_type, js_name) \ @@ -134,7 +134,7 @@ v8::Local<v8::Value> Converter<blink::WebInputEvent::Type>::ToV8( template <> struct Converter<blink::WebMouseEvent::Button> { static bool FromV8(v8::Isolate* isolate, - v8::Handle<v8::Value> val, + v8::Local<v8::Value> val, blink::WebMouseEvent::Button* out) { using Val = blink::WebMouseEvent::Button; static constexpr auto Lookup = @@ -193,7 +193,7 @@ static constexpr auto ReferrerPolicies = template <> struct Converter<blink::WebInputEvent::Modifiers> { static bool FromV8(v8::Isolate* isolate, - v8::Handle<v8::Value> val, + v8::Local<v8::Value> val, blink::WebInputEvent::Modifiers* out) { return FromV8WithLowerLookup(isolate, val, Modifiers, out) || FromV8WithLowerLookup(isolate, val, ModifierAliases, out); @@ -661,7 +661,7 @@ v8::Local<v8::Value> Converter<network::mojom::ReferrerPolicy>::ToV8( // static bool Converter<network::mojom::ReferrerPolicy>::FromV8( v8::Isolate* isolate, - v8::Handle<v8::Value> val, + v8::Local<v8::Value> val, network::mojom::ReferrerPolicy* out) { return FromV8WithLowerLookup(isolate, val, ReferrerPolicies, out); } @@ -700,7 +700,7 @@ v8::Local<v8::Value> Converter<blink::CloneableMessage>::ToV8( } bool Converter<blink::CloneableMessage>::FromV8(v8::Isolate* isolate, - v8::Handle<v8::Value> val, + v8::Local<v8::Value> val, blink::CloneableMessage* out) { return electron::SerializeV8Value(isolate, val, out); } diff --git a/shell/common/node_bindings.cc b/shell/common/node_bindings.cc index ed99776efa..617702f38e 100644 --- a/shell/common/node_bindings.cc +++ b/shell/common/node_bindings.cc @@ -577,7 +577,7 @@ void NodeBindings::Initialize(v8::Local<v8::Context> context) { } std::shared_ptr<node::Environment> NodeBindings::CreateEnvironment( - v8::Handle<v8::Context> context, + v8::Local<v8::Context> context, node::MultiIsolatePlatform* platform, std::vector<std::string> args, std::vector<std::string> exec_args, @@ -779,7 +779,7 @@ std::shared_ptr<node::Environment> NodeBindings::CreateEnvironment( } std::shared_ptr<node::Environment> NodeBindings::CreateEnvironment( - v8::Handle<v8::Context> context, + v8::Local<v8::Context> context, node::MultiIsolatePlatform* platform, std::optional<base::RepeatingCallback<void()>> on_app_code_ready) { #if BUILDFLAG(IS_WIN) diff --git a/shell/common/node_bindings.h b/shell/common/node_bindings.h index fce3f39ead..93363117df 100644 --- a/shell/common/node_bindings.h +++ b/shell/common/node_bindings.h @@ -93,7 +93,7 @@ class NodeBindings { // Create the environment and load node.js. std::shared_ptr<node::Environment> CreateEnvironment( - v8::Handle<v8::Context> context, + v8::Local<v8::Context> context, node::MultiIsolatePlatform* platform, std::vector<std::string> args, std::vector<std::string> exec_args, @@ -101,7 +101,7 @@ class NodeBindings { std::nullopt); std::shared_ptr<node::Environment> CreateEnvironment( - v8::Handle<v8::Context> context, + v8::Local<v8::Context> context, node::MultiIsolatePlatform* platform, std::optional<base::RepeatingCallback<void()>> on_app_code_ready = std::nullopt); diff --git a/shell/renderer/electron_render_frame_observer.cc b/shell/renderer/electron_render_frame_observer.cc index 6a6708b330..b8c7a464b6 100644 --- a/shell/renderer/electron_render_frame_observer.cc +++ b/shell/renderer/electron_render_frame_observer.cc @@ -78,7 +78,7 @@ void ElectronRenderFrameObserver::DidClearWindowObject() { !web_frame->IsOnInitialEmptyDocument()) { v8::Isolate* isolate = web_frame->GetAgentGroupScheduler()->Isolate(); v8::HandleScope handle_scope{isolate}; - v8::Handle<v8::Context> context = web_frame->MainWorldScriptContext(); + v8::Local<v8::Context> context = web_frame->MainWorldScriptContext(); v8::MicrotasksScope microtasks_scope( isolate, context->GetMicrotaskQueue(), v8::MicrotasksScope::kDoNotRunMicrotasks); @@ -91,7 +91,7 @@ void ElectronRenderFrameObserver::DidClearWindowObject() { } void ElectronRenderFrameObserver::DidInstallConditionalFeatures( - v8::Handle<v8::Context> context, + v8::Local<v8::Context> context, int world_id) { // When a child window is created with window.open, its WebPreferences will // be copied from its parent, and Chromium will initialize JS context in it diff --git a/shell/renderer/electron_render_frame_observer.h b/shell/renderer/electron_render_frame_observer.h index 7195e68998..5919cf6d0d 100644 --- a/shell/renderer/electron_render_frame_observer.h +++ b/shell/renderer/electron_render_frame_observer.h @@ -29,7 +29,7 @@ class ElectronRenderFrameObserver : private content::RenderFrameObserver { private: // content::RenderFrameObserver: void DidClearWindowObject() override; - void DidInstallConditionalFeatures(v8::Handle<v8::Context> context, + void DidInstallConditionalFeatures(v8::Local<v8::Context> context, int world_id) override; void WillReleaseScriptContext(v8::Local<v8::Context> context, int world_id) override; diff --git a/shell/renderer/electron_renderer_client.cc b/shell/renderer/electron_renderer_client.cc index 85b96c3940..d2ddd56b4c 100644 --- a/shell/renderer/electron_renderer_client.cc +++ b/shell/renderer/electron_renderer_client.cc @@ -71,7 +71,7 @@ void ElectronRendererClient::UndeferLoad(content::RenderFrame* render_frame) { } void ElectronRendererClient::DidCreateScriptContext( - v8::Handle<v8::Context> renderer_context, + v8::Local<v8::Context> renderer_context, content::RenderFrame* render_frame) { // TODO(zcbenz): Do not create Node environment if node integration is not // enabled. @@ -157,7 +157,7 @@ void ElectronRendererClient::DidCreateScriptContext( } void ElectronRendererClient::WillReleaseScriptContext( - v8::Handle<v8::Context> context, + v8::Local<v8::Context> context, content::RenderFrame* render_frame) { if (injected_frames_.erase(render_frame) == 0) return; diff --git a/shell/renderer/electron_renderer_client.h b/shell/renderer/electron_renderer_client.h index 0251fcb7a4..5471f872eb 100644 --- a/shell/renderer/electron_renderer_client.h +++ b/shell/renderer/electron_renderer_client.h @@ -29,9 +29,9 @@ class ElectronRendererClient : public RendererClientBase { ElectronRendererClient& operator=(const ElectronRendererClient&) = delete; // electron::RendererClientBase: - void DidCreateScriptContext(v8::Handle<v8::Context> context, + void DidCreateScriptContext(v8::Local<v8::Context> context, content::RenderFrame* render_frame) override; - void WillReleaseScriptContext(v8::Handle<v8::Context> context, + void WillReleaseScriptContext(v8::Local<v8::Context> context, content::RenderFrame* render_frame) override; private: diff --git a/shell/renderer/electron_sandboxed_renderer_client.cc b/shell/renderer/electron_sandboxed_renderer_client.cc index ea91e8fb77..50f03c641c 100644 --- a/shell/renderer/electron_sandboxed_renderer_client.cc +++ b/shell/renderer/electron_sandboxed_renderer_client.cc @@ -95,7 +95,7 @@ double Uptime() { .InSecondsF(); } -void InvokeEmitProcessEvent(v8::Handle<v8::Context> context, +void InvokeEmitProcessEvent(v8::Local<v8::Context> context, const std::string& event_name) { auto* isolate = context->GetIsolate(); // set by sandboxed_renderer/init.js @@ -167,7 +167,7 @@ void ElectronSandboxedRendererClient::RunScriptsAtDocumentEnd( } void ElectronSandboxedRendererClient::DidCreateScriptContext( - v8::Handle<v8::Context> context, + v8::Local<v8::Context> context, content::RenderFrame* render_frame) { // Only allow preload for the main frame or // For devtools we still want to run the preload_bundle script @@ -198,7 +198,7 @@ void ElectronSandboxedRendererClient::DidCreateScriptContext( } void ElectronSandboxedRendererClient::WillReleaseScriptContext( - v8::Handle<v8::Context> context, + v8::Local<v8::Context> context, content::RenderFrame* render_frame) { if (injected_frames_.erase(render_frame) == 0) return; diff --git a/shell/renderer/electron_sandboxed_renderer_client.h b/shell/renderer/electron_sandboxed_renderer_client.h index a80573efb8..bc01047803 100644 --- a/shell/renderer/electron_sandboxed_renderer_client.h +++ b/shell/renderer/electron_sandboxed_renderer_client.h @@ -34,9 +34,9 @@ class ElectronSandboxedRendererClient : public RendererClientBase { v8::Local<v8::Context> context, content::RenderFrame* render_frame); // electron::RendererClientBase: - void DidCreateScriptContext(v8::Handle<v8::Context> context, + void DidCreateScriptContext(v8::Local<v8::Context> context, content::RenderFrame* render_frame) override; - void WillReleaseScriptContext(v8::Handle<v8::Context> context, + void WillReleaseScriptContext(v8::Local<v8::Context> context, content::RenderFrame* render_frame) override; // content::ContentRendererClient: void RenderFrameCreated(content::RenderFrame*) override; diff --git a/shell/renderer/renderer_client_base.cc b/shell/renderer/renderer_client_base.cc index d89a3ddff4..c958c3fa22 100644 --- a/shell/renderer/renderer_client_base.cc +++ b/shell/renderer/renderer_client_base.cc @@ -214,7 +214,7 @@ void RendererClientBase::BindProcess(v8::Isolate* isolate, } bool RendererClientBase::ShouldLoadPreload( - v8::Handle<v8::Context> context, + v8::Local<v8::Context> context, content::RenderFrame* render_frame) const { auto prefs = render_frame->GetBlinkPreferences(); bool is_main_frame = render_frame->IsMainFrame(); @@ -580,7 +580,7 @@ extensions::ExtensionsClient* RendererClientBase::CreateExtensionsClient() { #endif bool RendererClientBase::IsWebViewFrame( - v8::Handle<v8::Context> context, + v8::Local<v8::Context> context, content::RenderFrame* render_frame) const { auto* isolate = context->GetIsolate(); @@ -601,7 +601,7 @@ bool RendererClientBase::IsWebViewFrame( } void RendererClientBase::SetupMainWorldOverrides( - v8::Handle<v8::Context> context, + v8::Local<v8::Context> context, content::RenderFrame* render_frame) { auto prefs = render_frame->GetBlinkPreferences(); // We only need to run the isolated bundle if webview is enabled diff --git a/shell/renderer/renderer_client_base.h b/shell/renderer/renderer_client_base.h index c1dad2738f..39753ddee5 100644 --- a/shell/renderer/renderer_client_base.h +++ b/shell/renderer/renderer_client_base.h @@ -64,12 +64,12 @@ class RendererClientBase : public content::ContentRendererClient mojo::ScopedMessagePipeHandle interface_pipe) override; #endif - virtual void DidCreateScriptContext(v8::Handle<v8::Context> context, + virtual void DidCreateScriptContext(v8::Local<v8::Context> context, content::RenderFrame* render_frame) = 0; - virtual void WillReleaseScriptContext(v8::Handle<v8::Context> context, + virtual void WillReleaseScriptContext(v8::Local<v8::Context> context, content::RenderFrame* render_frame) = 0; virtual void DidClearWindowObject(content::RenderFrame* render_frame); - virtual void SetupMainWorldOverrides(v8::Handle<v8::Context> context, + virtual void SetupMainWorldOverrides(v8::Local<v8::Context> context, content::RenderFrame* render_frame); std::unique_ptr<blink::WebPrescientNetworking> CreatePrescientNetworking( @@ -84,7 +84,7 @@ class RendererClientBase : public content::ContentRendererClient v8::Local<v8::Object> context, v8::Local<v8::Function> register_cb); - bool IsWebViewFrame(v8::Handle<v8::Context> context, + bool IsWebViewFrame(v8::Local<v8::Context> context, content::RenderFrame* render_frame) const; #if BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER) @@ -96,7 +96,7 @@ class RendererClientBase : public content::ContentRendererClient gin_helper::Dictionary* process, content::RenderFrame* render_frame); - bool ShouldLoadPreload(v8::Handle<v8::Context> context, + bool ShouldLoadPreload(v8::Local<v8::Context> context, content::RenderFrame* render_frame) const; // content::ContentRendererClient:
chore
f27b0340454ada29977a7d08f2dbc8321923e1b1
Milan Burda
2023-09-04 12:33:29
test: convert a few more specs to async/await (#39712)
diff --git a/spec/api-browser-view-spec.ts b/spec/api-browser-view-spec.ts index ec4d5a38aa..76e86adb73 100644 --- a/spec/api-browser-view-spec.ts +++ b/spec/api-browser-view-spec.ts @@ -300,18 +300,14 @@ describe('BrowserView module', () => { }).to.not.throw(); }); - it('can be called on a BrowserView with a destroyed webContents', (done) => { + it('can be called on a BrowserView with a destroyed webContents', async () => { view = new BrowserView(); w.addBrowserView(view); - - view.webContents.on('destroyed', () => { - w.removeBrowserView(view); - done(); - }); - - view.webContents.loadURL('data:text/html,hello there').then(() => { - view.webContents.close(); - }); + await view.webContents.loadURL('data:text/html,hello there'); + const destroyed = once(view.webContents, 'destroyed'); + view.webContents.close(); + await destroyed; + w.removeBrowserView(view); }); }); diff --git a/spec/api-browser-window-spec.ts b/spec/api-browser-window-spec.ts index 4b5c752404..540ad42d14 100644 --- a/spec/api-browser-window-spec.ts +++ b/spec/api-browser-window-spec.ts @@ -589,7 +589,7 @@ describe('BrowserWindow module', () => { describe('will-frame-navigate event', () => { let server = null as unknown as http.Server; let url = null as unknown as string; - before((done) => { + before(async () => { server = http.createServer((req, res) => { if (req.url === '/navigate-top') { res.end('<a target=_top href="/">navigate _top</a>'); @@ -609,10 +609,7 @@ describe('BrowserWindow module', () => { res.end(''); } }); - server.listen(0, '127.0.0.1', () => { - url = `http://127.0.0.1:${(server.address() as AddressInfo).port}/`; - done(); - }); + url = (await listen(server)).url; }); after(() => { @@ -683,7 +680,7 @@ describe('BrowserWindow module', () => { resolve(e.url); }); }); - expect(navigatedTo).to.equal(url); + expect(navigatedTo).to.equal(url + '/'); expect(w.webContents.getURL()).to.match(/^file:/); }); @@ -696,7 +693,7 @@ describe('BrowserWindow module', () => { resolve(e.url); }); }); - expect(navigatedTo).to.equal(url); + expect(navigatedTo).to.equal(url + '/'); expect(w.webContents.getURL()).to.equal('about:blank'); }); @@ -883,7 +880,7 @@ describe('BrowserWindow module', () => { 'did-frame-navigate', 'did-navigate' ]; - before((done) => { + before(async () => { server = http.createServer((req, res) => { if (req.url === '/navigate') { res.end('<a href="/">navigate</a>'); @@ -899,10 +896,7 @@ describe('BrowserWindow module', () => { res.end(''); } }); - server.listen(0, '127.0.0.1', () => { - url = `http://127.0.0.1:${(server.address() as AddressInfo).port}/`; - done(); - }); + url = (await listen(server)).url; }); it('for initial navigation, event order is consistent', async () => { const firedEvents: string[] = []; @@ -929,7 +923,7 @@ describe('BrowserWindow module', () => { 'did-frame-navigate', 'did-navigate' ]; - w.loadURL(`${url}navigate`); + w.loadURL(url + '/navigate'); await once(w.webContents, 'did-navigate'); await setTimeout(2000); Promise.all(navigationEvents.map(event => @@ -972,7 +966,7 @@ describe('BrowserWindow module', () => { 'did-frame-navigate', 'did-navigate' ]; - w.loadURL(`${url}redirect`); + w.loadURL(url + '/redirect'); await once(w.webContents, 'did-navigate'); await setTimeout(2000); Promise.all(navigationEvents.map(event => @@ -1010,7 +1004,7 @@ describe('BrowserWindow module', () => { 'did-start-navigation', 'did-navigate-in-page' ]; - w.loadURL(`${url}in-page`); + w.loadURL(url + '/in-page'); await once(w.webContents, 'did-navigate'); await setTimeout(2000); Promise.all(navigationEvents.map(event => @@ -4729,7 +4723,7 @@ describe('BrowserWindow module', () => { expect(c.isVisible()).to.be.true('child is visible'); }); - it('closes a grandchild window when a middle child window is destroyed', (done) => { + it('closes a grandchild window when a middle child window is destroyed', async () => { const w = new BrowserWindow(); w.loadFile(path.join(fixtures, 'pages', 'base-page.html')); @@ -4739,12 +4733,12 @@ describe('BrowserWindow module', () => { const childWindow = new BrowserWindow({ parent: window }); await setTimeout(); + + const closed = once(childWindow, 'closed'); window.close(); + await closed; - childWindow.on('closed', () => { - expect(() => { BrowserWindow.getFocusedWindow(); }).to.not.throw(); - done(); - }); + expect(() => { BrowserWindow.getFocusedWindow(); }).to.not.throw(); }); }); diff --git a/spec/api-menu-spec.ts b/spec/api-menu-spec.ts index a6a6243a60..019f5b43a2 100644 --- a/spec/api-menu-spec.ts +++ b/spec/api-menu-spec.ts @@ -813,15 +813,17 @@ describe('Menu module', function () { }).to.not.throw(); }); - it('should emit menu-will-show event', (done) => { - menu.on('menu-will-show', () => { done(); }); + it('should emit menu-will-show event', async () => { + const menuWillShow = once(menu, 'menu-will-show'); menu.popup({ window: w }); + await menuWillShow; }); - it('should emit menu-will-close event', (done) => { - menu.on('menu-will-close', () => { done(); }); + it('should emit menu-will-close event', async () => { + const menuWillClose = once(menu, 'menu-will-close'); menu.popup({ window: w }); menu.closePopup(); + await menuWillClose; }); it('returns immediately', () => { diff --git a/spec/api-protocol-spec.ts b/spec/api-protocol-spec.ts index 72dfe18fe8..1bb267c281 100644 --- a/spec/api-protocol-spec.ts +++ b/spec/api-protocol-spec.ts @@ -263,7 +263,7 @@ describe('protocol module', () => { expect(r.headers).to.have.property('x-great-header', 'sogreat'); }); - it('can load iframes with custom protocols', (done) => { + it('can load iframes with custom protocols', async () => { registerFileProtocol('custom', (request, callback) => { const filename = request.url.substring(9); const p = path.join(__dirname, 'fixtures', 'pages', filename); @@ -278,8 +278,9 @@ describe('protocol module', () => { } }); + const loaded = once(ipcMain, 'loaded-iframe-custom-protocol'); w.loadFile(path.join(__dirname, 'fixtures', 'pages', 'iframe-protocol.html')); - ipcMain.once('loaded-iframe-custom-protocol', () => done()); + await loaded; }); it('sends object as response', async () => { diff --git a/spec/api-tray-spec.ts b/spec/api-tray-spec.ts index a5a0b2aed1..067d529330 100644 --- a/spec/api-tray-spec.ts +++ b/spec/api-tray-spec.ts @@ -3,6 +3,7 @@ import { Menu, Tray } from 'electron/main'; import { nativeImage } from 'electron/common'; import { ifdescribe, ifit } from './lib/spec-helpers'; import * as path from 'node:path'; +import { setTimeout } from 'node:timers/promises'; describe('tray module', () => { let tray: Tray; @@ -74,12 +75,11 @@ describe('tray module', () => { }); describe('tray.popUpContextMenu()', () => { - ifit(process.platform === 'win32')('can be called when menu is showing', function (done) { + ifit(process.platform === 'win32')('can be called when menu is showing', async function () { tray.setContextMenu(Menu.buildFromTemplate([{ label: 'Test' }])); - setTimeout(() => { - tray.popUpContextMenu(); - done(); - }); + const timeout = setTimeout(); + tray.popUpContextMenu(); + await timeout; tray.popUpContextMenu(); }); @@ -115,14 +115,13 @@ describe('tray module', () => { }); describe('tray.closeContextMenu()', () => { - ifit(process.platform === 'win32')('does not crash when called more than once', function (done) { + ifit(process.platform === 'win32')('does not crash when called more than once', async function () { tray.setContextMenu(Menu.buildFromTemplate([{ label: 'Test' }])); - setTimeout(() => { - tray.closeContextMenu(); - tray.closeContextMenu(); - done(); - }); + const timeout = setTimeout(); tray.popUpContextMenu(); + await timeout; + tray.closeContextMenu(); + tray.closeContextMenu(); }); }); diff --git a/spec/api-web-contents-spec.ts b/spec/api-web-contents-spec.ts index b440ef2b3e..089523c953 100644 --- a/spec/api-web-contents-spec.ts +++ b/spec/api-web-contents-spec.ts @@ -1218,8 +1218,7 @@ describe('webContents module', () => { res.end(); }); }); - server.listen(0, '127.0.0.1', () => { - const url = 'http://127.0.0.1:' + (server.address() as AddressInfo).port; + listen(server).then(({ url }) => { const content = `<iframe src=${url}></iframe>`; w.webContents.on('did-frame-finish-load', (e, isMainFrame) => { if (!isMainFrame) { @@ -1591,8 +1590,9 @@ describe('webContents module', () => { default: done('unsupported endpoint'); } - }).listen(0, '127.0.0.1', () => { - serverUrl = 'http://127.0.0.1:' + (server.address() as AddressInfo).port; + }); + listen(server).then(({ url }) => { + serverUrl = url; done(); }); }); @@ -1721,11 +1721,10 @@ describe('webContents module', () => { } res.end('<a id="a" href="/should_have_referrer" target="_blank">link</a>'); }); - server.listen(0, '127.0.0.1', () => { - const url = 'http://127.0.0.1:' + (server.address() as AddressInfo).port + '/'; + listen(server).then(({ url }) => { w.webContents.once('did-finish-load', () => { w.webContents.setWindowOpenHandler(details => { - expect(details.referrer.url).to.equal(url); + expect(details.referrer.url).to.equal(url + '/'); expect(details.referrer.policy).to.equal('strict-origin-when-cross-origin'); return { action: 'allow' }; }); @@ -1748,11 +1747,10 @@ describe('webContents module', () => { } res.end(''); }); - server.listen(0, '127.0.0.1', () => { - const url = 'http://127.0.0.1:' + (server.address() as AddressInfo).port + '/'; + listen(server).then(({ url }) => { w.webContents.once('did-finish-load', () => { w.webContents.setWindowOpenHandler(details => { - expect(details.referrer.url).to.equal(url); + expect(details.referrer.url).to.equal(url + '/'); expect(details.referrer.policy).to.equal('strict-origin-when-cross-origin'); return { action: 'allow' }; }); diff --git a/spec/api-web-request-spec.ts b/spec/api-web-request-spec.ts index f3091b579a..3d29cc6142 100644 --- a/spec/api-web-request-spec.ts +++ b/spec/api-web-request-spec.ts @@ -7,7 +7,7 @@ import * as fs from 'node:fs'; import * as url from 'node:url'; import * as WebSocket from 'ws'; import { ipcMain, protocol, session, WebContents, webContents } from 'electron/main'; -import { AddressInfo, Socket } from 'node:net'; +import { Socket } from 'node:net'; import { listen, defer } from './lib/spec-helpers'; import { once } from 'node:events'; import { ReadableStream } from 'node:stream/web'; @@ -60,10 +60,7 @@ describe('webRequest module', () => { before(async () => { protocol.registerStringProtocol('cors', (req, cb) => cb('')); defaultURL = (await listen(server)).url + '/'; - await new Promise<void>((resolve) => { - h2server.listen(0, '127.0.0.1', () => resolve()); - }); - http2URL = `https://127.0.0.1:${(h2server.address() as AddressInfo).port}/`; + http2URL = (await listen(h2server)).url + '/'; console.log(http2URL); }); diff --git a/spec/chromium-spec.ts b/spec/chromium-spec.ts index c1ccab48bd..9216038dfd 100644 --- a/spec/chromium-spec.ts +++ b/spec/chromium-spec.ts @@ -13,6 +13,7 @@ import { ifit, ifdescribe, defer, itremote, listen } from './lib/spec-helpers'; import { PipeTransport } from './pipe-transport'; import * as ws from 'ws'; import { setTimeout } from 'node:timers/promises'; +import { AddressInfo } from 'node:net'; const features = process._linkedBinding('electron_common_features'); @@ -56,12 +57,12 @@ describe('reporting api', () => { res.end('<script>window.navigator.vibrate(1)</script>'); }); - await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve)); + await listen(server); const bw = new BrowserWindow({ show: false }); try { const reportGenerated = once(reporting, 'report'); - await bw.loadURL(`https://localhost:${(server.address() as any).port}/a`); + await bw.loadURL(`https://localhost:${(server.address() as AddressInfo).port}/a`); const [reports] = await reportGenerated; expect(reports).to.be.an('array').with.lengthOf(1); diff --git a/spec/guest-window-manager-spec.ts b/spec/guest-window-manager-spec.ts index 8e4cffee3b..21011a32c4 100644 --- a/spec/guest-window-manager-spec.ts +++ b/spec/guest-window-manager-spec.ts @@ -200,29 +200,21 @@ describe('webContents.setWindowOpenHandler', () => { }); // Linux and arm64 platforms (WOA and macOS) do not return any capture sources - ifit(process.platform === 'darwin' && process.arch === 'x64')('should not make child window background transparent', (done) => { + ifit(process.platform === 'darwin' && process.arch === 'x64')('should not make child window background transparent', async () => { browserWindow.webContents.setWindowOpenHandler(() => ({ action: 'allow' })); - - browserWindow.webContents.once('did-create-window', async (childWindow) => { - const display = screen.getPrimaryDisplay(); - childWindow.setBounds(display.bounds); - await childWindow.webContents.executeJavaScript("const meta = document.createElement('meta'); meta.name = 'color-scheme'; meta.content = 'dark'; document.head.appendChild(meta); true;"); - await setTimeoutAsync(1000); - const screenCapture = await captureScreen(); - const centerColor = getPixelColor(screenCapture, { - x: display.size.width / 2, - y: display.size.height / 2 - }); - - try { - // color-scheme is set to dark so background should not be white - expect(areColorsSimilar(centerColor, HexColors.WHITE)).to.be.false(); - done(); - } catch (err) { - done(err); - } - }); - + const didCreateWindow = once(browserWindow.webContents, 'did-create-window'); browserWindow.webContents.executeJavaScript("window.open('about:blank') && true"); + const [childWindow] = await didCreateWindow; + const display = screen.getPrimaryDisplay(); + childWindow.setBounds(display.bounds); + await childWindow.webContents.executeJavaScript("const meta = document.createElement('meta'); meta.name = 'color-scheme'; meta.content = 'dark'; document.head.appendChild(meta); true;"); + await setTimeoutAsync(1000); + const screenCapture = await captureScreen(); + const centerColor = getPixelColor(screenCapture, { + x: display.size.width / 2, + y: display.size.height / 2 + }); + // color-scheme is set to dark so background should not be white + expect(areColorsSimilar(centerColor, HexColors.WHITE)).to.be.false(); }); }); diff --git a/spec/lib/spec-helpers.ts b/spec/lib/spec-helpers.ts index a94964f936..e814c5a453 100644 --- a/spec/lib/spec-helpers.ts +++ b/spec/lib/spec-helpers.ts @@ -2,6 +2,7 @@ import * as childProcess from 'node:child_process'; import * as path from 'node:path'; import * as http from 'node:http'; import * as https from 'node:https'; +import * as http2 from 'node:http2'; import * as net from 'node:net'; import * as v8 from 'node:v8'; import * as url from 'node:url'; @@ -194,10 +195,10 @@ export async function itremote (name: string, fn: Function, args?: any[]) { }); } -export async function listen (server: http.Server | https.Server) { +export async function listen (server: http.Server | https.Server | http2.Http2SecureServer) { const hostname = '127.0.0.1'; await new Promise<void>(resolve => server.listen(0, hostname, () => resolve())); const { port } = server.address() as net.AddressInfo; - const protocol = (server instanceof https.Server) ? 'https' : 'http'; + const protocol = (server instanceof http.Server) ? 'http' : 'https'; return { port, url: url.format({ protocol, hostname, port }) }; }
test
122a2fd177823e2bf26d8218992648d0483c1b1f
electron-appveyor-updater[bot]
2024-03-13 13:15:29
build: update appveyor image to latest version (#41579) Co-authored-by: electron-appveyor-updater[bot] <161660339+electron-appveyor-updater[bot]@users.noreply.github.com>
diff --git a/appveyor-woa.yml b/appveyor-woa.yml index 79e91e40c3..9785565cdf 100644 --- a/appveyor-woa.yml +++ b/appveyor-woa.yml @@ -29,7 +29,7 @@ version: 1.0.{build} build_cloud: electronhq-16-core -image: e-124.0.6331.0 +image: e-124.0.6351.0 environment: GIT_CACHE_PATH: C:\Users\appveyor\libcc_cache ELECTRON_OUT_DIR: Default diff --git a/appveyor.yml b/appveyor.yml index 6b7edcb0f9..a50c7b5f7b 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -29,7 +29,7 @@ version: 1.0.{build} build_cloud: electronhq-16-core -image: e-124.0.6331.0 +image: e-124.0.6351.0 environment: GIT_CACHE_PATH: C:\Users\appveyor\libcc_cache ELECTRON_OUT_DIR: Default
build
dfce1a9eb4de3a5789536cd511e81c6dfd81e393
Cheng Zhao
2024-01-04 16:34:08
fix: ignore all NODE_ envs from foreign parent in node process (#40770) * fix: ignore all NODE_ envs from foreign parent * fix: recognize ad-hoc signed binary
diff --git a/filenames.gni b/filenames.gni index 3824749663..d142f312bb 100644 --- a/filenames.gni +++ b/filenames.gni @@ -656,6 +656,7 @@ filenames = { "shell/common/node_includes.h", "shell/common/node_util.cc", "shell/common/node_util.h", + "shell/common/node_util_mac.mm", "shell/common/options_switches.cc", "shell/common/options_switches.h", "shell/common/platform_util.cc", diff --git a/shell/app/node_main.cc b/shell/app/node_main.cc index adca7ff483..469b7e31c8 100644 --- a/shell/app/node_main.cc +++ b/shell/app/node_main.cc @@ -31,6 +31,7 @@ #include "shell/common/gin_helper/dictionary.h" #include "shell/common/node_bindings.h" #include "shell/common/node_includes.h" +#include "shell/common/node_util.h" #if BUILDFLAG(IS_WIN) #include "chrome/child/v8_crashpad_support_win.h" @@ -107,8 +108,12 @@ int NodeMain(int argc, char* argv[]) { auto os_env = base::Environment::Create(); bool node_options_enabled = electron::fuses::IsNodeOptionsEnabled(); + if (!node_options_enabled) { + os_env->UnSetVar("NODE_OPTIONS"); + } + #if BUILDFLAG(IS_MAC) - if (node_options_enabled && os_env->HasVar("NODE_OPTIONS")) { + if (!ProcessSignatureIsSameWithCurrentApp(getppid())) { // On macOS, it is forbidden to run sandboxed app with custom arguments // from another app, i.e. args are discarded in following call: // exec("Sandboxed.app", ["--custom-args-will-be-discarded"]) @@ -117,18 +122,14 @@ int NodeMain(int argc, char* argv[]) { // exec("Electron.app", {env: {ELECTRON_RUN_AS_NODE: "1", // NODE_OPTIONS: "--require 'bad.js'"}}) // To prevent Electron apps from being used to work around macOS security - // restrictions, when NODE_OPTIONS is passed it will be checked whether - // this process is invoked by its own app. - if (!ProcessBelongToCurrentApp(getppid())) { - LOG(ERROR) << "NODE_OPTIONS is disabled because this process is invoked " - "by other apps."; - node_options_enabled = false; + // restrictions, when the parent process is not part of the app bundle, all + // environment variables starting with NODE_ will be removed. + if (util::UnsetAllNodeEnvs()) { + LOG(ERROR) << "Node.js environment variables are disabled because this " + "process is invoked by other apps."; } } #endif // BUILDFLAG(IS_MAC) - if (!node_options_enabled) { - os_env->UnSetVar("NODE_OPTIONS"); - } #if BUILDFLAG(IS_WIN) v8_crashpad_support::SetUp(); diff --git a/shell/common/mac/codesign_util.cc b/shell/common/mac/codesign_util.cc index 5171f90aac..2abfb2eb32 100644 --- a/shell/common/mac/codesign_util.cc +++ b/shell/common/mac/codesign_util.cc @@ -5,15 +5,60 @@ #include "shell/common/mac/codesign_util.h" +#include "base/apple/foundation_util.h" #include "base/apple/osstatus_logging.h" #include "base/apple/scoped_cftyperef.h" +#include "third_party/abseil-cpp/absl/types/optional.h" #include <CoreFoundation/CoreFoundation.h> #include <Security/Security.h> namespace electron { -bool ProcessBelongToCurrentApp(pid_t pid) { +absl::optional<bool> IsUnsignedOrAdHocSigned(SecCodeRef code) { + base::apple::ScopedCFTypeRef<SecStaticCodeRef> static_code; + OSStatus status = SecCodeCopyStaticCode(code, kSecCSDefaultFlags, + static_code.InitializeInto()); + if (status == errSecCSUnsigned) { + return true; + } + if (status != errSecSuccess) { + OSSTATUS_LOG(ERROR, status) << "SecCodeCopyStaticCode"; + return absl::optional<bool>(); + } + // Copy the signing info from the SecStaticCodeRef. + base::apple::ScopedCFTypeRef<CFDictionaryRef> signing_info; + status = + SecCodeCopySigningInformation(static_code.get(), kSecCSSigningInformation, + signing_info.InitializeInto()); + if (status != errSecSuccess) { + OSSTATUS_LOG(ERROR, status) << "SecCodeCopySigningInformation"; + return absl::optional<bool>(); + } + // Look up the code signing flags. If the flags are absent treat this as + // unsigned. This decision is consistent with the StaticCode source: + // https://github.com/apple-oss-distributions/Security/blob/Security-60157.40.30.0.1/OSX/libsecurity_codesigning/lib/StaticCode.cpp#L2270 + CFNumberRef signing_info_flags = + base::apple::GetValueFromDictionary<CFNumberRef>(signing_info.get(), + kSecCodeInfoFlags); + if (!signing_info_flags) { + return true; + } + // Using a long long to extract the value from the CFNumberRef to be + // consistent with how it was packed by Security.framework. + // https://github.com/apple-oss-distributions/Security/blob/Security-60157.40.30.0.1/OSX/libsecurity_utilities/lib/cfutilities.h#L262 + long long flags; + if (!CFNumberGetValue(signing_info_flags, kCFNumberLongLongType, &flags)) { + LOG(ERROR) << "CFNumberGetValue"; + return absl::optional<bool>(); + } + if (static_cast<uint32_t>(flags) & kSecCodeSignatureAdhoc) { + return true; + } + return false; +} + +bool ProcessSignatureIsSameWithCurrentApp(pid_t pid) { // Get and check the code signature of current app. base::apple::ScopedCFTypeRef<SecCodeRef> self_code; OSStatus status = @@ -22,6 +67,15 @@ bool ProcessBelongToCurrentApp(pid_t pid) { OSSTATUS_LOG(ERROR, status) << "SecCodeCopyGuestWithAttributes"; return false; } + absl::optional<bool> not_signed = IsUnsignedOrAdHocSigned(self_code.get()); + if (!not_signed.has_value()) { + // Error happened. + return false; + } + if (not_signed.value()) { + // Current app is not signed. + return true; + } // Get the code signature of process. base::apple::ScopedCFTypeRef<CFNumberRef> process_cf( CFNumberCreate(nullptr, kCFNumberIntType, &pid)); @@ -46,9 +100,14 @@ bool ProcessBelongToCurrentApp(pid_t pid) { OSSTATUS_LOG(ERROR, status) << "SecCodeCopyDesignatedRequirement"; return false; } + DCHECK(self_requirement.get()); // Check whether the process meets the signature requirement of current app. status = SecCodeCheckValidity(process_code.get(), kSecCSDefaultFlags, self_requirement.get()); + if (status != errSecSuccess && status != errSecCSReqFailed) { + OSSTATUS_LOG(ERROR, status) << "SecCodeCheckValidity"; + return false; + } return status == errSecSuccess; } diff --git a/shell/common/mac/codesign_util.h b/shell/common/mac/codesign_util.h index 8a2fb94ee8..1fabc4fe42 100644 --- a/shell/common/mac/codesign_util.h +++ b/shell/common/mac/codesign_util.h @@ -10,9 +10,14 @@ namespace electron { -// Given a pid, check if the process belongs to current app by comparing its -// code signature with current app. -bool ProcessBelongToCurrentApp(pid_t pid); +// Given a pid, return true if the process has the same code signature with +// with current app. +// This API returns true if current app is not signed or ad-hoc signed, because +// checking code signature is meaningless in this case, and failing the +// signature check would break some features with unsigned binary (for example, +// process.send stops working in processes created by child_process.fork, due +// to the NODE_CHANNEL_ID env getting removed). +bool ProcessSignatureIsSameWithCurrentApp(pid_t pid); } // namespace electron diff --git a/shell/common/node_util.h b/shell/common/node_util.h index 38f9d28b2b..d4aa75a0db 100644 --- a/shell/common/node_util.h +++ b/shell/common/node_util.h @@ -7,6 +7,7 @@ #include <vector> +#include "build/build_config.h" #include "v8/include/v8.h" namespace node { @@ -26,6 +27,12 @@ v8::MaybeLocal<v8::Value> CompileAndCall( std::vector<v8::Local<v8::String>>* parameters, std::vector<v8::Local<v8::Value>>* arguments); +#if BUILDFLAG(IS_MAC) +// Unset all environment variables that start with NODE_. Return false if there +// is no node env at all. +bool UnsetAllNodeEnvs(); +#endif + } // namespace electron::util #endif // ELECTRON_SHELL_COMMON_NODE_UTIL_H_ diff --git a/shell/common/node_util_mac.mm b/shell/common/node_util_mac.mm new file mode 100644 index 0000000000..85c0725098 --- /dev/null +++ b/shell/common/node_util_mac.mm @@ -0,0 +1,23 @@ +// Copyright (c) 2023 Microsoft, Inc. +// Use of this source code is governed by the MIT license that can be +// found in the LICENSE file. + +#include "shell/common/node_util.h" + +#include <Foundation/Foundation.h> + +namespace electron::util { + +bool UnsetAllNodeEnvs() { + bool has_unset = false; + for (NSString* env in NSProcessInfo.processInfo.environment) { + if (![env hasPrefix:@"NODE_"]) + continue; + const char* name = [[env componentsSeparatedByString:@"="][0] UTF8String]; + unsetenv(name); + has_unset = true; + } + return has_unset; +} + +} // namespace electron::util diff --git a/spec/fixtures/api/fork-with-node-options.js b/spec/fixtures/api/fork-with-node-options.js index 49dad89944..97439598f4 100644 --- a/spec/fixtures/api/fork-with-node-options.js +++ b/spec/fixtures/api/fork-with-node-options.js @@ -2,11 +2,14 @@ const { execFileSync } = require('node:child_process'); const path = require('node:path'); const fixtures = path.resolve(__dirname, '..'); +const failJs = path.join(fixtures, 'module', 'fail.js'); const env = { ELECTRON_RUN_AS_NODE: 'true', // Process will exit with 1 if NODE_OPTIONS is accepted. - NODE_OPTIONS: `--require "${path.join(fixtures, 'module', 'fail.js')}"` + NODE_OPTIONS: `--require "${failJs}"`, + // Try bypassing the check with NODE_REPL_EXTERNAL_MODULE. + NODE_REPL_EXTERNAL_MODULE: failJs }; // Provide a lower cased NODE_OPTIONS in case some code ignores case sensitivity // when reading NODE_OPTIONS. diff --git a/spec/node-spec.ts b/spec/node-spec.ts index 2bb967055e..e1d9c76d9e 100644 --- a/spec/node-spec.ts +++ b/spec/node-spec.ts @@ -673,7 +673,7 @@ describe('node feature', () => { }); const script = path.join(fixtures, 'api', 'fork-with-node-options.js'); - const nodeOptionsWarning = 'NODE_OPTIONS is disabled because this process is invoked by other apps'; + const nodeOptionsWarning = 'Node.js environment variables are disabled because this process is invoked by other apps'; it('is disabled when invoked by other apps in ELECTRON_RUN_AS_NODE mode', async () => { await withTempDirectory(async (dir) => {
fix
75d2caf451c925a826229ae27264c9b54de9b6db
Shelley Vohr
2022-11-10 22:31:20
chore: upgrade to Node.js v18 (#35999) * chore: update to Node.js v18 * child_process: improve argument validation https://github.com/nodejs/node/pull/41305 * bootstrap: support configure-time user-land snapshot https://github.com/nodejs/node/pull/42466 * chore: update GN patch * src: disambiguate terms used to refer to builtins and addons https://github.com/nodejs/node/pull/44135 * src: use a typed array internally for process._exiting https://github.com/nodejs/node/pull/43883 * chore: lib/internal/bootstrap -> lib/internal/process * src: disambiguate terms used to refer to builtins and addons https://github.com/nodejs/node/pull/44135 * chore: remove redudant browserGlobals patch * chore: update BoringSSL patch * src: allow embedder-provided PageAllocator in NodePlatform https://github.com/nodejs/node/pull/38362 * chore: fixup Node.js crypto tests - https://github.com/nodejs/node/pull/44171 - https://github.com/nodejs/node/pull/41600 * lib: add Promise methods to avoid-prototype-pollution lint rule https://github.com/nodejs/node/pull/43849 * deps: update V8 to 10.1 https://github.com/nodejs/node/pull/42657 * src: add kNoBrowserGlobals flag for Environment https://github.com/nodejs/node/pull/40532 * chore: consolidate asar initialization patches * deps: update V8 to 10.1 https://github.com/nodejs/node/pull/42657 * deps: update V8 to 9.8 https://github.com/nodejs/node/pull/41610 * src,crypto: remove AllocatedBuffers from crypto_spkac https://github.com/nodejs/node/pull/40752 * build: enable V8's shared read-only heap https://github.com/nodejs/node/pull/42809 * src: fix ssize_t error from nghttp2.h https://github.com/nodejs/node/pull/44393 * chore: fixup ESM patch * chore: fixup patch indices * src: merge NativeModuleEnv into NativeModuleLoader https://github.com/nodejs/node/pull/43824 * [API] Pass OOMDetails to OOMErrorCallback https://chromium-review.googlesource.com/c/v8/v8/+/3647827 * src: iwyu in cleanup_queue.cc * src: return Maybe from a couple of functions https://github.com/nodejs/node/pull/39603 * src: clean up embedder API https://github.com/nodejs/node/pull/35897 * src: refactor DH groups to delete crypto_groups.h https://github.com/nodejs/node/pull/43896 * deps,src: use SIMD for normal base64 encoding https://github.com/nodejs/node/pull/39775 * chore: remove deleted source file * chore: update patches * chore: remove deleted source file * lib: add fetch https://github.com/nodejs/node/pull/41749 * chore: remove nonexistent node specs * test: split report OOM tests https://github.com/nodejs/node/pull/44389 * src: trace fs async api https://github.com/nodejs/node/pull/44057 * http: trace http request / response https://github.com/nodejs/node/pull/44102 * test: split test-crypto-dh.js https://github.com/nodejs/node/pull/40451 * crypto: introduce X509Certificate API https://github.com/nodejs/node/pull/36804 * src: split property helpers from node::Environment https://github.com/nodejs/node/pull/44056 * https://github.com/nodejs/node/pull/38905 bootstrap: implement run-time user-land snapshots via --build-snapshot and --snapshot-blob * lib,src: implement WebAssembly Web API https://github.com/nodejs/node/pull/42701 * fixup! deps,src: use SIMD for normal base64 encoding * fixup! src: refactor DH groups to delete crypto_groups.h * chore: fixup base64 GN file * fix: check that node::InitializeContext() returns true * chore: delete _noBrowserGlobals usage * chore: disable fetch in renderer procceses * dns: default to verbatim=true in dns.lookup() https://github.com/nodejs/node/pull/39987 Co-authored-by: PatchUp <73610968+patchup[bot]@users.noreply.github.com>
diff --git a/DEPS b/DEPS index 86f587a8b7..0fd699c24c 100644 --- a/DEPS +++ b/DEPS @@ -4,7 +4,7 @@ vars = { 'chromium_version': '109.0.5382.0', 'node_version': - 'v16.17.1', + 'v18.10.0', 'nan_version': '16fa32231e2ccd89d2804b3f765319128b20c4ac', 'squirrel.mac_version': diff --git a/patches/node/.patches b/patches/node/.patches index 432a9d45b5..e276c698a7 100644 --- a/patches/node/.patches +++ b/patches/node/.patches @@ -9,9 +9,7 @@ build_modify_js2c_py_to_allow_injection_of_original-fs_and_custom_embedder_js.pa refactor_allow_embedder_overriding_of_internal_fs_calls.patch chore_allow_the_node_entrypoint_to_be_a_builtin_module.patch chore_add_context_to_context_aware_module_prevention.patch -chore_read_nobrowserglobals_from_global_not_process.patch fix_handle_boringssl_and_openssl_incompatibilities.patch -src_allow_embedders_to_provide_a_custom_pageallocator_to.patch fix_crypto_tests_to_run_with_bssl.patch fix_account_for_debugger_agent_race_condition.patch repl_fix_crash_when_sharedarraybuffer_disabled.patch @@ -20,10 +18,8 @@ fix_crash_caused_by_gethostnamew_on_windows_7.patch fix_suppress_clang_-wdeprecated-declarations_in_libuv.patch fix_serdes_test.patch darwin_bump_minimum_supported_version_to_10_15_3406.patch -fix_failing_node_js_test_on_outdated.patch be_compatible_with_cppgc.patch feat_add_knostartdebugsignalhandler_to_environment_to_prevent.patch -worker_thread_add_asar_support.patch process_monitor_for_exit_with_kqueue_on_bsds_3441.patch process_bsd_handle_kevent_note_exit_failure_3451.patch reland_macos_use_posix_spawn_instead_of_fork_3257.patch @@ -35,15 +31,12 @@ process_simplify_uv_write_int_calls_3519.patch macos_don_t_use_thread-unsafe_strtok_3524.patch process_fix_hang_after_note_exit_3521.patch feat_add_uv_loop_interrupt_on_io_change_option_to_uv_loop_configure.patch -fix_preserve_proper_method_names_as-is_in_error_stack.patch macos_avoid_posix_spawnp_cwd_bug_3597.patch -src_update_importmoduledynamically.patch json_parse_errors_made_user-friendly.patch support_v8_sandboxed_pointers.patch build_ensure_v8_pointer_compression_sandbox_is_enabled_on_64bit.patch build_ensure_native_module_compilation_fails_if_not_using_a_new.patch fix_override_createjob_in_node_platform.patch -src_fix_ssize_t_error_from_nghttp2_h.patch v8_api_advance_api_deprecation.patch enable_-wunqualified-std-cast-call.patch fixup_for_error_declaration_shadows_a_local_variable.patch @@ -53,3 +46,7 @@ fix_parallel_test-v8-stats.patch fix_expose_the_built-in_electron_module_via_the_esm_loader.patch heap_remove_allocationspace_map_space_enum_constant.patch test_remove_experimental-wasm-threads_flag.patch +api_pass_oomdetails_to_oomerrorcallback.patch +src_iwyu_in_cleanup_queue_cc.patch +fix_expose_lookupandcompile_with_parameters.patch +fix_prevent_changing_functiontemplateinfo_after_publish.patch diff --git a/patches/node/api_pass_oomdetails_to_oomerrorcallback.patch b/patches/node/api_pass_oomdetails_to_oomerrorcallback.patch new file mode 100644 index 0000000000..32823a7786 --- /dev/null +++ b/patches/node/api_pass_oomdetails_to_oomerrorcallback.patch @@ -0,0 +1,39 @@ +From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 +From: Shelley Vohr <[email protected]> +Date: Wed, 12 Oct 2022 21:25:49 +0200 +Subject: Pass OOMDetails to OOMErrorCallback + +Introduced in https://chromium-review.googlesource.com/c/v8/v8/+/3647827. + +This patch can be removed when Node.js updates to a V8 version containing +the above CL. + +diff --git a/src/node_errors.cc b/src/node_errors.cc +index 323fc7d4ff635ca287ee241cee234da0600340a2..36ab78f739f3faecab47eead99f9aa3c403672c0 100644 +--- a/src/node_errors.cc ++++ b/src/node_errors.cc +@@ -495,9 +495,9 @@ void OnFatalError(const char* location, const char* message) { + ABORT(); + } + +-void OOMErrorHandler(const char* location, bool is_heap_oom) { ++void OOMErrorHandler(const char* location, const v8::OOMDetails& details) { + const char* message = +- is_heap_oom ? "Allocation failed - JavaScript heap out of memory" ++ details.is_heap_oom ? "Allocation failed - JavaScript heap out of memory" + : "Allocation failed - process out of memory"; + if (location) { + FPrintF(stderr, "FATAL ERROR: %s %s\n", location, message); +diff --git a/src/node_errors.h b/src/node_errors.h +index 5587c2348626102febe33a20ff45748a6eec61ad..6dbba32858dc82bc04171da7ee2a33a0b4dee791 100644 +--- a/src/node_errors.h ++++ b/src/node_errors.h +@@ -21,7 +21,7 @@ void AppendExceptionLine(Environment* env, + + [[noreturn]] void FatalError(const char* location, const char* message); + void OnFatalError(const char* location, const char* message); +-void OOMErrorHandler(const char* location, bool is_heap_oom); ++void OOMErrorHandler(const char* location, const v8::OOMDetails& details); + + // Helpers to construct errors similar to the ones provided by + // lib/internal/errors.js. diff --git a/patches/node/be_compatible_with_cppgc.patch b/patches/node/be_compatible_with_cppgc.patch index c25df6ffe2..0ff406d305 100644 --- a/patches/node/be_compatible_with_cppgc.patch +++ b/patches/node/be_compatible_with_cppgc.patch @@ -46,7 +46,7 @@ This patch should be upstreamed to Node. See also: https://source.chromium.org/chromium/chromium/src/+/main:v8/include/v8-cppgc.h;l=70-76;drc=5a758a97032f0b656c3c36a3497560762495501a diff --git a/src/base_object.h b/src/base_object.h -index 842f763a56d75c55509534e3d44a8080dd283127..b6078fe83c82a5edec0f7652b8c2d1b6c2491ca4 100644 +index a17879be5b452aa208caf1b29c86f8e5d9baa693..c48d7a7e9d0535cabb4eb84b5700d0cf537ddc88 100644 --- a/src/base_object.h +++ b/src/base_object.h @@ -40,7 +40,7 @@ class TransferData; @@ -59,10 +59,10 @@ index 842f763a56d75c55509534e3d44a8080dd283127..b6078fe83c82a5edec0f7652b8c2d1b6 // Associates this object with `object`. It uses the 0th internal field for // that, and in particular aborts if there is no such field. diff --git a/src/env.cc b/src/env.cc -index 22be69ec30a5b8466caacc698c791494891e5dee..cc44d578df9e146aa72f8273c1271d6a3c00d610 100644 +index 24aeb329c593bfd5a35877d6f4e2b7afa9848306..de41e5b7f6ff9f818c661484a93b74db7569e31f 100644 --- a/src/env.cc +++ b/src/env.cc -@@ -2119,11 +2119,20 @@ void Environment::RunWeakRefCleanup() { +@@ -2013,11 +2013,20 @@ void Environment::RunWeakRefCleanup() { isolate()->ClearKeptObjects(); } @@ -84,7 +84,7 @@ index 22be69ec30a5b8466caacc698c791494891e5dee..cc44d578df9e146aa72f8273c1271d6a object->SetAlignedPointerInInternalField(BaseObject::kSlot, static_cast<void*>(this)); env->AddCleanupHook(DeleteMe, static_cast<void*>(this)); -@@ -2177,7 +2186,8 @@ void BaseObject::MakeWeak() { +@@ -2071,7 +2080,8 @@ void BaseObject::MakeWeak() { void BaseObject::LazilyInitializedJSTemplateConstructor( const FunctionCallbackInfo<Value>& args) { DCHECK(args.IsConstructCall()); diff --git a/patches/node/build_add_gn_build_files.patch b/patches/node/build_add_gn_build_files.patch index 74da2afe93..39af302fc0 100644 --- a/patches/node/build_add_gn_build_files.patch +++ b/patches/node/build_add_gn_build_files.patch @@ -7,7 +7,7 @@ This adds GN build files for Node, so we don't have to build with GYP. diff --git a/BUILD.gn b/BUILD.gn new file mode 100644 -index 0000000000000000000000000000000000000000..a47875642d8f825c84ba1e82e3892a97e98e76e4 +index 0000000000000000000000000000000000000000..db80a8f00a84bf54f723c21300e7579c994d0514 --- /dev/null +++ b/BUILD.gn @@ -0,0 +1,438 @@ @@ -224,6 +224,7 @@ index 0000000000000000000000000000000000000000..a47875642d8f825c84ba1e82e3892a97 + ":node_js2c", + "deps/googletest:gtest", + "deps/uvwasi", ++ "deps/base64", + "//third_party/zlib", + "//third_party/brotli:dec", + "//third_party/brotli:enc", @@ -281,7 +282,6 @@ index 0000000000000000000000000000000000000000..a47875642d8f825c84ba1e82e3892a97 + sources += [ + "$root_gen_dir/electron_natives.cc", + "$target_gen_dir/node_javascript.cc", -+ "src/node_code_cache_stub.cc", + "src/node_snapshot_stub.cc", + ] + @@ -449,6 +449,192 @@ index 0000000000000000000000000000000000000000..a47875642d8f825c84ba1e82e3892a97 + ":tar_headers", + ] +} +diff --git a/deps/base64/BUILD.gn b/deps/base64/BUILD.gn +new file mode 100644 +index 0000000000000000000000000000000000000000..694e1991bb11c9ea85fcc69a0e06265d4b0c5aab +--- /dev/null ++++ b/deps/base64/BUILD.gn +@@ -0,0 +1,152 @@ ++config("base64_config") { ++ include_dirs = [ ++ "base64/include", ++ "base64/lib", ++ ] ++ ++ defines = [ "BASE64_STATIC_DEFINE" ] ++} ++ ++static_library("base64") { ++ defines = [] ++ deps = [] ++ ++ public_configs = [ ":base64_config" ] ++ ++ cflags_c = [ ++ "-Wno-implicit-fallthrough", ++ "-Wno-unused-but-set-variable", ++ "-Wno-shadow", ++ ] ++ ++ sources = [ ++ "base64/include/libbase64.h", ++ "base64/lib/arch/generic/codec.c", ++ "base64/lib/codec_choose.c", ++ "base64/lib/codecs.h", ++ "base64/lib/lib.c", ++ "base64/lib/tables/tables.c", ++ ] ++ ++ if (target_cpu == "arm") { ++ defines += [ "HAVE_NEON32=1" ] ++ deps += [ ":base64_neon32" ] ++ } else { ++ sources += [ "base64/lib/arch/neon32/neon32_codec.c" ] ++ } ++ ++ if (target_cpu == "arm64") { ++ defines += [ "HAVE_NEON64=1" ] ++ deps += [ ":base64_neon64" ] ++ } else { ++ sources += [ "base64/lib/arch/neon64/neon64_codec.c" ] ++ } ++ ++ if (target_cpu == "ia32" || target_cpu == "x64" || target_cpu == "x32") { ++ defines += [ ++ "HAVE_SSSE3=1", ++ "HAVE_SSE41=1", ++ "HAVE_SSE42=1", ++ "HAVE_AVX=1", ++ "HAVE_AVX2=1", ++ ] ++ ++ deps += [ ++ ":base64_avx", ++ ":base64_avx2", ++ ":base64_sse41", ++ ":base64_sse42", ++ ":base64_ssse3", ++ ] ++ } else { ++ sources += [ ++ "base64/lib/arch/avx/avx_codec.c", ++ "base64/lib/arch/avx2/avx2_codec.c", ++ "base64/lib/arch/sse41/sse41_codec.c", ++ "base64/lib/arch/sse42/sse42_codec.c", ++ "base64/lib/arch/ssse3/ssse3_codec.c", ++ ] ++ } ++} ++ ++source_set("base64_ssse3") { ++ public_configs = [ ":base64_config" ] ++ ++ defines = [ "HAVE_SSSE3=1" ] ++ ++ cflags = [ "-mssse3" ] ++ cflags_c = [ "-Wno-implicit-fallthrough" ] ++ ++ sources = [ "base64/lib/arch/ssse3/ssse3_codec.c" ] ++} ++ ++source_set("base64_sse41") { ++ public_configs = [ ":base64_config" ] ++ ++ defines = [ "HAVE_SSE41=1" ] ++ ++ cflags = [ "-msse4.1" ] ++ cflags_c = [ "-Wno-implicit-fallthrough" ] ++ ++ sources = [ "base64/lib/arch/sse41/sse41_codec.c" ] ++} ++ ++source_set("base64_sse42") { ++ public_configs = [ ":base64_config" ] ++ ++ defines = [ ++ "BASE64_STATIC_DEFINE", ++ "HAVE_SSE42=1", ++ ] ++ ++ cflags = [ "-msse4.2" ] ++ cflags_c = [ "-Wno-implicit-fallthrough" ] ++ ++ sources = [ "base64/lib/arch/sse42/sse42_codec.c" ] ++} ++ ++source_set("base64_avx") { ++ public_configs = [ ":base64_config" ] ++ ++ defines = [ "HAVE_AVX=1" ] ++ ++ cflags = [ "-mavx" ] ++ cflags_c = [ "-Wno-implicit-fallthrough" ] ++ ++ sources = [ "base64/lib/arch/avx/avx_codec.c" ] ++} ++ ++source_set("base64_avx2") { ++ public_configs = [ ":base64_config" ] ++ ++ defines = [ "HAVE_AVX2=1" ] ++ ++ cflags = [ "-mavx2" ] ++ cflags_c = [ ++ "-Wno-implicit-fallthrough", ++ "-Wno-implicit-function-declaration", ++ ] ++ ++ sources = [ "base64/lib/arch/avx2/avx2_codec.c" ] ++} ++ ++source_set("base64_neon32") { ++ public_configs = [ ":base64_config" ] ++ ++ defines = [ "HAVE_NEON32=1" ] ++ ++ cflags = [ "-mfpu=neon" ] ++ cflags_c = [ "-Wno-implicit-fallthrough" ] ++ ++ sources = [ "base64/lib/arch/neon32/neon32_codec.c" ] ++} ++ ++source_set("base64_neon64") { ++ public_configs = [ ":base64_config" ] ++ ++ defines = [ "HAVE_NEON64=1" ] ++ ++ cflags_c = [ "-Wno-implicit-fallthrough" ] ++ ++ sources = [ "base64/lib/arch/neon64/neon64_codec.c" ] ++} +diff --git a/deps/base64/base64/lib/arch/avx/codec.c b/deps/base64/base64/lib/arch/avx/avx_codec.c +similarity index 100% +rename from deps/base64/base64/lib/arch/avx/codec.c +rename to deps/base64/base64/lib/arch/avx/avx_codec.c +diff --git a/deps/base64/base64/lib/arch/avx2/codec.c b/deps/base64/base64/lib/arch/avx2/avx2_codec.c +similarity index 100% +rename from deps/base64/base64/lib/arch/avx2/codec.c +rename to deps/base64/base64/lib/arch/avx2/avx2_codec.c +diff --git a/deps/base64/base64/lib/arch/neon32/codec.c b/deps/base64/base64/lib/arch/neon32/neon32_codec.c +similarity index 100% +rename from deps/base64/base64/lib/arch/neon32/codec.c +rename to deps/base64/base64/lib/arch/neon32/neon32_codec.c +diff --git a/deps/base64/base64/lib/arch/neon64/codec.c b/deps/base64/base64/lib/arch/neon64/neon64_codec.c +similarity index 100% +rename from deps/base64/base64/lib/arch/neon64/codec.c +rename to deps/base64/base64/lib/arch/neon64/neon64_codec.c +diff --git a/deps/base64/base64/lib/arch/sse41/codec.c b/deps/base64/base64/lib/arch/sse41/sse41_codec.c +similarity index 100% +rename from deps/base64/base64/lib/arch/sse41/codec.c +rename to deps/base64/base64/lib/arch/sse41/sse41_codec.c +diff --git a/deps/base64/base64/lib/arch/sse42/codec.c b/deps/base64/base64/lib/arch/sse42/sse42_codec.c +similarity index 100% +rename from deps/base64/base64/lib/arch/sse42/codec.c +rename to deps/base64/base64/lib/arch/sse42/sse42_codec.c +diff --git a/deps/base64/base64/lib/arch/ssse3/codec.c b/deps/base64/base64/lib/arch/ssse3/ssse3_codec.c +similarity index 100% +rename from deps/base64/base64/lib/arch/ssse3/codec.c +rename to deps/base64/base64/lib/arch/ssse3/ssse3_codec.c diff --git a/deps/cares/BUILD.gn b/deps/cares/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..71a37834f4e693c190eb7e7d04e3f5ce67c487ad @@ -1006,10 +1192,10 @@ index 0000000000000000000000000000000000000000..2c9d2826c85bdd033f1df1d6188df636 +} diff --git a/filenames.json b/filenames.json new file mode 100644 -index 0000000000000000000000000000000000000000..13fd1469ef0aa33853ddc6f31eda5b15f6312138 +index 0000000000000000000000000000000000000000..da2056ec2ab06924d64a3028646d983824263778 --- /dev/null +++ b/filenames.json -@@ -0,0 +1,625 @@ +@@ -0,0 +1,635 @@ +// This file is automatically generated by generate_gn_filenames_json.py +// DO NOT EDIT +{ @@ -1197,6 +1383,7 @@ index 0000000000000000000000000000000000000000..13fd1469ef0aa33853ddc6f31eda5b15 + "lib/stream/consumers.js", + "lib/stream/promises.js", + "lib/stream/web.js", ++ "lib/readline/promises.js", + "lib/internal/constants.js", + "lib/internal/abort_controller.js", + "lib/internal/net.js", @@ -1211,6 +1398,7 @@ index 0000000000000000000000000000000000000000..13fd1469ef0aa33853ddc6f31eda5b15 + "lib/internal/histogram.js", + "lib/internal/error_serdes.js", + "lib/internal/dgram.js", ++ "lib/internal/structured_clone.js", + "lib/internal/child_process.js", + "lib/internal/assert.js", + "lib/internal/fixed_queue.js", @@ -1238,11 +1426,13 @@ index 0000000000000000000000000000000000000000..13fd1469ef0aa33853ddc6f31eda5b15 + "lib/internal/stream_base_commons.js", + "lib/internal/url.js", + "lib/internal/async_hooks.js", ++ "lib/internal/wasm_web_api.js", + "lib/internal/http.js", + "lib/internal/buffer.js", + "lib/internal/trace_events_async_hooks.js", + "lib/internal/v8/startup_snapshot.js", + "lib/internal/test_runner/test.js", ++ "lib/internal/test_runner/runner.js", + "lib/internal/test_runner/harness.js", + "lib/internal/test_runner/utils.js", + "lib/internal/test_runner/tap_stream.js", @@ -1282,9 +1472,8 @@ index 0000000000000000000000000000000000000000..13fd1469ef0aa33853ddc6f31eda5b15 + "lib/internal/webstreams/adapters.js", + "lib/internal/webstreams/transfer.js", + "lib/internal/bootstrap/loaders.js", -+ "lib/internal/bootstrap/pre_execution.js", + "lib/internal/bootstrap/node.js", -+ "lib/internal/bootstrap/environment.js", ++ "lib/internal/bootstrap/browser.js", + "lib/internal/bootstrap/switches/does_not_own_process_state.js", + "lib/internal/bootstrap/switches/is_not_main_thread.js", + "lib/internal/bootstrap/switches/does_own_process_state.js", @@ -1318,6 +1507,7 @@ index 0000000000000000000000000000000000000000..13fd1469ef0aa33853ddc6f31eda5b15 + "lib/internal/streams/duplex.js", + "lib/internal/streams/pipeline.js", + "lib/internal/readline/interface.js", ++ "lib/internal/readline/promises.js", + "lib/internal/readline/utils.js", + "lib/internal/readline/emitKeypressEvents.js", + "lib/internal/readline/callbacks.js", @@ -1326,6 +1516,7 @@ index 0000000000000000000000000000000000000000..13fd1469ef0aa33853ddc6f31eda5b15 + "lib/internal/repl/await.js", + "lib/internal/legacy/processbinding.js", + "lib/internal/assert/calltracker.js", ++ "lib/internal/assert/snapshot.js", + "lib/internal/assert/assertion_error.js", + "lib/internal/http2/util.js", + "lib/internal/http2/core.js", @@ -1335,7 +1526,6 @@ index 0000000000000000000000000000000000000000..13fd1469ef0aa33853ddc6f31eda5b15 + "lib/internal/per_context/domexception.js", + "lib/internal/vm/module.js", + "lib/internal/tls/secure-pair.js", -+ "lib/internal/tls/parse-cert-string.js", + "lib/internal/tls/secure-context.js", + "lib/internal/child_process/serialization.js", + "lib/internal/debugger/inspect_repl.js", @@ -1354,6 +1544,7 @@ index 0000000000000000000000000000000000000000..13fd1469ef0aa33853ddc6f31eda5b15 + "lib/internal/main/inspect.js", + "lib/internal/main/eval_stdin.js", + "lib/internal/main/run_main_module.js", ++ "lib/internal/main/environment.js", + "lib/internal/modules/run_main.js", + "lib/internal/modules/package_json_reader.js", + "lib/internal/modules/esm/module_job.js", @@ -1367,6 +1558,7 @@ index 0000000000000000000000000000000000000000..13fd1469ef0aa33853ddc6f31eda5b15 + "lib/internal/modules/esm/initialize_import_meta.js", + "lib/internal/modules/esm/module_map.js", + "lib/internal/modules/esm/get_format.js", ++ "lib/internal/modules/esm/package_config.js", + "lib/internal/modules/esm/formats.js", + "lib/internal/modules/esm/loader.js", + "lib/internal/modules/cjs/helpers.js", @@ -1374,6 +1566,7 @@ index 0000000000000000000000000000000000000000..13fd1469ef0aa33853ddc6f31eda5b15 + "lib/internal/source_map/source_map.js", + "lib/internal/source_map/prepare_stack_trace.js", + "lib/internal/source_map/source_map_cache.js", ++ "lib/internal/dns/callback_resolver.js", + "lib/internal/dns/promises.js", + "lib/internal/dns/utils.js", + "lib/internal/fs/watchers.js", @@ -1403,6 +1596,7 @@ index 0000000000000000000000000000000000000000..13fd1469ef0aa33853ddc6f31eda5b15 + "lib/internal/process/warning.js", + "lib/internal/process/policy.js", + "lib/internal/process/promises.js", ++ "lib/internal/process/pre_execution.js", + "lib/internal/process/signal.js", + "lib/internal/process/execution.js", + "lib/internal/process/esm_loader.js", @@ -1441,6 +1635,7 @@ index 0000000000000000000000000000000000000000..13fd1469ef0aa33853ddc6f31eda5b15 + "src/api/utils.cc", + "src/async_wrap.cc", + "src/cares_wrap.cc", ++ "src/cleanup_queue.cc", + "src/connect_wrap.cc", + "src/connection_wrap.cc", + "src/debug_utils.cc", @@ -1463,6 +1658,7 @@ index 0000000000000000000000000000000000000000..13fd1469ef0aa33853ddc6f31eda5b15 + "src/node_binding.cc", + "src/node_blob.cc", + "src/node_buffer.cc", ++ "src/node_builtins.cc", + "src/node_config.cc", + "src/node_constants.cc", + "src/node_contextify.cc", @@ -1478,8 +1674,6 @@ index 0000000000000000000000000000000000000000..13fd1469ef0aa33853ddc6f31eda5b15 + "src/node_main_instance.cc", + "src/node_messaging.cc", + "src/node_metadata.cc", -+ "src/node_native_module.cc", -+ "src/node_native_module_env.cc", + "src/node_options.cc", + "src/node_os.cc", + "src/node_perf.cc", @@ -1504,6 +1698,7 @@ index 0000000000000000000000000000000000000000..13fd1469ef0aa33853ddc6f31eda5b15 + "src/node_util.cc", + "src/node_v8.cc", + "src/node_wasi.cc", ++ "src/node_wasm_web_api.cc", + "src/node_watchdog.cc", + "src/node_worker.cc", + "src/node_zlib.cc", @@ -1539,6 +1734,8 @@ index 0000000000000000000000000000000000000000..13fd1469ef0aa33853ddc6f31eda5b15 + "src/base64-inl.h", + "src/callback_queue.h", + "src/callback_queue-inl.h", ++ "src/cleanup_queue.h", ++ "src/cleanup_queue-inl.h", + "src/connect_wrap.h", + "src/connection_wrap.h", + "src/debug_utils.h", @@ -1561,6 +1758,7 @@ index 0000000000000000000000000000000000000000..13fd1469ef0aa33853ddc6f31eda5b15 + "src/node_binding.h", + "src/node_blob.h", + "src/node_buffer.h", ++ "src/node_builtins.h", + "src/node_constants.h", + "src/node_context_data.h", + "src/node_contextify.h", @@ -1581,8 +1779,6 @@ index 0000000000000000000000000000000000000000..13fd1469ef0aa33853ddc6f31eda5b15 + "src/node_messaging.h", + "src/node_metadata.h", + "src/node_mutex.h", -+ "src/node_native_module.h", -+ "src/node_native_module_env.h", + "src/node_object_wrap.h", + "src/node_options.h", + "src/node_options-inl.h", @@ -1876,7 +2072,7 @@ index 0000000000000000000000000000000000000000..d1d6b51e8c0c5bc6a5d09e217eb30483 + args = rebase_path(inputs + outputs, root_build_dir) +} diff --git a/src/node_version.h b/src/node_version.h -index aea46f3dad19d604d76b6726ce46141be48746c4..8620780de82f08940c40bddc449d281e4e348736 100644 +index 5403dd847814737132dfd004daddee0efc1bc34d..eba54c354ae930ce957a150bc52d78c4dc6b8322 100644 --- a/src/node_version.h +++ b/src/node_version.h @@ -89,7 +89,10 @@ @@ -1885,7 +2081,7 @@ index aea46f3dad19d604d76b6726ce46141be48746c4..8620780de82f08940c40bddc449d281e */ +// Electron sets NODE_MODULE_VERSION in their GN configuration +#ifndef NODE_MODULE_VERSION - #define NODE_MODULE_VERSION 93 + #define NODE_MODULE_VERSION 108 +#endif // The NAPI_VERSION provided by this version of the runtime. This is the version @@ -2003,10 +2199,10 @@ index 0000000000000000000000000000000000000000..2a92eccfa582df361f2a889c0d9b32c1 + + out_file.writelines(new_contents) diff --git a/tools/install.py b/tools/install.py -index a6d1f8b3caa8e24148b1930ea109508f8e612735..c80c1b8202ba59bd63340baca36df8bca5e1f81d 100755 +index 9d5f4a48bca2c926b3ffb3c51c070222d4f7ce7b..728b8596b348b827dbc279498123053aea446ff3 100755 --- a/tools/install.py +++ b/tools/install.py -@@ -202,17 +202,72 @@ def files(action): +@@ -202,60 +202,72 @@ def files(action): def headers(action): def wanted_v8_headers(files_arg, dest): v8_headers = [ @@ -2015,10 +2211,53 @@ index a6d1f8b3caa8e24148b1930ea109508f8e612735..c80c1b8202ba59bd63340baca36df8bc - 'deps/v8/include/libplatform/libplatform-export.h', - 'deps/v8/include/libplatform/v8-tracing.h', - 'deps/v8/include/v8.h', +- 'deps/v8/include/v8-array-buffer.h', +- 'deps/v8/include/v8-callbacks.h', +- 'deps/v8/include/v8-container.h', +- 'deps/v8/include/v8-context.h', +- 'deps/v8/include/v8-data.h', +- 'deps/v8/include/v8-date.h', +- 'deps/v8/include/v8-debug.h', +- 'deps/v8/include/v8-embedder-heap.h', +- 'deps/v8/include/v8-embedder-state-scope.h', +- 'deps/v8/include/v8-exception.h', +- 'deps/v8/include/v8-extension.h', +- 'deps/v8/include/v8-external.h', +- 'deps/v8/include/v8-forward.h', +- 'deps/v8/include/v8-function-callback.h', +- 'deps/v8/include/v8-function.h', +- 'deps/v8/include/v8-initialization.h', - 'deps/v8/include/v8-internal.h', +- 'deps/v8/include/v8-isolate.h', +- 'deps/v8/include/v8-json.h', +- 'deps/v8/include/v8-local-handle.h', +- 'deps/v8/include/v8-locker.h', +- 'deps/v8/include/v8-maybe.h', +- 'deps/v8/include/v8-memory-span.h', +- 'deps/v8/include/v8-message.h', +- 'deps/v8/include/v8-microtask-queue.h', +- 'deps/v8/include/v8-microtask.h', +- 'deps/v8/include/v8-object.h', +- 'deps/v8/include/v8-persistent-handle.h', - 'deps/v8/include/v8-platform.h', +- 'deps/v8/include/v8-primitive-object.h', +- 'deps/v8/include/v8-primitive.h', - 'deps/v8/include/v8-profiler.h', +- 'deps/v8/include/v8-promise.h', +- 'deps/v8/include/v8-proxy.h', +- 'deps/v8/include/v8-regexp.h', +- 'deps/v8/include/v8-script.h', +- 'deps/v8/include/v8-snapshot.h', +- 'deps/v8/include/v8-statistics.h', +- 'deps/v8/include/v8-template.h', +- 'deps/v8/include/v8-traced-handle.h', +- 'deps/v8/include/v8-typed-array.h', +- 'deps/v8/include/v8-unwinder.h', +- 'deps/v8/include/v8-value-serializer.h', +- 'deps/v8/include/v8-value.h', - 'deps/v8/include/v8-version.h', +- 'deps/v8/include/v8-wasm.h', +- 'deps/v8/include/v8-weak-callback-info.h', - 'deps/v8/include/v8config.h', + '../../v8/include/cppgc/common.h', + '../../v8/include/libplatform/libplatform.h', @@ -2089,7 +2328,7 @@ index a6d1f8b3caa8e24148b1930ea109508f8e612735..c80c1b8202ba59bd63340baca36df8bc files_arg = [name for name in files_arg if name in v8_headers] action(files_arg, dest) -@@ -239,7 +294,7 @@ def headers(action): +@@ -282,7 +294,7 @@ def headers(action): if sys.platform.startswith('aix'): action(['out/Release/node.exp'], 'include/node/') @@ -2099,7 +2338,7 @@ index a6d1f8b3caa8e24148b1930ea109508f8e612735..c80c1b8202ba59bd63340baca36df8bc if 'false' == variables.get('node_shared_libuv'): subdir_files('deps/uv/include', 'include/node/', action) diff --git a/tools/js2c.py b/tools/js2c.py -index d93be2123e0f8c75dd6a0041ef164982db0860e4..4d9317527d46ac8c6d8066bfba707233053b8615 100755 +index e295949a18508d7989f0925093a9dd6a284fecd6..8ba46c5d78c5c86d9f7b8b6972f3febbe87de61e 100755 --- a/tools/js2c.py +++ b/tools/js2c.py @@ -131,6 +131,14 @@ def NormalizeFileName(filename): diff --git a/patches/node/build_ensure_native_module_compilation_fails_if_not_using_a_new.patch b/patches/node/build_ensure_native_module_compilation_fails_if_not_using_a_new.patch index 2e23477369..854eaec1d9 100644 --- a/patches/node/build_ensure_native_module_compilation_fails_if_not_using_a_new.patch +++ b/patches/node/build_ensure_native_module_compilation_fails_if_not_using_a_new.patch @@ -7,10 +7,10 @@ Subject: build: ensure native module compilation fails if not using a new This should not be upstreamed, it is a quality-of-life patch for downstream module builders. diff --git a/common.gypi b/common.gypi -index a80b57fbba17b5025351ef41dd83f62832bbd781..8441a5270212af7e4643e6b4ee100a22f8e6f51c 100644 +index 3e73073fb3f0e3bed74ff00521fc1b98997d9540..ca089eee5eafef6e08960d2a96ef27d8cfa95180 100644 --- a/common.gypi +++ b/common.gypi -@@ -83,6 +83,8 @@ +@@ -79,6 +79,8 @@ # TODO(refack): make v8-perfetto happen 'v8_use_perfetto': 0, @@ -19,7 +19,7 @@ index a80b57fbba17b5025351ef41dd83f62832bbd781..8441a5270212af7e4643e6b4ee100a22 ##### end V8 defaults ##### # When building native modules using 'npm install' with the system npm, -@@ -288,6 +290,7 @@ +@@ -282,6 +284,7 @@ 'V8_DEPRECATION_WARNINGS', 'V8_IMMINENT_DEPRECATION_WARNINGS', '_GLIBCXX_USE_CXX11_ABI=1', @@ -27,7 +27,7 @@ index a80b57fbba17b5025351ef41dd83f62832bbd781..8441a5270212af7e4643e6b4ee100a22 ], # Forcibly disable -Werror. We support a wide range of compilers, it's -@@ -395,6 +398,11 @@ +@@ -392,6 +395,11 @@ }], ], }], @@ -40,19 +40,19 @@ index a80b57fbba17b5025351ef41dd83f62832bbd781..8441a5270212af7e4643e6b4ee100a22 'defines': [ 'V8_COMPRESS_POINTERS', diff --git a/configure.py b/configure.py -index 08894bf3908916d1cb639810c5e1b2afae74ff4d..19cbde58df38009258db145c5f7dbe73b0dc5cdf 100755 +index 1b7a721585764aecfd855ee47c47a3bd235d2ef3..c152ea9f29478729ec3752132140e3ec44dbd366 100755 --- a/configure.py +++ b/configure.py -@@ -1447,6 +1447,7 @@ def configure_library(lib, output, pkgname=None): +@@ -1464,6 +1464,7 @@ def configure_library(lib, output, pkgname=None): def configure_v8(o): + o['variables']['using_electron_config_gypi'] = 1 o['variables']['v8_enable_webassembly'] = 1 + o['variables']['v8_enable_javascript_promise_hooks'] = 1 o['variables']['v8_enable_lite_mode'] = 1 if options.v8_lite_mode else 0 - o['variables']['v8_enable_gdbjit'] = 1 if options.gdb else 0 diff --git a/src/node.h b/src/node.h -index b6a26f8adf11959f94a00de0cbf9016fcc8707cb..38bbb20968772a4ba6bceddb04a83589f8582fc8 100644 +index 4966df8d4dd0726ba0777b5b8f2f1bfc3071d951..30cfd68159be7f4e22da463ccac5e9bc5ac6e6dd 100644 --- a/src/node.h +++ b/src/node.h @@ -22,6 +22,12 @@ diff --git a/patches/node/build_ensure_v8_pointer_compression_sandbox_is_enabled_on_64bit.patch b/patches/node/build_ensure_v8_pointer_compression_sandbox_is_enabled_on_64bit.patch index 4b508b6cc0..b108f9a447 100644 --- a/patches/node/build_ensure_v8_pointer_compression_sandbox_is_enabled_on_64bit.patch +++ b/patches/node/build_ensure_v8_pointer_compression_sandbox_is_enabled_on_64bit.patch @@ -8,7 +8,7 @@ Aligns common.gypi with the current build flag state of //v8. Specifically enables `V8_ENABLE_SANDBOX`, `V8_SANDBOXED_POINTERS`, `V8_COMPRESS_POINTERS` and `V8_COMPRESS_POINTERS_IN_SHARED_CAGE`. diff --git a/common.gypi b/common.gypi -index fcd55b95b44050e4d88eeb0d3100ba6e6a5d5e78..a80b57fbba17b5025351ef41dd83f62832bbd781 100644 +index e58cc4b4fb4ba28f23133530dc3d908c4cb68426..3e73073fb3f0e3bed74ff00521fc1b98997d9540 100644 --- a/common.gypi +++ b/common.gypi @@ -65,6 +65,7 @@ @@ -17,9 +17,9 @@ index fcd55b95b44050e4d88eeb0d3100ba6e6a5d5e78..a80b57fbba17b5025351ef41dd83f628 'v8_enable_31bit_smis_on_64bit_arch%': 0, + 'v8_enable_sandbox%': 0, - # Disable V8 untrusted code mitigations. - # See https://github.com/v8/v8/wiki/Untrusted-code-mitigations -@@ -132,6 +133,7 @@ + # Disable v8 hugepage by default. + 'v8_enable_hugepage%': 0, +@@ -123,6 +124,7 @@ ['target_arch in "arm ia32 mips mipsel ppc"', { 'v8_enable_pointer_compression': 0, 'v8_enable_31bit_smis_on_64bit_arch': 0, @@ -27,7 +27,7 @@ index fcd55b95b44050e4d88eeb0d3100ba6e6a5d5e78..a80b57fbba17b5025351ef41dd83f628 }], ['target_arch in "ppc64 s390x"', { 'v8_enable_backtrace': 1, -@@ -396,9 +398,14 @@ +@@ -393,9 +395,12 @@ ['v8_enable_pointer_compression == 1', { 'defines': [ 'V8_COMPRESS_POINTERS', @@ -36,22 +36,20 @@ index fcd55b95b44050e4d88eeb0d3100ba6e6a5d5e78..a80b57fbba17b5025351ef41dd83f628 ], }], + ['v8_enable_sandbox == 1', { -+ 'defines': [ -+ 'V8_ENABLE_SANDBOX', -+ ] ++ 'defines': ['V8_ENABLE_SANDBOX'] + }], ['v8_enable_pointer_compression == 1 or v8_enable_31bit_smis_on_64bit_arch == 1', { 'defines': ['V8_31BIT_SMIS_ON_64BIT_ARCH'], }], diff --git a/configure.py b/configure.py -index 1a7023dece588631b8281c67b223204c1ebb5ee7..08894bf3908916d1cb639810c5e1b2afae74ff4d 100755 +index a4e5723067f286d4a836f329d0049b6bbaac9419..1b7a721585764aecfd855ee47c47a3bd235d2ef3 100755 --- a/configure.py +++ b/configure.py -@@ -1459,6 +1459,7 @@ def configure_v8(o): +@@ -1477,6 +1477,7 @@ def configure_v8(o): o['variables']['v8_use_siphash'] = 0 if options.without_siphash else 1 o['variables']['v8_enable_pointer_compression'] = 1 if options.enable_pointer_compression else 0 o['variables']['v8_enable_31bit_smis_on_64bit_arch'] = 1 if options.enable_pointer_compression else 0 + o['variables']['v8_enable_sandbox'] = 1 if options.enable_pointer_compression else 0 + o['variables']['v8_enable_shared_ro_heap'] = 0 if options.enable_pointer_compression else 1 o['variables']['v8_trace_maps'] = 1 if options.trace_maps else 0 o['variables']['node_use_v8_platform'] = b(not options.without_v8_platform) - o['variables']['node_use_bundled_v8'] = b(not options.without_bundled_v8) diff --git a/patches/node/build_modify_js2c_py_to_allow_injection_of_original-fs_and_custom_embedder_js.patch b/patches/node/build_modify_js2c_py_to_allow_injection_of_original-fs_and_custom_embedder_js.patch index c069383f9f..7435001246 100644 --- a/patches/node/build_modify_js2c_py_to_allow_injection_of_original-fs_and_custom_embedder_js.patch +++ b/patches/node/build_modify_js2c_py_to_allow_injection_of_original-fs_and_custom_embedder_js.patch @@ -36,32 +36,32 @@ index 7b820e70df1613a9f5565d6221b71354ff059560..405bda5d83c3312909439082ef69e8f2 async function* watch(filename, options = {}) { const path = toNamespacedPath(getValidatedPath(filename)); -diff --git a/src/node_native_module.cc b/src/node_native_module.cc -index 5d20e1d6a86416c0de9f01a22b992aad889078d3..c836540c7d9328ae4646097ecc18023c1d8add8f 100644 ---- a/src/node_native_module.cc -+++ b/src/node_native_module.cc -@@ -20,6 +20,7 @@ NativeModuleLoader NativeModuleLoader::instance_; +diff --git a/src/node_builtins.cc b/src/node_builtins.cc +index 4a8e5f2d23ecb50b127a20a3d0f6216ae60455fe..3bc9d113b6b818dcda332966f09f17248b421263 100644 +--- a/src/node_builtins.cc ++++ b/src/node_builtins.cc +@@ -32,6 +32,7 @@ BuiltinLoader BuiltinLoader::instance_; - NativeModuleLoader::NativeModuleLoader() : config_(GetConfig()) { + BuiltinLoader::BuiltinLoader() : config_(GetConfig()), has_code_cache_(false) { LoadJavaScriptSource(); + LoadEmbedderJavaScriptSource(); } - NativeModuleLoader* NativeModuleLoader::GetInstance() { -diff --git a/src/node_native_module.h b/src/node_native_module.h -index 7acd154d419de8fd1349a9811f68becec5902297..4981586b4b62cb642e10e1f737a136472ea50697 100644 ---- a/src/node_native_module.h -+++ b/src/node_native_module.h -@@ -44,6 +44,7 @@ class NODE_EXTERN_PRIVATE NativeModuleLoader { + BuiltinLoader* BuiltinLoader::GetInstance() { +diff --git a/src/node_builtins.h b/src/node_builtins.h +index fa87a2042c043bb20fedbb83e60cc160c3f9b7e5..7f0a25af306ffefbc51ac43689ed208d4cd94f0b 100644 +--- a/src/node_builtins.h ++++ b/src/node_builtins.h +@@ -69,6 +69,7 @@ class NODE_EXTERN_PRIVATE BuiltinLoader { // Generated by tools/js2c.py as node_javascript.cc void LoadJavaScriptSource(); // Loads data into source_ + void LoadEmbedderJavaScriptSource(); // Loads embedder data into source_ UnionBytes GetConfig(); // Return data for config.gypi - bool Exists(const char* id); + std::vector<std::string> GetBuiltinIds(); diff --git a/tools/js2c.py b/tools/js2c.py -index 4d9317527d46ac8c6d8066bfba707233053b8615..83225036208b68087a6066adf1d1948b84c5c234 100755 +index 8ba46c5d78c5c86d9f7b8b6972f3febbe87de61e..38057495e04eba46ca87f6a0ea607f0fff46846e 100755 --- a/tools/js2c.py +++ b/tools/js2c.py @@ -39,6 +39,8 @@ import codecs @@ -73,23 +73,23 @@ index 4d9317527d46ac8c6d8066bfba707233053b8615..83225036208b68087a6066adf1d1948b if is_verbose: print(filename) with codecs.open(filename, "r", "utf-8") as f: -@@ -57,13 +59,15 @@ namespace native_module {{ +@@ -57,13 +59,15 @@ namespace builtins {{ {0} --void NativeModuleLoader::LoadJavaScriptSource() {{ -+void NativeModuleLoader::Load{4}JavaScriptSource() {{ +-void BuiltinLoader::LoadJavaScriptSource() {{ ++void BuiltinLoader::Load{4}JavaScriptSource() {{ {1} }} +#if {2} - UnionBytes NativeModuleLoader::GetConfig() {{ + UnionBytes BuiltinLoader::GetConfig() {{ - return UnionBytes(config_raw, {2}); // config.gypi + return UnionBytes(config_raw, {3}); // config.gypi }} +#endif - }} // namespace native_module + }} // namespace builtins @@ -113,8 +117,8 @@ def GetDefinition(var, source, step=30): return definition, len(code_points) diff --git a/patches/node/chore_add_context_to_context_aware_module_prevention.patch b/patches/node/chore_add_context_to_context_aware_module_prevention.patch index 98d8cc711d..d9ea79fee3 100644 --- a/patches/node/chore_add_context_to_context_aware_module_prevention.patch +++ b/patches/node/chore_add_context_to_context_aware_module_prevention.patch @@ -8,18 +8,18 @@ modules from being used in the renderer process. This should be upstreamed as a customizable error message. diff --git a/src/node_binding.cc b/src/node_binding.cc -index 03e26027406e655ce876a9af689c7d97920c4327..d188b393ee1bd2ee7de6f4454dfa7785d4a5c52b 100644 +index 14b447c2245a2154399b89f15aa33288c194d4fc..c52fbc6a72d1842f56f1e37f3725b7ba2284bf29 100644 --- a/src/node_binding.cc +++ b/src/node_binding.cc @@ -4,6 +4,7 @@ + #include "node_builtins.h" #include "node_errors.h" #include "node_external_reference.h" - #include "node_native_module_env.h" +#include "node_process.h" #include "util.h" #include <string> -@@ -473,7 +474,12 @@ void DLOpen(const FunctionCallbackInfo<Value>& args) { +@@ -474,7 +475,12 @@ void DLOpen(const FunctionCallbackInfo<Value>& args) { if (mp->nm_context_register_func == nullptr) { if (env->force_context_aware()) { dlib->Close(); diff --git a/patches/node/chore_allow_the_node_entrypoint_to_be_a_builtin_module.patch b/patches/node/chore_allow_the_node_entrypoint_to_be_a_builtin_module.patch index 49475c8cf1..7f09d38e5c 100644 --- a/patches/node/chore_allow_the_node_entrypoint_to_be_a_builtin_module.patch +++ b/patches/node/chore_allow_the_node_entrypoint_to_be_a_builtin_module.patch @@ -7,11 +7,29 @@ This allows embedders to tell Node.js what the first "real" file is when they use themselves as the entry point. We should try to upstream some form of this. -diff --git a/lib/internal/bootstrap/pre_execution.js b/lib/internal/bootstrap/pre_execution.js -index 25a8464e4833ff4655db2fe37f4bd482dc147865..4b1f1b05b6c67f206f87618792fa528deb238d8d 100644 ---- a/lib/internal/bootstrap/pre_execution.js -+++ b/lib/internal/bootstrap/pre_execution.js -@@ -122,11 +122,13 @@ function patchProcessObject(expandArgv1) { +diff --git a/lib/internal/modules/cjs/loader.js b/lib/internal/modules/cjs/loader.js +index 4b592b0f7d9d481ee746b4e6db07620a27284f17..79b21e33ebf5849d83f462374905357d244224b0 100644 +--- a/lib/internal/modules/cjs/loader.js ++++ b/lib/internal/modules/cjs/loader.js +@@ -1123,6 +1123,13 @@ Module.prototype._compile = function(content, filename) { + if (getOptionValue('--inspect-brk') && process._eval == null) { + if (!resolvedArgv) { + // We enter the repl if we're not given a filename argument. ++ // process._firstFileName is used by Embedders to tell node what ++ // the first "real" file is when they use themselves as the entry ++ // point ++ if (process._firstFileName) { ++ resolvedArgv = process._firstFileName ++ delete process._firstFileName ++ } else + if (process.argv[1]) { + try { + resolvedArgv = Module._resolveFilename(process.argv[1], null, false); +diff --git a/lib/internal/process/pre_execution.js b/lib/internal/process/pre_execution.js +index db8bf724af5f113c7c86350a210d5eee82879d13..6659f03e9aa45c35d355399597f533ad20232575 100644 +--- a/lib/internal/process/pre_execution.js ++++ b/lib/internal/process/pre_execution.js +@@ -135,11 +135,13 @@ function patchProcessObject(expandArgv1) { if (expandArgv1 && process.argv[1] && !StringPrototypeStartsWith(process.argv[1], '-')) { // Expand process.argv[1] into a full path. @@ -30,21 +48,3 @@ index 25a8464e4833ff4655db2fe37f4bd482dc147865..4b1f1b05b6c67f206f87618792fa528d } } -diff --git a/lib/internal/modules/cjs/loader.js b/lib/internal/modules/cjs/loader.js -index 3a536aab1bdeea6829d76d6af48fdefe0e08908d..4e3388b0b1fe69f8aaff15e651f7f0201208a40f 100644 ---- a/lib/internal/modules/cjs/loader.js -+++ b/lib/internal/modules/cjs/loader.js -@@ -1100,6 +1100,13 @@ Module.prototype._compile = function(content, filename) { - if (getOptionValue('--inspect-brk') && process._eval == null) { - if (!resolvedArgv) { - // We enter the repl if we're not given a filename argument. -+ // process._firstFileName is used by Embedders to tell node what -+ // the first "real" file is when they use themselves as the entry -+ // point -+ if (process._firstFileName) { -+ resolvedArgv = process._firstFileName -+ delete process._firstFileName -+ } else - if (process.argv[1]) { - try { - resolvedArgv = Module._resolveFilename(process.argv[1], null, false); diff --git a/patches/node/chore_read_nobrowserglobals_from_global_not_process.patch b/patches/node/chore_read_nobrowserglobals_from_global_not_process.patch deleted file mode 100644 index 0ba77a8435..0000000000 --- a/patches/node/chore_read_nobrowserglobals_from_global_not_process.patch +++ /dev/null @@ -1,21 +0,0 @@ -From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 -From: Samuel Attard <[email protected]> -Date: Mon, 15 Jul 2019 17:45:02 -0700 -Subject: chore: read _noBrowserGlobals from global not config - -This is used so that we can modify the flag at runtime where -config can only be set at compile time. - -diff --git a/lib/internal/bootstrap/node.js b/lib/internal/bootstrap/node.js -index 376680f015d09a2cf3ce62de1fdeb9c5ed4c300b..026b47299ff3633a57c57af1512a0921fdafb0c4 100644 ---- a/lib/internal/bootstrap/node.js -+++ b/lib/internal/bootstrap/node.js -@@ -210,7 +210,7 @@ const { - queueMicrotask - } = require('internal/process/task_queues'); - --if (!config.noBrowserGlobals) { -+if (!global._noBrowserGlobals) { - // Override global console from the one provided by the VM - // to the one implemented by Node.js - // https://console.spec.whatwg.org/#console-namespace diff --git a/patches/node/drop_deserializerequest_move_constructor_for_c_20_compat.patch b/patches/node/drop_deserializerequest_move_constructor_for_c_20_compat.patch index 508606e6fc..4625280502 100644 --- a/patches/node/drop_deserializerequest_move_constructor_for_c_20_compat.patch +++ b/patches/node/drop_deserializerequest_move_constructor_for_c_20_compat.patch @@ -22,10 +22,10 @@ specified move constructor "shadows" the implicit initializer-list constructor. This patch seems to fix things, in any case. diff --git a/src/env.h b/src/env.h -index 6b18b6efd231d986c391a16966fdbc82a5d99eda..099d8c9efeeda1c851d526e4bf4ddece444c7299 100644 +index 417f0b3657cb068e7708cbeb787f8cb116501876..34c88c1addc5f64bd46332451e5b4ba8343c8818 100644 --- a/src/env.h +++ b/src/env.h -@@ -939,9 +939,6 @@ struct DeserializeRequest { +@@ -932,9 +932,6 @@ struct DeserializeRequest { v8::Global<v8::Object> holder; int index; InternalFieldInfo* info = nullptr; // Owned by the request diff --git a/patches/node/enable_-wunqualified-std-cast-call.patch b/patches/node/enable_-wunqualified-std-cast-call.patch index 0f8322430f..a40710debc 100644 --- a/patches/node/enable_-wunqualified-std-cast-call.patch +++ b/patches/node/enable_-wunqualified-std-cast-call.patch @@ -7,7 +7,7 @@ Refs https://chromium-review.googlesource.com/c/chromium/src/+/3825237 Should be upstreamed. diff --git a/src/node_http2.cc b/src/node_http2.cc -index 8df924a29028e2cfb31a22e72ee88887f790d777..c466fd8aecd6045841c2b39f707f747ee6f9fc6d 100644 +index 7a1e751929286d97c663c6feea133dae08126684..a1908f9b54807ce73daf775d9745234a27650c72 100644 --- a/src/node_http2.cc +++ b/src/node_http2.cc @@ -644,7 +644,7 @@ void Http2Stream::EmitStatistics() { diff --git a/patches/node/expose_get_builtin_module_function.patch b/patches/node/expose_get_builtin_module_function.patch index a651f9d2be..568481ce1b 100644 --- a/patches/node/expose_get_builtin_module_function.patch +++ b/patches/node/expose_get_builtin_module_function.patch @@ -9,10 +9,10 @@ modules to sandboxed renderers. TODO(codebytere): remove and replace with a public facing API. diff --git a/src/node_binding.cc b/src/node_binding.cc -index 29b9ccdaed8b109dcc93374ba9abc59b9d2ffdb9..03e26027406e655ce876a9af689c7d97920c4327 100644 +index 06af1841eb3d102a6883ae1a8ab69fee4791be6b..14b447c2245a2154399b89f15aa33288c194d4fc 100644 --- a/src/node_binding.cc +++ b/src/node_binding.cc -@@ -615,6 +615,10 @@ void GetInternalBinding(const FunctionCallbackInfo<Value>& args) { +@@ -608,6 +608,10 @@ void GetInternalBinding(const FunctionCallbackInfo<Value>& args) { args.GetReturnValue().Set(exports); } diff --git a/patches/node/feat_add_knostartdebugsignalhandler_to_environment_to_prevent.patch b/patches/node/feat_add_knostartdebugsignalhandler_to_environment_to_prevent.patch index faf4f5643c..69859135d8 100644 --- a/patches/node/feat_add_knostartdebugsignalhandler_to_environment_to_prevent.patch +++ b/patches/node/feat_add_knostartdebugsignalhandler_to_environment_to_prevent.patch @@ -7,10 +7,10 @@ Subject: feat: add kNoStartDebugSignalHandler to Environment to prevent This patch should be upstreamed, it allows embedders to prevent the call to StartDebugSignalHandler which handles SIGUSR1 and starts the inspector agent. Apps that have --inspect disabled also don't want SIGUSR1 to have this affect. diff --git a/src/env-inl.h b/src/env-inl.h -index 71d3b65729a71caf157555bc6bba88eb3c3656e1..62c53acdb5f9c98fb7eade00802de2946f5c600c 100644 +index cbe4b734b1c0cc88683c8bc27a4e89d7a1583b22..b2fcaa091924606da5604d194dcb7e445fa736b3 100644 --- a/src/env-inl.h +++ b/src/env-inl.h -@@ -672,6 +672,10 @@ inline bool Environment::no_global_search_paths() const { +@@ -671,6 +671,10 @@ inline bool Environment::no_global_search_paths() const { !options_->global_search_paths; } @@ -18,21 +18,21 @@ index 71d3b65729a71caf157555bc6bba88eb3c3656e1..62c53acdb5f9c98fb7eade00802de294 + return (flags_ & EnvironmentFlags::kNoStartDebugSignalHandler) == 0; +} + - bool Environment::filehandle_close_warning() const { - return emit_filehandle_warning_; - } + inline bool Environment::no_browser_globals() const { + // configure --no-browser-globals + #ifdef NODE_NO_BROWSER_GLOBALS diff --git a/src/env.h b/src/env.h -index ae234a99eb2d5f4f8f953b077f6261c8052f6346..6b18b6efd231d986c391a16966fdbc82a5d99eda 100644 +index 59dd7c8d9e172493d79be21079598a08629be128..417f0b3657cb068e7708cbeb787f8cb116501876 100644 --- a/src/env.h +++ b/src/env.h -@@ -1203,6 +1203,7 @@ class Environment : public MemoryRetainer { +@@ -1233,6 +1233,7 @@ class Environment : public MemoryRetainer { inline bool tracks_unmanaged_fds() const; inline bool hide_console_windows() const; inline bool no_global_search_paths() const; + inline bool should_start_debug_signal_handler() const; + inline bool no_browser_globals() const; inline uint64_t thread_id() const; inline worker::Worker* worker_context() const; - Environment* worker_parent_env() const; diff --git a/src/inspector_agent.cc b/src/inspector_agent.cc index 34bb11e7d7122cd2c659d45834be6889abec4ac1..f708933d8bd6a6dc6741d6af22665b37c56e333a 100644 --- a/src/inspector_agent.cc @@ -51,10 +51,10 @@ index 34bb11e7d7122cd2c659d45834be6889abec4ac1..f708933d8bd6a6dc6741d6af22665b37 parent_env_->AddCleanupHook([](void* data) { Environment* env = static_cast<Environment*>(data); diff --git a/src/node.h b/src/node.h -index 4eee4e96349ee49423d53819dd90a213f6a6e042..b6a26f8adf11959f94a00de0cbf9016fcc8707cb 100644 +index a6407dd1e78c8fa86dfc2a6c40813b1b4d6a6829..4966df8d4dd0726ba0777b5b8f2f1bfc3071d951 100644 --- a/src/node.h +++ b/src/node.h -@@ -455,7 +455,11 @@ enum Flags : uint64_t { +@@ -458,7 +458,11 @@ enum Flags : uint64_t { // This control is needed by embedders who may not want to initialize the V8 // inspector in situations where one has already been created, // e.g. Blink's in Chromium. diff --git a/patches/node/feat_initialize_asar_support.patch b/patches/node/feat_initialize_asar_support.patch index df54d3dbe8..5c2da28fa7 100644 --- a/patches/node/feat_initialize_asar_support.patch +++ b/patches/node/feat_initialize_asar_support.patch @@ -5,11 +5,32 @@ Subject: feat: initialize asar support This patch initializes asar support in Node.js. -diff --git a/lib/internal/bootstrap/pre_execution.js b/lib/internal/bootstrap/pre_execution.js -index 337b95133bc94e395229211c9a00a055b279fcc9..25a8464e4833ff4655db2fe37f4bd482dc147865 100644 ---- a/lib/internal/bootstrap/pre_execution.js -+++ b/lib/internal/bootstrap/pre_execution.js -@@ -94,6 +94,7 @@ function prepareMainThreadExecution(expandArgv1 = false, +diff --git a/lib/internal/main/worker_thread.js b/lib/internal/main/worker_thread.js +index f7ead4084ed4ed6a682bc62e7ad6fc350381d3b9..cd9ca227b9cac4ff021ce1643000ea4b45163df6 100644 +--- a/lib/internal/main/worker_thread.js ++++ b/lib/internal/main/worker_thread.js +@@ -31,6 +31,7 @@ const { + initializeReport, + initializeSourceMapsHandlers, + loadPreloadModules, ++ setupAsarSupport, + setupTraceCategoryState, + markBootstrapComplete + } = require('internal/process/pre_execution'); +@@ -164,6 +165,8 @@ port.on('message', (message) => { + }; + workerIo.sharedCwdCounter = cwdCounter; + ++ setupAsarSupport(); ++ + const CJSLoader = require('internal/modules/cjs/loader'); + assert(!CJSLoader.hasLoadedAnyUserCJSModule); + loadPreloadModules(); +diff --git a/lib/internal/process/pre_execution.js b/lib/internal/process/pre_execution.js +index 23d4dbcf6cd8e1e3e4a509672e203323d81e736c..db8bf724af5f113c7c86350a210d5eee82879d13 100644 +--- a/lib/internal/process/pre_execution.js ++++ b/lib/internal/process/pre_execution.js +@@ -103,12 +103,17 @@ function prepareMainThreadExecution(expandArgv1 = false, assert(!CJSLoader.hasLoadedAnyUserCJSModule); loadPreloadModules(); initializeFrozenIntrinsics(); @@ -17,14 +38,21 @@ index 337b95133bc94e395229211c9a00a055b279fcc9..25a8464e4833ff4655db2fe37f4bd482 } function refreshRuntimeOptions() { -@@ -584,6 +585,10 @@ function loadPreloadModules() { - } + refreshOptions(); } +function setupAsarSupport() { + process._linkedBinding('electron_common_asar').initAsarSupport(require); +} + - module.exports = { - refreshRuntimeOptions, - patchProcessObject, + function patchProcessObject(expandArgv1) { + const binding = internalBinding('process_methods'); + binding.patchProcessObject(process); +@@ -620,6 +625,7 @@ module.exports = { + loadPreloadModules, + setupTraceCategoryState, + setupInspectorHooks, ++ setupAsarSupport, + initializeReport, + initializeCJSLoader, + initializeWASI, diff --git a/patches/node/fix_add_default_values_for_variables_in_common_gypi.patch b/patches/node/fix_add_default_values_for_variables_in_common_gypi.patch index 270a83e742..e41109231d 100644 --- a/patches/node/fix_add_default_values_for_variables_in_common_gypi.patch +++ b/patches/node/fix_add_default_values_for_variables_in_common_gypi.patch @@ -7,10 +7,10 @@ common.gypi is a file that's included in the node header bundle, despite the fact that we do not build node with gyp. diff --git a/common.gypi b/common.gypi -index d68a4c9eafacfa37baf0c3e1a5eb40c70113cb54..fcd55b95b44050e4d88eeb0d3100ba6e6a5d5e78 100644 +index 3f708d89b1ef384e01726101263728367b6f4355..e58cc4b4fb4ba28f23133530dc3d908c4cb68426 100644 --- a/common.gypi +++ b/common.gypi -@@ -84,6 +84,23 @@ +@@ -80,6 +80,23 @@ ##### end V8 defaults ##### diff --git a/patches/node/fix_crypto_tests_to_run_with_bssl.patch b/patches/node/fix_crypto_tests_to_run_with_bssl.patch index 523b1c6ee8..d47e140585 100644 --- a/patches/node/fix_crypto_tests_to_run_with_bssl.patch +++ b/patches/node/fix_crypto_tests_to_run_with_bssl.patch @@ -538,11 +538,11 @@ index af2146982c7a3bf7bd7527f44e4b17a3b605026e..f6b91f675cfea367c608892dee078b56 // Non-XOF hash functions should accept valid outputLength options as well. assert.strictEqual(crypto.createHash('sha224', { outputLength: 28 }) diff --git a/test/parallel/test-crypto-hkdf.js b/test/parallel/test-crypto-hkdf.js -index 2d6689a486ddb6e42e53df2b1551af72dc5bc903..3b1a71e1396875c74e28ecbc058981c3c9d10a1f 100644 +index ff3abdf291efcd076b36e755de4147b0aad0b345..d29854cf0c0ce89f84c912def672e7c4e11427a3 100644 --- a/test/parallel/test-crypto-hkdf.js +++ b/test/parallel/test-crypto-hkdf.js -@@ -122,8 +122,6 @@ const algorithms = [ - ['sha256', 'secret', 'salt', 'info', 10], +@@ -124,8 +124,6 @@ const algorithms = [ + ['sha256', '', 'salt', '', 10], ['sha512', 'secret', 'salt', '', 15], ]; -if (!common.hasOpenSSL3) @@ -632,7 +632,7 @@ index 9afcb38616dafd6da1ab7b5843d68f4f796ca9a6..00d3381056a5a40c549f06d74c130149 } +*/ diff --git a/test/parallel/test-crypto-sign-verify.js b/test/parallel/test-crypto-sign-verify.js -index b2c14b1efcd68bd20e9c946106f1ab5fb58627c5..eef0bfe638b641c68fdadd95226a74df044921cb 100644 +index 74c0ff53eb18b749d4018b50d654df943403245b..aab253ca5d4504c445c88cd9519f8385a7b39b91 100644 --- a/test/parallel/test-crypto-sign-verify.js +++ b/test/parallel/test-crypto-sign-verify.js @@ -29,6 +29,7 @@ const keySize = 2048; @@ -715,7 +715,7 @@ index 008ab129f0e019c659eecf5a76b7eb412c947fe3..6688f5d916f50e1e4fcfff1619c8634a cipher.end('Papaya!'); // Should not cause an unhandled exception. diff --git a/test/parallel/test-crypto-x509.js b/test/parallel/test-crypto-x509.js -index d1782359277dc52d7a60830a6dd958544d610e6b..4c781f062bc505b860b821773070551f4cd80067 100644 +index 03f7c209679d9c0c7da4b82bddc45767945b596f..de2e088865743202db322b00f443771121ff6643 100644 --- a/test/parallel/test-crypto-x509.js +++ b/test/parallel/test-crypto-x509.js @@ -110,7 +110,7 @@ const der = Buffer.from( @@ -739,11 +739,11 @@ index d1782359277dc52d7a60830a6dd958544d610e6b..4c781f062bc505b860b821773070551f + // Verify that legacy encoding works const legacyObjectCheck = { - subject: 'C=US\n' + -@@ -219,11 +225,7 @@ const der = Buffer.from( - 'CA Issuers - URI:http://ca.nodejs.org/ca.cert' : - 'OCSP - URI:http://ocsp.nodejs.org/\n' + - 'CA Issuers - URI:http://ca.nodejs.org/ca.cert\n', + subject: Object.assign(Object.create(null), { +@@ -220,11 +226,7 @@ const der = Buffer.from( + 'OCSP - URI': ['http://ocsp.nodejs.org/'], + 'CA Issuers - URI': ['http://ca.nodejs.org/ca.cert'] + }), - modulus: 'EF5440701637E28ABB038E5641F828D834C342A9D25EDBB86A2BF' + - '6FBD809CB8E037A98B71708E001242E4DEB54C6164885F599DD87' + - 'A23215745955BE20417E33C4D0D1B80C9DA3DE419A2607195D2FB' + @@ -753,7 +753,7 @@ index d1782359277dc52d7a60830a6dd958544d610e6b..4c781f062bc505b860b821773070551f bits: 1024, exponent: '0x10001', valid_from: 'Nov 16 18:42:21 2018 GMT', -@@ -237,7 +239,7 @@ const der = Buffer.from( +@@ -238,7 +240,7 @@ const der = Buffer.from( 'D0:39:97:54:B6:D0:B4:46:5B:DE:13:5B:68:86:B6:F2:A8:' + '95:22:D5:6E:8B:35:DA:89:29:CA:A3:06:C5:CE:43:C1:7F:' + '2D:7E:5F:44:A5:EE:A3:CB:97:05:A3:E3:68', @@ -762,23 +762,24 @@ index d1782359277dc52d7a60830a6dd958544d610e6b..4c781f062bc505b860b821773070551f }; const legacyObject = x509.toLegacyObject(); -@@ -246,7 +248,7 @@ const der = Buffer.from( - assert.strictEqual(legacyObject.subject, legacyObjectCheck.subject); - assert.strictEqual(legacyObject.issuer, legacyObjectCheck.issuer); - assert.strictEqual(legacyObject.infoAccess, legacyObjectCheck.infoAccess); +@@ -247,7 +249,7 @@ const der = Buffer.from( + assert.deepStrictEqual(legacyObject.subject, legacyObjectCheck.subject); + assert.deepStrictEqual(legacyObject.issuer, legacyObjectCheck.issuer); + assert.deepStrictEqual(legacyObject.infoAccess, legacyObjectCheck.infoAccess); - assert.strictEqual(legacyObject.modulus, legacyObjectCheck.modulus); + assert.match(legacyObject.modulus, legacyObjectCheck.modulusPattern); assert.strictEqual(legacyObject.bits, legacyObjectCheck.bits); assert.strictEqual(legacyObject.exponent, legacyObjectCheck.exponent); assert.strictEqual(legacyObject.valid_from, legacyObjectCheck.valid_from); -@@ -255,7 +257,5 @@ const der = Buffer.from( +@@ -256,7 +258,7 @@ const der = Buffer.from( assert.strictEqual( legacyObject.fingerprint256, legacyObjectCheck.fingerprint256); - assert.strictEqual( -- legacyObject.serialNumber, ++ assert.match( + legacyObject.serialNumber, - legacyObjectCheck.serialNumber); -+ assert.match(legacyObject.serialNumber, legacyObjectCheck.serialNumberPattern); ++ legacyObjectCheck.serialNumberPattern); } diff --git a/test/parallel/test-crypto.js b/test/parallel/test-crypto.js index a8ceb169de2b3de73f062083c42292babc673e73..a3bb574d0e5dc85b4ba3fb0b3bd8782fbb8c8700 100644 @@ -1013,19 +1014,6 @@ index f8eb996000ec899abafbfd558f4f49bad2c69c9a..0bf5c7811eeccff6194d8df41887df0a test('X448').then(common.mustCall()); } +*/ -diff --git a/test/parallel/test-webcrypto-encrypt-decrypt-rsa.js b/test/parallel/test-webcrypto-encrypt-decrypt-rsa.js -index 151eebd36c9765df086a020ba42920b2442b1b77..efe97ff2499cba909ac5500d827364fa389a0469 100644 ---- a/test/parallel/test-webcrypto-encrypt-decrypt-rsa.js -+++ b/test/parallel/test-webcrypto-encrypt-decrypt-rsa.js -@@ -127,7 +127,7 @@ async function testEncryptionLongPlaintext({ algorithm, - - return assert.rejects( - subtle.encrypt(algorithm, publicKey, newplaintext), { -- message: /data too large/ -+ message: /data too large|DATA_TOO_LARGE_FOR_KEY_SIZE/ - }); - } - diff --git a/test/parallel/test-webcrypto-sign-verify.js b/test/parallel/test-webcrypto-sign-verify.js index 6c6b15781549a4b37781bf0b8014054dc5d8c746..142d41b169c836201660d78c19383f3ffc469407 100644 --- a/test/parallel/test-webcrypto-sign-verify.js @@ -1076,15 +1064,10 @@ index 1094845c73e14313860ad476fb7baba2a11b5af4..51972b4b34b191ac59145889dbf2da5c function generateWrappingKeys() { diff --git a/test/parallel/test-x509-escaping.js b/test/parallel/test-x509-escaping.js -index 99418e4c0bf21c26d5ba0ad9d617419abc625593..fc129b26ea13895353d6ede26bb2d91695c94ba4 100644 +index c31a6d21351dc97054daf6276454e2cd98263e26..e339fcc3f9af9c55a9000bb1b836b553ef1bf795 100644 --- a/test/parallel/test-x509-escaping.js +++ b/test/parallel/test-x509-escaping.js -@@ -425,11 +425,11 @@ const { hasOpenSSL3 } = common; - assert.strictEqual(certX509.subjectAltName, 'DNS:evil.example.com'); - - // The newer X509Certificate API allows customizing this behavior: -- assert.strictEqual(certX509.checkHost(servername), servername); -+ assert.strictEqual(certX509.checkHost(servername), undefined); +@@ -447,7 +447,7 @@ const { hasOpenSSL3 } = common; assert.strictEqual(certX509.checkHost(servername, { subject: 'default' }), undefined); assert.strictEqual(certX509.checkHost(servername, { subject: 'always' }), @@ -1093,7 +1076,7 @@ index 99418e4c0bf21c26d5ba0ad9d617419abc625593..fc129b26ea13895353d6ede26bb2d916 assert.strictEqual(certX509.checkHost(servername, { subject: 'never' }), undefined); -@@ -464,11 +464,11 @@ const { hasOpenSSL3 } = common; +@@ -482,11 +482,11 @@ const { hasOpenSSL3 } = common; assert.strictEqual(certX509.subjectAltName, 'IP Address:1.2.3.4'); // The newer X509Certificate API allows customizing this behavior: diff --git a/patches/node/fix_expose_lookupandcompile_with_parameters.patch b/patches/node/fix_expose_lookupandcompile_with_parameters.patch new file mode 100644 index 0000000000..af6074e1ed --- /dev/null +++ b/patches/node/fix_expose_lookupandcompile_with_parameters.patch @@ -0,0 +1,54 @@ +From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 +From: Shelley Vohr <[email protected]> +Date: Thu, 13 Oct 2022 17:10:01 +0200 +Subject: fix: expose LookupAndCompile with parameters + +Node.js removed custom parameters from the public version of LookupAndCompile, +which we use in Electron. This patch re-exposes a wrapper to allow custom +parameters. + +This should be upstreamed. + +diff --git a/src/node_builtins.cc b/src/node_builtins.cc +index 3bc9d113b6b818dcda332966f09f17248b421263..549339b5b677fa242a7b60ae716789c2a11ab18d 100644 +--- a/src/node_builtins.cc ++++ b/src/node_builtins.cc +@@ -397,6 +397,22 @@ MaybeLocal<Function> BuiltinLoader::LookupAndCompile( + return maybe; + } + ++MaybeLocal<Function> BuiltinLoader::LookupAndCompile( ++ Local<Context> context, ++ const char* id, ++ std::vector<Local<String>>* parameters, ++ Environment* optional_env) { ++ Result result; ++ Isolate* isolate = context->GetIsolate(); ++ ++ MaybeLocal<Function> maybe = GetInstance()->LookupAndCompileInternal( ++ context, id, parameters, &result); ++ if (optional_env != nullptr) { ++ RecordResult(id, result, optional_env); ++ } ++ return maybe; ++} ++ + bool BuiltinLoader::CompileAllBuiltins(Local<Context> context) { + BuiltinLoader* loader = GetInstance(); + std::vector<std::string> ids = loader->GetBuiltinIds(); +diff --git a/src/node_builtins.h b/src/node_builtins.h +index 7f0a25af306ffefbc51ac43689ed208d4cd94f0b..a32a7a990082ea3dad73511f91a9c70c72f6fe31 100644 +--- a/src/node_builtins.h ++++ b/src/node_builtins.h +@@ -49,6 +49,11 @@ class NODE_EXTERN_PRIVATE BuiltinLoader { + v8::Local<v8::Context> context, + const char* id, + Environment* optional_env); ++ static v8::MaybeLocal<v8::Function> LookupAndCompile( ++ v8::Local<v8::Context> context, ++ const char* id, ++ std::vector<v8::Local<v8::String>>* parameters, ++ Environment* optional_env); + + static v8::Local<v8::Object> GetSourceObject(v8::Local<v8::Context> context); + // Returns config.gypi as a JSON string diff --git a/patches/node/fix_expose_the_built-in_electron_module_via_the_esm_loader.patch b/patches/node/fix_expose_the_built-in_electron_module_via_the_esm_loader.patch index e70d970682..118ed65580 100644 --- a/patches/node/fix_expose_the_built-in_electron_module_via_the_esm_loader.patch +++ b/patches/node/fix_expose_the_built-in_electron_module_via_the_esm_loader.patch @@ -6,22 +6,22 @@ Subject: fix: expose the built-in electron module via the ESM loader This allows usage of `import { app } from 'electron'` and `import('electron')` natively in the browser + non-sandboxed renderer diff --git a/lib/internal/modules/esm/get_format.js b/lib/internal/modules/esm/get_format.js -index 5ae0e17dcfb5e24a1a117c33c4d42891686e693f..619fe6cef3b02eb575410225f41d3e7d51f37b93 100644 +index a7329d279bb07542d3f4027e0c8e2b035d493e5b..5cff70923b4ea7a4df918b2d3d1fbc7106159218 100644 --- a/lib/internal/modules/esm/get_format.js +++ b/lib/internal/modules/esm/get_format.js -@@ -31,6 +31,7 @@ const protocolHandlers = ObjectAssign(ObjectCreate(null), { +@@ -30,6 +30,7 @@ const protocolHandlers = { 'http:': getHttpProtocolModuleFormat, 'https:': getHttpProtocolModuleFormat, 'node:'() { return 'builtin'; }, + 'electron:'() { return 'commonjs'; }, - }); + }; - function getDataProtocolModuleFormat(parsed) { + /** diff --git a/lib/internal/modules/esm/resolve.js b/lib/internal/modules/esm/resolve.js -index fc5dcd6863dc358102a74bd2cc723d54436fae64..97eea17d815967671a2a0fc2a9c95a9bb85947ac 100644 +index bfee280212fc4d85b2b0a92ac79d898de3cb5ab3..a79cec8d82b439202ecf40b3d55b75706d3aaf29 100644 --- a/lib/internal/modules/esm/resolve.js +++ b/lib/internal/modules/esm/resolve.js -@@ -883,6 +883,8 @@ function parsePackageName(specifier, base) { +@@ -795,6 +795,8 @@ function parsePackageName(specifier, base) { return { packageName, packageSubpath, isScoped }; } @@ -30,7 +30,7 @@ index fc5dcd6863dc358102a74bd2cc723d54436fae64..97eea17d815967671a2a0fc2a9c95a9b /** * @param {string} specifier * @param {string | URL | undefined} base -@@ -895,6 +897,10 @@ function packageResolve(specifier, base, conditions) { +@@ -807,6 +809,10 @@ function packageResolve(specifier, base, conditions) { return new URL('node:' + specifier); } @@ -41,7 +41,7 @@ index fc5dcd6863dc358102a74bd2cc723d54436fae64..97eea17d815967671a2a0fc2a9c95a9b const { packageName, packageSubpath, isScoped } = parsePackageName(specifier, base); -@@ -1095,7 +1101,7 @@ function checkIfDisallowedImport(specifier, parsed, parsedParentURL) { +@@ -1005,7 +1011,7 @@ function checkIfDisallowedImport(specifier, parsed, parsedParentURL) { function throwIfUnsupportedURLProtocol(url) { if (url.protocol !== 'file:' && url.protocol !== 'data:' && @@ -51,10 +51,10 @@ index fc5dcd6863dc358102a74bd2cc723d54436fae64..97eea17d815967671a2a0fc2a9c95a9b } } diff --git a/lib/internal/modules/esm/translators.js b/lib/internal/modules/esm/translators.js -index 8fb3c96f8dc4c535c3898755f7846ae24d9867c4..bda3ca0797e8f1b1d69295c2276c0f841cae99f2 100644 +index 6f25b2e67ab77613c6ed63c227bb875d5461f45f..d1527b859bbea15fdf30622fc8f2700bde5b4591 100644 --- a/lib/internal/modules/esm/translators.js +++ b/lib/internal/modules/esm/translators.js -@@ -155,7 +155,7 @@ translators.set('commonjs', async function commonjsStrategy(url, source, +@@ -154,7 +154,7 @@ translators.set('commonjs', async function commonjsStrategy(url, source, if (!cjsParse) await initCJSParse(); const { module, exportNames } = cjsPreparseModuleExports(filename); @@ -63,7 +63,7 @@ index 8fb3c96f8dc4c535c3898755f7846ae24d9867c4..bda3ca0797e8f1b1d69295c2276c0f84 [...exportNames] : ['default', ...exportNames]; return new ModuleWrap(url, undefined, namesWithDefault, function() { -@@ -174,7 +174,7 @@ translators.set('commonjs', async function commonjsStrategy(url, source, +@@ -173,7 +173,7 @@ translators.set('commonjs', async function commonjsStrategy(url, source, } } @@ -73,10 +73,10 @@ index 8fb3c96f8dc4c535c3898755f7846ae24d9867c4..bda3ca0797e8f1b1d69295c2276c0f84 exportName === 'default') continue; diff --git a/lib/internal/url.js b/lib/internal/url.js -index 22bff28595f6f5b109ae47c79aa1f5ac463ec6c3..d4eb2e044cc1152f48c92d0503f9216e3aad5f4b 100644 +index 2a4ffefe2450708af61e09d7a9530bec1c15d922..9a1c49df14e8b3cef7e66789242a625c6afb3ca9 100644 --- a/lib/internal/url.js +++ b/lib/internal/url.js -@@ -1432,6 +1432,8 @@ function fileURLToPath(path) { +@@ -1483,6 +1483,8 @@ function fileURLToPath(path) { path = new URL(path); else if (!isURLInstance(path)) throw new ERR_INVALID_ARG_TYPE('path', ['string', 'URL'], path); diff --git a/patches/node/fix_expose_tracing_agent_and_use_tracing_tracingcontroller_instead.patch b/patches/node/fix_expose_tracing_agent_and_use_tracing_tracingcontroller_instead.patch index d42e0b2c5c..07dbe2acea 100644 --- a/patches/node/fix_expose_tracing_agent_and_use_tracing_tracingcontroller_instead.patch +++ b/patches/node/fix_expose_tracing_agent_and_use_tracing_tracingcontroller_instead.patch @@ -7,10 +7,10 @@ Subject: fix: expose tracing::Agent and use tracing::TracingController instead This API is used by Electron to create Node's tracing controller. diff --git a/src/api/environment.cc b/src/api/environment.cc -index 5df88a9dbabf78b4e14b4124bdd466d5451ad0f6..9d33ebdc35516f65a977f7c1125453b0c99bee28 100644 +index 315e5c1d03a59dbb1eed5a79ec013a0815e3f5fe..8a7ad50b818448fa14eb4707c1dcec2a1339d2db 100644 --- a/src/api/environment.cc +++ b/src/api/environment.cc -@@ -467,6 +467,10 @@ MultiIsolatePlatform* GetMultiIsolatePlatform(IsolateData* env) { +@@ -474,6 +474,10 @@ MultiIsolatePlatform* GetMultiIsolatePlatform(IsolateData* env) { return env->platform(); } @@ -22,10 +22,10 @@ index 5df88a9dbabf78b4e14b4124bdd466d5451ad0f6..9d33ebdc35516f65a977f7c1125453b0 int thread_pool_size, node::tracing::TracingController* tracing_controller) { diff --git a/src/node.h b/src/node.h -index 4be002ac18f7c33f0242e1a660525133bf25d752..be619162d17728c1eb2ddf740947067913d6a348 100644 +index e8c72092c72b547946a09ec8e1f6cd7ece156235..a6407dd1e78c8fa86dfc2a6c40813b1b4d6a6829 100644 --- a/src/node.h +++ b/src/node.h -@@ -128,6 +128,7 @@ namespace node { +@@ -129,6 +129,7 @@ namespace node { namespace tracing { @@ -33,7 +33,7 @@ index 4be002ac18f7c33f0242e1a660525133bf25d752..be619162d17728c1eb2ddf7409470679 class TracingController; } -@@ -533,6 +534,8 @@ NODE_EXTERN v8::MaybeLocal<v8::Value> PrepareStackTraceCallback( +@@ -564,6 +565,8 @@ NODE_EXTERN void GetNodeReport(Environment* env, NODE_EXTERN MultiIsolatePlatform* GetMultiIsolatePlatform(Environment* env); NODE_EXTERN MultiIsolatePlatform* GetMultiIsolatePlatform(IsolateData* env); diff --git a/patches/node/fix_failing_node_js_test_on_outdated.patch b/patches/node/fix_failing_node_js_test_on_outdated.patch deleted file mode 100644 index 2a850f7c62..0000000000 --- a/patches/node/fix_failing_node_js_test_on_outdated.patch +++ /dev/null @@ -1,35 +0,0 @@ -From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 -From: Shelley Vohr <[email protected]> -Date: Wed, 16 Feb 2022 13:33:41 +0100 -Subject: fix: failing Node.js test on outdated - CurrentValueSerializerFormatVersion - -Corrects for a test that started failing as of https://chromium-review.googlesource.com/c/v8/v8/+/3417189 -becuase V8 updated the return value of CurrentValueSerializerFormatVersion() -from 14 to 15, and Node.js still expected 14 (0x0e). - -This patch can be removed as soon as Node.js updates to a version of V8 -containing the above CL. - -diff --git a/test/parallel/test-v8-serdes.js b/test/parallel/test-v8-serdes.js -index 12f20ed1c9d386122dd20fdd84a7a0c9b9079ee1..14552eeb493e8eb5b7c05c531b9628d8bcb13aae 100644 ---- a/test/parallel/test-v8-serdes.js -+++ b/test/parallel/test-v8-serdes.js -@@ -163,7 +163,7 @@ const hostObject = new (internalBinding('js_stream').JSStream)(); - } - - { -- const buf = Buffer.from('ff0e6f2203666f6f5e007b01', 'hex'); -+ const buf = Buffer.from('ff0f6f2203666f6f5e007b01', 'hex'); - - const des = new v8.DefaultDeserializer(buf); - des.readHeader(); -@@ -174,7 +174,7 @@ const hostObject = new (internalBinding('js_stream').JSStream)(); - ser.writeValue(des.readValue()); - - assert.deepStrictEqual(buf, ser.releaseBuffer()); -- assert.strictEqual(des.getWireFormatVersion(), 0x0e); -+ assert.strictEqual(des.getWireFormatVersion(), 0x0f); - } - - { diff --git a/patches/node/fix_handle_boringssl_and_openssl_incompatibilities.patch b/patches/node/fix_handle_boringssl_and_openssl_incompatibilities.patch index 5e1d0fafee..251511ee8d 100644 --- a/patches/node/fix_handle_boringssl_and_openssl_incompatibilities.patch +++ b/patches/node/fix_handle_boringssl_and_openssl_incompatibilities.patch @@ -17,10 +17,10 @@ Upstreams: - https://github.com/nodejs/node/pull/39136 diff --git a/src/crypto/crypto_cipher.cc b/src/crypto/crypto_cipher.cc -index 6c663a2b21d0a29708700d0e19b8e30fa696a1d0..1e4ff83faec60887e8169e612ac1a956130d7e4a 100644 +index a6ce4de49d9bf6962faddc99a3c5ed84046f0a13..678627d4ce460fc1519cd486a46eba1f78828a31 100644 --- a/src/crypto/crypto_cipher.cc +++ b/src/crypto/crypto_cipher.cc -@@ -25,7 +25,8 @@ using v8::Value; +@@ -27,7 +27,8 @@ using v8::Value; namespace crypto { namespace { bool IsSupportedAuthenticatedMode(const EVP_CIPHER* cipher) { @@ -31,10 +31,10 @@ index 6c663a2b21d0a29708700d0e19b8e30fa696a1d0..1e4ff83faec60887e8169e612ac1a956 case EVP_CIPH_GCM_MODE: #ifndef OPENSSL_NO_OCB diff --git a/src/crypto/crypto_common.cc b/src/crypto/crypto_common.cc -index ed1aea868d8385b6411103c614f4d12688c8cb30..4864d7cd6a310f31bfdda399996bd2c47977667a 100644 +index 3bf480f8f0c77d440324cf8847f4a214521f8162..40b6e311a14f5e824f8f0aff3121221eac94fd8a 100644 --- a/src/crypto/crypto_common.cc +++ b/src/crypto/crypto_common.cc -@@ -166,7 +166,7 @@ const char* GetClientHelloALPN(const SSLPointer& ssl) { +@@ -164,7 +164,7 @@ const char* GetClientHelloALPN(const SSLPointer& ssl) { const unsigned char* buf; size_t len; size_t rem; @@ -43,7 +43,7 @@ index ed1aea868d8385b6411103c614f4d12688c8cb30..4864d7cd6a310f31bfdda399996bd2c4 if (!SSL_client_hello_get0_ext( ssl.get(), TLSEXT_TYPE_application_layer_protocol_negotiation, -@@ -179,13 +179,15 @@ const char* GetClientHelloALPN(const SSLPointer& ssl) { +@@ -177,13 +177,15 @@ const char* GetClientHelloALPN(const SSLPointer& ssl) { len = (buf[0] << 8) | buf[1]; if (len + 2 != rem) return nullptr; return reinterpret_cast<const char*>(buf + 3); @@ -60,7 +60,7 @@ index ed1aea868d8385b6411103c614f4d12688c8cb30..4864d7cd6a310f31bfdda399996bd2c4 if (!SSL_client_hello_get0_ext( ssl.get(), TLSEXT_TYPE_server_name, -@@ -207,15 +209,20 @@ const char* GetClientHelloServerName(const SSLPointer& ssl) { +@@ -205,15 +207,20 @@ const char* GetClientHelloServerName(const SSLPointer& ssl) { if (len + 2 > rem) return nullptr; return reinterpret_cast<const char*>(buf + 5); @@ -84,7 +84,7 @@ index ed1aea868d8385b6411103c614f4d12688c8cb30..4864d7cd6a310f31bfdda399996bd2c4 const char* X509ErrorCode(long err) { // NOLINT(runtime/int) const char* code = "UNSPECIFIED"; -@@ -1103,14 +1110,14 @@ MaybeLocal<Array> GetClientHelloCiphers( +@@ -1045,14 +1052,14 @@ MaybeLocal<Array> GetClientHelloCiphers( Environment* env, const SSLPointer& ssl) { EscapableHandleScope scope(env->isolate()); @@ -104,10 +104,10 @@ index ed1aea868d8385b6411103c614f4d12688c8cb30..4864d7cd6a310f31bfdda399996bd2c4 if (!Set(env->context(), obj, diff --git a/src/crypto/crypto_dh.cc b/src/crypto/crypto_dh.cc -index c02e22bb542ff529e4d4fa32de63a07704b02b8e..38220d2e0d1a695f67bf7b9cb79a73fa199abeae 100644 +index dd69323b80076d7333b80453c9cc9ef5b680ce27..6431b768c83fa27b2287588e936f93ae00169ad5 100644 --- a/src/crypto/crypto_dh.cc +++ b/src/crypto/crypto_dh.cc -@@ -139,13 +139,11 @@ void DiffieHellman::MemoryInfo(MemoryTracker* tracker) const { +@@ -154,13 +154,11 @@ bool DiffieHellman::Init(BignumPointer&& bn_p, int g) { bool DiffieHellman::Init(const char* p, int p_len, int g) { dh_.reset(DH_new()); if (p_len <= 0) { @@ -123,7 +123,7 @@ index c02e22bb542ff529e4d4fa32de63a07704b02b8e..38220d2e0d1a695f67bf7b9cb79a73fa return false; } BIGNUM* bn_p = -@@ -163,21 +161,18 @@ bool DiffieHellman::Init(const char* p, int p_len, int g) { +@@ -178,21 +176,18 @@ bool DiffieHellman::Init(const char* p, int p_len, int g) { bool DiffieHellman::Init(const char* p, int p_len, const char* g, int g_len) { dh_.reset(DH_new()); if (p_len <= 0) { @@ -148,40 +148,48 @@ index c02e22bb542ff529e4d4fa32de63a07704b02b8e..38220d2e0d1a695f67bf7b9cb79a73fa return false; } BIGNUM* bn_p = -@@ -527,16 +522,20 @@ EVPKeyCtxPointer DhKeyGenTraits::Setup(DhKeyPairGenConfig* params) { - if (!BN_set_word(bn_g.get(), params->params.generator) || - !DH_set0_pqg(dh.get(), prime, nullptr, bn_g.get())) +@@ -219,8 +214,10 @@ typedef BignumPointer (*StandardizedGroupInstantiator)(); + inline StandardizedGroupInstantiator FindDiffieHellmanGroup(const char* name) { + #define V(n, p) \ + if (StringEqualNoCase(name, n)) return InstantiateStandardizedGroup<p> ++#ifndef OPENSSL_IS_BORINGSSL + V("modp1", BN_get_rfc2409_prime_768); + V("modp2", BN_get_rfc2409_prime_1024); ++#endif + V("modp5", BN_get_rfc3526_prime_1536); + V("modp14", BN_get_rfc3526_prime_2048); + V("modp15", BN_get_rfc3526_prime_3072); +@@ -559,15 +556,20 @@ EVPKeyCtxPointer DhKeyGenTraits::Setup(DhKeyPairGenConfig* params) { return EVPKeyCtxPointer(); -- + } + +#ifndef OPENSSL_IS_BORINGSSL - params->params.prime_fixed_value.release(); + prime_fixed_value->release(); bn_g.release(); key_params = EVPKeyPointer(EVP_PKEY_new()); CHECK(key_params); - EVP_PKEY_assign_DH(key_params.get(), dh.release()); + CHECK_EQ(EVP_PKEY_assign_DH(key_params.get(), dh.release()), 1); +#else + return EVPKeyCtxPointer(); +#endif - } else { + } else if (int* prime_size = std::get_if<int>(&params->params.prime)) { EVPKeyCtxPointer param_ctx(EVP_PKEY_CTX_new_id(EVP_PKEY_DH, nullptr)); EVP_PKEY* raw_params = nullptr; +#ifndef OPENSSL_IS_BORINGSSL if (!param_ctx || EVP_PKEY_paramgen_init(param_ctx.get()) <= 0 || EVP_PKEY_CTX_set_dh_paramgen_prime_len( -@@ -548,8 +547,10 @@ EVPKeyCtxPointer DhKeyGenTraits::Setup(DhKeyPairGenConfig* params) { - EVP_PKEY_paramgen(param_ctx.get(), &raw_params) <= 0) { - return EVPKeyCtxPointer(); +@@ -581,6 +583,9 @@ EVPKeyCtxPointer DhKeyGenTraits::Setup(DhKeyPairGenConfig* params) { } -- + key_params = EVPKeyPointer(raw_params); +#else + return EVPKeyCtxPointer(); +#endif + } else { + UNREACHABLE(); } - - EVPKeyCtxPointer ctx(EVP_PKEY_CTX_new(key_params.get(), nullptr)); diff --git a/src/crypto/crypto_dsa.cc b/src/crypto/crypto_dsa.cc index c7894baf00ee9ce4684f4c752f1c7c9b98163741..655895dbff8b88daa53c7b40a5feca42a461b689 100644 --- a/src/crypto/crypto_dsa.cc @@ -207,7 +215,7 @@ index c7894baf00ee9ce4684f4c752f1c7c9b98163741..655895dbff8b88daa53c7b40a5feca42 return EVPKeyCtxPointer(); diff --git a/src/crypto/crypto_random.cc b/src/crypto/crypto_random.cc -index 1459e410453da6850157444affa48b4a215edb03..2cf5861a110a2579329b9b0327d7b4296d0fb2c1 100644 +index 2f9e9aacb1e652202d72c69b46f8e76d6c5405a8..5f19c38a78e37d3e8d92bcc20ae1357f20349ad4 100644 --- a/src/crypto/crypto_random.cc +++ b/src/crypto/crypto_random.cc @@ -146,7 +146,7 @@ Maybe<bool> RandomPrimeTraits::AdditionalConfig( @@ -220,10 +228,10 @@ index 1459e410453da6850157444affa48b4a215edb03..2cf5861a110a2579329b9b0327d7b429 THROW_ERR_CRYPTO_OPERATION_FAILED(env, "could not generate prime"); return Nothing<bool>(); diff --git a/src/crypto/crypto_rsa.cc b/src/crypto/crypto_rsa.cc -index bd732a70a8ffe6212e06dddb352ca75cb45b50d3..cd025663f58d386e3b7c47823a7d6cf1a230e6a8 100644 +index ec339e5635d419db76f78974941493e32e968e84..e4a842b66994d4599d513296dff7d1891a9264a8 100644 --- a/src/crypto/crypto_rsa.cc +++ b/src/crypto/crypto_rsa.cc -@@ -626,10 +626,11 @@ Maybe<bool> GetRsaKeyDetail( +@@ -621,10 +621,11 @@ Maybe<bool> GetRsaKeyDetail( } if (params->saltLength != nullptr) { @@ -240,10 +248,10 @@ index bd732a70a8ffe6212e06dddb352ca75cb45b50d3..cd025663f58d386e3b7c47823a7d6cf1 if (target diff --git a/src/crypto/crypto_util.cc b/src/crypto/crypto_util.cc -index 652f6e0b12e2d56f33b1c18b80ec211b9c6bd5e9..840fe824617b951d4f4421155c5e1ce79c28525e 100644 +index e878c5ea15d58fb5eb096197209bc7122a504ca9..51973d7cb15f0650f3e94a7b8c9811c550ee9b0f 100644 --- a/src/crypto/crypto_util.cc +++ b/src/crypto/crypto_util.cc -@@ -522,24 +522,15 @@ Maybe<bool> Decorate(Environment* env, Local<Object> obj, +@@ -495,24 +495,15 @@ Maybe<bool> Decorate(Environment* env, Local<Object> obj, V(BIO) \ V(PKCS7) \ V(X509V3) \ @@ -269,16 +277,16 @@ index 652f6e0b12e2d56f33b1c18b80ec211b9c6bd5e9..840fe824617b951d4f4421155c5e1ce7 V(USER) \ #define V(name) case ERR_LIB_##name: lib = #name "_"; break; -@@ -698,7 +689,7 @@ void SecureBuffer(const FunctionCallbackInfo<Value>& args) { +@@ -671,7 +662,7 @@ void SecureBuffer(const FunctionCallbackInfo<Value>& args) { CHECK(args[0]->IsUint32()); Environment* env = Environment::GetCurrent(args); uint32_t len = args[0].As<Uint32>()->Value(); -- char* data = static_cast<char*>(OPENSSL_secure_malloc(len)); -+ char* data = static_cast<char*>(OPENSSL_malloc(len)); +- void* data = OPENSSL_secure_zalloc(len); ++ void* data = OPENSSL_malloc(len); if (data == nullptr) { // There's no memory available for the allocation. // Return nothing. -@@ -710,7 +701,7 @@ void SecureBuffer(const FunctionCallbackInfo<Value>& args) { +@@ -682,7 +673,7 @@ void SecureBuffer(const FunctionCallbackInfo<Value>& args) { data, len, [](void* data, size_t len, void* deleter_data) { @@ -287,7 +295,7 @@ index 652f6e0b12e2d56f33b1c18b80ec211b9c6bd5e9..840fe824617b951d4f4421155c5e1ce7 }, data); Local<ArrayBuffer> buffer = ArrayBuffer::New(env->isolate(), store); -@@ -718,10 +709,12 @@ void SecureBuffer(const FunctionCallbackInfo<Value>& args) { +@@ -690,10 +681,12 @@ void SecureBuffer(const FunctionCallbackInfo<Value>& args) { } void SecureHeapUsed(const FunctionCallbackInfo<Value>& args) { @@ -301,7 +309,7 @@ index 652f6e0b12e2d56f33b1c18b80ec211b9c6bd5e9..840fe824617b951d4f4421155c5e1ce7 } // namespace diff --git a/src/node_metadata.cc b/src/node_metadata.cc -index 46d9be0dfcfdcf778ebaf0337517b7da3f68bc9b..435762f7df47459dc4e6e73a7c3d2376184bebcf 100644 +index a221dcde050ad7b64cf25df1e1b3a3063a6f37e5..acf95e74882dbd65c65de75c933795c597817894 100644 --- a/src/node_metadata.cc +++ b/src/node_metadata.cc @@ -9,7 +9,7 @@ @@ -311,10 +319,10 @@ index 46d9be0dfcfdcf778ebaf0337517b7da3f68bc9b..435762f7df47459dc4e6e73a7c3d2376 -#if HAVE_OPENSSL +#if HAVE_OPENSSL && !defined(OPENSSL_IS_BORINGSSL) #include <openssl/opensslv.h> - #endif // HAVE_OPENSSL - + #if NODE_OPENSSL_HAS_QUIC + #include <openssl/quic.h> diff --git a/src/node_metadata.h b/src/node_metadata.h -index 4486d5af2c1622c7c8f44401dc3ebb986d8e3c2e..db1769f1b3f1617ed8dbbea57b5e324183b42be2 100644 +index b7cacae4c3d430c888fa7b5c66d8ed822e18f59d..d3b2ba33b06e1ebe140a30c777907f2bdffa098c 100644 --- a/src/node_metadata.h +++ b/src/node_metadata.h @@ -6,7 +6,7 @@ @@ -324,10 +332,10 @@ index 4486d5af2c1622c7c8f44401dc3ebb986d8e3c2e..db1769f1b3f1617ed8dbbea57b5e3241 -#if HAVE_OPENSSL +#if 0 #include <openssl/crypto.h> - #endif // HAVE_OPENSSL - + #if NODE_OPENSSL_HAS_QUIC + #include <openssl/quic.h> diff --git a/src/node_options.cc b/src/node_options.cc -index b82100b6907891063a37023e6ad21f79fffade1e..d78005d41bebff4e8729400cf08ab67d27098448 100644 +index bd4ad2f6408ca8127fa7f03b73f441884af81aa2..0e59521ed5a43189a175417eab89fd9daee000be 100644 --- a/src/node_options.cc +++ b/src/node_options.cc @@ -5,7 +5,7 @@ @@ -340,7 +348,7 @@ index b82100b6907891063a37023e6ad21f79fffade1e..d78005d41bebff4e8729400cf08ab67d #endif diff --git a/src/node_options.h b/src/node_options.h -index 32e68086502f3eebe2dbe232b198d663db951125..cb4b6215ffbace04ecd4ad694ae00493847a7324 100644 +index b20cfae141956a9817076e7a1fc7218a9ead6f0c..d7a0c84dd6de4811a371ef6615f3be470d39725c 100644 --- a/src/node_options.h +++ b/src/node_options.h @@ -11,7 +11,7 @@ diff --git a/patches/node/fix_override_createjob_in_node_platform.patch b/patches/node/fix_override_createjob_in_node_platform.patch index 252cf947f4..db1b20be50 100644 --- a/patches/node/fix_override_createjob_in_node_platform.patch +++ b/patches/node/fix_override_createjob_in_node_platform.patch @@ -9,10 +9,10 @@ This patch adds an override for NodePlatform::CreateJob, using the same parameters as PostJob. diff --git a/src/node_platform.cc b/src/node_platform.cc -index 5be79694fef65c9290f1b46d2657581dea16f543..e10caa9f6e39ec5b255acd9bc6b7f8efc77221d9 100644 +index b87413bcb9cfcbc8a51036edc5f6fd95e0906a96..389813fae96db76e385d88ad351b4bf4743298a5 100644 --- a/src/node_platform.cc +++ b/src/node_platform.cc -@@ -523,6 +523,12 @@ std::unique_ptr<v8::JobHandle> NodePlatform::PostJob(v8::TaskPriority priority, +@@ -525,6 +525,12 @@ std::unique_ptr<v8::JobHandle> NodePlatform::PostJob(v8::TaskPriority priority, this, priority, std::move(job_task), NumberOfWorkerThreads()); } diff --git a/patches/node/fix_parallel_test-v8-stats.patch b/patches/node/fix_parallel_test-v8-stats.patch index 6aab7511d2..ced725413e 100644 --- a/patches/node/fix_parallel_test-v8-stats.patch +++ b/patches/node/fix_parallel_test-v8-stats.patch @@ -8,10 +8,10 @@ match. node should eventually have this too once they roll up the newer v8. diff --git a/test/parallel/test-v8-stats.js b/test/parallel/test-v8-stats.js -index 7503a08c5a67fa4bead4f768242b47f418ebfc85..98ad11f11f9b9bf5699801814f8234e84dfaf638 100644 +index 2eaa3c5b0609149271afb85d7ecc33272e0ada2e..3af7ea1e4a4598dc4125ff78e426d6dc6a025c66 100644 --- a/test/parallel/test-v8-stats.js +++ b/test/parallel/test-v8-stats.js -@@ -46,6 +46,8 @@ const expectedHeapSpaces = [ +@@ -47,6 +47,8 @@ const expectedHeapSpaces = [ 'new_space', 'old_space', 'read_only_space', diff --git a/patches/node/fix_preserve_proper_method_names_as-is_in_error_stack.patch b/patches/node/fix_preserve_proper_method_names_as-is_in_error_stack.patch deleted file mode 100644 index bcd1c3ae56..0000000000 --- a/patches/node/fix_preserve_proper_method_names_as-is_in_error_stack.patch +++ /dev/null @@ -1,471 +0,0 @@ -From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 -From: Shelley Vohr <[email protected]> -Date: Thu, 7 Apr 2022 11:07:10 +0200 -Subject: fix: preserve "proper method names" as-is in error.stack - -Refs https://chromium-review.googlesource.com/c/v8/v8/+/3565724. - -This patch can be removed when Node.js updates to V8 10.2.60 or higher, -which includes the above CL. - -The above CL removes prepended Function. and Object. from -stack traces, and so we need to remove them from the comparison output. - -diff --git a/test/message/async_error_nexttick_main.out b/test/message/async_error_nexttick_main.out -index 8d11dea63d4191d4e492d42cad499e9e6f277bd4..9669e9b5102ff9ce8dfffbc45dadc60dab578458 100644 ---- a/test/message/async_error_nexttick_main.out -+++ b/test/message/async_error_nexttick_main.out -@@ -1,7 +1,7 @@ - Error: test - at one (*fixtures*async-error.js:4:9) - at two (*fixtures*async-error.js:17:9) -- at processTicksAndRejections (node:internal/process/task_queues:*:*) -+ at process.processTicksAndRejections (node:internal/process/task_queues:*:*) - at async three (*fixtures*async-error.js:20:3) - at async four (*fixtures*async-error.js:24:3) - at async main (*message*async_error_nexttick_main.js:7:5) -diff --git a/test/message/core_line_numbers.out b/test/message/core_line_numbers.out -index 97b017f66e2395ca90fc7562b9043579911ddc62..1d21462c8cf63ddbbf9e3b785b553a3104710132 100644 ---- a/test/message/core_line_numbers.out -+++ b/test/message/core_line_numbers.out -@@ -7,8 +7,8 @@ RangeError: Invalid input - at Object.decode (node:punycode:*:*) - at Object.<anonymous> (*test*message*core_line_numbers.js:*:*) - at Module._compile (node:internal/modules/cjs/loader:*:*) -- at Object.Module._extensions..js (node:internal/modules/cjs/loader:*:*) -+ at Module._extensions..js (node:internal/modules/cjs/loader:*:*) - at Module.load (node:internal/modules/cjs/loader:*:*) -- at Function.Module._load (node:internal/modules/cjs/loader:*:*) -+ at Module._load (node:internal/modules/cjs/loader:*:*) - at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:*:*) - at node:internal/main/run_main_module:*:* -diff --git a/test/message/error_aggregateTwoErrors.out b/test/message/error_aggregateTwoErrors.out -index 02e8738d47f57af4c457c15a0c3acfe0a1783078..d82704d95c2df6df36261c1494625b73c6507293 100644 ---- a/test/message/error_aggregateTwoErrors.out -+++ b/test/message/error_aggregateTwoErrors.out -@@ -4,9 +4,9 @@ throw aggregateTwoErrors(err, originalError); - AggregateError: original - at Object.<anonymous> (*test*message*error_aggregateTwoErrors.js:*:*) - at Module._compile (node:internal/modules/cjs/loader:*:*) -- at Object.Module._extensions..js (node:internal/modules/cjs/loader:*:*) -+ at Module._extensions..js (node:internal/modules/cjs/loader:*:*) - at Module.load (node:internal/modules/cjs/loader:*:*) -- at Function.Module._load (node:internal/modules/cjs/loader:*:*) -+ at Module._load (node:internal/modules/cjs/loader:*:*) - at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:*:*) - at node:internal/main/run_main_module:*:* { - code: 'ERR0', -@@ -14,9 +14,9 @@ AggregateError: original - Error: original - at Object.<anonymous> (*test*message*error_aggregateTwoErrors.js:*:*) - at Module._compile (node:internal/modules/cjs/loader:*:*) -- at Object.Module._extensions..js (node:internal/modules/cjs/loader:*:*) -+ at Module._extensions..js (node:internal/modules/cjs/loader:*:*) - at Module.load (node:internal/modules/cjs/loader:*:*) -- at Function.Module._load (node:internal/modules/cjs/loader:*:*) -+ at Module._load (node:internal/modules/cjs/loader:*:*) - at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:*:*) - at node:internal/main/run_main_module:*:* { - code: 'ERR0' -@@ -24,9 +24,9 @@ AggregateError: original - Error: second error - at Object.<anonymous> (*test*message*error_aggregateTwoErrors.js:*:*) - at Module._compile (node:internal/modules/cjs/loader:*:*) -- at Object.Module._extensions..js (node:internal/modules/cjs/loader:*:*) -+ at Module._extensions..js (node:internal/modules/cjs/loader:*:*) - at Module.load (node:internal/modules/cjs/loader:*:*) -- at Function.Module._load (node:internal/modules/cjs/loader:*:*) -+ at Module._load (node:internal/modules/cjs/loader:*:*) - at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:*:*) - at node:internal/main/run_main_module:*:* { - code: 'ERR1' -diff --git a/test/message/error_exit.out b/test/message/error_exit.out -index 2ef95b535dafe7b0a918b8d6a844e4c4a617818d..dc5e6e7d28cef3a23ca7ba2cfb1435cad55e2aeb 100644 ---- a/test/message/error_exit.out -+++ b/test/message/error_exit.out -@@ -9,9 +9,9 @@ AssertionError [ERR_ASSERTION]: Expected values to be strictly equal: - - at Object.<anonymous> (*test*message*error_exit.js:*:*) - at Module._compile (node:internal/modules/cjs/loader:*:*) -- at Object.Module._extensions..js (node:internal/modules/cjs/loader:*:*) -+ at Module._extensions..js (node:internal/modules/cjs/loader:*:*) - at Module.load (node:internal/modules/cjs/loader:*:*) -- at Function.Module._load (node:internal/modules/cjs/loader:*:*) -+ at Module._load (node:internal/modules/cjs/loader:*:*) - at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:*:*) - at node:internal/main/run_main_module:*:* { - generatedMessage: true, -diff --git a/test/message/error_with_nul.out b/test/message/error_with_nul.out -index 7fbb33f08e8dc342b9efc899e66f5e3350e9489b..a359999420fa76bd09b401a732acb7dcdfaa2198 100644 -GIT binary patch -delta 13 -VcmdnUvXEuMi;3^+Czmts0st)*2A2Q; - -delta 31 -ncmZ3;vXN!N3wHmctkmQZy@@aCIo(S0l1no4^YkXCGwuQa$o~w9 - -diff --git a/test/message/events_unhandled_error_common_trace.out b/test/message/events_unhandled_error_common_trace.out -index 19e89869ba74fae3f447e299904939da5a683280..2bdbe3df1b4c7e13ba33f099ae89f88365e6b690 100644 ---- a/test/message/events_unhandled_error_common_trace.out -+++ b/test/message/events_unhandled_error_common_trace.out -@@ -7,9 +7,9 @@ Error: foo:bar - at foo (*events_unhandled_error_common_trace.js:*:*) - at Object.<anonymous> (*events_unhandled_error_common_trace.js:*:*) - at Module._compile (node:internal/modules/cjs/loader:*:*) -- at Object.Module._extensions..js (node:internal/modules/cjs/loader:*:*) -+ at Module._extensions..js (node:internal/modules/cjs/loader:*:*) - at Module.load (node:internal/modules/cjs/loader:*:*) -- at Function.Module._load (node:internal/modules/cjs/loader:*:*) -+ at Module._load (node:internal/modules/cjs/loader:*:*) - at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:*:*) - at node:internal/main/run_main_module:*:* - Emitted 'error' event at: -diff --git a/test/message/events_unhandled_error_nexttick.out b/test/message/events_unhandled_error_nexttick.out -index 3e0d4697504e49eaae5ce1807a3794cccbcd6eec..87bb2fbb91a66e6dde9dfc61427682cba90f529c 100644 ---- a/test/message/events_unhandled_error_nexttick.out -+++ b/test/message/events_unhandled_error_nexttick.out -@@ -5,11 +5,11 @@ node:events:* - Error - at Object.<anonymous> (*events_unhandled_error_nexttick.js:*:*) - at Module._compile (node:internal/modules/cjs/loader:*:*) -- at Object.Module._extensions..js (node:internal/modules/cjs/loader:*:*) -+ at Module._extensions..js (node:internal/modules/cjs/loader:*:*) - at Module.load (node:internal/modules/cjs/loader:*:*) -- at Function.Module._load (node:internal/modules/cjs/loader:*:*) -+ at Module._load (node:internal/modules/cjs/loader:*:*) - at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:*:*) - at node:internal/main/run_main_module:*:* - Emitted 'error' event at: - at *events_unhandled_error_nexttick.js:*:* -- at processTicksAndRejections (node:internal/process/task_queues:*:*) -+ at process.processTicksAndRejections (node:internal/process/task_queues:*:*) -diff --git a/test/message/events_unhandled_error_sameline.out b/test/message/events_unhandled_error_sameline.out -index c027275033941df96d6ab24c1647f110a0436d9a..872556a3b393e737adb4ed3b613f2c0cf20b1d2c 100644 ---- a/test/message/events_unhandled_error_sameline.out -+++ b/test/message/events_unhandled_error_sameline.out -@@ -5,9 +5,9 @@ node:events:* - Error - at Object.<anonymous> (*events_unhandled_error_sameline.js:*:*) - at Module._compile (node:internal/modules/cjs/loader:*:*) -- at Object.Module._extensions..js (node:internal/modules/cjs/loader:*:*) -+ at Module._extensions..js (node:internal/modules/cjs/loader:*:*) - at Module.load (node:internal/modules/cjs/loader:*:*) -- at Function.Module._load (node:internal/modules/cjs/loader:*:*) -+ at Module._load (node:internal/modules/cjs/loader:*:*) - at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:*:*) - at node:internal/main/run_main_module:*:* - Emitted 'error' event at: -diff --git a/test/message/events_unhandled_error_subclass.out b/test/message/events_unhandled_error_subclass.out -index 5b8131970d50d50971184ccad0e2159c52fb0afd..073ab348a96f2e24efc2a661009287e4b7acda77 100644 ---- a/test/message/events_unhandled_error_subclass.out -+++ b/test/message/events_unhandled_error_subclass.out -@@ -5,9 +5,9 @@ node:events:* - Error - at Object.<anonymous> (*events_unhandled_error_subclass.js:*:*) - at Module._compile (node:internal/modules/cjs/loader:*:*) -- at Object.Module._extensions..js (node:internal/modules/cjs/loader:*:*) -+ at Module._extensions..js (node:internal/modules/cjs/loader:*:*) - at Module.load (node:internal/modules/cjs/loader:*:*) -- at Function.Module._load (node:internal/modules/cjs/loader:*:*) -+ at Module._load (node:internal/modules/cjs/loader:*:*) - at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:*:*) - at node:internal/main/run_main_module:*:* - Emitted 'error' event on Foo instance at: -diff --git a/test/message/if-error-has-good-stack.out b/test/message/if-error-has-good-stack.out -index d87581cd7675346d51261efa4e0e28c57f9652eb..c5188137124d38f48989d6774a177795617b4974 100644 ---- a/test/message/if-error-has-good-stack.out -+++ b/test/message/if-error-has-good-stack.out -@@ -12,9 +12,9 @@ AssertionError [ERR_ASSERTION]: ifError got unwanted exception: test error - at a (*if-error-has-good-stack.js:*:*) - at Object.<anonymous> (*if-error-has-good-stack.js:*:*) - at Module._compile (node:internal/modules/cjs/loader:*:*) -- at Object.Module._extensions..js (node:internal/modules/cjs/loader:*:*) -+ at Module._extensions..js (node:internal/modules/cjs/loader:*:*) - at Module.load (node:internal/modules/cjs/loader:*:*) -- at Function.Module._load (node:internal/modules/cjs/loader:*:*) -+ at Module._load (node:internal/modules/cjs/loader:*:*) - at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:*:*) - at node:internal/main/run_main_module:*:* { - generatedMessage: false, -@@ -25,9 +25,9 @@ AssertionError [ERR_ASSERTION]: ifError got unwanted exception: test error - at a (*if-error-has-good-stack.js:*:*) - at Object.<anonymous> (*if-error-has-good-stack.js:*:*) - at Module._compile (node:internal/modules/cjs/loader:*:*) -- at Object.Module._extensions..js (node:internal/modules/cjs/loader:*:*) -+ at Module._extensions..js (node:internal/modules/cjs/loader:*:*) - at Module.load (node:internal/modules/cjs/loader:*:*) -- at Function.Module._load (node:internal/modules/cjs/loader:*:*) -+ at Module._load (node:internal/modules/cjs/loader:*:*) - at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:*:*) - at node:internal/main/run_main_module:*:* - expected: null, -diff --git a/test/message/nexttick_throw.out b/test/message/nexttick_throw.out -index 955bcda6a26da019c9954c80ef9db24ea3094bef..3180f9a7de5df66f30c9dcee697ddfbb97df3725 100644 ---- a/test/message/nexttick_throw.out -+++ b/test/message/nexttick_throw.out -@@ -4,4 +4,4 @@ - ^ - ReferenceError: undefined_reference_error_maker is not defined - at *test*message*nexttick_throw.js:*:* -- at processTicksAndRejections (node:internal/process/task_queues:*:*) -+ at process.processTicksAndRejections (node:internal/process/task_queues:*:*) -diff --git a/test/message/source_map_disabled_by_api.out b/test/message/source_map_disabled_by_api.out -index d2cca7da5297e3772ae1acf7b8901eada6c21112..bbe017b05a20edd736ea13e2b501f8d9fdc7d0e6 100644 ---- a/test/message/source_map_disabled_by_api.out -+++ b/test/message/source_map_disabled_by_api.out -@@ -5,9 +5,9 @@ Error: an error! - at functionA (*enclosing-call-site-min.js:1:26) - at Object.<anonymous> (*enclosing-call-site-min.js:1:199) - at Module._compile (node:internal/modules/cjs/loader:*) -- at Object.Module._extensions..js (node:internal/modules/cjs/loader:*) -+ at Module._extensions..js (node:internal/modules/cjs/loader:*) - at Module.load (node:internal/modules/cjs/loader:*) -- at Function.Module._load (node:internal/modules/cjs/loader:*) -+ at Module._load (node:internal/modules/cjs/loader:*) - at Module.require (node:internal/modules/cjs/loader:*) - *enclosing-call-site.js:16 - throw new Error('an error!') -@@ -20,7 +20,7 @@ Error: an error! - at functionA (*enclosing-call-site.js:2:3) - at Object.<anonymous> (*enclosing-call-site.js:24:3) - at Module._compile (node:internal/modules/cjs/loader:*) -- at Object.Module._extensions..js (node:internal/modules/cjs/loader:*) -+ at Module._extensions..js (node:internal/modules/cjs/loader:*) - at Module.load (node:internal/modules/cjs/loader:*) -- at Function.Module._load (node:internal/modules/cjs/loader:*) -+ at Module._load (node:internal/modules/cjs/loader:*) - at Module.require (node:internal/modules/cjs/loader:*) -diff --git a/test/message/source_map_enabled_by_api.out b/test/message/source_map_enabled_by_api.out -index 525ceccec12e4bdb8a08964ade461692ee99beca..e85ecee7f14a8ba1a599aeaf1d9f5f4855c42c5d 100644 ---- a/test/message/source_map_enabled_by_api.out -+++ b/test/message/source_map_enabled_by_api.out -@@ -9,9 +9,9 @@ Error: an error! - at functionA (*enclosing-call-site.js:2:3) - at Object.<anonymous> (*enclosing-call-site.js:24:3) - at Module._compile (node:internal/modules/cjs/loader:*) -- at Object.Module._extensions..js (node:internal/modules/cjs/loader:*) -+ at Module._extensions..js (node:internal/modules/cjs/loader:*) - at Module.load (node:internal/modules/cjs/loader:*) -- at Function.Module._load (node:internal/modules/cjs/loader:*) -+ at Module._load (node:internal/modules/cjs/loader:*) - at Module.require (node:internal/modules/cjs/loader:*) - *enclosing-call-site-min.js:1 - var functionA=function(){functionB()};function functionB(){functionC()}var functionC=function(){functionD()},functionD=function(){if(0<Math.random())throw Error("an error!");},thrower=functionA;try{functionA()}catch(a){throw a;}; -@@ -24,7 +24,7 @@ Error: an error! - at functionA (*enclosing-call-site-min.js:1:26) - at Object.<anonymous> (*enclosing-call-site-min.js:1:199) - at Module._compile (node:internal/modules/cjs/loader:*) -- at Object.Module._extensions..js (node:internal/modules/cjs/loader:*) -+ at Module._extensions..js (node:internal/modules/cjs/loader:*) - at Module.load (node:internal/modules/cjs/loader:*) -- at Function.Module._load (node:internal/modules/cjs/loader:*) -+ at Module._load (node:internal/modules/cjs/loader:*) - at Module.require (node:internal/modules/cjs/loader:*) -diff --git a/test/message/source_map_enclosing_function.out b/test/message/source_map_enclosing_function.out -index 3eb76ecbbef31cd224e27001b825bce210f4e170..1babe95e398c61cdd3a4e1fd82fe418e4fbcd238 100644 ---- a/test/message/source_map_enclosing_function.out -+++ b/test/message/source_map_enclosing_function.out -@@ -9,7 +9,7 @@ Error: an error! - at functionA (*enclosing-call-site.js:2:3) - at Object.<anonymous> (*enclosing-call-site.js:24:3) - at Module._compile (node:internal/modules/cjs/loader:*) -- at Object.Module._extensions..js (node:internal/modules/cjs/loader:*) -+ at Module._extensions..js (node:internal/modules/cjs/loader:*) - at Module.load (node:internal/modules/cjs/loader:*) -- at Function.Module._load (node:internal/modules/cjs/loader:*) -+ at Module._load (node:internal/modules/cjs/loader:*) - at Module.require (node:internal/modules/cjs/loader:*) -diff --git a/test/message/source_map_eval.out b/test/message/source_map_eval.out -index 7cfd7c84fe65793cf01ee374506e18978774d730..533dbc6efc179c2d4cea844335e2863bf5741ad3 100644 ---- a/test/message/source_map_eval.out -+++ b/test/message/source_map_eval.out -@@ -3,8 +3,8 @@ ReferenceError: alert is not defined - at eval (*tabs.coffee:1:14) - at Object.<anonymous> (*source_map_eval.js:8:1) - at Module._compile (node:internal/modules/cjs/loader:*) -- at Object.Module._extensions..js (node:internal/modules/cjs/loader:*) -+ at Module._extensions..js (node:internal/modules/cjs/loader:*) - at Module.load (node:internal/modules/cjs/loader:*) -- at Function.Module._load (node:internal/modules/cjs/loader:*) -+ at Module._load (node:internal/modules/cjs/loader:*) - at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:*) - at node:internal/main/run_main_module:* -diff --git a/test/message/source_map_reference_error_tabs.out b/test/message/source_map_reference_error_tabs.out -index bce1b5f8911d4b34d3165d7a4bc5195cbe29211d..d56ef13b20bf9ca333e8806e3905059583c1f991 100644 ---- a/test/message/source_map_reference_error_tabs.out -+++ b/test/message/source_map_reference_error_tabs.out -@@ -6,9 +6,9 @@ ReferenceError: alert is not defined - at *tabs.coffee:26:2* - at *tabs.coffee:1:14* - at Module._compile (node:internal/modules/cjs/loader:* -- at Object.Module._extensions..js (node:internal/modules/cjs/loader:* -+ at Module._extensions..js (node:internal/modules/cjs/loader:* - at Module.load (node:internal/modules/cjs/loader:* -- at Function.Module._load (node:internal/modules/cjs/loader:* -+ at Module._load (node:internal/modules/cjs/loader:* - at Module.require (node:internal/modules/cjs/loader:* - at require (node:internal/modules/cjs/helpers:* - at Object.<anonymous> (*source_map_reference_error_tabs.js:* -diff --git a/test/message/source_map_throw_catch.out b/test/message/source_map_throw_catch.out -index 95bba5eee3e9dc6415ab44b7c842fc05b5d5dec2..9a98aa59e767592c04153c2a6d349710d7f28a2e 100644 ---- a/test/message/source_map_throw_catch.out -+++ b/test/message/source_map_throw_catch.out -@@ -6,9 +6,9 @@ Error: an exception - at *typescript-throw.ts:18:11* - at *typescript-throw.ts:24:1* - at Module._compile (node:internal/modules/cjs/loader:*) -- at Object.Module._extensions..js (node:internal/modules/cjs/loader:*) -+ at Module._extensions..js (node:internal/modules/cjs/loader:*) - at Module.load (node:internal/modules/cjs/loader:*) -- at Function.Module._load (node:internal/modules/cjs/loader:*) -+ at Module._load (node:internal/modules/cjs/loader:*) - at Module.require (node:internal/modules/cjs/loader:*) - at require (node:internal/modules/cjs/helpers:*) - at Object.<anonymous> (*source_map_throw_catch.js:6:3) -diff --git a/test/message/source_map_throw_first_tick.out b/test/message/source_map_throw_first_tick.out -index efa97a1d9f56ddbaf87422fa14d1f14f07a33061..1d76129d0c3506824d22be17711b1351285af937 100644 ---- a/test/message/source_map_throw_first_tick.out -+++ b/test/message/source_map_throw_first_tick.out -@@ -6,9 +6,9 @@ Error: an exception - at *typescript-throw.ts:18:11* - at *typescript-throw.ts:24:1* - at Module._compile (node:internal/modules/cjs/loader:*) -- at Object.Module._extensions..js (node:internal/modules/cjs/loader:*) -+ at Module._extensions..js (node:internal/modules/cjs/loader:*) - at Module.load (node:internal/modules/cjs/loader:*) -- at Function.Module._load (node:internal/modules/cjs/loader:*) -+ at Module._load (node:internal/modules/cjs/loader:*) - at Module.require (node:internal/modules/cjs/loader:*) - at require (node:internal/modules/cjs/helpers:*) - at Object.<anonymous> (*source_map_throw_first_tick.js:5:1) -diff --git a/test/message/source_map_throw_icu.out b/test/message/source_map_throw_icu.out -index 78482d73ddf0376de2443321c426fc6c84a1c29a..c5f699f80a9be862772ae5af8884d85bec72ebe3 100644 ---- a/test/message/source_map_throw_icu.out -+++ b/test/message/source_map_throw_icu.out -@@ -6,9 +6,9 @@ Error: an error - at *icu.jsx:3:23* - at *icu.jsx:9:5* - at Module._compile (node:internal/modules/cjs/loader:* -- at Object.Module._extensions..js (node:internal/modules/cjs/loader:* -+ at Module._extensions..js (node:internal/modules/cjs/loader:* - at Module.load (node:internal/modules/cjs/loader:* -- at Function.Module._load (node:internal/modules/cjs/loader:* -+ at Module._load (node:internal/modules/cjs/loader:* - at Module.require (node:internal/modules/cjs/loader:* - at require (node:internal/modules/cjs/helpers:* - at Object.<anonymous> (*source_map_throw_icu.js:* -diff --git a/test/message/source_map_throw_set_immediate.out b/test/message/source_map_throw_set_immediate.out -index c735e23cb955c5cb733ae766bd019848764b7ff1..21349d4c4598c0abac50b2b90e3bbf9b439257f5 100644 ---- a/test/message/source_map_throw_set_immediate.out -+++ b/test/message/source_map_throw_set_immediate.out -@@ -5,4 +5,4 @@ - Error: goodbye - at Hello *uglify-throw-original.js:5:9* - at *uglify-throw-original.js:9:3* -- at processImmediate (node:internal/timers:*) -+ at process.processImmediate (node:internal/timers:*) -diff --git a/test/message/timeout_throw.out b/test/message/timeout_throw.out -index 66e495eb84d0bda0c3f6b5f085aa2061f0e1b59a..968a5e4e4117713e4bf347e56ff84001ec86bb31 100644 ---- a/test/message/timeout_throw.out -+++ b/test/message/timeout_throw.out -@@ -4,4 +4,4 @@ - ReferenceError: undefined_reference_error_maker is not defined - at Timeout._onTimeout (*test*message*timeout_throw.js:*:*) - at listOnTimeout (node:internal/timers:*:*) -- at processTimers (node:internal/timers:*:*) -+ at process.processTimers (node:internal/timers:*:*) -diff --git a/test/message/undefined_reference_in_new_context.out b/test/message/undefined_reference_in_new_context.out -index 61dee9f6d4fba3696b91333c5fbdc20cf8e819fe..b06dc02a4861bd0eae89c682db0dce426b7409f3 100644 ---- a/test/message/undefined_reference_in_new_context.out -+++ b/test/message/undefined_reference_in_new_context.out -@@ -12,5 +12,5 @@ ReferenceError: foo is not defined - at Module._compile (node:internal/modules/cjs/loader:*) - at *..js (node:internal/modules/cjs/loader:*) - at Module.load (node:internal/modules/cjs/loader:*) -- at Function.Module._load (node:internal/modules/cjs/loader:*:*) -+ at Module._load (node:internal/modules/cjs/loader:*:*) - at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:*:*) -diff --git a/test/message/vm_display_runtime_error.out b/test/message/vm_display_runtime_error.out -index 8f1e9c37967f253071ad20c5a4f2b81f7b65b8cc..d7a39915f999101d4f2bfcc5f7bc9ba77eab8f0d 100644 ---- a/test/message/vm_display_runtime_error.out -+++ b/test/message/vm_display_runtime_error.out -@@ -9,9 +9,9 @@ Error: boo! - at Object.runInThisContext (node:vm:*) - at Object.<anonymous> (*test*message*vm_display_runtime_error.js:*) - at Module._compile (node:internal/modules/cjs/loader:*) -- at Object.Module._extensions..js (node:internal/modules/cjs/loader:*) -+ at Module._extensions..js (node:internal/modules/cjs/loader:*) - at Module.load (node:internal/modules/cjs/loader:*) -- at Function.Module._load (node:internal/modules/cjs/loader:*) -+ at Module._load (node:internal/modules/cjs/loader:*) - at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:*) - at node:internal/main/run_main_module:*:* - test.vm:1 -@@ -24,8 +24,8 @@ Error: spooky! - at Object.runInThisContext (node:vm:*) - at Object.<anonymous> (*test*message*vm_display_runtime_error.js:*) - at Module._compile (node:internal/modules/cjs/loader:*) -- at Object.Module._extensions..js (node:internal/modules/cjs/loader:*) -+ at Module._extensions..js (node:internal/modules/cjs/loader:*) - at Module.load (node:internal/modules/cjs/loader:*) -- at Function.Module._load (node:internal/modules/cjs/loader:*) -+ at Module._load (node:internal/modules/cjs/loader:*) - at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:*) - at node:internal/main/run_main_module:*:* -diff --git a/test/message/vm_display_syntax_error.out b/test/message/vm_display_syntax_error.out -index b0b70fcd75966825e0ff1893ff984a3e20edc926..ce82fb366e0375eeea8ced2320a3662584411160 100644 ---- a/test/message/vm_display_syntax_error.out -+++ b/test/message/vm_display_syntax_error.out -@@ -8,9 +8,9 @@ SyntaxError: Unexpected number - at Object.runInThisContext (node:vm:*) - at Object.<anonymous> (*test*message*vm_display_syntax_error.js:*) - at Module._compile (node:internal/modules/cjs/loader:*) -- at Object.Module._extensions..js (node:internal/modules/cjs/loader:*) -+ at Module._extensions..js (node:internal/modules/cjs/loader:*) - at Module.load (node:internal/modules/cjs/loader:*) -- at Function.Module._load (node:internal/modules/cjs/loader:*) -+ at Module._load (node:internal/modules/cjs/loader:*) - at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:*) - at node:internal/main/run_main_module:*:* - test.vm:1 -@@ -22,8 +22,8 @@ SyntaxError: Unexpected number - at Object.runInThisContext (node:vm:*) - at Object.<anonymous> (*test*message*vm_display_syntax_error.js:*) - at Module._compile (node:internal/modules/cjs/loader:*) -- at Object.Module._extensions..js (node:internal/modules/cjs/loader:*) -+ at Module._extensions..js (node:internal/modules/cjs/loader:*) - at Module.load (node:internal/modules/cjs/loader:*) -- at Function.Module._load (node:internal/modules/cjs/loader:*) -+ at Module._load (node:internal/modules/cjs/loader:*) - at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:*) - at node:internal/main/run_main_module:*:* -diff --git a/test/message/vm_dont_display_runtime_error.out b/test/message/vm_dont_display_runtime_error.out -index 2ff2e8355ab90c8d9d00aaa6bf743c4f3b7d0de0..72ef73d628e10f600e5e3e90691587f2f63b1a69 100644 ---- a/test/message/vm_dont_display_runtime_error.out -+++ b/test/message/vm_dont_display_runtime_error.out -@@ -10,8 +10,8 @@ Error: boo! - at Object.runInThisContext (node:vm:*) - at Object.<anonymous> (*test*message*vm_dont_display_runtime_error.js:*) - at Module._compile (node:internal/modules/cjs/loader:*) -- at Object.Module._extensions..js (node:internal/modules/cjs/loader:*) -+ at Module._extensions..js (node:internal/modules/cjs/loader:*) - at Module.load (node:internal/modules/cjs/loader:*) -- at Function.Module._load (node:internal/modules/cjs/loader:*) -+ at Module._load (node:internal/modules/cjs/loader:*) - at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:*) - at node:internal/main/run_main_module:*:* -diff --git a/test/message/vm_dont_display_syntax_error.out b/test/message/vm_dont_display_syntax_error.out -index d46dce2993f863622d2764d816adda548e568121..2ce14fe4013df2aa37c0339880294ba804c4f0c3 100644 ---- a/test/message/vm_dont_display_syntax_error.out -+++ b/test/message/vm_dont_display_syntax_error.out -@@ -10,8 +10,8 @@ SyntaxError: Unexpected number - at Object.runInThisContext (node:vm:*) - at Object.<anonymous> (*test*message*vm_dont_display_syntax_error.js:*) - at Module._compile (node:internal/modules/cjs/loader:*) -- at Object.Module._extensions..js (node:internal/modules/cjs/loader:*) -+ at Module._extensions..js (node:internal/modules/cjs/loader:*) - at Module.load (node:internal/modules/cjs/loader:*) -- at Function.Module._load (node:internal/modules/cjs/loader:*) -+ at Module._load (node:internal/modules/cjs/loader:*) - at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:*) - at node:internal/main/run_main_module:*:* diff --git a/patches/node/fix_prevent_changing_functiontemplateinfo_after_publish.patch b/patches/node/fix_prevent_changing_functiontemplateinfo_after_publish.patch new file mode 100644 index 0000000000..ac44e23703 --- /dev/null +++ b/patches/node/fix_prevent_changing_functiontemplateinfo_after_publish.patch @@ -0,0 +1,61 @@ +From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 +From: Shelley Vohr <[email protected]> +Date: Sun, 23 Oct 2022 23:36:19 +0200 +Subject: fix: prevent changing FunctionTemplateInfo after publish + +Refs https://chromium-review.googlesource.com/c/v8/v8/+/2718147 + +Fixes an issue where Node.js would try to call SetClassName on a +FunctionTemplate twice in some cases. The above CL made it so that +V8 CHECKs when this occurs. It is fixed by ensuring SetClassName +is only called once. + +This should be upstreamed. + +diff --git a/src/histogram.cc b/src/histogram.cc +index 3a3228ddc9eb6b53efc0721466479a9f62cd8967..175a67840348ca507d6e8b29835e5ab3b6d3e71a 100644 +--- a/src/histogram.cc ++++ b/src/histogram.cc +@@ -340,8 +340,9 @@ void HistogramBase::RegisterExternalReferences( + } + + void HistogramBase::Initialize(Environment* env, Local<Object> target) { +- SetConstructorFunction( +- env->context(), target, "Histogram", GetConstructorTemplate(env)); ++ SetConstructorFunction(env->context(), target, "Histogram", ++ GetConstructorTemplate(env), ++ SetConstructorFunctionFlag::NONE); + } + + BaseObjectPtr<BaseObject> HistogramBase::HistogramTransferData::Deserialize( +@@ -367,6 +368,7 @@ Local<FunctionTemplate> IntervalHistogram::GetConstructorTemplate( + Isolate* isolate = env->isolate(); + tmpl = NewFunctionTemplate(isolate, nullptr); + tmpl->Inherit(HandleWrap::GetConstructorTemplate(env)); ++ tmpl->SetClassName(OneByteString(isolate, "Histogram")); + tmpl->InstanceTemplate()->SetInternalFieldCount( + HistogramBase::kInternalFieldCount); + SetProtoMethodNoSideEffect(isolate, tmpl, "count", GetCount); +diff --git a/src/node_messaging.cc b/src/node_messaging.cc +index f88270fc75de91610a973c0649e1bc699c3e014d..e47f7a597a6ca0cfd71fec1e42f0fbb75cb539c7 100644 +--- a/src/node_messaging.cc ++++ b/src/node_messaging.cc +@@ -1467,13 +1467,16 @@ static void InitMessaging(Local<Object> target, + t->Inherit(BaseObject::GetConstructorTemplate(env)); + t->InstanceTemplate()->SetInternalFieldCount( + JSTransferable::kInternalFieldCount); +- SetConstructorFunction(context, target, "JSTransferable", t); ++ t->SetClassName(OneByteString(isolate, "JSTransferable")); ++ SetConstructorFunction(context, target, "JSTransferable", t, ++ SetConstructorFunctionFlag::NONE); + } + + SetConstructorFunction(context, + target, + env->message_port_constructor_string(), +- GetMessagePortConstructorTemplate(env)); ++ GetMessagePortConstructorTemplate(env), ++ SetConstructorFunctionFlag::NONE); + + // These are not methods on the MessagePort prototype, because + // the browser equivalents do not provide them. diff --git a/patches/node/fix_serdes_test.patch b/patches/node/fix_serdes_test.patch index 84190f55f7..a49ad55630 100644 --- a/patches/node/fix_serdes_test.patch +++ b/patches/node/fix_serdes_test.patch @@ -6,26 +6,24 @@ Subject: fix serdes test The V8 wire format version changed. diff --git a/test/parallel/test-v8-serdes.js b/test/parallel/test-v8-serdes.js -index ef9ef5945dba3b0748d5d0671f87eb20984de3c4..12f20ed1c9d386122dd20fdd84a7a0c9b9079ee1 100644 +index 1b6638ac1a90bdcec618b6c7b2a51c21fe6b548e..5ce5668925f0defb685d77063212f42eb524b3ad 100644 --- a/test/parallel/test-v8-serdes.js +++ b/test/parallel/test-v8-serdes.js -@@ -163,7 +163,7 @@ const hostObject = new (internalBinding('js_stream').JSStream)(); - } +@@ -164,11 +164,11 @@ const hostObject = new (internalBinding('js_stream').JSStream)(); { + // Test that an old serialized value can still be deserialized. - const buf = Buffer.from('ff0d6f2203666f6f5e007b01', 'hex'); -+ const buf = Buffer.from('ff0e6f2203666f6f5e007b01', 'hex'); ++ const buf = Buffer.from('ff0f6f2203666f6f5e007b01', 'hex'); const des = new v8.DefaultDeserializer(buf); des.readHeader(); -@@ -174,13 +174,13 @@ const hostObject = new (internalBinding('js_stream').JSStream)(); - ser.writeValue(des.readValue()); - - assert.deepStrictEqual(buf, ser.releaseBuffer()); - assert.strictEqual(des.getWireFormatVersion(), 0x0d); -+ assert.strictEqual(des.getWireFormatVersion(), 0x0e); - } ++ assert.strictEqual(des.getWireFormatVersion(), 0x0f); + const value = des.readValue(); + assert.strictEqual(value, value.foo); +@@ -203,7 +203,7 @@ const hostObject = new (internalBinding('js_stream').JSStream)(); { // Unaligned Uint16Array read, with padding in the underlying array buffer. let buf = Buffer.alloc(32 + 9); diff --git a/patches/node/fixup_for_wc_98-compat-extra-semi.patch b/patches/node/fixup_for_wc_98-compat-extra-semi.patch index d0da196ba8..59286b5160 100644 --- a/patches/node/fixup_for_wc_98-compat-extra-semi.patch +++ b/patches/node/fixup_for_wc_98-compat-extra-semi.patch @@ -7,7 +7,7 @@ Wc++98-compat-extra-semi is turned on for Electron so this patch fixes that error in node. diff --git a/src/node_serdes.cc b/src/node_serdes.cc -index 92d5020f293c98c81d3891a82f7320629bf9f926..2e815154ddbbd687e9c823cb7d42f11b7cb48000 100644 +index 0cd76078218433b46c17f350e3ba6073987438cf..ba13061b6aa7fd8f877aa456db9d352a847e682a 100644 --- a/src/node_serdes.cc +++ b/src/node_serdes.cc @@ -32,7 +32,7 @@ namespace serdes { diff --git a/patches/node/heap_remove_allocationspace_map_space_enum_constant.patch b/patches/node/heap_remove_allocationspace_map_space_enum_constant.patch index fb20fdd2e7..d8045bceb8 100644 --- a/patches/node/heap_remove_allocationspace_map_space_enum_constant.patch +++ b/patches/node/heap_remove_allocationspace_map_space_enum_constant.patch @@ -7,10 +7,10 @@ This was removed in: https://chromium-review.googlesource.com/c/v8/v8/+/3967841 diff --git a/test/parallel/test-v8-stats.js b/test/parallel/test-v8-stats.js -index 98ad11f11f9b9bf5699801814f8234e84dfaf638..678cb7626bc82bea17129ce2f8a4590350bf0983 100644 +index 3af7ea1e4a4598dc4125ff78e426d6dc6a025c66..83b375bd3c5b5dbd5189d48ad560580883ac91f6 100644 --- a/test/parallel/test-v8-stats.js +++ b/test/parallel/test-v8-stats.js -@@ -41,7 +41,6 @@ const expectedHeapSpaces = [ +@@ -42,7 +42,6 @@ const expectedHeapSpaces = [ 'code_large_object_space', 'code_space', 'large_object_space', diff --git a/patches/node/pass_all_globals_through_require.patch b/patches/node/pass_all_globals_through_require.patch index cf7be46950..3cd86f92ab 100644 --- a/patches/node/pass_all_globals_through_require.patch +++ b/patches/node/pass_all_globals_through_require.patch @@ -6,10 +6,10 @@ Subject: Pass all globals through "require" (cherry picked from commit 7d015419cb7a0ecfe6728431a4ed2056cd411d62) diff --git a/lib/internal/modules/cjs/loader.js b/lib/internal/modules/cjs/loader.js -index f1971c40a447b251f524717b906a5435bf0a0556..a65094ec21b0f40ab562608a9eeb36c5626cda31 100644 +index 67133b4926763429f4324c4f751d20c3c50a9155..ca83fa412f1979c0037254253939fd6dff6b5010 100644 --- a/lib/internal/modules/cjs/loader.js +++ b/lib/internal/modules/cjs/loader.js -@@ -127,6 +127,13 @@ const { +@@ -133,6 +133,13 @@ const { CHAR_COLON } = require('internal/constants'); @@ -23,7 +23,7 @@ index f1971c40a447b251f524717b906a5435bf0a0556..a65094ec21b0f40ab562608a9eeb36c5 const { isProxy } = require('internal/util/types'); -@@ -1121,10 +1128,12 @@ Module.prototype._compile = function(content, filename) { +@@ -1144,10 +1151,12 @@ Module.prototype._compile = function(content, filename) { if (requireDepth === 0) statCache = new SafeMap(); if (inspectorWrapper) { result = inspectorWrapper(compiledWrapper, thisValue, exports, diff --git a/patches/node/refactor_allow_embedder_overriding_of_internal_fs_calls.patch b/patches/node/refactor_allow_embedder_overriding_of_internal_fs_calls.patch index 33dabeac87..b92ff9c350 100644 --- a/patches/node/refactor_allow_embedder_overriding_of_internal_fs_calls.patch +++ b/patches/node/refactor_allow_embedder_overriding_of_internal_fs_calls.patch @@ -7,25 +7,25 @@ We use this to allow node's 'fs' module to read from ASAR files as if they were a real filesystem. diff --git a/lib/internal/bootstrap/node.js b/lib/internal/bootstrap/node.js -index 67cbdb9db09ca78f859032696c86f128bad64c46..376680f015d09a2cf3ce62de1fdeb9c5ed4c300b 100644 +index d2b82e7b699cd70ca300f4b036b88033e135910e..f2da9d4a1293d9879b0bb0867e68f7196f667dc6 100644 --- a/lib/internal/bootstrap/node.js +++ b/lib/internal/bootstrap/node.js -@@ -66,6 +66,10 @@ setupBuffer(); - process.domain = null; +@@ -88,6 +88,10 @@ process.domain = null; + } process._exiting = false; +// NOTE: Electron deletes this references before user code runs so that -+// internalBinding is not leaked to user code ++// internalBinding is not leaked to user code. +process.internalBinding = internalBinding; + // process.config is serialized config.gypi - const nativeModule = internalBinding('native_module'); + const nativeModule = internalBinding('builtins'); diff --git a/lib/internal/modules/cjs/loader.js b/lib/internal/modules/cjs/loader.js -index a65094ec21b0f40ab562608a9eeb36c5626cda31..3a536aab1bdeea6829d76d6af48fdefe0e08908d 100644 +index ca83fa412f1979c0037254253939fd6dff6b5010..4b592b0f7d9d481ee746b4e6db07620a27284f17 100644 --- a/lib/internal/modules/cjs/loader.js +++ b/lib/internal/modules/cjs/loader.js -@@ -86,7 +86,7 @@ const fs = require('fs'); +@@ -92,7 +92,7 @@ const fs = require('fs'); const internalFS = require('internal/fs/utils'); const path = require('path'); const { sep } = path; @@ -34,7 +34,7 @@ index a65094ec21b0f40ab562608a9eeb36c5626cda31..3a536aab1bdeea6829d76d6af48fdefe const packageJsonReader = require('internal/modules/package_json_reader'); const { safeGetenv } = internalBinding('credentials'); const { -@@ -161,7 +161,7 @@ function stat(filename) { +@@ -167,7 +167,7 @@ function stat(filename) { const result = statCache.get(filename); if (result !== undefined) return result; } diff --git a/patches/node/refactor_alter_child_process_fork_to_use_execute_script_with.patch b/patches/node/refactor_alter_child_process_fork_to_use_execute_script_with.patch index 14da2c5967..913f757367 100644 --- a/patches/node/refactor_alter_child_process_fork_to_use_execute_script_with.patch +++ b/patches/node/refactor_alter_child_process_fork_to_use_execute_script_with.patch @@ -7,13 +7,14 @@ Subject: refactor: alter child_process.fork to use execute script with When forking a child script, we setup a special environment to make the Electron binary run like the upstream node. On Mac, we use the helper app as node binary. diff --git a/lib/child_process.js b/lib/child_process.js -index 77b9ff35ff6ea780121aa1f4bb71850b9245965a..2a91c4820bebf55068c4d54a2e1133176de77a6d 100644 +index 6ce21363e1ee6acdd2e48763d0637ef1983e5264..f448bde2a570480a4390daf5392dc9d9b0f52df3 100644 --- a/lib/child_process.js +++ b/lib/child_process.js -@@ -161,6 +161,15 @@ function fork(modulePath, args = [], options) { - throw new ERR_CHILD_PROCESS_IPC_REQUIRED('options.stdio'); +@@ -136,6 +136,16 @@ function fork(modulePath, args = [], options) { + validateObject(options, 'options'); } - + options = { ...options, shell: false }; ++ + // When forking a child script, we setup a special environment to make + // the electron binary run like upstream Node.js + options.env = Object.create(options.env || process.env) @@ -24,5 +25,5 @@ index 77b9ff35ff6ea780121aa1f4bb71850b9245965a..2a91c4820bebf55068c4d54a2e113317 + } + options.execPath = options.execPath || process.execPath; - options.shell = false; + // Prepare arguments for fork: diff --git a/patches/node/repl_fix_crash_when_sharedarraybuffer_disabled.patch b/patches/node/repl_fix_crash_when_sharedarraybuffer_disabled.patch index cef8d21ccc..1eb1e9bd20 100644 --- a/patches/node/repl_fix_crash_when_sharedarraybuffer_disabled.patch +++ b/patches/node/repl_fix_crash_when_sharedarraybuffer_disabled.patch @@ -25,28 +25,27 @@ index a771b1813731edf4f0dd60f3505799e389f1d876..b9461677e2d7d1df192e752496e62cca bench.start(); for (let i = 0; i < n; i++) diff --git a/lib/internal/main/worker_thread.js b/lib/internal/main/worker_thread.js -index e21c1b1fe2cc7f55d3782419913568f51f1a87ea..1b6a8242bbd9eeb901950f1b9016bc2b85af5951 100644 +index cd9ca227b9cac4ff021ce1643000ea4b45163df6..0846afec28ab5fb507eb5f3eb211f635d61dca17 100644 --- a/lib/internal/main/worker_thread.js +++ b/lib/internal/main/worker_thread.js -@@ -9,7 +9,7 @@ const { - ArrayPrototypeSplice, +@@ -10,7 +10,7 @@ const { ObjectDefineProperty, - PromisePrototypeCatch, + PromisePrototypeThen, + RegExpPrototypeExec, - globalThis: { Atomics }, + globalThis: { Atomics, SharedArrayBuffer }, } = primordials; const { -@@ -150,6 +150,9 @@ port.on('message', (message) => { - const originalCwd = process.cwd; +@@ -157,6 +157,8 @@ port.on('message', (message) => { process.cwd = function() { + const currentCounter = Atomics.load(cwdCounter, 0); + // SharedArrayBuffers can be disabled with --no-harmony-sharedarraybuffer. + if (typeof SharedArrayBuffer === 'undefined') return originalCwd(); -+ - const currentCounter = Atomics.load(cwdCounter, 0); if (currentCounter === lastCounter) return cachedCwd; + lastCounter = currentCounter; diff --git a/lib/internal/worker.js b/lib/internal/worker.js index 8e396195209b83dff572792a78ee75d12d1f6610..4bb09b6ab5c31206a622814cbcd793c434b885d4 100644 --- a/lib/internal/worker.js diff --git a/patches/node/src_allow_embedders_to_provide_a_custom_pageallocator_to.patch b/patches/node/src_allow_embedders_to_provide_a_custom_pageallocator_to.patch deleted file mode 100644 index 646869cfd2..0000000000 --- a/patches/node/src_allow_embedders_to_provide_a_custom_pageallocator_to.patch +++ /dev/null @@ -1,128 +0,0 @@ -From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 -From: Samuel Attard <[email protected]> -Date: Tue, 3 Nov 2020 16:17:38 -0800 -Subject: src: allow embedders to provide a custom PageAllocator to - NodePlatform - -For certain embedder use cases there are more complex memory allocation requirements that -the default V8 page allocator does not handle, for example using MAP_JIT when running under -a hardened runtime environment on macOS. This allows such embedders to provide their own -allocator that does handle these cases. - -Upstreamed in https://github.com/nodejs/node/pull/38362. - -diff --git a/src/api/environment.cc b/src/api/environment.cc -index 9d33ebdc35516f65a977f7c1125453b0c99bee28..9cbe99596b1b8c148ac076acf8a9623d6989d505 100644 ---- a/src/api/environment.cc -+++ b/src/api/environment.cc -@@ -481,8 +481,9 @@ MultiIsolatePlatform* CreatePlatform( - - MultiIsolatePlatform* CreatePlatform( - int thread_pool_size, -- v8::TracingController* tracing_controller) { -- return MultiIsolatePlatform::Create(thread_pool_size, tracing_controller) -+ v8::TracingController* tracing_controller, -+ v8::PageAllocator* page_allocator) { -+ return MultiIsolatePlatform::Create(thread_pool_size, tracing_controller, page_allocator) - .release(); - } - -@@ -492,8 +493,9 @@ void FreePlatform(MultiIsolatePlatform* platform) { - - std::unique_ptr<MultiIsolatePlatform> MultiIsolatePlatform::Create( - int thread_pool_size, -- v8::TracingController* tracing_controller) { -- return std::make_unique<NodePlatform>(thread_pool_size, tracing_controller); -+ v8::TracingController* tracing_controller, -+ v8::PageAllocator* page_allocator) { -+ return std::make_unique<NodePlatform>(thread_pool_size, tracing_controller, page_allocator); - } - - MaybeLocal<Object> GetPerContextExports(Local<Context> context) { -diff --git a/src/node.h b/src/node.h -index be619162d17728c1eb2ddf740947067913d6a348..4eee4e96349ee49423d53819dd90a213f6a6e042 100644 ---- a/src/node.h -+++ b/src/node.h -@@ -342,7 +342,8 @@ class NODE_EXTERN MultiIsolatePlatform : public v8::Platform { - - static std::unique_ptr<MultiIsolatePlatform> Create( - int thread_pool_size, -- v8::TracingController* tracing_controller = nullptr); -+ v8::TracingController* tracing_controller = nullptr, -+ v8::PageAllocator* page_allocator = nullptr); - }; - - enum IsolateSettingsFlags { -@@ -539,7 +540,8 @@ NODE_EXTERN node::tracing::Agent* CreateAgent(); - NODE_DEPRECATED("Use MultiIsolatePlatform::Create() instead", - NODE_EXTERN MultiIsolatePlatform* CreatePlatform( - int thread_pool_size, -- v8::TracingController* tracing_controller)); -+ v8::TracingController* tracing_controller, -+ v8::PageAllocator* = nullptr)); - NODE_DEPRECATED("Use MultiIsolatePlatform::Create() instead", - NODE_EXTERN void FreePlatform(MultiIsolatePlatform* platform)); - -diff --git a/src/node_platform.cc b/src/node_platform.cc -index eb918bdd559c404a0e311e0dd92cfee8940491bc..5be79694fef65c9290f1b46d2657581dea16f543 100644 ---- a/src/node_platform.cc -+++ b/src/node_platform.cc -@@ -324,12 +324,16 @@ void PerIsolatePlatformData::DecreaseHandleCount() { - } - - NodePlatform::NodePlatform(int thread_pool_size, -- v8::TracingController* tracing_controller) { -+ v8::TracingController* tracing_controller, -+ v8::PageAllocator* page_allocator) { - if (tracing_controller != nullptr) { - tracing_controller_ = tracing_controller; - } else { - tracing_controller_ = new v8::TracingController(); - } -+ // This being nullptr is acceptable as V8 will default to its built -+ // in allocator if none is provided -+ page_allocator_ = page_allocator; - // TODO(addaleax): It's a bit icky that we use global state here, but we can't - // really do anything about it unless V8 starts exposing a way to access the - // current v8::Platform instance. -@@ -550,6 +554,10 @@ Platform::StackTracePrinter NodePlatform::GetStackTracePrinter() { - }; - } - -+v8::PageAllocator* NodePlatform::GetPageAllocator() { -+ return page_allocator_; -+} -+ - template <class T> - TaskQueue<T>::TaskQueue() - : lock_(), tasks_available_(), tasks_drained_(), -diff --git a/src/node_platform.h b/src/node_platform.h -index a7139ebdcc28d24087fb49697a0973331e0387a6..4a05f3bba58c8e875d0ab67f292589edbb3b812b 100644 ---- a/src/node_platform.h -+++ b/src/node_platform.h -@@ -138,7 +138,8 @@ class WorkerThreadsTaskRunner { - class NodePlatform : public MultiIsolatePlatform { - public: - NodePlatform(int thread_pool_size, -- v8::TracingController* tracing_controller); -+ v8::TracingController* tracing_controller, -+ v8::PageAllocator* page_allocator = nullptr); - ~NodePlatform() override; - - void DrainTasks(v8::Isolate* isolate) override; -@@ -170,6 +171,7 @@ class NodePlatform : public MultiIsolatePlatform { - v8::Isolate* isolate) override; - - Platform::StackTracePrinter GetStackTracePrinter() override; -+ v8::PageAllocator* GetPageAllocator() override; - - private: - IsolatePlatformDelegate* ForIsolate(v8::Isolate* isolate); -@@ -181,6 +183,7 @@ class NodePlatform : public MultiIsolatePlatform { - std::unordered_map<v8::Isolate*, DelegatePair> per_isolate_; - - v8::TracingController* tracing_controller_; -+ v8::PageAllocator* page_allocator_; - std::shared_ptr<WorkerThreadsTaskRunner> worker_thread_task_runner_; - bool has_shut_down_ = false; - }; diff --git a/patches/node/src_fix_ssize_t_error_from_nghttp2_h.patch b/patches/node/src_fix_ssize_t_error_from_nghttp2_h.patch deleted file mode 100644 index 71f5d6cf43..0000000000 --- a/patches/node/src_fix_ssize_t_error_from_nghttp2_h.patch +++ /dev/null @@ -1,27 +0,0 @@ -From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 -From: Darshan Sen <[email protected]> -Date: Thu, 25 Aug 2022 18:08:10 +0530 -Subject: src: fix ssize_t error from nghttp2.h - -The "node_http2.h" include reordering enforced by clang-format broke Electron's -Node.js upgrade on Windows. ssize_t is a part of the POSIX standard and it's not -available on Windows, so the fix for this is to typedef it on Windows like in -https://github.com/nodejs/node/blob/bb4dff783ddb3b20c67041f7ccef796c335c2407/src/node.h#L212-L220. - -Refs: https://github.com/electron/electron/pull/35350#discussion_r954890551 -Signed-off-by: Darshan Sen <[email protected]> - -diff --git a/src/node_http2.h b/src/node_http2.h -index 5bd715da8a269799ce8e6746a98184411dd859e0..6f3b93943b90e5984502f5d521b81bafad164fc7 100644 ---- a/src/node_http2.h -+++ b/src/node_http2.h -@@ -5,6 +5,9 @@ - - // FIXME(joyeecheung): nghttp2.h needs stdint.h to compile on Windows - #include <cstdint> -+// clang-format off -+#include "node.h" // nghttp2.h needs ssize_t -+// clang-format on - #include "nghttp2/nghttp2.h" - - #include "env.h" diff --git a/patches/node/src_iwyu_in_cleanup_queue_cc.patch b/patches/node/src_iwyu_in_cleanup_queue_cc.patch new file mode 100644 index 0000000000..2554390c32 --- /dev/null +++ b/patches/node/src_iwyu_in_cleanup_queue_cc.patch @@ -0,0 +1,17 @@ +From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 +From: Shelley Vohr <[email protected]> +Date: Wed, 12 Oct 2022 21:28:57 +0200 +Subject: src: iwyu in cleanup_queue.cc + +Upstreamed in https://github.com/nodejs/node/pull/44983. + +diff --git a/src/cleanup_queue.cc b/src/cleanup_queue.cc +index 5235513f16c2574a88675d5a2f19d9cae3c417ac..6290b6796c532702fb5e7549ff0c3ad14d2b89d8 100644 +--- a/src/cleanup_queue.cc ++++ b/src/cleanup_queue.cc +@@ -1,4 +1,5 @@ + #include "cleanup_queue.h" // NOLINT(build/include_inline) ++#include <algorithm> + #include <vector> + #include "cleanup_queue-inl.h" + diff --git a/patches/node/src_update_importmoduledynamically.patch b/patches/node/src_update_importmoduledynamically.patch deleted file mode 100644 index 70ccfd281a..0000000000 --- a/patches/node/src_update_importmoduledynamically.patch +++ /dev/null @@ -1,56 +0,0 @@ -From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 -From: Camillo Bruni <[email protected]> -Date: Mon, 15 Nov 2021 15:34:38 +0100 -Subject: src: update ImportModuleDynamically - -PR-URL: https://github.com/nodejs/node/pull/41610 -Reviewed-By: Jiawen Geng <[email protected]> -Reviewed-By: Antoine du Hamel <[email protected]> -Reviewed-By: Darshan Sen <[email protected]> -Reviewed-By: Colin Ihrig <[email protected]> - -diff --git a/src/module_wrap.cc b/src/module_wrap.cc -index b4b70ec1afd3eaa2489075156e7ccd7682ddd307..50ce8d510cb1a4299f3c161198ee6ed63fabc05f 100644 ---- a/src/module_wrap.cc -+++ b/src/module_wrap.cc -@@ -46,7 +46,6 @@ using v8::PrimitiveArray; - using v8::Promise; - using v8::ScriptCompiler; - using v8::ScriptOrigin; --using v8::ScriptOrModule; - using v8::String; - using v8::UnboundModuleScript; - using v8::Undefined; -@@ -553,7 +552,8 @@ MaybeLocal<Module> ModuleWrap::ResolveModuleCallback( - - static MaybeLocal<Promise> ImportModuleDynamically( - Local<Context> context, -- Local<ScriptOrModule> referrer, -+ Local<v8::Data> host_defined_options, -+ Local<Value> resource_name, - Local<String> specifier, - Local<FixedArray> import_assertions) { - Isolate* isolate = context->GetIsolate(); -@@ -568,7 +568,7 @@ static MaybeLocal<Promise> ImportModuleDynamically( - Local<Function> import_callback = - env->host_import_module_dynamically_callback(); - -- Local<PrimitiveArray> options = referrer->GetHostDefinedOptions(); -+ Local<FixedArray> options = host_defined_options.As<FixedArray>(); - if (options->Length() != HostDefinedOptions::kLength) { - Local<Promise::Resolver> resolver; - if (!Promise::Resolver::New(context).ToLocal(&resolver)) return {}; -@@ -582,11 +582,11 @@ static MaybeLocal<Promise> ImportModuleDynamically( - - Local<Value> object; - -- int type = options->Get(isolate, HostDefinedOptions::kType) -+ int type = options->Get(context, HostDefinedOptions::kType) - .As<Number>() - ->Int32Value(context) - .ToChecked(); -- uint32_t id = options->Get(isolate, HostDefinedOptions::kID) -+ uint32_t id = options->Get(context, HostDefinedOptions::kID) - .As<Number>() - ->Uint32Value(context) - .ToChecked(); diff --git a/patches/node/support_v8_sandboxed_pointers.patch b/patches/node/support_v8_sandboxed_pointers.patch index 9c78499e61..3e501f8e05 100644 --- a/patches/node/support_v8_sandboxed_pointers.patch +++ b/patches/node/support_v8_sandboxed_pointers.patch @@ -7,10 +7,10 @@ This refactors several allocators to allocate within the V8 memory cage, allowing them to be compatible with the V8_SANDBOXED_POINTERS feature. diff --git a/src/api/environment.cc b/src/api/environment.cc -index 9cbe99596b1b8c148ac076acf8a9623d6989d505..93d85d46dc6b3b30795b88ffa8070253f62e51bd 100644 +index 8a7ad50b818448fa14eb4707c1dcec2a1339d2db..b6981c37d5b286e22f24d11751eb05f72ca27619 100644 --- a/src/api/environment.cc +++ b/src/api/environment.cc -@@ -80,6 +80,14 @@ MaybeLocal<Value> PrepareStackTraceCallback(Local<Context> context, +@@ -82,6 +82,14 @@ MaybeLocal<Value> PrepareStackTraceCallback(Local<Context> context, return result; } @@ -26,10 +26,10 @@ index 9cbe99596b1b8c148ac076acf8a9623d6989d505..93d85d46dc6b3b30795b88ffa8070253 void* ret; if (zero_fill_field_ || per_process::cli_options->zero_fill_all_buffers) diff --git a/src/crypto/crypto_util.cc b/src/crypto/crypto_util.cc -index 840fe824617b951d4f4421155c5e1ce79c28525e..b1ae378993723d7a0a71bfe36fc5be94a899082a 100644 +index 51973d7cb15f0650f3e94a7b8c9811c550ee9b0f..1ab08092e8b8ad8a989eaa18f8e573b5948d295f 100644 --- a/src/crypto/crypto_util.cc +++ b/src/crypto/crypto_util.cc -@@ -332,10 +332,35 @@ ByteSource& ByteSource::operator=(ByteSource&& other) noexcept { +@@ -326,10 +326,35 @@ ByteSource& ByteSource::operator=(ByteSource&& other) noexcept { return *this; } @@ -66,7 +66,7 @@ index 840fe824617b951d4f4421155c5e1ce79c28525e..b1ae378993723d7a0a71bfe36fc5be94 std::unique_ptr<BackingStore> ptr = ArrayBuffer::NewBackingStore( allocated_data_, size(), -@@ -347,10 +372,11 @@ std::unique_ptr<BackingStore> ByteSource::ReleaseToBackingStore() { +@@ -341,10 +366,11 @@ std::unique_ptr<BackingStore> ByteSource::ReleaseToBackingStore() { data_ = nullptr; size_ = 0; return ptr; @@ -79,10 +79,10 @@ index 840fe824617b951d4f4421155c5e1ce79c28525e..b1ae378993723d7a0a71bfe36fc5be94 return ArrayBuffer::New(env->isolate(), std::move(store)); } -@@ -680,6 +706,16 @@ CryptoJobMode GetCryptoJobMode(v8::Local<v8::Value> args) { - } - - namespace { +@@ -658,6 +684,16 @@ namespace { + // in which case this has the same semantics as + // using OPENSSL_malloc. However, if the secure heap is + // initialized, SecureBuffer will automatically use it. +#if defined(V8_ENABLE_SANDBOX) +// When V8 sandboxed pointers are enabled, the secure heap cannot be used as +// all ArrayBuffers must be allocated inside the V8 memory cage. @@ -93,10 +93,10 @@ index 840fe824617b951d4f4421155c5e1ce79c28525e..b1ae378993723d7a0a71bfe36fc5be94 + args.GetReturnValue().Set(Uint8Array::New(buffer, 0, len)); +} +#else - // SecureBuffer uses openssl to allocate a Uint8Array using - // OPENSSL_secure_malloc. Because we do not yet actually - // make use of secure heap, this has the same semantics as -@@ -707,6 +743,7 @@ void SecureBuffer(const FunctionCallbackInfo<Value>& args) { + void SecureBuffer(const FunctionCallbackInfo<Value>& args) { + CHECK(args[0]->IsUint32()); + Environment* env = Environment::GetCurrent(args); +@@ -679,6 +715,7 @@ void SecureBuffer(const FunctionCallbackInfo<Value>& args) { Local<ArrayBuffer> buffer = ArrayBuffer::New(env->isolate(), store); args.GetReturnValue().Set(Uint8Array::New(buffer, 0, len)); } @@ -105,10 +105,10 @@ index 840fe824617b951d4f4421155c5e1ce79c28525e..b1ae378993723d7a0a71bfe36fc5be94 void SecureHeapUsed(const FunctionCallbackInfo<Value>& args) { #ifndef OPENSSL_IS_BORINGSSL diff --git a/src/crypto/crypto_util.h b/src/crypto/crypto_util.h -index f26422ee106ab7a816750ee717cb18ea454b5b62..5e5798e7e55dbb2df93ef4a8ab6f40aeb85616b4 100644 +index dc3bb15cfb48a8fdca471ac87840a8de30437920..f54555ae83e0bc2a4fc1bd1c6da08b30dfc1c6e4 100644 --- a/src/crypto/crypto_util.h +++ b/src/crypto/crypto_util.h -@@ -241,7 +241,7 @@ class ByteSource { +@@ -279,7 +279,7 @@ class ByteSource { // Creates a v8::BackingStore that takes over responsibility for // any allocated data. The ByteSource will be reset with size = 0 // after being called. @@ -118,7 +118,7 @@ index f26422ee106ab7a816750ee717cb18ea454b5b62..5e5798e7e55dbb2df93ef4a8ab6f40ae v8::Local<v8::ArrayBuffer> ToArrayBuffer(Environment* env); diff --git a/src/node_i18n.cc b/src/node_i18n.cc -index c537a247f55ff070da1988fc8b7309b5692b5c18..59bfb597849cd5a94800d6c83b238ef77245243e 100644 +index 581d52a7d05738133e5c3fad33cb73b7c575ef0b..6a4f24aa1d6853826e7ab5c729918c9048284128 100644 --- a/src/node_i18n.cc +++ b/src/node_i18n.cc @@ -104,7 +104,7 @@ namespace { @@ -131,10 +131,10 @@ index c537a247f55ff070da1988fc8b7309b5692b5c18..59bfb597849cd5a94800d6c83b238ef7 return ret; diff --git a/src/node_internals.h b/src/node_internals.h -index f7314c906e580664be445a8912030e17a3ac2fa4..99258ad0aa1e15ea1ba139fd0e83111e1436cc40 100644 +index 1449d2acd327b9cbbe32286ec6b7f6b412e693a2..d626d86c8dd8be78b3035be77867903fa0be68d7 100644 --- a/src/node_internals.h +++ b/src/node_internals.h -@@ -97,7 +97,9 @@ bool InitializePrimordials(v8::Local<v8::Context> context); +@@ -99,7 +99,9 @@ v8::Maybe<bool> InitializePrimordials(v8::Local<v8::Context> context); class NodeArrayBufferAllocator : public ArrayBufferAllocator { public: @@ -145,7 +145,7 @@ index f7314c906e580664be445a8912030e17a3ac2fa4..99258ad0aa1e15ea1ba139fd0e83111e void* Allocate(size_t size) override; // Defined in src/node.cc void* AllocateUninitialized(size_t size) override; -@@ -116,7 +118,7 @@ class NodeArrayBufferAllocator : public ArrayBufferAllocator { +@@ -118,7 +120,7 @@ class NodeArrayBufferAllocator : public ArrayBufferAllocator { } private: @@ -155,7 +155,7 @@ index f7314c906e580664be445a8912030e17a3ac2fa4..99258ad0aa1e15ea1ba139fd0e83111e // Delegate to V8's allocator for compatibility with the V8 memory cage. diff --git a/src/node_serdes.cc b/src/node_serdes.cc -index f6f0034bc24d09e3ad65491c7d6be0b9c9db1581..92d5020f293c98c81d3891a82f7320629bf9f926 100644 +index 45a16d9de43703c2115dde85c9faae3a04be2a88..0cd76078218433b46c17f350e3ba6073987438cf 100644 --- a/src/node_serdes.cc +++ b/src/node_serdes.cc @@ -29,6 +29,11 @@ using v8::ValueSerializer; diff --git a/patches/node/worker_thread_add_asar_support.patch b/patches/node/worker_thread_add_asar_support.patch deleted file mode 100644 index ec2526ecbd..0000000000 --- a/patches/node/worker_thread_add_asar_support.patch +++ /dev/null @@ -1,41 +0,0 @@ -From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 -From: Fedor Indutny <[email protected]> -Date: Wed, 9 Mar 2022 17:52:32 -0800 -Subject: worker_thread: add asar support - -This patch initializes asar support in workers threads in -Node.js. - -diff --git a/lib/internal/bootstrap/pre_execution.js b/lib/internal/bootstrap/pre_execution.js -index 4b1f1b05b6c67f206f87618792fa528deb238d8d..8993197ebd9eb54ec918767e16d665caebbf3554 100644 ---- a/lib/internal/bootstrap/pre_execution.js -+++ b/lib/internal/bootstrap/pre_execution.js -@@ -609,6 +609,7 @@ module.exports = { - loadPreloadModules, - setupTraceCategoryState, - setupInspectorHooks, -+ setupAsarSupport, - initializeReport, - initializeCJSLoader, - initializeWASI -diff --git a/lib/internal/main/worker_thread.js b/lib/internal/main/worker_thread.js -index 1b6a8242bbd9eeb901950f1b9016bc2b85af5951..af32601bc4bf0c7c61ee3ca0500bf26255081458 100644 ---- a/lib/internal/main/worker_thread.js -+++ b/lib/internal/main/worker_thread.js -@@ -30,6 +30,7 @@ const { - initializeReport, - initializeSourceMapsHandlers, - loadPreloadModules, -+ setupAsarSupport, - setupTraceCategoryState - } = require('internal/bootstrap/pre_execution'); - -@@ -162,6 +163,8 @@ port.on('message', (message) => { - }; - workerIo.sharedCwdCounter = cwdCounter; - -+ setupAsarSupport(); -+ - const CJSLoader = require('internal/modules/cjs/loader'); - assert(!CJSLoader.hasLoadedAnyUserCJSModule); - loadPreloadModules(); diff --git a/script/node-disabled-tests.json b/script/node-disabled-tests.json index 9aed5c7f0e..2477f1dc51 100644 --- a/script/node-disabled-tests.json +++ b/script/node-disabled-tests.json @@ -11,6 +11,9 @@ "parallel/test-crypto-aes-wrap", "parallel/test-crypto-authenticated-stream", "parallel/test-crypto-des3-wrap", + "parallel/test-crypto-modp1-error", + "parallel/test-crypto-dh-modp2", + "parallel/test-crypto-dh-modp2-views", "parallel/test-crypto-dh-stateless", "parallel/test-crypto-ecb", "parallel/test-crypto-fips", @@ -36,6 +39,16 @@ "parallel/test-process-versions", "parallel/test-repl", "parallel/test-repl-underscore", + "parallel/test-snapshot-api", + "parallel/test-snapshot-basic", + "parallel/test-snapshot-console", + "parallel/test-snapshot-cjs-main", + "parallel/test-snapshot-error", + "parallel/test-snapshot-gzip", + "parallel/test-snapshot-umd", + "parallel/test-snapshot-eval", + "parallel/test-snapshot-warning", + "parallel/test-snapshot-typescript", "parallel/test-stdout-close-catch", "parallel/test-tls-cert-chains-concat", "parallel/test-tls-cert-chains-in-ca", @@ -93,7 +106,9 @@ "parallel/test-trace-events-dynamic-enable-workers-disabled", "parallel/test-trace-events-environment", "parallel/test-trace-events-file-pattern", + "parallel/test-trace-events-fs-async", "parallel/test-trace-events-fs-sync", + "parallel/test-trace-events-http", "parallel/test-trace-events-metadata", "parallel/test-trace-events-net", "parallel/test-trace-events-none", @@ -102,24 +117,23 @@ "parallel/test-trace-events-v8", "parallel/test-trace-events-vm", "parallel/test-trace-events-worker-metadata", - "parallel/test-v8-untrusted-code-mitigations", - "parallel/test-webcrypto-derivebits-node-dh", + "parallel/test-wasm-web-api", "parallel/test-webcrypto-derivebits-cfrg", "parallel/test-webcrypto-derivekey-cfrg", - "parallel/test-webcrypto-ed25519-ed448", "parallel/test-webcrypto-encrypt-decrypt", "parallel/test-webcrypto-encrypt-decrypt-aes", "parallel/test-webcrypto-encrypt-decrypt-rsa", "parallel/test-webcrypto-export-import-cfrg", "parallel/test-webcrypto-keygen", - "parallel/test-webcrypto-rsa-pss-params", - "parallel/test-webcrypto-sign-verify-node-dsa", "parallel/test-webcrypto-sign-verify-eddsa", "parallel/test-worker-debug", "parallel/test-worker-stdio", "parallel/test-v8-serialize-leak", "parallel/test-zlib-unused-weak", - "report/test-report-fatal-error", + "report/test-report-fatalerror-oomerror-set", + "report/test-report-fatalerror-oomerror-directory", + "report/test-report-fatalerror-oomerror-filename", + "report/test-report-fatalerror-oomerror-compact", "report/test-report-getreport", "report/test-report-signal", "report/test-report-uncaught-exception", diff --git a/shell/browser/javascript_environment.cc b/shell/browser/javascript_environment.cc index c1fab43482..0e674a72c5 100644 --- a/shell/browser/javascript_environment.cc +++ b/shell/browser/javascript_environment.cc @@ -262,11 +262,11 @@ v8::Isolate* JavascriptEnvironment::Initialize(uv_loop_t* event_loop) { auto* tracing_agent = node::CreateAgent(); auto* tracing_controller = new TracingControllerImpl(); node::tracing::TraceEventHelper::SetAgent(tracing_agent); - platform_ = node::CreatePlatform( + platform_ = node::MultiIsolatePlatform::Create( base::RecommendedMaxNumberOfThreadsInThreadGroup(3, 8, 0.1, 0), tracing_controller, gin::V8Platform::PageAllocator()); - v8::V8::InitializePlatform(platform_); + v8::V8::InitializePlatform(platform_.get()); gin::IsolateHolder::Initialize(gin::IsolateHolder::kNonStrictMode, gin::ArrayBufferAllocator::SharedInstance(), nullptr /* external_reference_table */, diff --git a/shell/browser/javascript_environment.h b/shell/browser/javascript_environment.h index d8f91525b4..de9cbf409e 100644 --- a/shell/browser/javascript_environment.h +++ b/shell/browser/javascript_environment.h @@ -32,7 +32,7 @@ class JavascriptEnvironment { void CreateMicrotasksRunner(); void DestroyMicrotasksRunner(); - node::MultiIsolatePlatform* platform() const { return platform_; } + node::MultiIsolatePlatform* platform() const { return platform_.get(); } v8::Isolate* isolate() const { return isolate_; } v8::Local<v8::Context> context() const { return v8::Local<v8::Context>::New(isolate_, context_); @@ -42,8 +42,7 @@ class JavascriptEnvironment { private: v8::Isolate* Initialize(uv_loop_t* event_loop); - // Leaked on exit. - node::MultiIsolatePlatform* platform_; + std::unique_ptr<node::MultiIsolatePlatform> platform_; v8::Isolate* isolate_; gin::IsolateHolder isolate_holder_; diff --git a/shell/common/node_bindings.cc b/shell/common/node_bindings.cc index c291875556..5e4ab461c2 100644 --- a/shell/common/node_bindings.cc +++ b/shell/common/node_bindings.cc @@ -210,46 +210,6 @@ GetAllowedDebugOptions() { return {}; } -// Initialize Node.js cli options to pass to Node.js -// See https://nodejs.org/api/cli.html#cli_options -void SetNodeCliFlags() { - const std::unordered_set<base::StringPiece, base::StringPieceHash> allowed = - GetAllowedDebugOptions(); - - const auto argv = base::CommandLine::ForCurrentProcess()->argv(); - std::vector<std::string> args; - - // TODO(codebytere): We need to set the first entry in args to the - // process name owing to src/node_options-inl.h#L286-L290 but this is - // redundant and so should be refactored upstream. - args.reserve(argv.size() + 1); - args.emplace_back("electron"); - - for (const auto& arg : argv) { -#if BUILDFLAG(IS_WIN) - const auto& option = base::WideToUTF8(arg); -#else - const auto& option = arg; -#endif - const auto stripped = base::StringPiece(option).substr(0, option.find('=')); - - // Only allow in no-op (--) option or DebugOptions - if (allowed.count(stripped) != 0 || stripped == "--") - args.push_back(option); - } - - std::vector<std::string> errors; - const int exit_code = ProcessGlobalArgs(&args, nullptr, &errors, - node::kDisallowedInEnvironment); - - const std::string err_str = "Error parsing Node.js cli flags "; - if (exit_code != 0) { - LOG(ERROR) << err_str; - } else if (!errors.empty()) { - LOG(ERROR) << err_str << base::JoinString(errors, " "); - } -} - // Initialize NODE_OPTIONS to pass to Node.js // See https://nodejs.org/api/cli.html#cli_node_options_options void SetNodeOptions(base::Environment* env) { @@ -370,6 +330,53 @@ bool NodeBindings::IsInitialized() { return g_is_initialized; } +// Initialize Node.js cli options to pass to Node.js +// See https://nodejs.org/api/cli.html#cli_options +void NodeBindings::SetNodeCliFlags() { + const std::unordered_set<base::StringPiece, base::StringPieceHash> allowed = + GetAllowedDebugOptions(); + + const auto argv = base::CommandLine::ForCurrentProcess()->argv(); + std::vector<std::string> args; + + // TODO(codebytere): We need to set the first entry in args to the + // process name owing to src/node_options-inl.h#L286-L290 but this is + // redundant and so should be refactored upstream. + args.reserve(argv.size() + 1); + args.emplace_back("electron"); + + for (const auto& arg : argv) { +#if BUILDFLAG(IS_WIN) + const auto& option = base::WideToUTF8(arg); +#else + const auto& option = arg; +#endif + const auto stripped = base::StringPiece(option).substr(0, option.find('=')); + + // Only allow in no-op (--) option or DebugOptions + if (allowed.count(stripped) != 0 || stripped == "--") + args.push_back(option); + } + + // We need to disable Node.js' fetch implementation to prevent + // conflict with Blink's in renderer and worker processes. + if (browser_env_ == BrowserEnvironment::kRenderer || + browser_env_ == BrowserEnvironment::kWorker) { + args.push_back("--no-experimental-fetch"); + } + + std::vector<std::string> errors; + const int exit_code = ProcessGlobalArgs(&args, nullptr, &errors, + node::kDisallowedInEnvironment); + + const std::string err_str = "Error parsing Node.js cli flags "; + if (exit_code != 0) { + LOG(ERROR) << err_str; + } else if (!errors.empty()) { + LOG(ERROR) << err_str << base::JoinString(errors, " "); + } +} + void NodeBindings::Initialize() { TRACE_EVENT0("electron", "NodeBindings::Initialize"); // Open node's error reporting system for browser process. @@ -445,14 +452,6 @@ node::Environment* NodeBindings::CreateEnvironment( v8::Isolate* isolate = context->GetIsolate(); gin_helper::Dictionary global(isolate, context->Global()); - // Avoids overriding globals like setImmediate, clearImmediate - // queueMicrotask etc during the bootstrap phase of Node.js - // for processes that already have these defined by DOM. - // Check //third_party/electron_node/lib/internal/bootstrap/node.js - // for the list of overrides on globalThis. - if (browser_env_ == BrowserEnvironment::kRenderer || - browser_env_ == BrowserEnvironment::kWorker) - global.Set("_noBrowserGlobals", true); if (browser_env_ == BrowserEnvironment::kBrowser) { const std::vector<std::string> search_paths = {"app.asar", "app", @@ -487,7 +486,13 @@ node::Environment* NodeBindings::CreateEnvironment( // Only one ESM loader can be registered per isolate - // in renderer processes this should be blink. We need to tell Node.js // not to register its handler (overriding blinks) in non-browser processes. + // We also avoid overriding globals like setImmediate, clearImmediate + // queueMicrotask etc during the bootstrap phase of Node.js + // for processes that already have these defined by DOM. + // Check //third_party/electron_node/lib/internal/bootstrap/node.js + // for the list of overrides on globalThis. flags |= node::EnvironmentFlags::kNoRegisterESMLoader | + node::EnvironmentFlags::kNoBrowserGlobals | node::EnvironmentFlags::kNoCreateInspector; } @@ -517,15 +522,6 @@ node::Environment* NodeBindings::CreateEnvironment( DCHECK(env); - // Clean up the global _noBrowserGlobals that we unironically injected into - // the global scope - if (browser_env_ == BrowserEnvironment::kRenderer || - browser_env_ == BrowserEnvironment::kWorker) { - // We need to bootstrap the env in non-browser processes so that - // _noBrowserGlobals is read correctly before we remove it - global.Delete("_noBrowserGlobals"); - } - node::IsolateSettings is; // Use a custom fatal error callback to allow us to add diff --git a/shell/common/node_bindings.h b/shell/common/node_bindings.h index c56e1aecd5..efd33fc62c 100644 --- a/shell/common/node_bindings.h +++ b/shell/common/node_bindings.h @@ -87,6 +87,8 @@ class NodeBindings { // Setup V8, libuv. void Initialize(); + void SetNodeCliFlags(); + // Create the environment and load node.js. node::Environment* CreateEnvironment(v8::Handle<v8::Context> context, node::MultiIsolatePlatform* platform, diff --git a/shell/common/node_includes.h b/shell/common/node_includes.h index c678769324..104d73520e 100644 --- a/shell/common/node_includes.h +++ b/shell/common/node_includes.h @@ -20,9 +20,9 @@ #include "env.h" #include "node.h" #include "node_buffer.h" +#include "node_builtins.h" #include "node_errors.h" #include "node_internals.h" -#include "node_native_module_env.h" #include "node_object_wrap.h" #include "node_options-inl.h" #include "node_options.h" diff --git a/shell/common/node_util.cc b/shell/common/node_util.cc index 7cee76b7c4..bfa98d8c26 100644 --- a/shell/common/node_util.cc +++ b/shell/common/node_util.cc @@ -18,8 +18,8 @@ v8::MaybeLocal<v8::Value> CompileAndCall( v8::Isolate* isolate = context->GetIsolate(); v8::TryCatch try_catch(isolate); v8::MaybeLocal<v8::Function> compiled = - node::native_module::NativeModuleEnv::LookupAndCompile( - context, id, parameters, optional_env); + node::builtins::BuiltinLoader::LookupAndCompile(context, id, parameters, + optional_env); if (compiled.IsEmpty()) { return v8::MaybeLocal<v8::Value>(); } diff --git a/shell/renderer/electron_renderer_client.cc b/shell/renderer/electron_renderer_client.cc index c3884cb6ba..66cadfbcbe 100644 --- a/shell/renderer/electron_renderer_client.cc +++ b/shell/renderer/electron_renderer_client.cc @@ -85,8 +85,8 @@ void ElectronRendererClient::DidCreateScriptContext( node::tracing::TraceEventHelper::SetAgent(node::CreateAgent()); // Setup node environment for each window. - bool initialized = node::InitializeContext(renderer_context); - CHECK(initialized); + v8::Maybe<bool> initialized = node::InitializeContext(renderer_context); + CHECK(!initialized.IsNothing() && initialized.FromJust()); node::Environment* env = node_bindings_->CreateEnvironment(renderer_context, nullptr); diff --git a/shell/renderer/web_worker_observer.cc b/shell/renderer/web_worker_observer.cc index ea5f60daba..0eb07182fa 100644 --- a/shell/renderer/web_worker_observer.cc +++ b/shell/renderer/web_worker_observer.cc @@ -63,8 +63,8 @@ void WebWorkerObserver::WorkerScriptReadyForEvaluation( node::tracing::TraceEventHelper::SetAgent(node::CreateAgent()); // Setup node environment for each window. - bool initialized = node::InitializeContext(worker_context); - CHECK(initialized); + v8::Maybe<bool> initialized = node::InitializeContext(worker_context); + CHECK(!initialized.IsNothing() && initialized.FromJust()); node::Environment* env = node_bindings_->CreateEnvironment(worker_context, nullptr); diff --git a/spec/api-net-spec.ts b/spec/api-net-spec.ts index fc70135fa3..97f7e5ca90 100644 --- a/spec/api-net-spec.ts +++ b/spec/api-net-spec.ts @@ -1,4 +1,5 @@ import { expect } from 'chai'; +import * as dns from 'dns'; import { net, session, ClientRequest, BrowserWindow, ClientRequestConstructorOptions } from 'electron/main'; import * as http from 'http'; import * as url from 'url'; @@ -6,6 +7,9 @@ import { AddressInfo, Socket } from 'net'; import { emittedOnce } from './events-helpers'; import { defer, delay } from './spec-helpers'; +// See https://github.com/nodejs/node/issues/40702. +dns.setDefaultResultOrder('ipv4first'); + const kOneKiloByte = 1024; const kOneMegaByte = kOneKiloByte * kOneKiloByte;
chore
38850112200a8fa5e17c7c393b409bb33a747f9a
Milan Burda
2024-02-26 13:47:16
chore: remove deprecated `inputFieldType` (#41239) chore: remove deprecated inputFieldType
diff --git a/docs/api/web-contents.md b/docs/api/web-contents.md index ff5735c52b..e01852a831 100644 --- a/docs/api/web-contents.md +++ b/docs/api/web-contents.md @@ -778,9 +778,6 @@ Returns: `input-text`, `input-time`, `input-url`, `input-week`, `output`, `reset-button`, `select-list`, `select-list`, `select-multiple`, `select-one`, `submit-button`, and `text-area`, - * `inputFieldType` string _Deprecated_ - If the context menu was invoked on an - input field, the type of that field. Possible values include `none`, - `plainText`, `password`, `other`. * `spellcheckEnabled` boolean - If the context is editable, whether or not spellchecking is enabled. * `menuSourceType` string - Input source that invoked the context menu. Can be `none`, `mouse`, `keyboard`, `touch`, `touchMenu`, `longPress`, `longTap`, `touchHandle`, `stylus`, `adjustSelection`, or `adjustSelectionReset`. diff --git a/docs/api/webview-tag.md b/docs/api/webview-tag.md index ac049bed19..74bcbb24db 100644 --- a/docs/api/webview-tag.md +++ b/docs/api/webview-tag.md @@ -1111,9 +1111,6 @@ Returns: `input-text`, `input-time`, `input-url`, `input-week`, `output`, `reset-button`, `select-list`, `select-list`, `select-multiple`, `select-one`, `submit-button`, and `text-area`, - * `inputFieldType` string _Deprecated_ - If the context menu was invoked on an - input field, the type of that field. Possible values include `none`, - `plainText`, `password`, `other`. * `spellcheckEnabled` boolean - If the context is editable, whether or not spellchecking is enabled. * `menuSourceType` string - Input source that invoked the context menu. Can be `none`, `mouse`, `keyboard`, `touch`, `touchMenu`, `longPress`, `longTap`, `touchHandle`, `stylus`, `adjustSelection`, or `adjustSelectionReset`. diff --git a/docs/breaking-changes.md b/docs/breaking-changes.md index fbfe95a912..bc954f3d76 100644 --- a/docs/breaking-changes.md +++ b/docs/breaking-changes.md @@ -38,6 +38,12 @@ The autoresizing behavior is now standardized across all platforms. If your app uses `BrowserView.setAutoResize` to do anything more complex than making a BrowserView fill the entire window, it's likely you already had custom logic in place to handle this difference in behavior on macOS. If so, that logic will no longer be needed in Electron 30 as autoresizing behavior is consistent. +### Removed: `params.inputFormType` property on `context-menu` on `WebContents` + +The `inputFormType` property of the params object in the `context-menu` +event from `WebContents` has been removed. Use the new `formControlType` +property instead. + ## Planned Breaking API Changes (29.0) ### Behavior Changed: `ipcRenderer` can no longer be sent over the `contextBridge` diff --git a/shell/common/gin_converters/content_converter.cc b/shell/common/gin_converters/content_converter.cc index 8529206507..49e51b0f52 100644 --- a/shell/common/gin_converters/content_converter.cc +++ b/shell/common/gin_converters/content_converter.cc @@ -23,51 +23,6 @@ #include "ui/events/keycodes/dom/keycode_converter.h" #include "ui/events/keycodes/keyboard_code_conversion.h" -namespace { - -[[nodiscard]] constexpr std::string_view FormControlToInputFieldTypeString( - const std::optional<blink::mojom::FormControlType> form_control_type) { - if (!form_control_type) - return "none"; - - switch (*form_control_type) { - case blink::mojom::FormControlType::kInputPassword: - return "password"; - - case blink::mojom::FormControlType::kInputText: - return "plainText"; - - // other input types: - case blink::mojom::FormControlType::kInputButton: - case blink::mojom::FormControlType::kInputCheckbox: - case blink::mojom::FormControlType::kInputColor: - case blink::mojom::FormControlType::kInputDate: - case blink::mojom::FormControlType::kInputDatetimeLocal: - case blink::mojom::FormControlType::kInputEmail: - case blink::mojom::FormControlType::kInputFile: - case blink::mojom::FormControlType::kInputHidden: - case blink::mojom::FormControlType::kInputImage: - case blink::mojom::FormControlType::kInputMonth: - case blink::mojom::FormControlType::kInputNumber: - case blink::mojom::FormControlType::kInputRadio: - case blink::mojom::FormControlType::kInputRange: - case blink::mojom::FormControlType::kInputReset: - case blink::mojom::FormControlType::kInputSearch: - case blink::mojom::FormControlType::kInputSubmit: - case blink::mojom::FormControlType::kInputTelephone: - case blink::mojom::FormControlType::kInputTime: - case blink::mojom::FormControlType::kInputUrl: - case blink::mojom::FormControlType::kInputWeek: - return "other"; - - // not an input type - default: - return "none"; - } -} - -} // namespace - namespace gin { static constexpr auto MenuSourceTypes = @@ -162,12 +117,6 @@ v8::Local<v8::Value> Converter<ContextMenuParamsWithRenderFrameHost>::ToV8( dict.Set("frameCharset", params.frame_charset); dict.Set("referrerPolicy", params.referrer_policy); dict.Set("formControlType", params.form_control_type); - - // NB: inputFieldType is deprecated because the upstream - // field was removed; we are emulating it now until removal - dict.Set("inputFieldType", - FormControlToInputFieldTypeString(params.form_control_type)); - dict.Set("menuSourceType", params.source_type); return gin::ConvertToV8(isolate, dict); diff --git a/spec/ts-smoke/electron/main.ts b/spec/ts-smoke/electron/main.ts index a324586e3f..099ac12148 100644 --- a/spec/ts-smoke/electron/main.ts +++ b/spec/ts-smoke/electron/main.ts @@ -1319,6 +1319,11 @@ win4.webContents.on('scroll-touch-end', () => {}); // @ts-expect-error Removed API win4.webContents.on('crashed', () => {}); +win4.webContents.on('context-menu', (event, params) => { + // @ts-expect-error Removed API + console.log(params.inputFieldType); +}); + // TouchBar // https://github.com/electron/electron/blob/main/docs/api/touch-bar.md
chore
18abeb3add82eac62c72c39db2b4b87080bc69fb
Shelley Vohr
2024-06-19 16:28:07
build: re-enable self-cert codesigning on x64 macOS (#42576) build: re-enable self-cert codesigning
diff --git a/.github/workflows/pipeline-segment-electron-test.yml b/.github/workflows/pipeline-segment-electron-test.yml index a159ec9656..4767e4211d 100644 --- a/.github/workflows/pipeline-segment-electron-test.yml +++ b/.github/workflows/pipeline-segment-electron-test.yml @@ -130,12 +130,12 @@ jobs: unzip -:o dist.zip unzip -:o chromedriver.zip unzip -:o mksnapshot.zip - # - name: Import & Trust Self-Signed Codesigning Cert on MacOS - # if: ${{ inputs.target-platform == 'macos' }} - # run: | - # sudo security authorizationdb write com.apple.trust-settings.admin allow - # cd src/electron - # ./script/codesign/generate-identity.sh + - name: Import & Trust Self-Signed Codesigning Cert on MacOS + if: ${{ inputs.target-platform == 'macos' && inputs.target-arch == 'x64' }} + run: | + sudo security authorizationdb write com.apple.trust-settings.admin allow + cd src/electron + ./script/codesign/generate-identity.sh - name: Run Electron Tests shell: bash env: diff --git a/spec/lib/codesign-helpers.ts b/spec/lib/codesign-helpers.ts index 6b0cf7c43b..a78411b886 100644 --- a/spec/lib/codesign-helpers.ts +++ b/spec/lib/codesign-helpers.ts @@ -8,7 +8,7 @@ const fixturesPath = path.resolve(__dirname, '..', 'fixtures'); export const shouldRunCodesignTests = process.platform === 'darwin' && - !process.env.CI && + !(process.env.CI && process.arch === 'arm64') && !process.mas && !features.isComponentBuild();
build
c548f8f59e4a5fb6cf87ffffd96298f023530559
Fedor Indutny
2023-05-02 00:53:00
feat: net.resolveHost (#37853)
diff --git a/docs/api/net.md b/docs/api/net.md index 590c74f7e3..858ba19ea4 100644 --- a/docs/api/net.md +++ b/docs/api/net.md @@ -129,6 +129,45 @@ won't be able to connect to remote sites. However, a return value of whether a particular connection attempt to a particular remote site will be successful. +#### `net.resolveHost(host, [options])` + +* `host` string - Hostname to resolve. +* `options` Object (optional) + * `queryType` string (optional) - Requested DNS query type. If unspecified, + resolver will pick A or AAAA (or both) based on IPv4/IPv6 settings: + * `A` - Fetch only A records + * `AAAA` - Fetch only AAAA records. + * `source` string (optional) - The source to use for resolved addresses. + Default allows the resolver to pick an appropriate source. Only affects use + of big external sources (e.g. calling the system for resolution or using + DNS). Even if a source is specified, results can still come from cache, + resolving "localhost" or IP literals, etc. One of the following values: + * `any` (default) - Resolver will pick an appropriate source. Results could + come from DNS, MulticastDNS, HOSTS file, etc + * `system` - Results will only be retrieved from the system or OS, e.g. via + the `getaddrinfo()` system call + * `dns` - Results will only come from DNS queries + * `mdns` - Results will only come from Multicast DNS queries + * `localOnly` - No external sources will be used. Results will only come + from fast local sources that are available no matter the source setting, + e.g. cache, hosts file, IP literal resolution, etc. + * `cacheUsage` string (optional) - Indicates what DNS cache entries, if any, + can be used to provide a response. One of the following values: + * `allowed` (default) - Results may come from the host cache if non-stale + * `staleAllowed` - Results may come from the host cache even if stale (by + expiration or network changes) + * `disallowed` - Results will not come from the host cache. + * `secureDnsPolicy` string (optional) - Controls the resolver's Secure DNS + behavior for this request. One of the following values: + * `allow` (default) + * `disable` + +Returns [`Promise<ResolvedHost>`](structures/resolved-host.md) - Resolves with the resolved IP addresses for the `host`. + +This method will resolve hosts from the [default +session](session.md#sessiondefaultsession). To resolve a host from +another session, use [ses.resolveHost()](session.md#sesresolvehosthost-options). + ## Properties ### `net.online` _Readonly_ diff --git a/lib/browser/api/net.ts b/lib/browser/api/net.ts index a2a7198143..7d2ec17563 100644 --- a/lib/browser/api/net.ts +++ b/lib/browser/api/net.ts @@ -12,6 +12,10 @@ export function fetch (input: RequestInfo, init?: RequestInit): Promise<Response return session.defaultSession.fetch(input, init); } +export function resolveHost (host: string, options?: Electron.ResolveHostOptions): Promise<Electron.ResolvedHost> { + return session.defaultSession.resolveHost(host, options); +} + exports.isOnline = isOnline; Object.defineProperty(exports, 'online', {
feat
0df8878da4233c56772152fdc31a7e3357dc3e7a
Aman Gupta
2022-09-22 22:16:11
docs: update the link for Introduction to Node.js (#35761) Updated the link for Introduction to NodeJs
diff --git a/docs/tutorial/tutorial-1-prerequisites.md b/docs/tutorial/tutorial-1-prerequisites.md index 4c73758ab4..164811fc4e 100644 --- a/docs/tutorial/tutorial-1-prerequisites.md +++ b/docs/tutorial/tutorial-1-prerequisites.md @@ -123,7 +123,7 @@ the list of versions in the [electron/releases] repository. [homebrew]: https://brew.sh/ [mdn-guide]: https://developer.mozilla.org/en-US/docs/Learn/ [node]: https://nodejs.org/ -[node-guide]: https://nodejs.dev/learn +[node-guide]: https://nodejs.dev/en/learn/ [node-download]: https://nodejs.org/en/download/ [nvm]: https://github.com/nvm-sh/nvm [process-model]: ./process-model.md
docs
d3bead5e0edb3df5205675e27e0a8fc9dbd6fd74
Niklas Wenzel
2025-02-03 22:19:26
docs: mention C++20 requirement in breaking changes document (#45413) * docs: mention C++20 requirement in breaking changes document * chore: fix linter issue
diff --git a/docs/breaking-changes.md b/docs/breaking-changes.md index 67862f71f8..8e92ef21ff 100644 --- a/docs/breaking-changes.md +++ b/docs/breaking-changes.md @@ -145,6 +145,16 @@ macOS 10.15 (Catalina) is no longer supported by [Chromium](https://chromium-rev Older versions of Electron will continue to run on Catalina, but macOS 11 (Big Sur) or later will be required to run Electron v33.0.0 and higher. +### Behavior Changed: Native modules now require C++20 + +Due to changes made upstream, both +[V8](https://chromium-review.googlesource.com/c/v8/v8/+/5587859) and +[Node.js](https://github.com/nodejs/node/pull/45427) now require C++20 as a +minimum version. Developers using native node modules should build their +modules with `--std=c++20` rather than `--std=c++17`. Images using gcc9 or +lower may need to update to gcc10 in order to compile. See +[#43555](https://github.com/electron/electron/pull/43555) for more details. + ### Deprecated: `systemPreferences.accessibilityDisplayShouldReduceTransparency` The `systemPreferences.accessibilityDisplayShouldReduceTransparency` property is now deprecated in favor of the new `nativeTheme.prefersReducedTransparency`, which provides identical information and works cross-platform.
docs
309d5dade36c391183adef14f36f631524155d66
Keeley Hammond
2024-09-10 16:05:57
feat: add support for system picker in setDisplayMediaRequestHandler (#43581) * tmp * feat: add support for system picker in setDisplayMediaRequestHandler * oops * Apply suggestions from code review Co-authored-by: Erick Zhao <[email protected]> * stuff * well... * seems legit * chore: update patch to handle screenCapturer * feat: modify API to use useSystemPicker * fix: gate ScreenCaptureKitPicker to macos 15 or higher * fix: don't use native picker with legacy media selection * chore: code review, boolean set & docs update * fix: add cancelCallback * docs: clarify session & desktopCapturer docs --------- Co-authored-by: Samuel Attard <[email protected]> Co-authored-by: Samuel Attard <[email protected]> Co-authored-by: Erick Zhao <[email protected]>
diff --git a/docs/api/desktop-capturer.md b/docs/api/desktop-capturer.md index f415e14819..89f6f12006 100644 --- a/docs/api/desktop-capturer.md +++ b/docs/api/desktop-capturer.md @@ -20,7 +20,11 @@ app.whenReady().then(() => { // Grant access to the first screen found. callback({ video: sources[0], audio: 'loopback' }) }) - }) + // If true, use the system picker if available. + // Note: this is currently experimental. If the system picker + // is available, it will be used and the media request handler + // will not be invoked. + }, { useSystemPicker: true }) mainWindow.loadFile('index.html') }) diff --git a/docs/api/session.md b/docs/api/session.md index ad3c10515f..c0312b47df 100644 --- a/docs/api/session.md +++ b/docs/api/session.md @@ -953,7 +953,7 @@ session.fromPartition('some-partition').setPermissionCheckHandler((webContents, }) ``` -#### `ses.setDisplayMediaRequestHandler(handler)` +#### `ses.setDisplayMediaRequestHandler(handler[, opts])` * `handler` Function | null * `request` Object @@ -980,12 +980,18 @@ session.fromPartition('some-partition').setPermissionCheckHandler((webContents, and this is set to `true`, then local playback of audio will not be muted (e.g. using `MediaRecorder` to record `WebFrameMain` with this flag set to `true` will allow audio to pass through to the speakers while recording). Default is `false`. +* `opts` Object (optional) _macOS_ _Experimental_ + * `useSystemPicker` Boolean - true if the available native system picker should be used. Default is `false`. _macOS_ _Experimental_ This handler will be called when web content requests access to display media via the `navigator.mediaDevices.getDisplayMedia` API. Use the [desktopCapturer](desktop-capturer.md) API to choose which stream(s) to grant access to. +`useSystemPicker` allows an application to use the system picker instead of providing a specific video source from `getSources`. +This option is experimental, and currently available for MacOS 15+ only. If the system picker is available and `useSystemPicker` +is set to `true`, the handler will not be invoked. + ```js const { session, desktopCapturer } = require('electron') @@ -994,7 +1000,11 @@ session.defaultSession.setDisplayMediaRequestHandler((request, callback) => { // Grant access to the first screen found. callback({ video: sources[0] }) }) -}) + // Use the system picker if available. + // Note: this is currently experimental. If the system picker + // is available, it will be used and the media request handler + // will not be invoked. +}, { useSystemPicker: true }) ``` Passing a [WebFrameMain](web-frame-main.md) object as a video or audio stream diff --git a/filenames.gni b/filenames.gni index 9a7e3d4e91..aa1148d00a 100644 --- a/filenames.gni +++ b/filenames.gni @@ -270,6 +270,7 @@ filenames = { "shell/browser/api/electron_api_debugger.h", "shell/browser/api/electron_api_desktop_capturer.cc", "shell/browser/api/electron_api_desktop_capturer.h", + "shell/browser/api/electron_api_desktop_capturer_mac.mm", "shell/browser/api/electron_api_dialog.cc", "shell/browser/api/electron_api_download_item.cc", "shell/browser/api/electron_api_download_item.h", diff --git a/lib/browser/api/desktop-capturer.ts b/lib/browser/api/desktop-capturer.ts index 6b9720510f..3ea4d6198c 100644 --- a/lib/browser/api/desktop-capturer.ts +++ b/lib/browser/api/desktop-capturer.ts @@ -1,5 +1,5 @@ import { BrowserWindow } from 'electron/main'; -const { createDesktopCapturer } = process._linkedBinding('electron_browser_desktop_capturer'); +const { createDesktopCapturer, isDisplayMediaSystemPickerAvailable } = process._linkedBinding('electron_browser_desktop_capturer'); const deepEqual = (a: ElectronInternal.GetSourcesOptions, b: ElectronInternal.GetSourcesOptions) => JSON.stringify(a) === JSON.stringify(b); @@ -13,6 +13,8 @@ function isValid (options: Electron.SourcesOptions) { return Array.isArray(options?.types); } +export { isDisplayMediaSystemPickerAvailable }; + export async function getSources (args: Electron.SourcesOptions) { if (!isValid(args)) throw new Error('Invalid options'); diff --git a/lib/browser/api/session.ts b/lib/browser/api/session.ts index 5f9343c1bd..c47c331705 100644 --- a/lib/browser/api/session.ts +++ b/lib/browser/api/session.ts @@ -1,11 +1,37 @@ import { fetchWithSession } from '@electron/internal/browser/api/net-fetch'; import { net } from 'electron/main'; const { fromPartition, fromPath, Session } = process._linkedBinding('electron_browser_session'); +const { isDisplayMediaSystemPickerAvailable } = process._linkedBinding('electron_browser_desktop_capturer'); + +// Fake video source that activates the native system picker +// This is used to get around the need for a screen/window +// id in Chrome's desktopCapturer. +let fakeVideoSourceId = -1; +const systemPickerVideoSource = Object.create(null); +Object.defineProperty(systemPickerVideoSource, 'id', { + get () { + return `window:${fakeVideoSourceId--}:0`; + } +}); +systemPickerVideoSource.name = ''; +Object.freeze(systemPickerVideoSource); Session.prototype.fetch = function (input: RequestInfo, init?: RequestInit) { return fetchWithSession(input, init, this, net.request); }; +Session.prototype.setDisplayMediaRequestHandler = function (handler, opts) { + if (!handler) return this._setDisplayMediaRequestHandler(handler, opts); + + this._setDisplayMediaRequestHandler(async (req, callback) => { + if (opts && opts.useSystemPicker && isDisplayMediaSystemPickerAvailable()) { + return callback({ video: systemPickerVideoSource }); + } + + return handler(req, callback); + }, opts); +}; + export default { fromPartition, fromPath, diff --git a/patches/chromium/.patches b/patches/chromium/.patches index 7c857e69b5..9cc077e89a 100644 --- a/patches/chromium/.patches +++ b/patches/chromium/.patches @@ -130,3 +130,4 @@ chore_remove_reference_to_chrome_browser_themes.patch feat_enable_customizing_symbol_color_in_framecaptionbutton.patch build_expose_webplugininfo_interface_to_electron.patch osr_shared_texture_remove_keyed_mutex_on_win_dxgi.patch +feat_allow_usage_of_sccontentsharingpicker_on_supported_platforms.patch diff --git a/patches/chromium/feat_allow_usage_of_sccontentsharingpicker_on_supported_platforms.patch b/patches/chromium/feat_allow_usage_of_sccontentsharingpicker_on_supported_platforms.patch new file mode 100644 index 0000000000..c03151f2d3 --- /dev/null +++ b/patches/chromium/feat_allow_usage_of_sccontentsharingpicker_on_supported_platforms.patch @@ -0,0 +1,331 @@ +From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 +From: Samuel Attard <[email protected]> +Date: Thu, 8 Aug 2024 08:39:10 -0700 +Subject: feat: allow usage of SCContentSharingPicker on supported platforms + +This is implemented as a magic "window id" that instead of pulling an SCStream manually +instead farms out to the screen picker. + +diff --git a/content/browser/media/capture/desktop_capture_device_mac.cc b/content/browser/media/capture/desktop_capture_device_mac.cc +index 88c56f4dfcc1f8517ef1e8b6f1d37f5ba4d0b2c7..a75493a6d4d8ce8340a2d820eff5eed4e6a95109 100644 +--- a/content/browser/media/capture/desktop_capture_device_mac.cc ++++ b/content/browser/media/capture/desktop_capture_device_mac.cc +@@ -28,7 +28,7 @@ class DesktopCaptureDeviceMac : public IOSurfaceCaptureDeviceBase { + ~DesktopCaptureDeviceMac() override = default; + + // IOSurfaceCaptureDeviceBase: +- void OnStart() override { ++ void OnStart(std::optional<bool> use_native_picker) override { + requested_format_ = capture_params().requested_format; + requested_format_.pixel_format = media::PIXEL_FORMAT_NV12; + DCHECK_GT(requested_format_.frame_size.GetArea(), 0); +diff --git a/content/browser/media/capture/io_surface_capture_device_base_mac.cc b/content/browser/media/capture/io_surface_capture_device_base_mac.cc +index 8a774911ce0f610b2c993976d108f840696c1d02..5ead7287e2d765d043f8b9c0229a2ee825d9f544 100644 +--- a/content/browser/media/capture/io_surface_capture_device_base_mac.cc ++++ b/content/browser/media/capture/io_surface_capture_device_base_mac.cc +@@ -20,7 +20,7 @@ void IOSurfaceCaptureDeviceBase::AllocateAndStart( + client_ = std::move(client); + capture_params_ = params; + +- OnStart(); ++ OnStart(params.use_native_picker); + } + + void IOSurfaceCaptureDeviceBase::StopAndDeAllocate() { +diff --git a/content/browser/media/capture/io_surface_capture_device_base_mac.h b/content/browser/media/capture/io_surface_capture_device_base_mac.h +index 8ac12480f663a74dfbdcf7128a582a81b4474d25..db6802a2603e1d3c3039e49737438124bf2ee1f1 100644 +--- a/content/browser/media/capture/io_surface_capture_device_base_mac.h ++++ b/content/browser/media/capture/io_surface_capture_device_base_mac.h +@@ -25,7 +25,7 @@ class CONTENT_EXPORT IOSurfaceCaptureDeviceBase + ~IOSurfaceCaptureDeviceBase() override; + + // OnStart is called by AllocateAndStart. +- virtual void OnStart() = 0; ++ virtual void OnStart(std::optional<bool> use_native_picker) = 0; + + // OnStop is called by StopAndDeAllocate. + virtual void OnStop() = 0; +diff --git a/content/browser/media/capture/screen_capture_kit_device_mac.mm b/content/browser/media/capture/screen_capture_kit_device_mac.mm +index b6129282c6807702cf88e0a3e2ba233e41a20960..1c2d0c6dd4101fe0bac69e3018bbbedadce224cc 100644 +--- a/content/browser/media/capture/screen_capture_kit_device_mac.mm ++++ b/content/browser/media/capture/screen_capture_kit_device_mac.mm +@@ -24,24 +24,83 @@ + std::optional<gfx::Size>, + std::optional<gfx::Rect>)>; + using ErrorCallback = base::RepeatingClosure; ++using CancelCallback = base::RepeatingClosure; ++ ++API_AVAILABLE(macos(15.0)) ++@interface ScreenCaptureKitPickerHelper ++ : NSObject <SCContentSharingPickerObserver> ++ ++- (void)contentSharingPicker:(SCContentSharingPicker *)picker ++ didCancelForStream:(SCStream *)stream; ++ ++- (void)contentSharingPicker:(SCContentSharingPicker *)picker ++ didUpdateWithFilter:(SCContentFilter *)filter ++ forStream:(SCStream *)stream; ++ ++- (void)contentSharingPickerStartDidFailWithError:(NSError *)error; ++ ++@end ++ ++@implementation ScreenCaptureKitPickerHelper { ++ base::RepeatingCallback<void(SCContentFilter *)> _pickerCallback; ++ ErrorCallback _errorCallback; ++ CancelCallback _cancelCallback; ++} ++ ++- (void)contentSharingPicker:(SCContentSharingPicker *)picker ++ didCancelForStream:(SCStream *)stream { ++ // TODO: This doesn't appear to be called on Apple's side; ++ // implement this logic ++ _cancelCallback.Run(); ++} ++ ++- (void)contentSharingPicker:(SCContentSharingPicker *)picker ++ didUpdateWithFilter:(SCContentFilter *)filter ++ forStream:(SCStream *)stream { ++ if (stream == nil) { ++ _pickerCallback.Run(filter); ++ [picker removeObserver:self]; ++ } ++} ++ ++- (void)contentSharingPickerStartDidFailWithError:(NSError *)error { ++ _errorCallback.Run(); ++} ++ ++- (instancetype)initWithStreamPickCallback:(base::RepeatingCallback<void(SCContentFilter *)>)pickerCallback ++ cancelCallback:(CancelCallback)cancelCallback ++ errorCallback:(ErrorCallback)errorCallback { ++ if (self = [super init]) { ++ _pickerCallback = pickerCallback; ++ _cancelCallback = cancelCallback; ++ _errorCallback = errorCallback; ++ } ++ return self; ++} ++ ++@end + + API_AVAILABLE(macos(12.3)) + @interface ScreenCaptureKitDeviceHelper + : NSObject <SCStreamDelegate, SCStreamOutput> + + - (instancetype)initWithSampleCallback:(SampleCallback)sampleCallback ++ cancelCallback:(CancelCallback)cancelCallback + errorCallback:(ErrorCallback)errorCallback; + @end + + @implementation ScreenCaptureKitDeviceHelper { + SampleCallback _sampleCallback; ++ CancelCallback _cancelCallback; + ErrorCallback _errorCallback; + } + + - (instancetype)initWithSampleCallback:(SampleCallback)sampleCallback ++ cancelCallback:(CancelCallback)cancelCallback + errorCallback:(ErrorCallback)errorCallback { + if (self = [super init]) { + _sampleCallback = sampleCallback; ++ _cancelCallback = cancelCallback; + _errorCallback = errorCallback; + } + return self; +@@ -141,7 +200,8 @@ + (SCStreamConfiguration*)streamConfigurationWithFrameSize:(gfx::Size)frameSize + + class API_AVAILABLE(macos(12.3)) ScreenCaptureKitDeviceMac + : public IOSurfaceCaptureDeviceBase, +- public ScreenCaptureKitResetStreamInterface { ++ public ScreenCaptureKitResetStreamInterface ++ { + public: + explicit ScreenCaptureKitDeviceMac(const DesktopMediaID& source, + SCContentFilter* filter) +@@ -152,18 +212,41 @@ explicit ScreenCaptureKitDeviceMac(const DesktopMediaID& source, + device_task_runner_, + base::BindRepeating(&ScreenCaptureKitDeviceMac::OnStreamSample, + weak_factory_.GetWeakPtr())); ++ CancelCallback cancel_callback = base::BindPostTask( ++ device_task_runner_, ++ base::BindRepeating(&ScreenCaptureKitDeviceMac::OnStreamError, ++ weak_factory_.GetWeakPtr())); + ErrorCallback error_callback = base::BindPostTask( + device_task_runner_, + base::BindRepeating(&ScreenCaptureKitDeviceMac::OnStreamError, + weak_factory_.GetWeakPtr())); + helper_ = [[ScreenCaptureKitDeviceHelper alloc] + initWithSampleCallback:sample_callback ++ cancelCallback:cancel_callback + errorCallback:error_callback]; ++ ++ if (@available(macOS 15.0, *)) { ++ auto picker_callback = base::BindPostTask( ++ device_task_runner_, ++ base::BindRepeating(&ScreenCaptureKitDeviceMac::OnContentFilterReady, weak_factory_.GetWeakPtr()) ++ ); ++ auto* picker_observer = [[ScreenCaptureKitPickerHelper alloc] initWithStreamPickCallback:picker_callback cancelCallback:cancel_callback errorCallback:error_callback]; ++ [[SCContentSharingPicker sharedPicker] addObserver:picker_observer]; ++ } + } + ScreenCaptureKitDeviceMac(const ScreenCaptureKitDeviceMac&) = delete; + ScreenCaptureKitDeviceMac& operator=(const ScreenCaptureKitDeviceMac&) = + delete; +- ~ScreenCaptureKitDeviceMac() override = default; ++ ~ScreenCaptureKitDeviceMac() override { ++ if (@available(macOS 15.0, *)) { ++ auto* picker = [SCContentSharingPicker sharedPicker]; ++ ScreenCaptureKitDeviceMac::active_streams_--; ++ picker.maximumStreamCount = @(ScreenCaptureKitDeviceMac::active_streams_); ++ if (ScreenCaptureKitDeviceMac::active_streams_ == 0 && picker.active) { ++ picker.active = false; ++ } ++ } ++ } + + void OnShareableContentCreated(SCShareableContent* content) { + DCHECK(device_task_runner_->RunsTasksInCurrentSequence()); +@@ -232,7 +315,7 @@ void CreateStream(SCContentFilter* filter) { + return; + } + +- if (@available(macOS 14.0, *)) { ++ if (@available(macOS 15.0, *)) { + // Update the content size. This step is neccessary when used together + // with SCContentSharingPicker. If the Chrome picker is used, it will + // change to retina resolution if applicable. +@@ -241,6 +324,9 @@ void CreateStream(SCContentFilter* filter) { + filter.contentRect.size.height * filter.pointPixelScale); + } + ++ OnContentFilterReady(filter); ++ } ++ void OnContentFilterReady(SCContentFilter* filter) { + gfx::RectF dest_rect_in_frame; + actual_capture_format_ = capture_params().requested_format; + actual_capture_format_.pixel_format = media::PIXEL_FORMAT_NV12; +@@ -254,6 +340,7 @@ void CreateStream(SCContentFilter* filter) { + stream_ = [[SCStream alloc] initWithFilter:filter + configuration:config + delegate:helper_]; ++ + { + NSError* error = nil; + bool add_stream_output_result = +@@ -395,7 +482,7 @@ void OnStreamError() { + if (fullscreen_module_) { + fullscreen_module_->Reset(); + } +- OnStart(); ++ OnStart(std::nullopt); + } else { + client()->OnError(media::VideoCaptureError::kScreenCaptureKitStreamError, + FROM_HERE, "Stream delegate called didStopWithError"); +@@ -418,23 +505,39 @@ void OnUpdateConfigurationError() { + } + + // IOSurfaceCaptureDeviceBase: +- void OnStart() override { ++ void OnStart(std::optional<bool> use_native_picker) override { + DCHECK(device_task_runner_->RunsTasksInCurrentSequence()); +- if (filter_) { +- // SCContentSharingPicker is used where filter_ is set on creation. +- CreateStream(filter_); +- } else { +- // Chrome picker is used. +- auto content_callback = base::BindPostTask( +- device_task_runner_, +- base::BindRepeating( +- &ScreenCaptureKitDeviceMac::OnShareableContentCreated, +- weak_factory_.GetWeakPtr())); +- auto handler = ^(SCShareableContent* content, NSError* error) { +- content_callback.Run(content); +- }; +- [SCShareableContent getShareableContentWithCompletionHandler:handler]; ++ ++ if (@available(macOS 15.0, *)) { ++ constexpr bool DefaultUseNativePicker = true; ++ if (use_native_picker.value_or(DefaultUseNativePicker) && source_.id < 0 && source_.window_id == 0) { ++ auto* picker = [SCContentSharingPicker sharedPicker]; ++ ScreenCaptureKitDeviceMac::active_streams_++; ++ picker.maximumStreamCount = @(ScreenCaptureKitDeviceMac::active_streams_); ++ if (!picker.active) { ++ picker.active = true; ++ } ++ NSMutableArray<NSNumber*>* exclude_ns_windows = [NSMutableArray array]; ++ [[[[NSApplication sharedApplication] windows] filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(NSWindow* win, NSDictionary *bindings) { ++ return [win sharingType] == NSWindowSharingNone; ++ }]] enumerateObjectsUsingBlock:^(NSWindow* win, NSUInteger idx, BOOL *stop) { ++ [exclude_ns_windows addObject:@([win windowNumber])]; ++ }]; ++ picker.defaultConfiguration.excludedWindowIDs = exclude_ns_windows; ++ [picker present]; ++ return; ++ } + } ++ ++ auto content_callback = base::BindPostTask( ++ device_task_runner_, ++ base::BindRepeating( ++ &ScreenCaptureKitDeviceMac::OnShareableContentCreated, ++ weak_factory_.GetWeakPtr())); ++ auto handler = ^(SCShareableContent* content, NSError* error) { ++ content_callback.Run(content); ++ }; ++ [SCShareableContent getShareableContentWithCompletionHandler:handler]; + } + void OnStop() override { + DCHECK(device_task_runner_->RunsTasksInCurrentSequence()); +@@ -492,6 +595,8 @@ void ResetStreamTo(SCWindow* window) override { + } + + private: ++ static int active_streams_; ++ + const DesktopMediaID source_; + SCContentFilter* const filter_; + const scoped_refptr<base::SingleThreadTaskRunner> device_task_runner_; +@@ -521,6 +626,8 @@ void ResetStreamTo(SCWindow* window) override { + base::WeakPtrFactory<ScreenCaptureKitDeviceMac> weak_factory_{this}; + }; + ++int ScreenCaptureKitDeviceMac::active_streams_ = 0; ++ + } // namespace + + // Although ScreenCaptureKit is available in 12.3 there were some bugs that +diff --git a/content/browser/renderer_host/media/in_process_video_capture_device_launcher.cc b/content/browser/renderer_host/media/in_process_video_capture_device_launcher.cc +index 7adf8264cfa9980c4a8414bf0f8bfa9ad70ec0b3..d162612dc70a2b57190aaf558aca8f46cbdedcad 100644 +--- a/content/browser/renderer_host/media/in_process_video_capture_device_launcher.cc ++++ b/content/browser/renderer_host/media/in_process_video_capture_device_launcher.cc +@@ -360,13 +360,15 @@ void InProcessVideoCaptureDeviceLauncher::LaunchDeviceAsync( + std::move(after_start_capture_callback)); + break; + #else ++ media::VideoCaptureParams updated_params = params; ++ updated_params.use_native_picker = stream_type != blink::mojom::MediaStreamType::GUM_DESKTOP_VIDEO_CAPTURE; + // All cases other than tab capture or Aura desktop/window capture. + TRACE_EVENT_INSTANT0(TRACE_DISABLED_BY_DEFAULT("video_and_image_capture"), + "UsingDesktopCapturer", TRACE_EVENT_SCOPE_THREAD); + start_capture_closure = base::BindOnce( + &InProcessVideoCaptureDeviceLauncher:: + DoStartDesktopCaptureOnDeviceThread, +- base::Unretained(this), desktop_id, params, ++ base::Unretained(this), desktop_id, updated_params, + CreateDeviceClient(media::VideoCaptureBufferType::kSharedMemory, + kMaxNumberOfBuffers, std::move(receiver), + std::move(receiver_on_io_thread)), +diff --git a/media/capture/video_capture_types.h b/media/capture/video_capture_types.h +index f2b75f5b2f547ad135c1288bf3639b26dedc8053..ef18724d9f2ea68a47b66fc3981f58a73ac1b51d 100644 +--- a/media/capture/video_capture_types.h ++++ b/media/capture/video_capture_types.h +@@ -355,6 +355,8 @@ struct CAPTURE_EXPORT VideoCaptureParams { + // Flag indicating whether HiDPI mode should be enabled for tab capture + // sessions. + bool is_high_dpi_enabled = true; ++ ++ std::optional<bool> use_native_picker; + }; + + CAPTURE_EXPORT std::ostream& operator<<( diff --git a/shell/browser/api/electron_api_desktop_capturer.cc b/shell/browser/api/electron_api_desktop_capturer.cc index d7b3fecc47..62beae3da1 100644 --- a/shell/browser/api/electron_api_desktop_capturer.cc +++ b/shell/browser/api/electron_api_desktop_capturer.cc @@ -503,6 +503,13 @@ gin::Handle<DesktopCapturer> DesktopCapturer::Create(v8::Isolate* isolate) { return handle; } +// static +#if !BUILDFLAG(IS_MAC) +bool DesktopCapturer::IsDisplayMediaSystemPickerAvailable() { + return false; +} +#endif + gin::ObjectTemplateBuilder DesktopCapturer::GetObjectTemplateBuilder( v8::Isolate* isolate) { return gin::Wrappable<DesktopCapturer>::GetObjectTemplateBuilder(isolate) @@ -524,6 +531,9 @@ void Initialize(v8::Local<v8::Object> exports, gin_helper::Dictionary dict(context->GetIsolate(), exports); dict.SetMethod("createDesktopCapturer", &electron::api::DesktopCapturer::Create); + dict.SetMethod( + "isDisplayMediaSystemPickerAvailable", + &electron::api::DesktopCapturer::IsDisplayMediaSystemPickerAvailable); } } // namespace diff --git a/shell/browser/api/electron_api_desktop_capturer.h b/shell/browser/api/electron_api_desktop_capturer.h index 1a146feb52..ed830856e8 100644 --- a/shell/browser/api/electron_api_desktop_capturer.h +++ b/shell/browser/api/electron_api_desktop_capturer.h @@ -36,6 +36,8 @@ class DesktopCapturer final : public gin::Wrappable<DesktopCapturer>, static gin::Handle<DesktopCapturer> Create(v8::Isolate* isolate); + static bool IsDisplayMediaSystemPickerAvailable(); + void StartHandling(bool capture_window, bool capture_screen, const gfx::Size& thumbnail_size, diff --git a/shell/browser/api/electron_api_desktop_capturer_mac.mm b/shell/browser/api/electron_api_desktop_capturer_mac.mm new file mode 100644 index 0000000000..1ca3093c3f --- /dev/null +++ b/shell/browser/api/electron_api_desktop_capturer_mac.mm @@ -0,0 +1,17 @@ +// Copyright (c) 2024 Salesforce, Inc. +// Use of this source code is governed by the MIT license that can be +// found in the LICENSE file. + +#include "shell/browser/api/electron_api_desktop_capturer.h" + +namespace electron::api { + +// static +bool DesktopCapturer::IsDisplayMediaSystemPickerAvailable() { + if (@available(macOS 15.0, *)) { + return true; + } + return false; +} + +} // namespace electron::api diff --git a/shell/browser/api/electron_api_session.cc b/shell/browser/api/electron_api_session.cc index 1791955b07..fcb23d5ad3 100644 --- a/shell/browser/api/electron_api_session.cc +++ b/shell/browser/api/electron_api_session.cc @@ -1607,7 +1607,7 @@ void Session::FillObjectTemplate(v8::Isolate* isolate, &Session::SetPermissionRequestHandler) .SetMethod("setPermissionCheckHandler", &Session::SetPermissionCheckHandler) - .SetMethod("setDisplayMediaRequestHandler", + .SetMethod("_setDisplayMediaRequestHandler", &Session::SetDisplayMediaRequestHandler) .SetMethod("setDevicePermissionHandler", &Session::SetDevicePermissionHandler) diff --git a/shell/browser/feature_list.cc b/shell/browser/feature_list.cc index 53e5dcd4fa..ed2f12e43b 100644 --- a/shell/browser/feature_list.cc +++ b/shell/browser/feature_list.cc @@ -58,6 +58,11 @@ void InitializeFeatureList() { if (platform_specific_enable_features.size() > 0) { enable_features += std::string(",") + platform_specific_enable_features; } + std::string platform_specific_disable_features = + DisablePlatformSpecificFeatures(); + if (platform_specific_disable_features.size() > 0) { + disable_features += std::string(",") + platform_specific_disable_features; + } base::FeatureList::InitInstance(enable_features, disable_features); } @@ -73,6 +78,9 @@ void InitializeFieldTrials() { std::string EnablePlatformSpecificFeatures() { return ""; } +std::string DisablePlatformSpecificFeatures() { + return ""; +} #endif } // namespace electron diff --git a/shell/browser/feature_list.h b/shell/browser/feature_list.h index 34fdeb5850..c3be0ed97a 100644 --- a/shell/browser/feature_list.h +++ b/shell/browser/feature_list.h @@ -11,6 +11,7 @@ namespace electron { void InitializeFeatureList(); void InitializeFieldTrials(); std::string EnablePlatformSpecificFeatures(); +std::string DisablePlatformSpecificFeatures(); } // namespace electron #endif // ELECTRON_SHELL_BROWSER_FEATURE_LIST_H_ diff --git a/shell/browser/feature_list_mac.mm b/shell/browser/feature_list_mac.mm index cde16007e9..6c57209399 100644 --- a/shell/browser/feature_list_mac.mm +++ b/shell/browser/feature_list_mac.mm @@ -31,4 +31,13 @@ std::string EnablePlatformSpecificFeatures() { return ""; } +std::string DisablePlatformSpecificFeatures() { + if (@available(macOS 14.4, *)) { + // Required to stop timing out getDisplayMedia while waiting for + // the user to select a window with the picker + return "TimeoutHangingVideoCaptureStarts"; + } + return ""; +} + } // namespace electron diff --git a/typings/internal-ambient.d.ts b/typings/internal-ambient.d.ts index 2ac2f55868..27c0b9f32e 100644 --- a/typings/internal-ambient.d.ts +++ b/typings/internal-ambient.d.ts @@ -213,7 +213,7 @@ declare namespace NodeJS { _linkedBinding(name: 'electron_browser_app'): { app: Electron.App, App: Function }; _linkedBinding(name: 'electron_browser_auto_updater'): { autoUpdater: Electron.AutoUpdater }; _linkedBinding(name: 'electron_browser_crash_reporter'): CrashReporterBinding; - _linkedBinding(name: 'electron_browser_desktop_capturer'): { createDesktopCapturer(): ElectronInternal.DesktopCapturer; }; + _linkedBinding(name: 'electron_browser_desktop_capturer'): { createDesktopCapturer(): ElectronInternal.DesktopCapturer; isDisplayMediaSystemPickerAvailable(): boolean; }; _linkedBinding(name: 'electron_browser_event_emitter'): { setEventEmitterPrototype(prototype: Object): void; }; _linkedBinding(name: 'electron_browser_global_shortcut'): { globalShortcut: Electron.GlobalShortcut }; _linkedBinding(name: 'electron_browser_image_view'): { ImageView: any }; diff --git a/typings/internal-electron.d.ts b/typings/internal-electron.d.ts index c2ef3a496c..04e04b311b 100644 --- a/typings/internal-electron.d.ts +++ b/typings/internal-electron.d.ts @@ -127,6 +127,10 @@ declare namespace Electron { type?: 'backgroundPage' | 'window' | 'browserView' | 'remote' | 'webview' | 'offscreen'; } + interface Session { + _setDisplayMediaRequestHandler: Electron.Session['setDisplayMediaRequestHandler']; + } + type CreateWindowFunction = (options: BrowserWindowConstructorOptions) => WebContents; interface Menu {
feat
1c991ff765b068f584e5be3002154977b133eb23
electron-appveyor-updater[bot]
2024-08-15 16:09:47
build: update appveyor image to latest version (#43331) Co-authored-by: electron-appveyor-updater[bot] <161660339+electron-appveyor-updater[bot]@users.noreply.github.com>
diff --git a/appveyor-woa.yml b/appveyor-woa.yml index d6000d91df..0fe5cabd30 100644 --- a/appveyor-woa.yml +++ b/appveyor-woa.yml @@ -29,7 +29,7 @@ version: 1.0.{build} build_cloud: electronhq-16-core -image: e-129.0.6654.0 +image: e-129.0.6656.0 environment: GIT_CACHE_PATH: C:\Users\appveyor\libcc_cache ELECTRON_OUT_DIR: Default diff --git a/appveyor.yml b/appveyor.yml index 2da889b5d6..2410c0c71a 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -29,7 +29,7 @@ version: 1.0.{build} build_cloud: electronhq-16-core -image: e-129.0.6654.0 +image: e-129.0.6656.0 environment: GIT_CACHE_PATH: C:\Users\appveyor\libcc_cache ELECTRON_OUT_DIR: Default
build
ea219dd7022ae88091ae7373b13af9ac7b772697
George Xu
2024-06-11 14:36:36
docs: update timelines for E32 (#42431) docs: update timelines for e32
diff --git a/docs/tutorial/electron-timelines.md b/docs/tutorial/electron-timelines.md index 108c441dd4..a42505e8ac 100644 --- a/docs/tutorial/electron-timelines.md +++ b/docs/tutorial/electron-timelines.md @@ -9,10 +9,11 @@ check out our [Electron Versioning](./electron-versioning.md) doc. | Electron | Alpha | Beta | Stable | EOL | Chrome | Node | Supported | | ------- | ----- | ------- | ------ | ------ | ---- | ---- | ---- | -| 31.0.0 | 2024-Apr-18 | 2024-May-15 | 2024-Jun-11 | 2025-Jan-07 | M126 | TBD | ✅ | +| 32.0.0 | 2024-Jun-14 | 2024-Jul-24 | 2024-Aug-20 | 2025-Mar-04 | M128 | TBD | ✅ | +| 31.0.0 | 2024-Apr-18 | 2024-May-15 | 2024-Jun-11 | 2025-Jan-07 | M126 | v20.14 | ✅ | | 30.0.0 | 2024-Feb-22 | 2024-Mar-20 | 2024-Apr-16 | 2024-Oct-15 | M124 | v20.11 | ✅ | | 29.0.0 | 2023-Dec-07 | 2024-Jan-24 | 2024-Feb-20 | 2024-Aug-20 | M122 | v20.9 | ✅ | -| 28.0.0 | 2023-Oct-11 | 2023-Nov-06 | 2023-Dec-05 | 2024-Jun-11 | M120 | v18.18 | ✅ | +| 28.0.0 | 2023-Oct-11 | 2023-Nov-06 | 2023-Dec-05 | 2024-Jun-11 | M120 | v18.18 | 🚫 | | 27.0.0 | 2023-Aug-17 | 2023-Sep-13 | 2023-Oct-10 | 2024-Apr-16 | M118 | v18.17 | 🚫 | | 26.0.0 | 2023-Jun-01 | 2023-Jun-27 | 2023-Aug-15 | 2024-Feb-20 | M116 | v18.16 | 🚫 | | 25.0.0 | 2023-Apr-10 | 2023-May-02 | 2023-May-30 | 2023-Dec-05 | M114 | v18.15 | 🚫 |
docs
5669a40d5cc8207f8ede8244a28e5ccbf6666207
Shelley Vohr
2024-07-24 14:38:22
feat: add transparency checking to `nativeTheme` (#42862) * feat: add transparency checking to nativeTheme Refs https://chromium-review.googlesource.com/c/chromium/src/+/4684870 * chore: deprecate previous function * chore: fix lint
diff --git a/docs/api/native-theme.md b/docs/api/native-theme.md index 3235eba9a7..e6bdd6c806 100644 --- a/docs/api/native-theme.md +++ b/docs/api/native-theme.md @@ -72,3 +72,7 @@ or is being instructed to use an inverted color scheme. A `boolean` indicating whether Chromium is in forced colors mode, controlled by system accessibility settings. Currently, Windows high contrast is the only system setting that triggers forced colors mode. + +### `nativeTheme.prefersReducedTransparency` _Readonly_ + +A `boolean` that indicates the whether the user has chosen via system accessibility settings to reduce transparency at the OS level. diff --git a/docs/api/system-preferences.md b/docs/api/system-preferences.md index 1c4512bc6a..ad6f72007a 100644 --- a/docs/api/system-preferences.md +++ b/docs/api/system-preferences.md @@ -401,10 +401,12 @@ Returns an object with system animation settings. ## Properties -### `systemPreferences.accessibilityDisplayShouldReduceTransparency()` _macOS_ +### `systemPreferences.accessibilityDisplayShouldReduceTransparency` _macOS_ _Deprecated_ A `boolean` property which determines whether the app avoids using semitransparent backgrounds. This maps to [NSWorkspace.accessibilityDisplayShouldReduceTransparency](https://developer.apple.com/documentation/appkit/nsworkspace/1533006-accessibilitydisplayshouldreduce) +**Deprecated:** Use the new [`nativeTheme.prefersReducedTransparency`](native-theme.md#nativethemeprefersreducedtransparency-readonly) API. + ### `systemPreferences.effectiveAppearance` _macOS_ _Readonly_ A `string` property that can be `dark`, `light` or `unknown`. diff --git a/docs/breaking-changes.md b/docs/breaking-changes.md index 7099131f69..1f5774ca12 100644 --- a/docs/breaking-changes.md +++ b/docs/breaking-changes.md @@ -12,6 +12,20 @@ This document uses the following convention to categorize breaking changes: * **Deprecated:** An API was marked as deprecated. The API will continue to function, but will emit a deprecation warning, and will be removed in a future release. * **Removed:** An API or feature was removed, and is no longer supported by Electron. +## Planned Breaking API Changes (33.0) + +### Deprecated: `systemPreferences.accessibilityDisplayShouldReduceTransparency` + +The `systemPreferences.accessibilityDisplayShouldReduceTransparency` property is now deprecated in favor of the new `nativeTheme.prefersReducedTransparency`, which provides identical information and works cross-platform. + +```js +// Deprecated +const shouldReduceTransparency = systemPreferences.accessibilityDisplayShouldReduceTransparency + +// Replace with: +const prefersReducedTransparency = nativeTheme.prefersReducedTransparency +``` + ## Planned Breaking API Changes (32.0) ### Removed: `File.path` diff --git a/filenames.auto.gni b/filenames.auto.gni index a9a4f6d7c0..574797c555 100644 --- a/filenames.auto.gni +++ b/filenames.auto.gni @@ -354,6 +354,7 @@ auto_filenames = { "lib/browser/message-port-main.ts", "lib/common/api/net-client-request.ts", "lib/common/define-properties.ts", + "lib/common/deprecate.ts", "lib/common/init.ts", "lib/common/webpack-globals-provider.ts", "lib/utility/api/exports/electron.ts", diff --git a/lib/browser/api/system-preferences.ts b/lib/browser/api/system-preferences.ts index 3c17fbc5ad..33c1a4eb7d 100644 --- a/lib/browser/api/system-preferences.ts +++ b/lib/browser/api/system-preferences.ts @@ -1,3 +1,4 @@ +import * as deprecate from '@electron/internal/common/deprecate'; const { systemPreferences } = process._linkedBinding('electron_browser_system_preferences'); if ('getEffectiveAppearance' in systemPreferences) { @@ -7,4 +8,15 @@ if ('getEffectiveAppearance' in systemPreferences) { }); } +if ('accessibilityDisplayShouldReduceTransparency' in systemPreferences) { + const reduceTransparencyDeprecated = deprecate.warnOnce('systemPreferences.accessibilityDisplayShouldReduceTransparency', 'nativeTheme.prefersReducedTransparency'); + const nativeReduceTransparency = systemPreferences.accessibilityDisplayShouldReduceTransparency; + Object.defineProperty(systemPreferences, 'accessibilityDisplayShouldReduceTransparency', { + get: () => { + reduceTransparencyDeprecated(); + return nativeReduceTransparency; + } + }); +} + export default systemPreferences; diff --git a/shell/browser/api/electron_api_native_theme.cc b/shell/browser/api/electron_api_native_theme.cc index 3235f51ac9..a86481e4d6 100644 --- a/shell/browser/api/electron_api_native_theme.cc +++ b/shell/browser/api/electron_api_native_theme.cc @@ -67,6 +67,10 @@ bool NativeTheme::InForcedColorsMode() { return ui_theme_->InForcedColorsMode(); } +bool NativeTheme::GetPrefersReducedTransparency() { + return ui_theme_->GetPrefersReducedTransparency(); +} + #if BUILDFLAG(IS_MAC) const CFStringRef WhiteOnBlack = CFSTR("whiteOnBlack"); const CFStringRef UniversalAccessDomain = CFSTR("com.apple.universalaccess"); @@ -107,7 +111,9 @@ gin::ObjectTemplateBuilder NativeTheme::GetObjectTemplateBuilder( &NativeTheme::ShouldUseHighContrastColors) .SetProperty("shouldUseInvertedColorScheme", &NativeTheme::ShouldUseInvertedColorScheme) - .SetProperty("inForcedColorsMode", &NativeTheme::InForcedColorsMode); + .SetProperty("inForcedColorsMode", &NativeTheme::InForcedColorsMode) + .SetProperty("prefersReducedTransparency", + &NativeTheme::GetPrefersReducedTransparency); } const char* NativeTheme::GetTypeName() { diff --git a/shell/browser/api/electron_api_native_theme.h b/shell/browser/api/electron_api_native_theme.h index a1f7798014..51db378549 100644 --- a/shell/browser/api/electron_api_native_theme.h +++ b/shell/browser/api/electron_api_native_theme.h @@ -46,6 +46,7 @@ class NativeTheme : public gin::Wrappable<NativeTheme>, bool ShouldUseHighContrastColors(); bool ShouldUseInvertedColorScheme(); bool InForcedColorsMode(); + bool GetPrefersReducedTransparency(); // ui::NativeThemeObserver: void OnNativeThemeUpdated(ui::NativeTheme* theme) override; diff --git a/spec/api-native-theme-spec.ts b/spec/api-native-theme-spec.ts index 70bf2f0a02..a6abb6762c 100644 --- a/spec/api-native-theme-spec.ts +++ b/spec/api-native-theme-spec.ts @@ -105,4 +105,10 @@ describe('nativeTheme module', () => { expect(nativeTheme.inForcedColorsMode).to.be.a('boolean'); }); }); + + describe('nativeTheme.prefersReducesTransparency', () => { + it('returns a boolean', () => { + expect(nativeTheme.prefersReducedTransparency).to.be.a('boolean'); + }); + }); });
feat
a6c9aefb4aa37341017359a43d041bcdcacf98e8
Shelley Vohr
2023-05-08 10:39:04
chore: fix TrustedTypes policy in `chrome://accessibility` (#38179) chore: fix TrustedTypes policy in chrome://accessibility
diff --git a/shell/browser/ui/webui/accessibility_ui.cc b/shell/browser/ui/webui/accessibility_ui.cc index 3f9851e673..e8da092393 100644 --- a/shell/browser/ui/webui/accessibility_ui.cc +++ b/shell/browser/ui/webui/accessibility_ui.cc @@ -321,6 +321,10 @@ ElectronAccessibilityUI::ElectronAccessibilityUI(content::WebUI* web_ui) base::BindRepeating(&HandleAccessibilityRequestCallback, web_ui->GetWebContents()->GetBrowserContext())); + html_source->OverrideContentSecurityPolicy( + network::mojom::CSPDirectiveName::TrustedTypes, + "trusted-types parse-html-subset sanitize-inner-html;"); + web_ui->AddMessageHandler( std::make_unique<ElectronAccessibilityUIMessageHandler>()); }
chore
b4acbbb1e90d79819e70e6044930fd4d65252dcc
github-actions[bot]
2023-02-06 13:42:32
build: update appveyor image to latest version (#37151) Co-authored-by: jkleinsc <[email protected]>
diff --git a/appveyor.yml b/appveyor.yml index dafd2bafaf..4295d20641 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -29,7 +29,7 @@ version: 1.0.{build} build_cloud: electronhq-16-core -image: e-111.0.5518.0 +image: e-111.0.5560.0 environment: GIT_CACHE_PATH: C:\Users\appveyor\libcc_cache ELECTRON_OUT_DIR: Default
build
b55d7f4a16293164693618b8a0822370f7f4d46c
Felix Rieseberg
2023-11-06 13:38:12
fix: Do not activate app when calling focus on inactive panel window (#40307) * fix: Do not activate app when calling focus on inactive panel window * Use activate * Use "activate" for all windows
diff --git a/shell/browser/native_window_mac.mm b/shell/browser/native_window_mac.mm index 5bc222a127..cf7672ed78 100644 --- a/shell/browser/native_window_mac.mm +++ b/shell/browser/native_window_mac.mm @@ -469,7 +469,20 @@ void NativeWindowMac::Focus(bool focus) { return; if (focus) { - [[NSApplication sharedApplication] activateIgnoringOtherApps:NO]; + // On macOS < Sonoma, "activateIgnoringOtherApps:NO" would not + // activate apps if focusing a window that is inActive. That + // changed with macOS Sonoma. + // + // There's a slim chance we should have never called + // activateIgnoringOtherApps, but we tried that many years ago + // and saw weird focus bugs on other macOS versions. So, to make + // this safe, we're gating by versions. + if (@available(macOS 14.0, *)) { + [[NSApplication sharedApplication] activate]; + } else { + [[NSApplication sharedApplication] activateIgnoringOtherApps:NO]; + } + [window_ makeKeyAndOrderFront:nil]; } else { [window_ orderOut:nil]; diff --git a/spec/api-browser-window-spec.ts b/spec/api-browser-window-spec.ts index 41986ed7ae..3fc5b94058 100644 --- a/spec/api-browser-window-spec.ts +++ b/spec/api-browser-window-spec.ts @@ -1196,6 +1196,40 @@ describe('BrowserWindow module', () => { await isClosed3; } }); + + ifit(process.platform === 'darwin')('it does not activate the app if focusing an inactive panel', async () => { + // Show to focus app, then remove existing window + w.show(); + w.destroy(); + + // We first need to resign app focus for this test to work + const isInactive = once(app, 'did-resign-active'); + childProcess.execSync('osascript -e \'tell application "Finder" to activate\''); + await isInactive; + + // Create new window + w = new BrowserWindow({ + type: 'panel', + height: 200, + width: 200, + center: true, + show: false + }); + + const isShow = once(w, 'show'); + const isFocus = once(w, 'focus'); + + w.showInactive(); + w.focus(); + + await isShow; + await isFocus; + + const getActiveAppOsa = 'tell application "System Events" to get the name of the first process whose frontmost is true'; + const activeApp = childProcess.execSync(`osascript -e '${getActiveAppOsa}'`).toString().trim(); + + expect(activeApp).to.equal('Finder'); + }); }); // TODO(RaisinTen): Make this work on Windows too.
fix
3e3152008ff569632e0b36d53ac9a24fae515709
Athul Iddya
2023-07-10 13:52:12
fix: remove types from GTK CSS selectors (#39003) Remove types from GTK CSS selectors similar to Chromium's changes in CL 4289229. Fixes #38786 Co-authored-by: Athul Iddya <[email protected]>
diff --git a/shell/browser/ui/views/client_frame_view_linux.cc b/shell/browser/ui/views/client_frame_view_linux.cc index e245f2aa2f..9a52533a5a 100644 --- a/shell/browser/ui/views/client_frame_view_linux.cc +++ b/shell/browser/ui/views/client_frame_view_linux.cc @@ -309,13 +309,13 @@ void ClientFrameViewLinux::PaintAsActiveChanged() { void ClientFrameViewLinux::UpdateThemeValues() { gtk::GtkCssContext window_context = - gtk::AppendCssNodeToStyleContext({}, "GtkWindow#window.background.csd"); + gtk::AppendCssNodeToStyleContext({}, "window.background.csd"); gtk::GtkCssContext headerbar_context = gtk::AppendCssNodeToStyleContext( - {}, "GtkHeaderBar#headerbar.default-decoration.titlebar"); - gtk::GtkCssContext title_context = gtk::AppendCssNodeToStyleContext( - headerbar_context, "GtkLabel#label.title"); + {}, "headerbar.default-decoration.titlebar"); + gtk::GtkCssContext title_context = + gtk::AppendCssNodeToStyleContext(headerbar_context, "label.title"); gtk::GtkCssContext button_context = gtk::AppendCssNodeToStyleContext( - headerbar_context, "GtkButton#button.image-button"); + headerbar_context, "button.image-button"); gtk_style_context_set_parent(headerbar_context, window_context); gtk_style_context_set_parent(title_context, headerbar_context);
fix
4867b5dc7533740f78ba95344067226d0432328c
Shelley Vohr
2025-02-20 23:44:35
refactor: bluetooth in serial chooser when exclusively wireless serial ports are expected (#45671) * refactor: bluetooth in serial chooser when exclusively wireless serial ports are expected https://chromium-review.googlesource.com/c/chromium/src/+/5737296 * chore: review feedback
diff --git a/shell/browser/serial/serial_chooser_controller.cc b/shell/browser/serial/serial_chooser_controller.cc index 4677481982..a871867806 100644 --- a/shell/browser/serial/serial_chooser_controller.cc +++ b/shell/browser/serial/serial_chooser_controller.cc @@ -10,6 +10,8 @@ #include "base/containers/contains.h" #include "base/functional/bind.h" #include "content/public/browser/web_contents.h" +#include "device/bluetooth/bluetooth_adapter.h" +#include "device/bluetooth/bluetooth_adapter_factory.h" #include "device/bluetooth/public/cpp/bluetooth_uuid.h" #include "services/device/public/cpp/bluetooth/bluetooth_utils.h" #include "services/device/public/mojom/serial.mojom.h" @@ -65,6 +67,8 @@ namespace electron { namespace { +using ::device::BluetoothAdapter; +using ::device::BluetoothAdapterFactory; using ::device::mojom::SerialPortType; bool FilterMatchesPort(const blink::mojom::SerialPortFilter& filter, @@ -124,8 +128,11 @@ SerialChooserController::SerialChooserController( web_contents_->GetBrowserContext()) ->AsWeakPtr(); DCHECK(chooser_context_); - chooser_context_->GetPortManager()->GetDevices(base::BindOnce( - &SerialChooserController::OnGetDevices, weak_factory_.GetWeakPtr())); + + base::SequencedTaskRunner::GetCurrentDefault()->PostTask( + FROM_HERE, base::BindOnce(&SerialChooserController::GetDevices, + weak_factory_.GetWeakPtr())); + observation_.Observe(chooser_context_.get()); } @@ -140,6 +147,29 @@ api::Session* SerialChooserController::GetSession() { return api::Session::FromBrowserContext(web_contents_->GetBrowserContext()); } +void SerialChooserController::GetDevices() { + if (IsWirelessSerialPortOnly()) { + if (!adapter_) { + BluetoothAdapterFactory::Get()->GetAdapter(base::BindOnce( + &SerialChooserController::OnGetAdapter, weak_factory_.GetWeakPtr(), + base::BindOnce(&SerialChooserController::GetDevices, + weak_factory_.GetWeakPtr()))); + return; + } + } + + chooser_context_->GetPortManager()->GetDevices(base::BindOnce( + &SerialChooserController::OnGetDevices, weak_factory_.GetWeakPtr())); +} + +void SerialChooserController::AdapterPoweredChanged(BluetoothAdapter* adapter, + bool powered) { + // TODO(codebytere): maybe emit an event here? + if (powered) { + GetDevices(); + } +} + void SerialChooserController::OnPortAdded( const device::mojom::SerialPortInfo& port) { if (!DisplayDevice(port)) @@ -196,6 +226,7 @@ void SerialChooserController::OnGetDevices( return port1->path.BaseName() < port2->path.BaseName(); }); + ports_.clear(); for (auto& port : ports) { if (DisplayDevice(*port)) ports_.push_back(std::move(port)); @@ -235,5 +266,33 @@ void SerialChooserController::RunCallback( std::move(callback_).Run(std::move(port)); } } +void SerialChooserController::OnGetAdapter( + base::OnceClosure callback, + scoped_refptr<BluetoothAdapter> adapter) { + CHECK(adapter); + adapter_ = std::move(adapter); + adapter_observation_.Observe(adapter_.get()); + std::move(callback).Run(); +} + +bool SerialChooserController::IsWirelessSerialPortOnly() const { + if (allowed_bluetooth_service_class_ids_.empty()) { + return false; + } + + // The system's wired and wireless serial ports can be shown if there is no + // filter. + if (filters_.empty()) { + return false; + } + + // Check if all the filters are meant for serial port from Bluetooth device. + for (const auto& filter : filters_) { + if (!filter->bluetooth_service_class_id) { + return false; + } + } + return true; +} } // namespace electron diff --git a/shell/browser/serial/serial_chooser_controller.h b/shell/browser/serial/serial_chooser_controller.h index 603fa45154..e88db05bb8 100644 --- a/shell/browser/serial/serial_chooser_controller.h +++ b/shell/browser/serial/serial_chooser_controller.h @@ -12,6 +12,7 @@ #include "base/scoped_observation.h" #include "content/public/browser/global_routing_id.h" #include "content/public/browser/serial_chooser.h" +#include "device/bluetooth/bluetooth_adapter.h" #include "services/device/public/mojom/serial.mojom-forward.h" #include "shell/browser/serial/serial_chooser_context.h" #include "third_party/blink/public/mojom/serial/serial.mojom-forward.h" @@ -31,7 +32,8 @@ class ElectronSerialDelegate; // SerialChooserController provides data for the Serial API permission prompt. class SerialChooserController final - : private SerialChooserContext::PortObserver { + : private SerialChooserContext::PortObserver, + private device::BluetoothAdapter::Observer { public: SerialChooserController( content::RenderFrameHost* render_frame_host, @@ -55,12 +57,21 @@ class SerialChooserController final void OnPermissionRevoked(const url::Origin& origin) override {} void OnSerialChooserContextShutdown() override; + // BluetoothAdapter::Observer + void AdapterPoweredChanged(device::BluetoothAdapter* adapter, + bool powered) override; + private: api::Session* GetSession(); + void GetDevices(); void OnGetDevices(std::vector<device::mojom::SerialPortInfoPtr> ports); bool DisplayDevice(const device::mojom::SerialPortInfo& port) const; void RunCallback(device::mojom::SerialPortInfoPtr port); void OnDeviceChosen(const std::string& port_id); + void OnGetAdapter(base::OnceClosure callback, + scoped_refptr<device::BluetoothAdapter> adapter); + // Whether it will only show ports from bluetooth devices. + [[nodiscard]] bool IsWirelessSerialPortOnly() const; base::WeakPtr<content::WebContents> web_contents_; @@ -77,8 +88,12 @@ class SerialChooserController final std::vector<device::mojom::SerialPortInfoPtr> ports_; - base::WeakPtr<ElectronSerialDelegate> serial_delegate_; + scoped_refptr<device::BluetoothAdapter> adapter_; + base::ScopedObservation<device::BluetoothAdapter, + device::BluetoothAdapter::Observer> + adapter_observation_{this}; + base::WeakPtr<ElectronSerialDelegate> serial_delegate_; content::GlobalRenderFrameHostId render_frame_host_id_; base::WeakPtrFactory<SerialChooserController> weak_factory_{this};
refactor
46bed807ca362aa415821c3d3808f79b93af0524
electron-appveyor-updater[bot]
2024-08-22 10:12:57
build: update appveyor image to latest version (#43369) Co-authored-by: electron-appveyor-updater[bot] <161660339+electron-appveyor-updater[bot]@users.noreply.github.com>
diff --git a/appveyor-woa.yml b/appveyor-woa.yml index 0fe5cabd30..2da029e224 100644 --- a/appveyor-woa.yml +++ b/appveyor-woa.yml @@ -29,7 +29,7 @@ version: 1.0.{build} build_cloud: electronhq-16-core -image: e-129.0.6656.0 +image: e-129.0.6664.0 environment: GIT_CACHE_PATH: C:\Users\appveyor\libcc_cache ELECTRON_OUT_DIR: Default diff --git a/appveyor.yml b/appveyor.yml index 2410c0c71a..d654f6e42b 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -29,7 +29,7 @@ version: 1.0.{build} build_cloud: electronhq-16-core -image: e-129.0.6656.0 +image: e-129.0.6664.0 environment: GIT_CACHE_PATH: C:\Users\appveyor\libcc_cache ELECTRON_OUT_DIR: Default
build
3609fc7402881b1d51f6c56249506d5dd3fcbe93
Albert Xing
2023-12-01 11:37:52
fix: clean up devtools frontend_host on webcontents destroy (#40666) * fix: clean up devtools frontend_host on destroy * chore: use IsInPrimaryMainFrame instead of IsInMainFrame * test: add a test for re-opening devtools
diff --git a/shell/browser/ui/inspectable_web_contents.cc b/shell/browser/ui/inspectable_web_contents.cc index b2488e6954..cf47c78eb6 100644 --- a/shell/browser/ui/inspectable_web_contents.cc +++ b/shell/browser/ui/inspectable_web_contents.cc @@ -1007,6 +1007,7 @@ void InspectableWebContents::WebContentsDestroyed() { Observe(nullptr); Detach(); embedder_message_dispatcher_.reset(); + frontend_host_.reset(); if (view_ && view_->GetDelegate()) view_->GetDelegate()->DevToolsClosed(); @@ -1052,7 +1053,7 @@ void InspectableWebContents::OnWebContentsFocused( void InspectableWebContents::ReadyToCommitNavigation( content::NavigationHandle* navigation_handle) { - if (navigation_handle->IsInMainFrame()) { + if (navigation_handle->IsInPrimaryMainFrame()) { if (navigation_handle->GetRenderFrameHost() == GetDevToolsWebContents()->GetPrimaryMainFrame() && frontend_host_) { @@ -1069,7 +1070,7 @@ void InspectableWebContents::ReadyToCommitNavigation( void InspectableWebContents::DidFinishNavigation( content::NavigationHandle* navigation_handle) { - if (navigation_handle->IsInMainFrame() || + if (navigation_handle->IsInPrimaryMainFrame() || !navigation_handle->GetURL().SchemeIs("chrome-extension") || !navigation_handle->HasCommitted()) return; diff --git a/spec/api-web-contents-spec.ts b/spec/api-web-contents-spec.ts index cfd366554f..ba517e831b 100644 --- a/spec/api-web-contents-spec.ts +++ b/spec/api-web-contents-spec.ts @@ -639,6 +639,24 @@ describe('webContents module', () => { await devtoolsOpened; expect(w.webContents.getDevToolsTitle()).to.equal('myTitle'); }); + + it('can re-open devtools', async () => { + const w = new BrowserWindow({ show: false }); + const devtoolsOpened = once(w.webContents, 'devtools-opened'); + w.webContents.openDevTools({ mode: 'detach', activate: true }); + await devtoolsOpened; + expect(w.webContents.isDevToolsOpened()).to.be.true(); + + const devtoolsClosed = once(w.webContents, 'devtools-closed'); + w.webContents.closeDevTools(); + await devtoolsClosed; + expect(w.webContents.isDevToolsOpened()).to.be.false(); + + const devtoolsOpened2 = once(w.webContents, 'devtools-opened'); + w.webContents.openDevTools({ mode: 'detach', activate: true }); + await devtoolsOpened2; + expect(w.webContents.isDevToolsOpened()).to.be.true(); + }); }); describe('setDevToolsTitle() API', () => {
fix
00d96970cb4879773b8b4651f9e7136db383243e
Shelley Vohr
2023-07-18 22:58:26
build: fixup Codespaces build-tools setup (#39138) * build: fixup Codespaces build-tools setup * oops evm.testing1.json -> evm.testing.json
diff --git a/.devcontainer/on-create-command.sh b/.devcontainer/on-create-command.sh index ce3fb5ca3e..4e9ffd6f23 100755 --- a/.devcontainer/on-create-command.sh +++ b/.devcontainer/on-create-command.sh @@ -16,6 +16,8 @@ ln -s $buildtools_configs $buildtools/configs # Write the gclient config if it does not already exist if [ ! -f $gclient_root/.gclient ]; then + echo "Creating gclient config" + echo "solutions = [ { \"name\" : \"src/electron\", \"url\" : \"https://github.com/electron/electron\", @@ -32,6 +34,8 @@ fi # Write the default buildtools config file if it does # not already exist if [ ! -f $buildtools/configs/evm.testing.json ]; then + echo "Creating build-tools testing config" + write_config() { echo " { @@ -53,7 +57,7 @@ if [ ! -f $buildtools/configs/evm.testing.json ]; then \"CHROMIUM_BUILDTOOLS_PATH\": \"/workspaces/gclient/src/buildtools\", \"GIT_CACHE_PATH\": \"/workspaces/gclient/.git-cache\" }, - \"$schema\": \"file:///home/builduser/.electron_build_tools/evm-config.schema.json\" + \"\$schema\": \"file:///home/builduser/.electron_build_tools/evm-config.schema.json\" } " >$buildtools/configs/evm.testing.json } @@ -67,10 +71,12 @@ if [ ! -f $buildtools/configs/evm.testing.json ]; then # if it works we can use the goma cluster export NOTGOMA_CODESPACES_TOKEN=$GITHUB_TOKEN if e d goma_auth login; then + echo "$GITHUB_USER has GOMA access - switching to cluster mode" write_config cluster fi else - # Even if the config file existed we still need to re-auth with the goma - # cluster + echo "build-tools testing config already exists" + + # Re-auth with the goma cluster regardless. NOTGOMA_CODESPACES_TOKEN=$GITHUB_TOKEN e d goma_auth login || true fi
build
9df092e034f25cdbe035f942ec4adc46f1e85190
Charles Kerr
2024-10-02 15:36:06
fix: remove use of deprecated API base::Hash() (#44076)
diff --git a/shell/browser/notifications/win/windows_toast_notification.cc b/shell/browser/notifications/win/windows_toast_notification.cc index 9c0947b2d0..b4e39ccd77 100644 --- a/shell/browser/notifications/win/windows_toast_notification.cc +++ b/shell/browser/notifications/win/windows_toast_notification.cc @@ -70,8 +70,8 @@ void DebugLog(std::string_view log_msg) { LOG(INFO) << log_msg; } -std::wstring GetTag(const std::string& notification_id) { - return base::NumberToWString(base::Hash(notification_id)); +std::wstring GetTag(const std::string_view notification_id) { + return base::NumberToWString(base::FastHash(notification_id)); } } // namespace
fix
d93285dde1bb8b2184e262a447875e87d471574f
John Kleinschmidt
2024-10-11 06:08:51
ci: don't call datadog test logging on forks (#44181)
diff --git a/.github/workflows/pipeline-segment-electron-test.yml b/.github/workflows/pipeline-segment-electron-test.yml index 137fe91996..5282ac11e2 100644 --- a/.github/workflows/pipeline-segment-electron-test.yml +++ b/.github/workflows/pipeline-segment-electron-test.yml @@ -196,7 +196,10 @@ jobs: DD_API_KEY: ${{ secrets.DD_API_KEY }} DD_CIVISIBILITY_LOGS_ENABLED: true DD_TAGS: "os.architecture:${{ inputs.target-arch }},os.family:${{ inputs.target-platform }},os.platform:${{ inputs.target-platform }},asan:${{ inputs.is-asan }}" - run: datadog-ci junit upload src/electron/junit/test-results-main.xml + run: | + if ! [ -z $DD_API_KEY ]; then + datadog-ci junit upload src/electron/junit/test-results-main.xml + fi if: always() && !cancelled() - name: Upload Test Artifacts if: always() && !cancelled() diff --git a/appveyor-woa.yml b/appveyor-woa.yml index b5823be68c..efe6ce71f2 100644 --- a/appveyor-woa.yml +++ b/appveyor-woa.yml @@ -335,7 +335,7 @@ for: # - ps: $blockRdp = $true; iex ((new-object net.webclient).DownloadString('https://raw.githubusercontent.com/appveyor/ci/master/scripts/enable-rdp.ps1')) - if exist electron\junit\test-results-main.xml ( appveyor-retry appveyor PushArtifact electron\junit\test-results-main.xml ) - ps: | - if ($env:RUN_TESTS -eq 'true') { + if ($env:DD_API_KEY) { $env:DD_GIT_COMMIT_SHA = $env:APPVEYOR_REPO_COMMIT $env:DD_GIT_BRANCH = $env:APPVEYOR_PULL_REQUEST_HEAD_REPO_BRANCH $env:DD_TAGS = "os.architecture:$env:TARGET_ARCH,os.family:windows,os.platform:win32" diff --git a/appveyor.yml b/appveyor.yml index 9df8a5b83c..8231c28d05 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -330,7 +330,7 @@ for: # - ps: $blockRdp = $true; iex ((new-object net.webclient).DownloadString('https://raw.githubusercontent.com/appveyor/ci/master/scripts/enable-rdp.ps1')) - if exist electron\junit\test-results-main.xml ( appveyor-retry appveyor PushArtifact electron\junit\test-results-main.xml ) - ps: | - if ($env:RUN_TESTS -eq 'true') { + if ($env:RUN_TESTS -eq 'true' -And $env:DD_API_KEY) { $env:DD_GIT_COMMIT_SHA = $env:APPVEYOR_REPO_COMMIT $env:DD_GIT_BRANCH = $env:APPVEYOR_PULL_REQUEST_HEAD_REPO_BRANCH $env:DD_TAGS = "os.architecture:$env:TARGET_ARCH,os.family:windows,os.platform:win32"
ci
4e85bb921bef97a5bedb4188d0e360ec4a0b70c0
Jeremy Rose
2023-03-06 16:24:52
docs: remove misleading info from will-finish-launching docs (#37514)
diff --git a/docs/api/app.md b/docs/api/app.md index cd6eb3aab9..e29973ad52 100755 --- a/docs/api/app.md +++ b/docs/api/app.md @@ -23,8 +23,7 @@ The `app` object emits the following events: Emitted when the application has finished basic startup. On Windows and Linux, the `will-finish-launching` event is the same as the `ready` event; on macOS, this event represents the `applicationWillFinishLaunching` notification of -`NSApplication`. You would usually set up listeners for the `open-file` and -`open-url` events here, and start the crash reporter and auto updater. +`NSApplication`. In most cases, you should do everything in the `ready` event handler.
docs
c05051e307a2f1ec611bce744ed830c6ff51839a
Shelley Vohr
2023-05-16 14:29:01
chore: remove obsoleted `DecrementCapturerCount` patch (#38294) chore: remove obsoleted DecrementCapturerCount patch
diff --git a/patches/chromium/.patches b/patches/chromium/.patches index 37137b1d45..627b4cde97 100644 --- a/patches/chromium/.patches +++ b/patches/chromium/.patches @@ -84,7 +84,6 @@ logging_win32_only_create_a_console_if_logging_to_stderr.patch fix_media_key_usage_with_globalshortcuts.patch feat_expose_raw_response_headers_from_urlloader.patch process_singleton.patch -fix_expose_decrementcapturercount_in_web_contents_impl.patch add_ui_scopedcliboardwriter_writeunsaferawdata.patch feat_add_data_parameter_to_processsingleton.patch load_v8_snapshot_in_browser_process.patch diff --git a/patches/chromium/fix_expose_decrementcapturercount_in_web_contents_impl.patch b/patches/chromium/fix_expose_decrementcapturercount_in_web_contents_impl.patch deleted file mode 100644 index 85446f4d99..0000000000 --- a/patches/chromium/fix_expose_decrementcapturercount_in_web_contents_impl.patch +++ /dev/null @@ -1,37 +0,0 @@ -From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 -From: deepak1556 <[email protected]> -Date: Fri, 3 Sep 2021 18:28:51 -0700 -Subject: fix: expose DecrementCapturerCount in web_contents_impl - -This was made private in https://chromium-review.googlesource.com/c/chromium/src/+/2807829 but -we invoke it in order to expose contents.decrementCapturerCount([stayHidden, stayAwake]) -to users. We should try to upstream this. - -diff --git a/content/browser/web_contents/web_contents_impl.h b/content/browser/web_contents/web_contents_impl.h -index 69f9ffbf4826421491118a0b200d6c71e41f8950..c3b7f6fa146ac335b0d18a749a61600cf8241c8d 100644 ---- a/content/browser/web_contents/web_contents_impl.h -+++ b/content/browser/web_contents/web_contents_impl.h -@@ -1860,7 +1860,7 @@ class CONTENT_EXPORT WebContentsImpl : public WebContents, - // IncrementCapturerCount() is destructed. - void DecrementCapturerCount(bool stay_hidden, - bool stay_awake, -- bool is_activity = true); -+ bool is_activity = true) override; - - // Calculates the PageVisibilityState for |visibility|, taking the capturing - // state into account. -diff --git a/content/public/browser/web_contents.h b/content/public/browser/web_contents.h -index 44d75c043805f9bfb4b08741fc652aafc6c50740..41c15ba67ad66245fdac2ada8e9f0de755fe01be 100644 ---- a/content/public/browser/web_contents.h -+++ b/content/public/browser/web_contents.h -@@ -702,6 +702,10 @@ class WebContents : public PageNavigator, - bool stay_awake, - bool is_activity = true) = 0; - -+ virtual void DecrementCapturerCount(bool stay_hidden, -+ bool stay_awake, -+ bool is_activity = true) = 0; -+ - // Getter for the capture handle, which allows a captured application to - // opt-in to exposing information to its capturer(s). - virtual const blink::mojom::CaptureHandleConfig& GetCaptureHandleConfig() = 0;
chore
ff05d4a96ca9652bea76f63270c0b19c0707a4e1
Dietrich Ayala
2025-02-27 10:32:42
docs: dialog.md - typo fix s/wndow/window/ (#45831) Update dialog.md - typo fix
diff --git a/docs/api/dialog.md b/docs/api/dialog.md index 27590bf6c2..a3a18584e6 100644 --- a/docs/api/dialog.md +++ b/docs/api/dialog.md @@ -228,7 +228,7 @@ The `filters` specifies an array of file types that can be displayed, see **Note:** On macOS, using the asynchronous version is recommended to avoid issues when expanding and collapsing the dialog. -### `dialog.showMessageBoxSync([wndow, ]options)` +### `dialog.showMessageBoxSync([window, ]options)` * `window` [BaseWindow](base-window.md) (optional) * `options` Object
docs
73b7aac6a413ed044e018947e8e7741ecb309bcf
Alexey Kuzmin
2023-02-17 10:14:00
test: fix "crash cases" tests not failing properly (#37304) * test: fix "crash cases" tests not failing properly * fixup! test: fix "crash cases" tests not failing properly
diff --git a/spec/crash-spec.ts b/spec/crash-spec.ts index 5cb9e64f5a..ab517120e5 100644 --- a/spec/crash-spec.ts +++ b/spec/crash-spec.ts @@ -8,7 +8,7 @@ const fixturePath = path.resolve(__dirname, 'fixtures', 'crash-cases'); let children: cp.ChildProcessWithoutNullStreams[] = []; -const runFixtureAndEnsureCleanExit = (args: string[]) => { +const runFixtureAndEnsureCleanExit = async (args: string[]) => { let out = ''; const child = cp.spawn(process.execPath, args); children.push(child); @@ -18,17 +18,20 @@ const runFixtureAndEnsureCleanExit = (args: string[]) => { child.stderr.on('data', (chunk: Buffer) => { out += chunk.toString(); }); - return new Promise<void>((resolve) => { + + type CodeAndSignal = {code: number | null, signal: NodeJS.Signals | null}; + const { code, signal } = await new Promise<CodeAndSignal>((resolve) => { child.on('exit', (code, signal) => { - if (code !== 0 || signal !== null) { - console.error(out); - } - expect(signal).to.equal(null, 'exit signal should be null'); - expect(code).to.equal(0, 'should have exited with code 0'); - children = children.filter(c => c !== child); - resolve(); + resolve({ code, signal }); }); }); + if (code !== 0 || signal !== null) { + console.error(out); + } + children = children.filter(c => c !== child); + + expect(signal).to.equal(null, 'exit signal should be null'); + expect(code).to.equal(0, 'should have exited with code 0'); }; const shouldRunCase = (crashCase: string) => { diff --git a/spec/modules-spec.ts b/spec/modules-spec.ts index fbf71c5f98..7b639f228b 100644 --- a/spec/modules-spec.ts +++ b/spec/modules-spec.ts @@ -62,10 +62,10 @@ describe('modules support', () => { ifit(features.isRunAsNodeEnabled())('can be required in node binary', async function () { const child = childProcess.fork(path.join(fixtures, 'module', 'uv-dlopen.js')); - await new Promise<void>(resolve => child.once('exit', (exitCode) => { - expect(exitCode).to.equal(0); - resolve(); + const exitCode = await new Promise<number | null>(resolve => child.once('exit', (exitCode) => { + resolve(exitCode); })); + expect(exitCode).to.equal(0); }); });
test
f25c87dc7024397526bbe221efdaa0260392c243
Ryan Manuel
2022-09-15 15:21:16
feat: allow custom v8 snapshots to be used in the main process and the default snapshot in the renderer process (#35266) * Updates to allow for using a custom v8 snapshot file name * Allow using a custom v8 snapshot file name * Fix up patch due to merge * Use fuse to set up custom v8 snapshot file in browser process * Refactor to use delegate instead of command line parameter * Refactoring * Update due to merge * PR comments * Rename patch * Rename patch
diff --git a/build/fuses/fuses.json5 b/build/fuses/fuses.json5 index f4984aa2a1..e8df5ffd7a 100644 --- a/build/fuses/fuses.json5 +++ b/build/fuses/fuses.json5 @@ -7,5 +7,6 @@ "node_options": "1", "node_cli_inspect": "1", "embedded_asar_integrity_validation": "0", - "only_load_app_from_asar": "0" + "only_load_app_from_asar": "0", + "load_browser_process_specific_v8_snapshot": "0" } diff --git a/docs/tutorial/fuses.md b/docs/tutorial/fuses.md index bb0c61b475..d933a841c4 100644 --- a/docs/tutorial/fuses.md +++ b/docs/tutorial/fuses.md @@ -54,6 +54,13 @@ For more information on how to use asar integrity validation please read the [As The onlyLoadAppFromAsar fuse changes the search system that Electron uses to locate your app code. By default Electron will search in the following order `app.asar` -> `app` -> `default_app.asar`. When this fuse is enabled the search order becomes a single entry `app.asar` thus ensuring that when combined with the `embeddedAsarIntegrityValidation` fuse it is impossible to load non-validated code. +### `loadBrowserProcessSpecificV8Snapshot` + +**Default:** Disabled +**@electron/fuses:** `FuseV1Options.LoadBrowserProcessSpecificV8Snapshot` + +The loadBrowserProcessSpecificV8Snapshot fuse changes which V8 snapshot file is used for the browser process. By default Electron's processes will all use the same V8 snapshot file. When this fuse is enabled the browser process uses the file called `browser_v8_context_snapshot.bin` for its V8 snapshot. The other processes will use the V8 snapshot file that they normally do. + ## How do I flip the fuses? ### The easy way diff --git a/patches/chromium/.patches b/patches/chromium/.patches index 517793caf9..efa176d161 100644 --- a/patches/chromium/.patches +++ b/patches/chromium/.patches @@ -121,3 +121,4 @@ fix_revert_emulationhandler_update_functions_to_early_return.patch fix_crash_loading_non-standard_schemes_in_iframes.patch disable_optimization_guide_for_preconnect_feature.patch fix_return_v8_value_from_localframe_requestexecutescript.patch +create_browser_v8_snapshot_file_name_fuse.patch diff --git a/patches/chromium/create_browser_v8_snapshot_file_name_fuse.patch b/patches/chromium/create_browser_v8_snapshot_file_name_fuse.patch new file mode 100644 index 0000000000..6b074078b5 --- /dev/null +++ b/patches/chromium/create_browser_v8_snapshot_file_name_fuse.patch @@ -0,0 +1,156 @@ +From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 +From: Ryan Manuel <[email protected]> +Date: Thu, 4 Aug 2022 22:37:01 -0500 +Subject: Create browser v8 snapshot file name fuse + +By default, chromium sets up one v8 snapshot to be used in all v8 contexts. This patch allows consumers +to have a dedicated browser process v8 snapshot defined by the file `browser_v8_context_snapshot.bin`. + +diff --git a/content/app/content_main_runner_impl.cc b/content/app/content_main_runner_impl.cc +index 6242f0a0070b2b862f9fa5ed70825a16d6e270ef..af355d4b0adb509f6b04d8bc2eddbb3a6b3c9a08 100644 +--- a/content/app/content_main_runner_impl.cc ++++ b/content/app/content_main_runner_impl.cc +@@ -37,6 +37,7 @@ + #include "base/process/memory.h" + #include "base/process/process.h" + #include "base/process/process_handle.h" ++#include "base/strings/string_piece.h" + #include "base/strings/string_number_conversions.h" + #include "base/strings/string_util.h" + #include "base/task/thread_pool/thread_pool_instance.h" +@@ -232,8 +233,13 @@ std::string GetSnapshotDataDescriptor(const base::CommandLine& command_line) { + + #endif + +-void LoadV8SnapshotFile(const base::CommandLine& command_line) { ++void LoadV8SnapshotFile(const raw_ptr<ContentMainDelegate> delegate, const base::CommandLine& command_line) { + const gin::V8SnapshotFileType snapshot_type = GetSnapshotType(command_line); ++ base::StringPiece browser_v8_snapshot_file_name = delegate->GetBrowserV8SnapshotFilename(); ++ if (!browser_v8_snapshot_file_name.empty()) { ++ gin::V8Initializer::LoadV8SnapshotFromFileName(browser_v8_snapshot_file_name, snapshot_type); ++ return; ++ } + #if BUILDFLAG(IS_POSIX) && !BUILDFLAG(IS_MAC) + base::FileDescriptorStore& file_descriptor_store = + base::FileDescriptorStore::GetInstance(); +@@ -262,11 +268,12 @@ bool ShouldLoadV8Snapshot(const base::CommandLine& command_line, + + #endif // V8_USE_EXTERNAL_STARTUP_DATA + +-void LoadV8SnapshotIfNeeded(const base::CommandLine& command_line, ++void LoadV8SnapshotIfNeeded(const raw_ptr<ContentMainDelegate> delegate, ++ const base::CommandLine& command_line, + const std::string& process_type) { + #if defined(V8_USE_EXTERNAL_STARTUP_DATA) + if (ShouldLoadV8Snapshot(command_line, process_type)) +- LoadV8SnapshotFile(command_line); ++ LoadV8SnapshotFile(delegate, command_line); + #endif // V8_USE_EXTERNAL_STARTUP_DATA + } + +@@ -925,7 +932,7 @@ int ContentMainRunnerImpl::Initialize(ContentMainParams params) { + return TerminateForFatalInitializationError(); + #endif // BUILDFLAG(IS_ANDROID) && (ICU_UTIL_DATA_IMPL == ICU_UTIL_DATA_FILE) + +- LoadV8SnapshotIfNeeded(command_line, process_type); ++ LoadV8SnapshotIfNeeded(delegate_, command_line, process_type); + + blink::TrialTokenValidator::SetOriginTrialPolicyGetter( + base::BindRepeating([]() -> blink::OriginTrialPolicy* { +diff --git a/content/public/app/content_main_delegate.cc b/content/public/app/content_main_delegate.cc +index 5450eb6ba565164953b778f861d8fc75a06b6115..3f15d5a83d6e8011da09da178a0a9dfd2dd95d30 100644 +--- a/content/public/app/content_main_delegate.cc ++++ b/content/public/app/content_main_delegate.cc +@@ -5,6 +5,7 @@ + #include "content/public/app/content_main_delegate.h" + + #include "base/check.h" ++#include "base/strings/string_piece.h" + #include "build/build_config.h" + #include "content/public/browser/content_browser_client.h" + #include "content/public/common/content_client.h" +@@ -83,6 +84,10 @@ absl::optional<int> ContentMainDelegate::PostEarlyInitialization( + return absl::nullopt; + } + ++base::StringPiece ContentMainDelegate::GetBrowserV8SnapshotFilename() { ++ return base::StringPiece(); ++} ++ + ContentClient* ContentMainDelegate::CreateContentClient() { + return new ContentClient(); + } +diff --git a/content/public/app/content_main_delegate.h b/content/public/app/content_main_delegate.h +index f40146c4ed20e63dd09450e43c26736171f02ed4..5e3246a1346bd0210e7b83842a17dcc1986c8647 100644 +--- a/content/public/app/content_main_delegate.h ++++ b/content/public/app/content_main_delegate.h +@@ -9,6 +9,7 @@ + #include <string> + #include <vector> + ++#include "base/strings/string_piece.h" + #include "build/build_config.h" + #include "content/common/content_export.h" + #include "content/public/common/main_function_params.h" +@@ -154,6 +155,8 @@ class CONTENT_EXPORT ContentMainDelegate { + virtual bool ShouldHandleConsoleControlEvents(); + #endif + ++ virtual base::StringPiece GetBrowserV8SnapshotFilename(); ++ + protected: + friend class ContentClientCreator; + friend class ContentClientInitializer; +diff --git a/gin/v8_initializer.cc b/gin/v8_initializer.cc +index 5530d975303cc96701e4b70ffbcaf6e7c02bb016..edd9959cc0fd23711e19de4aee104199a8a3599e 100644 +--- a/gin/v8_initializer.cc ++++ b/gin/v8_initializer.cc +@@ -496,8 +496,7 @@ void V8Initializer::GetV8ExternalSnapshotData(const char** snapshot_data_out, + + #if defined(V8_USE_EXTERNAL_STARTUP_DATA) + +-// static +-void V8Initializer::LoadV8Snapshot(V8SnapshotFileType snapshot_file_type) { ++void V8Initializer::LoadV8SnapshotFromFileName(base::StringPiece file_name, V8SnapshotFileType snapshot_file_type) { + if (g_mapped_snapshot) { + // TODO(crbug.com/802962): Confirm not loading different type of snapshot + // files in a process. +@@ -506,10 +505,17 @@ void V8Initializer::LoadV8Snapshot(V8SnapshotFileType snapshot_file_type) { + + base::MemoryMappedFile::Region file_region; + base::File file = +- OpenV8File(GetSnapshotFileName(snapshot_file_type), &file_region); ++ OpenV8File(file_name.data(), &file_region); + LoadV8SnapshotFromFile(std::move(file), &file_region, snapshot_file_type); + } + ++// static ++void V8Initializer::LoadV8Snapshot(V8SnapshotFileType snapshot_file_type) { ++ const char* file_name = GetSnapshotFileName(snapshot_file_type); ++ ++ LoadV8SnapshotFromFileName(file_name, snapshot_file_type); ++} ++ + // static + void V8Initializer::LoadV8SnapshotFromFile( + base::File snapshot_file, +diff --git a/gin/v8_initializer.h b/gin/v8_initializer.h +index 13a120c7fe8e69a44793473f3124c33d572a07a3..acb294780873c1d84546eb2b9acc00f86838361d 100644 +--- a/gin/v8_initializer.h ++++ b/gin/v8_initializer.h +@@ -9,6 +9,7 @@ + + #include "base/files/file.h" + #include "base/files/memory_mapped_file.h" ++#include "base/strings/string_piece.h" + #include "build/build_config.h" + #include "gin/array_buffer.h" + #include "gin/gin_export.h" +@@ -42,6 +43,7 @@ class GIN_EXPORT V8Initializer { + int* snapshot_size_out); + + #if defined(V8_USE_EXTERNAL_STARTUP_DATA) ++ static void LoadV8SnapshotFromFileName(base::StringPiece file_name, V8SnapshotFileType snapshot_file_type); + // Load V8 snapshot from default resources, if they are available. + static void LoadV8Snapshot( + V8SnapshotFileType snapshot_file_type = V8SnapshotFileType::kDefault); diff --git a/shell/app/electron_main_delegate.cc b/shell/app/electron_main_delegate.cc index 537f74a14d..73d063026a 100644 --- a/shell/app/electron_main_delegate.cc +++ b/shell/app/electron_main_delegate.cc @@ -23,6 +23,7 @@ #include "components/content_settings/core/common/content_settings_pattern.h" #include "content/public/common/content_switches.h" #include "electron/buildflags/buildflags.h" +#include "electron/fuses.h" #include "extensions/common/constants.h" #include "ipc/ipc_buildflags.h" #include "sandbox/policy/switches.h" @@ -422,6 +423,20 @@ absl::optional<int> ElectronMainDelegate::PreBrowserMain() { return absl::nullopt; } +base::StringPiece ElectronMainDelegate::GetBrowserV8SnapshotFilename() { + const base::CommandLine* command_line = + base::CommandLine::ForCurrentProcess(); + std::string process_type = + command_line->GetSwitchValueASCII(::switches::kProcessType); + bool load_browser_process_specific_v8_snapshot = + process_type.empty() && + electron::fuses::IsLoadBrowserProcessSpecificV8SnapshotEnabled(); + if (load_browser_process_specific_v8_snapshot) { + return "browser_v8_context_snapshot.bin"; + } + return ContentMainDelegate::GetBrowserV8SnapshotFilename(); +} + content::ContentBrowserClient* ElectronMainDelegate::CreateContentBrowserClient() { browser_client_ = std::make_unique<ElectronBrowserClient>(); diff --git a/shell/app/electron_main_delegate.h b/shell/app/electron_main_delegate.h index e8e57fad85..0a8363fb7a 100644 --- a/shell/app/electron_main_delegate.h +++ b/shell/app/electron_main_delegate.h @@ -30,6 +30,8 @@ class ElectronMainDelegate : public content::ContentMainDelegate { ElectronMainDelegate(const ElectronMainDelegate&) = delete; ElectronMainDelegate& operator=(const ElectronMainDelegate&) = delete; + base::StringPiece GetBrowserV8SnapshotFilename() override; + protected: // content::ContentMainDelegate: absl::optional<int> BasicStartupComplete() override;
feat
777e54792244b92565eb6bf32fed166217f46de7
John Kleinschmidt
2024-11-11 18:44:13
fix: segfault when moving WebContentsView between BrowserWindows (#44599) * fix: segfault when moving WebContentsView between BrowserWindows * chore: actually enable fix * fixup segfault when moving WebContentsView between BrowserWindows
diff --git a/shell/browser/api/electron_api_view.cc b/shell/browser/api/electron_api_view.cc index b01a08be88..c65f80b164 100644 --- a/shell/browser/api/electron_api_view.cc +++ b/shell/browser/api/electron_api_view.cc @@ -124,6 +124,15 @@ struct Converter<views::FlexAllocationOrder> { } }; +template <> +struct Converter<electron::api::View> { + static bool FromV8(v8::Isolate* isolate, + v8::Local<v8::Value> val, + electron::api::View* out) { + return gin::ConvertFromV8(isolate, val, &out); + } +}; + template <> struct Converter<views::SizeBound> { static v8::Local<v8::Value> ToV8(v8::Isolate* isolate, @@ -257,11 +266,13 @@ void View::RemoveChildView(gin::Handle<View> child) { #if BUILDFLAG(IS_MAC) ScopedCAActionDisabler disable_animations; #endif + // Remove from child_views first so that OnChildViewRemoved doesn't try to + // remove it again + child_views_.erase(it); // It's possible for the child's view to be invalid here // if the child's webContents was closed or destroyed. if (child->view()) view_->RemoveChildView(child->view()); - child_views_.erase(it); } } @@ -388,6 +399,19 @@ void View::OnViewIsDeleting(views::View* observed_view) { view_ = nullptr; } +void View::OnChildViewRemoved(views::View* observed_view, views::View* child) { + v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); + auto it = std::ranges::find_if( + child_views_, [&](const v8::Global<v8::Object>& child_view) { + View current_view; + gin::ConvertFromV8(isolate, child_view.Get(isolate), &current_view); + return current_view.view()->GetID() == child->GetID(); + }); + if (it != child_views_.end()) { + child_views_.erase(it); + } +} + // static gin_helper::WrappableBase* View::New(gin::Arguments* args) { View* view = new View(); diff --git a/shell/browser/api/electron_api_view.h b/shell/browser/api/electron_api_view.h index 6eeb165219..1b0a3f815a 100644 --- a/shell/browser/api/electron_api_view.h +++ b/shell/browser/api/electron_api_view.h @@ -47,6 +47,8 @@ class View : public gin_helper::EventEmitter<View>, // views::ViewObserver void OnViewBoundsChanged(views::View* observed_view) override; void OnViewIsDeleting(views::View* observed_view) override; + void OnChildViewRemoved(views::View* observed_view, + views::View* child) override; views::View* view() const { return view_; } std::optional<int> border_radius() const { return border_radius_; } diff --git a/spec/fixtures/crash-cases/webview-move-between-windows/index.js b/spec/fixtures/crash-cases/webview-move-between-windows/index.js new file mode 100644 index 0000000000..de9053ec65 --- /dev/null +++ b/spec/fixtures/crash-cases/webview-move-between-windows/index.js @@ -0,0 +1,31 @@ +const { app, BrowserWindow, WebContentsView } = require('electron'); + +function createWindow () { + // Create the browser window. + const mainWindow = new BrowserWindow(); + const secondaryWindow = new BrowserWindow(); + + const contentsView = new WebContentsView(); + mainWindow.contentView.addChildView(contentsView); + mainWindow.webContents.setDevToolsWebContents(contentsView.webContents); + mainWindow.openDevTools(); + + contentsView.setBounds({ + x: 400, + y: 0, + width: 400, + height: 600 + }); + + setTimeout(() => { + secondaryWindow.contentView.addChildView(contentsView); + setTimeout(() => { + mainWindow.contentView.addChildView(contentsView); + app.quit(); + }, 1000); + }, 1000); +} + +app.whenReady().then(() => { + createWindow(); +});
fix
062d14e553fa85b14ca67b221911e82c5bc1bd12
Charles Kerr
2025-01-08 20:46:17
perf: cache whether or not ELECTRON_DEBUG_NOTIFICATIONS env var is set (#45143) * perf: cache whether or not ELECTRON_DEBUG_NOTIFICATIONS env var is set * chore: remove unused #include
diff --git a/shell/browser/notifications/mac/cocoa_notification.mm b/shell/browser/notifications/mac/cocoa_notification.mm index 9138515dc5..a90842f096 100644 --- a/shell/browser/notifications/mac/cocoa_notification.mm +++ b/shell/browser/notifications/mac/cocoa_notification.mm @@ -44,7 +44,7 @@ void CocoaNotification::Show(const NotificationOptions& options) { [notification_ setInformativeText:base::SysUTF16ToNSString(options.msg)]; [notification_ setIdentifier:identifier]; - if (getenv("ELECTRON_DEBUG_NOTIFICATIONS")) { + if (electron::debug_notifications) { LOG(INFO) << "Notification created (" << [identifier UTF8String] << ")"; } @@ -170,7 +170,7 @@ void CocoaNotification::NotificationDismissed() { } void CocoaNotification::LogAction(const char* action) { - if (getenv("ELECTRON_DEBUG_NOTIFICATIONS") && notification_) { + if (electron::debug_notifications && notification_) { NSString* identifier = [notification_ valueForKey:@"identifier"]; DCHECK(identifier); LOG(INFO) << "Notification " << action << " (" << [identifier UTF8String] diff --git a/shell/browser/notifications/mac/notification_center_delegate.mm b/shell/browser/notifications/mac/notification_center_delegate.mm index aceec2336b..64513e7c41 100644 --- a/shell/browser/notifications/mac/notification_center_delegate.mm +++ b/shell/browser/notifications/mac/notification_center_delegate.mm @@ -39,7 +39,7 @@ didActivateNotification:(NSUserNotification*)notif { auto* notification = presenter_->GetNotification(notif); - if (getenv("ELECTRON_DEBUG_NOTIFICATIONS")) { + if (electron::debug_notifications) { LOG(INFO) << "Notification activated (" << [notif.identifier UTF8String] << ")"; } diff --git a/shell/browser/notifications/mac/notification_presenter_mac.mm b/shell/browser/notifications/mac/notification_presenter_mac.mm index d94181ef59..e2c8ec63e1 100644 --- a/shell/browser/notifications/mac/notification_presenter_mac.mm +++ b/shell/browser/notifications/mac/notification_presenter_mac.mm @@ -30,7 +30,7 @@ CocoaNotification* NotificationPresenterMac::GetNotification( return native_notification; } - if (getenv("ELECTRON_DEBUG_NOTIFICATIONS")) { + if (electron::debug_notifications) { LOG(INFO) << "Could not find notification for " << [ns_notification.identifier UTF8String]; } diff --git a/shell/browser/notifications/notification.cc b/shell/browser/notifications/notification.cc index 7239080482..39d9bc8f8e 100644 --- a/shell/browser/notifications/notification.cc +++ b/shell/browser/notifications/notification.cc @@ -4,11 +4,15 @@ #include "shell/browser/notifications/notification.h" +#include "base/environment.h" #include "shell/browser/notifications/notification_delegate.h" #include "shell/browser/notifications/notification_presenter.h" namespace electron { +const bool debug_notifications = + base::Environment::Create()->HasVar("ELECTRON_DEBUG_NOTIFICATIONS"); + NotificationOptions::NotificationOptions() = default; NotificationOptions::~NotificationOptions() = default; diff --git a/shell/browser/notifications/notification.h b/shell/browser/notifications/notification.h index ab9f81845c..f4b687b866 100644 --- a/shell/browser/notifications/notification.h +++ b/shell/browser/notifications/notification.h @@ -15,6 +15,8 @@ namespace electron { +extern const bool debug_notifications; + class NotificationDelegate; class NotificationPresenter; diff --git a/shell/browser/notifications/win/notification_presenter_win.cc b/shell/browser/notifications/win/notification_presenter_win.cc index 073bd19e67..4ceb7e6b64 100644 --- a/shell/browser/notifications/win/notification_presenter_win.cc +++ b/shell/browser/notifications/win/notification_presenter_win.cc @@ -10,7 +10,6 @@ #include <string> #include <vector> -#include "base/environment.h" #include "base/files/file_util.h" #include "base/hash/md5.h" #include "base/logging.h" @@ -27,10 +26,6 @@ namespace electron { namespace { -bool IsDebuggingNotifications() { - return base::Environment::Create()->HasVar("ELECTRON_DEBUG_NOTIFICATIONS"); -} - bool SaveIconToPath(const SkBitmap& bitmap, const base::FilePath& path) { std::optional<std::vector<uint8_t>> png_data = gfx::PNGCodec::EncodeBGRASkBitmap(bitmap, false); @@ -50,7 +45,7 @@ std::unique_ptr<NotificationPresenter> NotificationPresenter::Create() { if (!presenter->Init()) return {}; - if (IsDebuggingNotifications()) + if (electron::debug_notifications) LOG(INFO) << "Successfully created Windows notifications presenter"; return presenter; diff --git a/shell/browser/notifications/win/windows_toast_notification.cc b/shell/browser/notifications/win/windows_toast_notification.cc index 1f5d3c3167..73fd9a36f3 100644 --- a/shell/browser/notifications/win/windows_toast_notification.cc +++ b/shell/browser/notifications/win/windows_toast_notification.cc @@ -13,7 +13,6 @@ #include <shlobj.h> #include <wrl\wrappers\corewrappers.h> -#include "base/environment.h" #include "base/hash/hash.h" #include "base/logging.h" #include "base/strings/strcat.h" @@ -66,7 +65,7 @@ namespace { constexpr wchar_t kGroup[] = L"Notifications"; void DebugLog(std::string_view log_msg) { - if (base::Environment::Create()->HasVar("ELECTRON_DEBUG_NOTIFICATIONS")) + if (electron::debug_notifications) LOG(INFO) << log_msg; }
perf
517225b99e5ba2bac068a58208ce9a85402ba9eb
Step Security Bot
2022-11-16 12:44:25
ci: add default action permissions (#36363) * [StepSecurity] Apply security best practices Signed-off-by: StepSecurity Bot <[email protected]> * Delete dependabot.yml Signed-off-by: StepSecurity Bot <[email protected]> Co-authored-by: Jeremy Rose <[email protected]>
diff --git a/.github/workflows/electron_woa_testing.yml b/.github/workflows/electron_woa_testing.yml index a7667da1af..3af8d005f3 100644 --- a/.github/workflows/electron_woa_testing.yml +++ b/.github/workflows/electron_woa_testing.yml @@ -10,6 +10,9 @@ on: type: text required: true +permissions: # added using https://github.com/step-security/secure-workflows + contents: read + jobs: electron-woa-init: if: ${{ github.event_name == 'push' && github.repository == 'electron/electron' }} diff --git a/.github/workflows/issue-labeled.yml b/.github/workflows/issue-labeled.yml index 085fec0936..11d9945852 100644 --- a/.github/workflows/issue-labeled.yml +++ b/.github/workflows/issue-labeled.yml @@ -4,8 +4,14 @@ on: issues: types: [labeled] +permissions: # added using https://github.com/step-security/secure-workflows + contents: read + jobs: issue-labeled: + permissions: + issues: write # for actions-cool/issues-helper to update issues + pull-requests: write # for actions-cool/issues-helper to update PRs runs-on: ubuntu-latest steps: - name: blocked/need-repro diff --git a/.github/workflows/release_dependency_versions.yml b/.github/workflows/release_dependency_versions.yml index 425f4ce4ab..32806dcc68 100644 --- a/.github/workflows/release_dependency_versions.yml +++ b/.github/workflows/release_dependency_versions.yml @@ -7,6 +7,9 @@ on: env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} +permissions: # added using https://github.com/step-security/secure-workflows + contents: read + jobs: check_tag: runs-on: ubuntu-latest
ci
0005ae9557294c076d8c2e183f6ed7b0a4b8ca05
Charles Kerr
2024-11-21 10:51:19
docs: sync 34.0.0 release date to Chromium 132 release date (#44766)
diff --git a/docs/tutorial/electron-timelines.md b/docs/tutorial/electron-timelines.md index b7f5a4ff47..cec0954ec7 100644 --- a/docs/tutorial/electron-timelines.md +++ b/docs/tutorial/electron-timelines.md @@ -9,10 +9,10 @@ check out our [Electron Versioning](./electron-versioning.md) doc. | Electron | Alpha | Beta | Stable | EOL | Chrome | Node | Supported | | ------- | ----- | ------- | ------ | ------ | ---- | ---- | ---- | -| 34.0.0 | 2024-Oct-17 | 2024-Nov-13 | 2024-Jan-07 | 2025-Jun-24 | M132 | TBD | ✅ | +| 34.0.0 | 2024-Oct-17 | 2024-Nov-13 | 2024-Jan-14 | 2025-Jun-24 | M132 | TBD | ✅ | | 33.0.0 | 2024-Aug-22 | 2024-Sep-18 | 2024-Oct-15 | 2025-Apr-29 | M130 | v20.18 | ✅ | | 32.0.0 | 2024-Jun-14 | 2024-Jul-24 | 2024-Aug-20 | 2025-Mar-04 | M128 | v20.16 | ✅ | -| 31.0.0 | 2024-Apr-18 | 2024-May-15 | 2024-Jun-11 | 2025-Jan-07 | M126 | v20.14 | ✅ | +| 31.0.0 | 2024-Apr-18 | 2024-May-15 | 2024-Jun-11 | 2025-Jan-14 | M126 | v20.14 | ✅ | | 30.0.0 | 2024-Feb-22 | 2024-Mar-20 | 2024-Apr-16 | 2024-Oct-15 | M124 | v20.11 | 🚫 | | 29.0.0 | 2023-Dec-07 | 2024-Jan-24 | 2024-Feb-20 | 2024-Aug-20 | M122 | v20.9 | 🚫 | | 28.0.0 | 2023-Oct-11 | 2023-Nov-06 | 2023-Dec-05 | 2024-Jun-11 | M120 | v18.18 | 🚫 |
docs
eacdf56e0b0a08a391e749ad057b3517ebcb0307
Keeley Hammond
2024-06-11 14:43:11
build: build ffmpeg on MAS publish (#42448)
diff --git a/.github/workflows/macos-pipeline.yml b/.github/workflows/macos-pipeline.yml index a219e02eef..75da7d7e48 100644 --- a/.github/workflows/macos-pipeline.yml +++ b/.github/workflows/macos-pipeline.yml @@ -507,7 +507,7 @@ jobs: else electron/script/zip-symbols.py -b $BUILD_PATH fi - - name: Generate FFMpeg + - name: Generate FFMpeg (darwin) if: ${{ inputs.is-release }} run: | cd src @@ -628,6 +628,12 @@ jobs: else electron/script/zip-symbols.py -b $BUILD_PATH fi + - name: Generate FFMpeg (mas) + if: ${{ inputs.is-release }} + run: | + cd src + gn gen out/ffmpeg --args="import(\"//electron/build/args/ffmpeg.gn\") use_remoteexec=true $GN_EXTRA_ARGS" + autoninja -C out/ffmpeg electron:electron_ffmpeg_zip -j $NUMBER_OF_NINJA_PROCESSES # TODO(vertedinde): These uploads currently point to a different Azure bucket & GitHub Repo - name: Publish Electron Dist if: ${{ inputs.is-release }}
build
a043a60b89deda3b6342f08f9ad6b3de9d01a950
Milan Burda
2023-05-24 20:01:07
refactor: cleanup global variable declarations (#38410) refactor: eliminate duplicate isolatedApi typing Co-authored-by: Milan Burda <[email protected]>
diff --git a/lib/isolated_renderer/init.ts b/lib/isolated_renderer/init.ts index d2cbf4207f..30b8eec246 100644 --- a/lib/isolated_renderer/init.ts +++ b/lib/isolated_renderer/init.ts @@ -1,6 +1,7 @@ -/* global isolatedApi */ - import type * as webViewElementModule from '@electron/internal/renderer/web-view/web-view-element'; +import type { WebViewImplHooks } from '@electron/internal/renderer/web-view/web-view-impl'; + +declare const isolatedApi: WebViewImplHooks; if (isolatedApi.guestViewInternal) { // Must setup the WebView element in main world. diff --git a/lib/sandboxed_renderer/init.ts b/lib/sandboxed_renderer/init.ts index 079dd38b06..9c07a19824 100644 --- a/lib/sandboxed_renderer/init.ts +++ b/lib/sandboxed_renderer/init.ts @@ -1,10 +1,15 @@ -/* global binding */ import * as events from 'events'; import { IPC_MESSAGES } from '@electron/internal/common/ipc-messages'; import type * as ipcRendererUtilsModule from '@electron/internal/renderer/ipc-renderer-internal-utils'; import type * as ipcRendererInternalModule from '@electron/internal/renderer/ipc-renderer-internal'; +declare const binding: { + get: (name: string) => any; + process: NodeJS.Process; + createPreloadScript: (src: string) => Function +}; + const { EventEmitter } = events; process._linkedBinding = binding.get; diff --git a/typings/internal-ambient.d.ts b/typings/internal-ambient.d.ts index 805236ddd6..0876477804 100644 --- a/typings/internal-ambient.d.ts +++ b/typings/internal-ambient.d.ts @@ -1,13 +1,3 @@ -/* eslint-disable no-var */ -declare var internalBinding: any; -declare var binding: { get: (name: string) => any; process: NodeJS.Process; createPreloadScript: (src: string) => Function }; - -declare var isolatedApi: { - guestViewInternal: any; - allowGuestViewElementDefinition: NodeJS.InternalWebFrame['allowGuestViewElementDefinition']; - setIsWebView: (iframe: HTMLIFrameElement) => void; -} - declare const BUILDFLAG: (flag: boolean) => boolean; declare const ENABLE_DESKTOP_CAPTURER: boolean;
refactor
d9a9d5b8fe30ee0a9539d9e546f6d51c62c957b8
Ani Betts
2024-11-02 21:56:02
docs: Update Squirrel Run at Login docs to be modern (#44487) Update Squirrel Run at Login docs to be modern The current docs for setting up Run at Login use the legacy way that Squirrel does shortcuts. This was replaced by an easier method, let's use that instead
diff --git a/docs/api/app.md b/docs/api/app.md index 2a137c2983..d465922ce8 100755 --- a/docs/api/app.md +++ b/docs/api/app.md @@ -1302,23 +1302,24 @@ Returns `Object`: Set the app's login item settings. To work with Electron's `autoUpdater` on Windows, which uses [Squirrel][Squirrel-Windows], -you'll want to set the launch path to Update.exe, and pass arguments that specify your -application name. For example: +you'll want to set the launch path to your executable's name but a directory up, which is +a stub application automatically generated by Squirrel which will automatically launch the +latest version. ``` js const { app } = require('electron') const path = require('node:path') const appFolder = path.dirname(process.execPath) -const updateExe = path.resolve(appFolder, '..', 'Update.exe') -const exeName = path.basename(process.execPath) +const ourExeName = path.basename(process.execPath) +const stubLauncher = path.resolve(appFolder, '..', ourExeName) app.setLoginItemSettings({ openAtLogin: true, - path: updateExe, + path: stubLauncher, args: [ - '--processStart', `"${exeName}"`, - '--process-start-args', '"--hidden"' + // You might want to pass a parameter here indicating that this + // app was launched via login, but you don't have to ] }) ```
docs
2b8706bf44c3dbe03c11697c80eeda7595f2b396
Charles Kerr
2025-02-13 17:27:35
chore: change node test timeout from 20m to 30m (#45611)
diff --git a/.github/workflows/pipeline-segment-node-nan-test.yml b/.github/workflows/pipeline-segment-node-nan-test.yml index 0d44a2b77a..f4f5fdd9c0 100644 --- a/.github/workflows/pipeline-segment-node-nan-test.yml +++ b/.github/workflows/pipeline-segment-node-nan-test.yml @@ -38,7 +38,7 @@ jobs: node-tests: name: Run Node.js Tests runs-on: electron-arc-linux-amd64-8core - timeout-minutes: 20 + timeout-minutes: 30 env: TARGET_ARCH: ${{ inputs.target-arch }} BUILD_TYPE: linux @@ -101,7 +101,7 @@ jobs: nan-tests: name: Run Nan Tests runs-on: electron-arc-linux-amd64-4core - timeout-minutes: 20 + timeout-minutes: 30 env: TARGET_ARCH: ${{ inputs.target-arch }} BUILD_TYPE: linux
chore
6961e9458a521ac76d7966e983e82c972d88d595
Sam Maddock
2024-12-11 17:22:50
chore: update vm module warning (#44985) * chore: update vm module warning * Update lib/renderer/init.ts Co-authored-by: Keeley Hammond <[email protected]> --------- Co-authored-by: Keeley Hammond <[email protected]>
diff --git a/lib/renderer/init.ts b/lib/renderer/init.ts index 7d53e0b792..2de705c3f2 100644 --- a/lib/renderer/init.ts +++ b/lib/renderer/init.ts @@ -12,7 +12,7 @@ const Module = require('module') as NodeJS.ModuleInternal; const originalModuleLoad = Module._load; Module._load = function (request: string) { if (request === 'vm') { - console.warn('The vm module of Node.js is deprecated in the renderer process and will be removed.'); + console.warn('The vm module of Node.js is unsupported in Electron\'s renderer process due to incompatibilities with the Blink rendering engine. Crashes are likely and avoiding the module is highly recommended. This module may be removed in a future release.'); } return originalModuleLoad.apply(this, arguments as any); };
chore
d8baceb08caae374d3931d5747152e3971a1a379
Shelley Vohr
2025-02-20 18:07:15
fix: crash loading `about:blank` in subframes (#45694) fix: crash loading about:blank in subframes
diff --git a/patches/chromium/fix_crash_loading_non-standard_schemes_in_iframes.patch b/patches/chromium/fix_crash_loading_non-standard_schemes_in_iframes.patch index 101a4175e6..3015eeadbb 100644 --- a/patches/chromium/fix_crash_loading_non-standard_schemes_in_iframes.patch +++ b/patches/chromium/fix_crash_loading_non-standard_schemes_in_iframes.patch @@ -28,17 +28,17 @@ The patch should be removed in favor of either: Upstream bug https://bugs.chromium.org/p/chromium/issues/detail?id=1081397. diff --git a/content/browser/renderer_host/navigation_request.cc b/content/browser/renderer_host/navigation_request.cc -index 0c67607fd99b2fceba176308a041c8f08643506a..82c4a7e1d441f1444d6ca32a56e8b0381209ec2f 100644 +index 0c67607fd99b2fceba176308a041c8f08643506a..6b38139e1b58db7c7a0c4d553ed2cdaa11a63d2d 100644 --- a/content/browser/renderer_host/navigation_request.cc +++ b/content/browser/renderer_host/navigation_request.cc @@ -10980,6 +10980,12 @@ NavigationRequest::GetOriginForURLLoaderFactoryUncheckedWithDebugInfo() { "blob"); } -+ if (!IsInMainFrame() && !common_params().url.IsStandard()) { ++ if (!common_params().url.IsStandard() && !common_params().url.IsAboutBlank()) { + return std::make_pair(url::Origin::Resolve(common_params().url, -+ url::Origin()), -+ "url_non_standard"); ++ url::Origin()), ++ "url_non_standard"); + } + // In cases not covered above, URLLoaderFactory should be associated with the diff --git a/spec/api-subframe-spec.ts b/spec/api-subframe-spec.ts index 66b5dcc00e..3004c2f12b 100644 --- a/spec/api-subframe-spec.ts +++ b/spec/api-subframe-spec.ts @@ -217,6 +217,40 @@ describe('renderer nodeIntegrationInSubFrames', () => { }); }); +describe('subframe with non-standard schemes', () => { + it('should not crash when changing subframe src to about:blank and back', async () => { + const w = new BrowserWindow({ show: false, width: 400, height: 400 }); + + const fwfPath = path.resolve(__dirname, 'fixtures/sub-frames/frame-with-frame.html'); + await w.loadFile(fwfPath); + + const originalSrc = await w.webContents.executeJavaScript(` + const iframe = document.querySelector('iframe'); + iframe.src; + `); + + const updatedSrc = await w.webContents.executeJavaScript(` + new Promise((resolve, reject) => { + const iframe = document.querySelector('iframe'); + iframe.src = 'about:blank'; + resolve(iframe.src); + }) + `); + + expect(updatedSrc).to.equal('about:blank'); + + const restoredSrc = await w.webContents.executeJavaScript(` + new Promise((resolve, reject) => { + const iframe = document.querySelector('iframe'); + iframe.src = '${originalSrc}'; + resolve(iframe.src); + }) + `); + + expect(restoredSrc).to.equal(originalSrc); + }); +}); + // app.getAppMetrics() does not return sandbox information on Linux. ifdescribe(process.platform !== 'linux')('cross-site frame sandboxing', () => { let server: http.Server;
fix
8eee4f2df1982ae52f1ed1a7ca3e2183ba701c4f
Shelley Vohr
2023-02-14 18:40:37
fix: `BrowserView` crash when 'beforeunload' prevented (#37205) fix: crash when beforeunload prevented
diff --git a/shell/browser/api/electron_api_browser_window.cc b/shell/browser/api/electron_api_browser_window.cc index 867b77786f..f1fd37e0c7 100644 --- a/shell/browser/api/electron_api_browser_window.cc +++ b/shell/browser/api/electron_api_browser_window.cc @@ -112,7 +112,6 @@ BrowserWindow::~BrowserWindow() { api_web_contents_->RemoveObserver(this); // Destroy the WebContents. OnCloseContents(); - api_web_contents_->Destroy(); } } @@ -140,6 +139,7 @@ void BrowserWindow::WebContentsDestroyed() { void BrowserWindow::OnCloseContents() { BaseWindow::ResetBrowserViews(); + api_web_contents_->Destroy(); } void BrowserWindow::OnRendererResponsive(content::RenderProcessHost*) { diff --git a/shell/browser/api/electron_api_web_contents.cc b/shell/browser/api/electron_api_web_contents.cc index 3f3ea285cf..c30fa2e8d2 100644 --- a/shell/browser/api/electron_api_web_contents.cc +++ b/shell/browser/api/electron_api_web_contents.cc @@ -1222,7 +1222,9 @@ void WebContents::CloseContents(content::WebContents* source) { for (ExtendedWebContentsObserver& observer : observers_) observer.OnCloseContents(); - Destroy(); + // If there are observers, OnCloseContents will call Destroy() + if (observers_.empty()) + Destroy(); } void WebContents::ActivateContents(content::WebContents* source) {
fix
705d92c5f6dfaaa7be9459b3ea7fa8060ecdb194
IsmaelMartinez
2024-05-29 13:41:17
docs: fix broken notification-spec markdown link (#42243) * docs: fix broken notification-spec markdown link * docs: update notification-spec linkt to point to freedesktop
diff --git a/docs/tutorial/notifications.md b/docs/tutorial/notifications.md index fc30925466..ae6adc6059 100644 --- a/docs/tutorial/notifications.md +++ b/docs/tutorial/notifications.md @@ -161,7 +161,7 @@ Notifications are sent using `libnotify`, which can show notifications on any desktop environment that follows [Desktop Notifications Specification][notification-spec], including Cinnamon, Enlightenment, Unity, GNOME, and KDE. -[notification-spec]: https://developer-old.gnome.org/notification-spec/ +[notification-spec]: https://specifications.freedesktop.org/notification-spec/notification-spec-latest.html [app-user-model-id]: https://learn.microsoft.com/en-us/windows/win32/shell/appids [set-app-user-model-id]: ../api/app.md#appsetappusermodelidid-windows [squirrel-events]: https://github.com/electron/windows-installer/blob/main/README.md#handling-squirrel-events
docs
b92a4023c137b1850bd2a48712b8804d0f50a836
Samuel Attard
2024-06-13 16:02:38
build: unify pipelines (#42482)
diff --git a/.github/actions/build-electron/action.yml b/.github/actions/build-electron/action.yml new file mode 100644 index 0000000000..90d6d1dea2 --- /dev/null +++ b/.github/actions/build-electron/action.yml @@ -0,0 +1,187 @@ +name: 'Build Electron' +description: 'Builds Electron & Friends' +inputs: + target-arch: + description: 'Target arch' + required: true + target-platform: + description: 'Target platform' + required: true + artifact-platform: + description: 'Artifact platform, should be linux, darwin or mas' + required: true + step-suffix: + description: 'Suffix for build steps' + required: false + default: '' + is-release: + description: 'Is release build' + required: true + generate-symbols: + description: 'Generate symbols' + required: true + upload-to-storage: + description: 'Upload to storage' + required: true +runs: + using: "composite" + steps: + - name: Build Electron ${{ inputs.step-suffix }} + shell: bash + run: | + rm -rf "src/out/Default/Electron Framework.framework" + rm -rf src/out/Default/Electron*.app + + cd src/electron + # TODO(codebytere): remove this once we figure out why .git/packed-refs is initially missing + git pack-refs + cd .. + + if [ "`uname`" = "Darwin" ]; then + ulimit -n 10000 + sudo launchctl limit maxfiles 65536 200000 + fi + + NINJA_SUMMARIZE_BUILD=1 e build -j $NUMBER_OF_NINJA_PROCESSES + cp out/Default/.ninja_log out/electron_ninja_log + node electron/script/check-symlinks.js + - name: Build Electron dist.zip ${{ inputs.step-suffix }} + shell: bash + run: | + cd src + e build electron:electron_dist_zip -j $NUMBER_OF_NINJA_PROCESSES + if [ "${{ env.CHECK_DIST_MANIFEST }}" = "true" ]; then + target_os=${{ inputs.target-platform == 'linux' && 'linux' || 'mac'}} + if [ "${{ inputs.artifact-platform }}" = "mas" ]; then + target_os="${target_os}_mas" + fi + electron/script/zip_manifests/check-zip-manifest.py out/Default/dist.zip electron/script/zip_manifests/dist_zip.$target_os.${{ inputs.target-arch }}.manifest + fi + - name: Build Mksnapshot ${{ inputs.step-suffix }} + shell: bash + run: | + cd src + e build electron:electron_mksnapshot -j $NUMBER_OF_NINJA_PROCESSES + gn desc out/Default v8:run_mksnapshot_default args > out/Default/mksnapshot_args + # Remove unused args from mksnapshot_args + SEDOPTION="-i" + if [ "`uname`" = "Darwin" ]; then + SEDOPTION="-i ''" + fi + sed $SEDOPTION '/.*builtins-pgo/d' out/Default/mksnapshot_args + sed $SEDOPTION '/--turbo-profiling-input/d' out/Default/mksnapshot_args + sed $SEDOPTION '/The gn arg use_goma=true .*/d' out/Default/mksnapshot_args + + if [ "`uname`" = "Linux" ]; then + if [ "${{ inputs.target-arch }}" = "arm" ]; then + electron/script/strip-binaries.py --file $PWD/out/Default/clang_x86_v8_arm/mksnapshot + electron/script/strip-binaries.py --file $PWD/out/Default/clang_x86_v8_arm/v8_context_snapshot_generator + elif [ "${{ inputs.target-arch }}" = "arm64" ]; then + electron/script/strip-binaries.py --file $PWD/out/Default/clang_x64_v8_arm64/mksnapshot + electron/script/strip-binaries.py --file $PWD/out/Default/clang_x64_v8_arm64/v8_context_snapshot_generator + else + electron/script/strip-binaries.py --file $PWD/out/Default/mksnapshot + electron/script/strip-binaries.py --file $PWD/out/Default/v8_context_snapshot_generator + fi + fi + + e build electron:electron_mksnapshot_zip -j $NUMBER_OF_NINJA_PROCESSES + (cd out/Default; zip mksnapshot.zip mksnapshot_args gen/v8/embedded.S) + - name: Generate Cross-Arch Snapshot (arm/arm64) ${{ inputs.step-suffix }} + shell: bash + if: ${{ (inputs.target-arch == 'arm' || inputs.target-arch == 'arm64') && inputs.target-platform == 'linux' }} + run: | + cd src + if [ "${{ inputs.target-arch }}" = "arm" ]; then + MKSNAPSHOT_PATH="clang_x86_v8_arm" + elif [ "${{ inputs.target-arch }}" = "arm64" ]; then + MKSNAPSHOT_PATH="clang_x64_v8_arm64" + fi + + cp "out/Default/$MKSNAPSHOT_PATH/mksnapshot" out/Default + cp "out/Default/$MKSNAPSHOT_PATH/v8_context_snapshot_generator" out/Default + cp "out/Default/$MKSNAPSHOT_PATH/libffmpeg.so" out/Default + + python3 electron/script/verify-mksnapshot.py --source-root "$PWD" --build-dir out/Default --create-snapshot-only + mkdir cross-arch-snapshots + cp out/Default-mksnapshot-test/*.bin cross-arch-snapshots + # Clean up so that ninja does not get confused + rm -f out/Default/libffmpeg.so + - name: Build Chromedriver ${{ inputs.step-suffix }} + shell: bash + run: | + cd src + e build electron:electron_chromedriver -j $NUMBER_OF_NINJA_PROCESSES + e build electron:electron_chromedriver_zip + - name: Build Node.js headers ${{ inputs.step-suffix }} + shell: bash + run: | + cd src + e build electron:node_headers + - name: Generate & Zip Symbols ${{ inputs.step-suffix }} + shell: bash + run: | + # Generate breakpad symbols on release builds + if [ "${{ inputs.generate-symbols }}" = "true" ]; then + e build electron:electron_symbols + fi + cd src + export BUILD_PATH="$(pwd)/out/Default" + e build electron:licenses + e build electron:electron_version_file + if [ "${{ inputs.is-release }}" = "true" ]; then + DELETE_DSYMS_AFTER_ZIP=1 electron/script/zip-symbols.py -b $BUILD_PATH + else + electron/script/zip-symbols.py -b $BUILD_PATH + fi + - name: Generate FFMpeg ${{ inputs.step-suffix }} + shell: bash + if: ${{ inputs.is-release == 'true' }} + run: | + cd src + gn gen out/ffmpeg --args="import(\"//electron/build/args/ffmpeg.gn\") use_remoteexec=true $GN_EXTRA_ARGS" + autoninja -C out/ffmpeg electron:electron_ffmpeg_zip -j $NUMBER_OF_NINJA_PROCESSES + - name: Generate Hunspell Dictionaries ${{ inputs.step-suffix }} + shell: bash + if: ${{ inputs.is-release == 'true' && inputs.target-platform == 'linux' }} + run: | + cd src + autoninja -C out/Default electron:hunspell_dictionaries_zip -j $NUMBER_OF_NINJA_PROCESSES + - name: Generate Libcxx ${{ inputs.step-suffix }} + shell: bash + if: ${{ inputs.is-release == 'true' && inputs.target-platform == 'linux' }} + run: | + cd src + autoninja -C out/Default electron:libcxx_headers_zip -j $NUMBER_OF_NINJA_PROCESSES + autoninja -C out/Default electron:libcxxabi_headers_zip -j $NUMBER_OF_NINJA_PROCESSES + autoninja -C out/Default electron:libcxx_objects_zip -j $NUMBER_OF_NINJA_PROCESSES + - name: Generate TypeScript Definitions ${{ inputs.step-suffix }} + if: ${{ inputs.is-release == 'true' }} + shell: bash + run: | + cd src/electron + node script/yarn create-typescript-definitions + # TODO(vertedinde): These uploads currently point to a different Azure bucket & GitHub Repo + - name: Publish Electron Dist ${{ inputs.step-suffix }} + if: ${{ inputs.is-release == 'true' }} + shell: bash + run: | + rm -rf src/out/Default/obj + cd src/electron + if [ "${{ inputs.upload-to-storage }}" = "1" ]; then + echo 'Uploading Electron release distribution to Azure' + script/release/uploaders/upload.py --verbose --upload_to_storage + else + echo 'Uploading Electron release distribution to GitHub releases' + script/release/uploaders/upload.py --verbose + fi + # The current generated_artifacts_<< artifact.key >> name was taken from CircleCI + # to ensure we don't break anything, but we may be able to improve that. + - name: Move all Generated Artifacts to Upload Folder ${{ inputs.step-suffix }} + shell: bash + run: ./src/electron/script/actions/move-artifacts.sh + - name: Upload Generated Artifacts ${{ inputs.step-suffix }} + uses: actions/upload-artifact@65462800fd760344b1a7b4382951275a0abb4808 + with: + name: generated_artifacts_${{ inputs.artifact-platform }}_${{ env.TARGET_ARCH }} + path: ./generated_artifacts_${{ inputs.artifact-platform }}_${{ env.TARGET_ARCH }} \ No newline at end of file diff --git a/.github/actions/fix-sync-macos/action.yml b/.github/actions/fix-sync-macos/action.yml new file mode 100644 index 0000000000..e9e2c92228 --- /dev/null +++ b/.github/actions/fix-sync-macos/action.yml @@ -0,0 +1,61 @@ +name: 'Fix Sync macOS' +description: 'Checks out Electron and stores it in the AKS Cache' +runs: + using: "composite" + steps: + - name: Fix Sync + shell: bash + # This step is required to correct for differences between "gclient sync" + # on Linux and the expected state on macOS. This requires: + # 1. Fixing Clang Install (wrong binary) + # 2. Fixing esbuild (wrong binary) + # 3. Fixing rustc (wrong binary) + # 4. Fixing gn (wrong binary) + # 5. Fix reclient (wrong binary) + # 6. Fixing dsymutil (wrong binary) + # 7. Ensuring we are using the correct ninja and adding it to PATH + # 8. Fixing angle (wrong remote) + run : | + SEDOPTION="-i ''" + rm -rf src/third_party/llvm-build + python3 src/tools/clang/scripts/update.py + + echo 'infra/3pp/tools/esbuild/${platform}' `gclient getdep --deps-file=src/third_party/devtools-frontend/src/DEPS -r 'third_party/esbuild:infra/3pp/tools/esbuild/${platform}'` > esbuild_ensure_file + # Remove extra output from calling gclient getdep which always calls update_depot_tools + sed -i '' "s/Updating depot_tools... //g" esbuild_ensure_file + cipd ensure --root src/third_party/devtools-frontend/src/third_party/esbuild -ensure-file esbuild_ensure_file + + rm -rf src/third_party/rust-toolchain + python3 src/tools/rust/update_rust.py + + # Prevent calling gclient getdep which always calls update_depot_tools + echo 'gn/gn/mac-${arch}' `gclient getdep --deps-file=src/DEPS -r 'src/buildtools/mac:gn/gn/mac-${arch}'` > gn_ensure_file + sed -i '' "s/Updating depot_tools... //g" gn_ensure_file + cipd ensure --root src/buildtools/mac -ensure-file gn_ensure_file + + # Prevent calling gclient getdep which always calls update_depot_tools + echo 'infra/rbe/client/${platform}' `gclient getdep --deps-file=src/DEPS -r 'src/buildtools/reclient:infra/rbe/client/${platform}'` > gn_ensure_file + sed -i '' "s/Updating depot_tools... //g" gn_ensure_file + cipd ensure --root src/buildtools/reclient -ensure-file gn_ensure_file + python3 src/buildtools/reclient_cfgs/configure_reclient_cfgs.py --rbe_instance "projects/rbe-chrome-untrusted/instances/default_instance" --reproxy_cfg_template reproxy.cfg.template --rewrapper_cfg_project "" --skip_remoteexec_cfg_fetch + + if [ "${{ env.TARGET_ARCH }}" == "arm64" ]; then + DSYM_SHA_FILE=src/tools/clang/dsymutil/bin/dsymutil.arm64.sha1 + else + DSYM_SHA_FILE=src/tools/clang/dsymutil/bin/dsymutil.x64.sha1 + fi + python3 src/third_party/depot_tools/download_from_google_storage.py --no_resume --no_auth --bucket chromium-browser-clang -s $DSYM_SHA_FILE -o src/tools/clang/dsymutil/bin/dsymutil + + echo 'infra/3pp/tools/ninja/${platform}' `gclient getdep --deps-file=src/DEPS -r 'src/third_party/ninja:infra/3pp/tools/ninja/${platform}'` > ninja_ensure_file + sed $SEDOPTION "s/Updating depot_tools... //g" ninja_ensure_file + cipd ensure --root src/third_party/ninja -ensure-file ninja_ensure_file + + echo "$(pwd)/src/third_party/ninja" >> $GITHUB_PATH + + cd src/third_party/angle + rm -f .git/objects/info/alternates + git remote set-url origin https://chromium.googlesource.com/angle/angle.git + cp .git/config .git/config.backup + git remote remove origin + mv .git/config.backup .git/config + git fetch diff --git a/.github/actions/free-space-macos/action.yml b/.github/actions/free-space-macos/action.yml new file mode 100644 index 0000000000..75350ca796 --- /dev/null +++ b/.github/actions/free-space-macos/action.yml @@ -0,0 +1,65 @@ +name: 'Free Space macOS' +description: 'Checks out Electron and stores it in the AKS Cache' +runs: + using: "composite" + steps: + - name: Free Space on MacOS + shell: bash + run: | + sudo mkdir -p $TMPDIR/del-target + + tmpify() { + if [ -d "$1" ]; then + sudo mv "$1" $TMPDIR/del-target/$(echo $1|shasum -a 256|head -n1|cut -d " " -f1) + fi + } + + strip_universal_deep() { + opwd=$(pwd) + cd $1 + f=$(find . -perm +111 -type f) + for fp in $f + do + if [[ $(file "$fp") == *"universal binary"* ]]; then + if [ "`arch`" == "arm64" ]; then + if [[ $(file "$fp") == *"x86_64"* ]]; then + sudo lipo -remove x86_64 "$fp" -o "$fp" || true + fi + else + if [[ $(file "$fp") == *"arm64e)"* ]]; then + sudo lipo -remove arm64e "$fp" -o "$fp" || true + fi + if [[ $(file "$fp") == *"arm64)"* ]]; then + sudo lipo -remove arm64 "$fp" -o "$fp" || true + fi + fi + fi + done + + cd $opwd + } + + tmpify /Library/Developer/CoreSimulator + tmpify ~/Library/Developer/CoreSimulator + tmpify $(xcode-select -p)/Platforms/AppleTVOS.platform + tmpify $(xcode-select -p)/Platforms/iPhoneOS.platform + tmpify $(xcode-select -p)/Platforms/WatchOS.platform + tmpify $(xcode-select -p)/Platforms/WatchSimulator.platform + tmpify $(xcode-select -p)/Platforms/AppleTVSimulator.platform + tmpify $(xcode-select -p)/Platforms/iPhoneSimulator.platform + tmpify $(xcode-select -p)/Toolchains/XcodeDefault.xctoolchain/usr/metal/ios + tmpify $(xcode-select -p)/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift + tmpify $(xcode-select -p)/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift-5.0 + tmpify ~/.rubies + tmpify ~/Library/Caches/Homebrew + tmpify /usr/local/Homebrew + + sudo rm -rf $TMPDIR/del-target + + sudo rm -rf /Applications/Safari.app + sudo rm -rf ~/project/src/third_party/catapult/tracing/test_data + sudo rm -rf ~/project/src/third_party/angle/third_party/VK-GL-CTS + + # lipo off some huge binaries arm64 versions to save space + strip_universal_deep $(xcode-select -p)/../SharedFrameworks + # strip_arm_deep /System/Volumes/Data/Library/Developer/CommandLineTools/usr \ No newline at end of file diff --git a/.github/actions/restore-cache-aks/action.yml b/.github/actions/restore-cache-aks/action.yml new file mode 100644 index 0000000000..eccbb5ebfc --- /dev/null +++ b/.github/actions/restore-cache-aks/action.yml @@ -0,0 +1,36 @@ +name: 'Restore Cache AKS' +description: 'Restores Electron src cache via AKS' +runs: + using: "composite" + steps: + - name: Restore and Ensure Src Cache + shell: bash + run: | + cache_path=/mnt/cross-instance-cache/$DEPSHASH.tar + echo "Using cache key: $DEPSHASH" + echo "Checking for cache in: $cache_path" + if [ ! -f "$cache_path" ]; then + echo "Cache Does Not Exist for $DEPSHASH - exiting" + exit 1 + else + echo "Found Cache for $DEPSHASH at $cache_path" + fi + + echo "Persisted cache is $(du -sh $cache_path | cut -f1)" + mkdir temp-cache + tar -xf $cache_path -C temp-cache + echo "Unzipped cache is $(du -sh temp-cache/src | cut -f1)" + + if [ -d "temp-cache/src" ]; then + echo "Relocating Cache" + rm -rf src + mv temp-cache/src src + fi + + if [ ! -d "src/third_party/blink" ]; then + echo "Cache was not correctly restored - exiting" + exit 1 + fi + + echo "Wiping Electron Directory" + rm -rf src/electron diff --git a/.github/actions/restore-cache-azcopy/action.yml b/.github/actions/restore-cache-azcopy/action.yml new file mode 100644 index 0000000000..2d861b4252 --- /dev/null +++ b/.github/actions/restore-cache-azcopy/action.yml @@ -0,0 +1,51 @@ +name: 'Restore Cache AZCopy' +description: 'Restores Electron src cache via AZCopy' +runs: + using: "composite" + steps: + - name: Obtain SAS Key + uses: actions/cache/restore@v4 + with: + path: | + sas-token + key: sas-key-${{ github.run_number }}-${{ github.run_attempt }} + - name: Download Src Cache from AKS + # The cache will always exist here as a result of the checkout job + # Either it was uploaded to Azure in the checkout job for this commit + # or it was uploaded in the checkout job for a previous commit. + uses: nick-fields/retry@7152eba30c6575329ac0576536151aca5a72780e # v3.0.0 + with: + timeout_minutes: 20 + max_attempts: 3 + retry_on: error + command: | + sas_token=$(cat sas-token) + azcopy copy \ + "https://${{ env.AZURE_AKS_CACHE_STORAGE_ACCOUNT }}.file.core.windows.net/${{ env.AZURE_AKS_CACHE_SHARE_NAME }}/${{ env.CACHE_PATH }}?$sas_token" $DEPSHASH.tar + - name: Clean SAS Key + shell: bash + run: rm -f sas-token + - name: Unzip and Ensure Src Cache + shell: bash + run: | + echo "Downloaded cache is $(du -sh $DEPSHASH.tar | cut -f1)" + mkdir temp-cache + tar -xf $DEPSHASH.tar -C temp-cache + echo "Unzipped cache is $(du -sh temp-cache/src | cut -f1)" + + if [ -d "temp-cache/src" ]; then + echo "Relocating Cache" + rm -rf src + mv temp-cache/src src + + echo "Deleting zip file" + rm -rf $DEPSHASH.tar + fi + + if [ ! -d "src/third_party/blink" ]; then + echo "Cache was not correctly restored - exiting" + exit 1 + fi + + echo "Wiping Electron Directory" + rm -rf src/electron \ No newline at end of file diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml new file mode 100644 index 0000000000..23f98be5ec --- /dev/null +++ b/.github/workflows/build.yml @@ -0,0 +1,120 @@ +name: Build + +on: + workflow_dispatch: + # push + # pull_request: + +jobs: + # Checkout Jobs + checkout-macos: + runs-on: aks-linux-large + container: + image: ghcr.io/electron/build:latest + options: --user root + volumes: + - /mnt/cross-instance-cache:/mnt/cross-instance-cache + - /var/run/sas:/var/run/sas + env: + GCLIENT_EXTRA_ARGS: '--custom-var=checkout_mac=True --custom-var=host_os=mac' + steps: + - name: Checkout Electron + uses: actions/checkout@a5ac7e51b41094c92402da3b24376905380afc29 + with: + path: src/electron + fetch-depth: 0 + - name: Checkout & Sync & Save + uses: ./src/electron/.github/actions/checkout + with: + generate-sas-token: 'true' + checkout-linux: + runs-on: aks-linux-large + container: + image: ghcr.io/electron/build:latest + options: --user root + volumes: + - /mnt/cross-instance-cache:/mnt/cross-instance-cache + - /var/run/sas:/var/run/sas + env: + GCLIENT_EXTRA_ARGS: '--custom-var=checkout_mac=True --custom-var=host_os=mac' + steps: + - name: Checkout Electron + uses: actions/checkout@a5ac7e51b41094c92402da3b24376905380afc29 + with: + path: src/electron + fetch-depth: 0 + - name: Checkout & Sync & Save + uses: ./src/electron/.github/actions/checkout + + macos-x64: + uses: ./.github/workflows/pipeline-electron-build-and-test.yml + needs: checkout-macos + with: + build-runs-on: macos-14-xlarge + test-runs-on: macos-14-xlarge + target-platform: macos + target-arch: x64 + is-release: false + gn-build-type: testing + generate-symbols: false + upload-to-storage: '0' + secrets: inherit + + macos-arm64: + uses: ./.github/workflows/pipeline-electron-build-and-test.yml + needs: checkout-macos + with: + build-runs-on: macos-14-xlarge + test-runs-on: macos-14-xlarge + target-platform: macos + target-arch: arm64 + is-release: false + gn-build-type: testing + generate-symbols: false + upload-to-storage: '0' + secrets: inherit + + linux-x64: + uses: ./.github/workflows/pipeline-electron-build-and-test-and-nan.yml + needs: checkout-linux + with: + build-runs-on: aks-linux-large + test-runs-on: aks-linux-medium + build-container: '{"image":"ghcr.io/electron/build:latest","options":"--user root","volumes":["/mnt/cross-instance-cache:/mnt/cross-instance-cache"]}' + target-platform: linux + target-arch: x64 + is-release: false + gn-build-type: testing + generate-symbols: false + upload-to-storage: '0' + secrets: inherit + + linux-arm: + uses: ./.github/workflows/pipeline-electron-build-and-test.yml + needs: checkout-linux + with: + build-runs-on: aks-linux-large + test-runs-on: aks-linux-medium + build-container: '{"image":"ghcr.io/electron/build:latest","options":"--user root","volumes":["/mnt/cross-instance-cache:/mnt/cross-instance-cache"]}' + target-platform: linux + target-arch: arm + is-release: false + gn-build-type: testing + generate-symbols: false + upload-to-storage: '0' + secrets: inherit + + linux-arm64: + uses: ./.github/workflows/pipeline-electron-build-and-test.yml + needs: checkout-linux + with: + build-runs-on: aks-linux-large + test-runs-on: aks-linux-medium + build-container: '{"image":"ghcr.io/electron/build:latest","options":"--user root","volumes":["/mnt/cross-instance-cache:/mnt/cross-instance-cache"]}' + target-platform: linux + target-arch: arm64 + is-release: false + gn-build-type: testing + generate-symbols: false + upload-to-storage: '0' + secrets: inherit diff --git a/.github/workflows/linux-build.yml b/.github/workflows/linux-build.yml deleted file mode 100644 index 2ebe367436..0000000000 --- a/.github/workflows/linux-build.yml +++ /dev/null @@ -1,17 +0,0 @@ -name: Build Linux - -on: - workflow_dispatch: - # push: - # pull_request: - -jobs: - build: - uses: ./.github/workflows/linux-pipeline.yml - with: - is-release: false - gn-config: //electron/build/args/testing.gn - gn-build-type: testing - generate-symbols: false - upload-to-storage: '0' - secrets: inherit diff --git a/.github/workflows/linux-pipeline.yml b/.github/workflows/linux-pipeline.yml deleted file mode 100644 index 7f6c897b6d..0000000000 --- a/.github/workflows/linux-pipeline.yml +++ /dev/null @@ -1,505 +0,0 @@ -name: Linux Pipeline - -on: - workflow_call: - inputs: - is-release: - description: 'Whether this build job is a release job' - required: true - type: boolean - default: false - gn-config: - description: 'The gn arg configuration to use' - required: true - type: string - default: //electron/build/args/testing.gn - gn-build-type: - description: 'The gn build type - testing or release' - required: true - type: string - default: testing - generate-symbols: - description: 'Whether or not to generate symbols' - required: true - type: boolean - default: false - upload-to-storage: - description: 'Whether or not to upload build artifacts to external storage' - required: true - type: string - default: '0' - -concurrency: - group: ${{ github.workflow }}-${{ github.ref }} - cancel-in-progress: true - -env: - ELECTRON_ARTIFACTS_BLOB_STORAGE: ${{ secrets.ELECTRON_ARTIFACTS_BLOB_STORAGE }} - ELECTRON_RBE_JWT: ${{ secrets.ELECTRON_RBE_JWT }} - ELECTRON_GITHUB_TOKEN: ${{ secrets.ELECTRON_GITHUB_TOKEN }} - GN_CONFIG: ${{ inputs.gn-config }} - # Disable pre-compiled headers to reduce out size - only useful for rebuilds - GN_BUILDFLAG_ARGS: 'enable_precompiled_headers = false' - GCLIENT_EXTRA_ARGS: '--custom-var=checkout_arm=True --custom-var=checkout_arm64=True' - # Only disable this in the Asan build - CHECK_DIST_MANIFEST: true - IS_GHA_RELEASE: true - ELECTRON_OUT_DIR: Default - -jobs: - checkout: - runs-on: aks-linux-large - container: - image: ghcr.io/electron/build:latest - options: --user root - volumes: - - /mnt/cross-instance-cache:/mnt/cross-instance-cache - steps: - - name: Checkout Electron - uses: actions/checkout@a5ac7e51b41094c92402da3b24376905380afc29 - with: - path: src/electron - fetch-depth: 0 - - name: Checkout & Sync & Save - uses: ./src/electron/.github/actions/checkout - build: - strategy: - fail-fast: false - matrix: - build-arch: [ x64 ] # arm64, arm - env: - TARGET_ARCH: ${{ matrix.build-arch }} - runs-on: aks-linux-large - container: - image: ghcr.io/electron/build:latest - options: --user root - volumes: - - /mnt/cross-instance-cache:/mnt/cross-instance-cache - needs: checkout - steps: - - name: Load Build Tools - run: | - export BUILD_TOOLS_SHA=ef894bc3cfa99d84a3b731252da0f83f500e4032 - npm i -g @electron/build-tools - e auto-update disable - e init --root=$(pwd) --out=Default ${{ inputs.gn-build-type }} --import ${{ inputs.gn-build-type }} --target-cpu ${{ matrix.build-arch }} - - name: Checkout Electron - uses: actions/checkout@a5ac7e51b41094c92402da3b24376905380afc29 - with: - path: src/electron - fetch-depth: 0 - - name: Install Dependencies - run: | - cd src/electron - node script/yarn install - - name: Set GN_EXTRA_ARGS - run: | - if [ "${{ matrix.build-arch }}" = "arm" ]; then - GN_EXTRA_ARGS='target_cpu="arm" build_tflite_with_xnnpack=false' - elif [ "${{ matrix.build-arch }}" = "arm64" ]; then - GN_EXTRA_ARGS='target_cpu="arm64" fatal_linker_warnings=false enable_linux_installer=false' - fi - echo "GN_EXTRA_ARGS=$GN_EXTRA_ARGS" >> $GITHUB_ENV - - name: Get Depot Tools - timeout-minutes: 5 - run: | - git clone --depth=1 https://chromium.googlesource.com/chromium/tools/depot_tools.git - - sed -i '/ninjalog_uploader_wrapper.py/d' ./depot_tools/autoninja - cd depot_tools - git apply --3way ../src/electron/.github/workflows/config/gclient.diff - - # Ensure depot_tools does not update. - test -d depot_tools && cd depot_tools - touch .disable_auto_update - - name: Add Depot Tools to PATH - run: echo "$(pwd)/depot_tools" >> $GITHUB_PATH - - name: Generate DEPS Hash - run: | - node src/electron/script/generate-deps-hash.js && cat src/electron/.depshash-target - echo "DEPSHASH=v1-src-cache-$(shasum src/electron/.depshash | cut -f1 -d' ')" >> $GITHUB_ENV - - name: Restore and Ensure Src Cache - run: | - cache_path=/mnt/cross-instance-cache/$DEPSHASH.tar - echo "Using cache key: $DEPSHASH" - echo "Checking for cache in: $cache_path" - if [ ! -f "$cache_path" ]; then - echo "Cache Does Not Exist for $DEPSHASH - exiting" - exit 1 - else - echo "Found Cache for $DEPSHASH at $cache_path" - fi - - echo "Persisted cache is $(du -sh $cache_path | cut -f1)" - mkdir temp-cache - tar -xf $cache_path -C temp-cache - echo "Unzipped cache is $(du -sh temp-cache/src | cut -f1)" - - if [ -d "temp-cache/src" ]; then - echo "Relocating Cache" - rm -rf src - mv temp-cache/src src - fi - - if [ ! -d "src/third_party/blink" ]; then - echo "Cache was not correctly restored - exiting" - exit 1 - fi - - echo "Wiping Electron Directory" - rm -rf src/electron - - name: Checkout Electron - uses: actions/checkout@a5ac7e51b41094c92402da3b24376905380afc29 - with: - path: src/electron - fetch-depth: 0 - - name: Run Electron Only Hooks - run: | - echo "Running Electron Only Hooks" - gclient runhooks --spec="solutions=[{'name':'src/electron','url':None,'deps_file':'DEPS','custom_vars':{'process_deps':False},'managed':False}]" - - name: Regenerate DEPS Hash - run: | - (cd src/electron && git checkout .) && node src/electron/script/generate-deps-hash.js && cat src/electron/.depshash-target - echo "DEPSHASH=$(shasum src/electron/.depshash | cut -f1 -d' ')" >> $GITHUB_ENV - - name: Add CHROMIUM_BUILDTOOLS_PATH to env - run: echo "CHROMIUM_BUILDTOOLS_PATH=$(pwd)/src/buildtools" >> $GITHUB_ENV - - name: Install build-tools & Setup RBE - run: | - echo "NUMBER_OF_NINJA_PROCESSES=300" >> $GITHUB_ENV - cd ~/.electron_build_tools - npx yarn --ignore-engines - - # Pull down credential helper and print status - node -e "require('./src/utils/reclient.js').downloadAndPrepare({})" - HELPER=$(node -p "require('./src/utils/reclient.js').helperPath({})") - $HELPER login - - echo 'RBE_service='`node -e "console.log(require('./src/utils/reclient.js').serviceAddress)"` >> $GITHUB_ENV - echo 'RBE_experimental_credentials_helper='`node -e "console.log(require('./src/utils/reclient.js').helperPath({}))"` >> $GITHUB_ENV - echo 'RBE_experimental_credentials_helper_args=print' >> $GITHUB_ENV - - name: Build Electron - run: | - cd src/electron - # TODO(codebytere): remove this once we figure out why .git/packed-refs is initially missing - git pack-refs - cd .. - - NINJA_SUMMARIZE_BUILD=1 e build -j $NUMBER_OF_NINJA_PROCESSES - cp out/Default/.ninja_log out/electron_ninja_log - node electron/script/check-symlinks.js - - name: Build Electron dist.zip - run: | - cd src - e build electron:electron_dist_zip -j $NUMBER_OF_NINJA_PROCESSES - if [ "${{ env.CHECK_DIST_MANIFEST }}" = "true" ]; then - target_os=linux - target_cpu=${{ matrix.build-arch }} - electron/script/zip_manifests/check-zip-manifest.py out/Default/dist.zip electron/script/zip_manifests/dist_zip.$target_os.${{ matrix.build-arch }}.manifest - fi - - name: Build Mksnapshot - run: | - cd src - e build electron:electron_mksnapshot -j $NUMBER_OF_NINJA_PROCESSES - gn desc out/Default v8:run_mksnapshot_default args > out/Default/mksnapshot_args - - # Remove unused args from mksnapshot_args - SEDOPTION="-i" - sed $SEDOPTION '/.*builtins-pgo/d' out/Default/mksnapshot_args - sed $SEDOPTION '/--turbo-profiling-input/d' out/Default/mksnapshot_args - sed $SEDOPTION '/The gn arg use_goma=true .*/d' out/Default/mksnapshot_args - - if [ "${{ matrix.build-arch }}" = "arm" ]; then - electron/script/strip-binaries.py --file $PWD/out/Default/clang_x86_v8_arm/mksnapshot - electron/script/strip-binaries.py --file $PWD/out/Default/clang_x86_v8_arm/v8_context_snapshot_generator - elif [ "${{ matrix.build-arch }}" = "arm64" ]; then - electron/script/strip-binaries.py --file $PWD/out/Default/clang_x64_v8_arm64/mksnapshot - electron/script/strip-binaries.py --file $PWD/out/Default/clang_x64_v8_arm64/v8_context_snapshot_generator - else - electron/script/strip-binaries.py --file $PWD/out/Default/mksnapshot - electron/script/strip-binaries.py --file $PWD/out/Default/v8_context_snapshot_generator - fi - - e build electron:electron_mksnapshot_zip -j $NUMBER_OF_NINJA_PROCESSES - (cd out/Default; zip mksnapshot.zip mksnapshot_args gen/v8/embedded.S) - - name: Generate Cross-Arch Snapshot (arm/arm64) - if: ${{ matrix.build-arch == 'arm' || matrix.build-arch == 'arm64' }} - run: | - cd src - if [ "${{ matrix.build-arch }}" = "arm" ]; then - MKSNAPSHOT_PATH="clang_x86_v8_arm" - elif [ "${{ matrix.build-arch }}" = "arm64" ]; then - MKSNAPSHOT_PATH="clang_x64_v8_arm64" - fi - - cp "out/Default/$MKSNAPSHOT_PATH/mksnapshot" out/Default - cp "out/Default/$MKSNAPSHOT_PATH/v8_context_snapshot_generator" out/Default - cp "out/Default/$MKSNAPSHOT_PATH/libffmpeg.so" out/Default - - python3 electron/script/verify-mksnapshot.py --source-root "$PWD" --build-dir out/Default --create-snapshot-only - mkdir cross-arch-snapshots - cp out/Default-mksnapshot-test/*.bin cross-arch-snapshots - # Clean up so that ninja does not get confused - rm -f out/Default/libffmpeg.so - - name: Build Chromedriver - run: | - cd src - e build electron:electron_chromedriver -j $NUMBER_OF_NINJA_PROCESSES - e build electron:electron_chromedriver_zip - - name: Build Node.js headers - run: | - cd src - e build electron:node_headers - - name: Generate & Zip Symbols - run: | - # Generate breakpad symbols on release builds - if [ "${{ inputs.generate-symbols }}" = "true" ]; then - e build electron:electron_symbols - fi - cd src - export BUILD_PATH="$(pwd)/out/Default" - e build electron:licenses - e build electron:electron_version_file - if [ "${{ inputs.is-release }}" = "true" ]; then - DELETE_DSYMS_AFTER_ZIP=1 electron/script/zip-symbols.py -b $BUILD_PATH - else - electron/script/zip-symbols.py -b $BUILD_PATH - fi - - name: Generate FFMpeg - if: ${{ inputs.is-release }} - run: | - cd src - gn gen out/ffmpeg --args="import(\"//electron/build/args/ffmpeg.gn\") use_remoteexec=true $GN_EXTRA_ARGS" - autoninja -C out/ffmpeg electron:electron_ffmpeg_zip -j $NUMBER_OF_NINJA_PROCESSES - - name: Generate Hunspell Dictionaries - if: ${{ inputs.is-release }} - run: | - cd src - autoninja -C out/Default electron:hunspell_dictionaries_zip -j $NUMBER_OF_NINJA_PROCESSES - - name: Generate Libcxx - if: ${{ inputs.is-release }} - run: | - cd src - autoninja -C out/Default electron:libcxx_headers_zip -j $NUMBER_OF_NINJA_PROCESSES - autoninja -C out/Default electron:libcxxabi_headers_zip -j $NUMBER_OF_NINJA_PROCESSES - autoninja -C out/Default electron:libcxx_objects_zip -j $NUMBER_OF_NINJA_PROCESSES - - name: Publish Electron Dist - if: ${{ inputs.is-release }} - run: | - rm -rf src/out/Default/obj - cd src/electron - if [ "${{ inputs.upload-to-storage }}" = "1" ]; then - echo 'Uploading Electron release distribution to Azure' - script/release/uploaders/upload.py --verbose --upload_to_storage - else - echo 'Uploading Electron release distribution to GitHub releases' - script/release/uploaders/upload.py --verbose - fi - - name: Move all Generated Artifacts to Upload Folder - run: ./src/electron/script/actions/move-artifacts.sh - - name: Upload Generated Artifacts - uses: actions/upload-artifact@65462800fd760344b1a7b4382951275a0abb4808 - with: - name: generated_artifacts_linux_${{ matrix.build-arch }} - path: ./generated_artifacts_linux_${{ matrix.build-arch }} - test: - if: ${{ inputs.is-release == false }} - runs-on: aks-linux-medium - container: - image: ghcr.io/electron/build:latest - options: --user root - needs: build - strategy: - fail-fast: false - matrix: - build-arch: [ arm64 ] # x64, arm - env: - TARGET_ARCH: ${{ matrix.build-arch }} - steps: - - name: Load Build Tools - run: | - export BUILD_TOOLS_SHA=ef894bc3cfa99d84a3b731252da0f83f500e4032 - npm i -g @electron/build-tools - e auto-update disable - e init --root=$(pwd) --out=Default ${{ inputs.gn-build-type }} - - name: Checkout Electron - uses: actions/checkout@a5ac7e51b41094c92402da3b24376905380afc29 - with: - path: src/electron - fetch-depth: 0 - - name: Install Dependencies - run: | - cd src/electron - node script/yarn install - - name: Get Depot Tools - timeout-minutes: 5 - run: | - git clone --depth=1 https://chromium.googlesource.com/chromium/tools/depot_tools.git - - sed -i '/ninjalog_uploader_wrapper.py/d' ./depot_tools/autoninja - cd depot_tools - git apply --3way ../src/electron/.github/workflows/config/gclient.diff - - # Ensure depot_tools does not update. - test -d depot_tools && cd depot_tools - touch .disable_auto_update - - name: Add Depot Tools to PATH - run: echo "$(pwd)/depot_tools" >> $GITHUB_PATH - - name: Download Generated Artifacts - uses: actions/download-artifact@65a9edc5881444af0b9093a5e628f2fe47ea3b2e - with: - name: generated_artifacts_linux_${{ matrix.build-arch }} - path: ./generated_artifacts_linux_${{ matrix.build-arch }} - - name: Restore Generated Artifacts - run: ./src/electron/script/actions/restore-artifacts.sh - - name: Unzip Dist, Mksnapshot & Chromedriver - run: | - cd src/out/Default - unzip -:o dist.zip - unzip -:o chromedriver.zip - unzip -:o mksnapshot.zip - - name: Setup for headless testing - run: sh -e /etc/init.d/xvfb start - - name: Run Electron Tests - env: - MOCHA_REPORTER: mocha-multi-reporters - ELECTRON_TEST_RESULTS_DIR: junit - MOCHA_MULTI_REPORTERS: mocha-junit-reporter, tap - ELECTRON_DISABLE_SECURITY_WARNINGS: 1 - ELECTRON_SKIP_NATIVE_MODULE_TESTS: true - run: | - cd src/electron - node script/yarn test --runners=main --trace-uncaught --enable-logging - - name: Wait for active SSH sessions - if: always() && !cancelled() - run: | - while [ -f /var/.ssh-lock ] - do - sleep 60 - done - node-tests: - name: Run Node.js Tests - if: ${{ inputs.is-release == false }} - runs-on: aks-linux-medium - needs: build - timeout-minutes: 20 - env: - TARGET_ARCH: x64 - container: - image: ghcr.io/electron/build:latest - options: --user root - steps: - - name: Load Build Tools - run: | - export BUILD_TOOLS_SHA=ef894bc3cfa99d84a3b731252da0f83f500e4032 - npm i -g @electron/build-tools - e auto-update disable - e init --root=$(pwd) --out=Default ${{ inputs.gn-build-type }} - - name: Checkout Electron - uses: actions/checkout@a5ac7e51b41094c92402da3b24376905380afc29 - with: - path: src/electron - fetch-depth: 0 - - name: Install Dependencies - run: | - cd src/electron - node script/yarn install - - name: Get Depot Tools - timeout-minutes: 5 - run: | - git clone --depth=1 https://chromium.googlesource.com/chromium/tools/depot_tools.git - sed -i '/ninjalog_uploader_wrapper.py/d' ./depot_tools/autoninja - cd depot_tools - git apply --3way ../src/electron/.github/workflows/config/gclient.diff - # Ensure depot_tools does not update. - test -d depot_tools && cd depot_tools - touch .disable_auto_update - - name: Add Depot Tools to PATH - run: echo "$(pwd)/depot_tools" >> $GITHUB_PATH - - name: Download Generated Artifacts - uses: actions/download-artifact@65a9edc5881444af0b9093a5e628f2fe47ea3b2e - with: - name: generated_artifacts_linux_${{ env.TARGET_ARCH }} - path: ./generated_artifacts_linux_${{ env.TARGET_ARCH }} - - name: Restore Generated Artifacts - run: ./src/electron/script/actions/restore-artifacts.sh - - name: Unzip Dist - run: | - cd src/out/Default - unzip -:o dist.zip - - name: Setup Linux for Headless Testing - run: sh -e /etc/init.d/xvfb start - - name: Run Node.js Tests - run: | - cd src - node electron/script/node-spec-runner.js --default --jUnitDir=junit - - name: Wait for active SSH sessions - if: always() && !cancelled() - run: | - while [ -f /var/.ssh-lock ] - do - sleep 60 - done - nan-tests: - name: Run Nan Tests - if: ${{ inputs.is-release == false }} - runs-on: aks-linux-medium - needs: build - timeout-minutes: 20 - env: - TARGET_ARCH: x64 - container: - image: ghcr.io/electron/build:latest - options: --user root - steps: - - name: Load Build Tools - run: | - export BUILD_TOOLS_SHA=ef894bc3cfa99d84a3b731252da0f83f500e4032 - npm i -g @electron/build-tools - e auto-update disable - e init --root=$(pwd) --out=Default ${{ inputs.gn-build-type }} - - name: Checkout Electron - uses: actions/checkout@a5ac7e51b41094c92402da3b24376905380afc29 - with: - path: src/electron - fetch-depth: 0 - - name: Install Dependencies - run: | - cd src/electron - node script/yarn install - - name: Get Depot Tools - timeout-minutes: 5 - run: | - git clone --depth=1 https://chromium.googlesource.com/chromium/tools/depot_tools.git - sed -i '/ninjalog_uploader_wrapper.py/d' ./depot_tools/autoninja - cd depot_tools - git apply --3way ../src/electron/.github/workflows/config/gclient.diff - # Ensure depot_tools does not update. - test -d depot_tools && cd depot_tools - touch .disable_auto_update - - name: Add Depot Tools to PATH - run: echo "$(pwd)/depot_tools" >> $GITHUB_PATH - - name: Download Generated Artifacts - uses: actions/download-artifact@65a9edc5881444af0b9093a5e628f2fe47ea3b2e - with: - name: generated_artifacts_linux_${{ env.TARGET_ARCH }} - path: ./generated_artifacts_linux_${{ env.TARGET_ARCH }} - - name: Restore Generated Artifacts - run: ./src/electron/script/actions/restore-artifacts.sh - - name: Unzip Dist - run: | - cd src/out/Default - unzip -:o dist.zip - - name: Setup Linux for Headless Testing - run: sh -e /etc/init.d/xvfb start - - name: Run Node.js Tests - run: | - cd src - node electron/script/nan-spec-runner.js - - name: Wait for active SSH sessions - if: always() && !cancelled() - run: | - while [ -f /var/.ssh-lock ] - do - sleep 60 - done - diff --git a/.github/workflows/linux-publish.yml b/.github/workflows/linux-publish.yml index edb985d8ef..65cca48697 100644 --- a/.github/workflows/linux-publish.yml +++ b/.github/workflows/linux-publish.yml @@ -14,11 +14,64 @@ on: default: false jobs: - publish: - uses: ./.github/workflows/linux-pipeline.yml + checkout-linux: + runs-on: aks-linux-large + container: + image: ghcr.io/electron/build:latest + options: --user root + volumes: + - /mnt/cross-instance-cache:/mnt/cross-instance-cache + - /var/run/sas:/var/run/sas + env: + GCLIENT_EXTRA_ARGS: '--custom-var=checkout_mac=True --custom-var=host_os=mac' + steps: + - name: Checkout Electron + uses: actions/checkout@a5ac7e51b41094c92402da3b24376905380afc29 + with: + path: src/electron + fetch-depth: 0 + - name: Checkout & Sync & Save + uses: ./src/electron/.github/actions/checkout + with: + gclient-extra-args: '--custom-var=checkout_arm=True --custom-var=checkout_arm64=True' + + publish-x64: + uses: ./.github/workflows/pipeline-segment-electron-build.yml + needs: checkout-linux + with: + build-runs-on: aks-linux-large + build-container: '{"image":"ghcr.io/electron/build:latest","options":"--user root","volumes":["/mnt/cross-instance-cache:/mnt/cross-instance-cache"]}' + target-platform: linux + target-arch: x64 + is-release: true + gn-build-type: release + generate-symbols: true + upload-to-storage: ${{ inputs.upload-to-storage }} + secrets: inherit + + publish-arm: + uses: ./.github/workflows/pipeline-segment-electron-build.yml + needs: checkout-linux + with: + build-runs-on: aks-linux-large + build-container: '{"image":"ghcr.io/electron/build:latest","options":"--user root","volumes":["/mnt/cross-instance-cache:/mnt/cross-instance-cache"]}' + target-platform: linux + target-arch: arm + is-release: true + gn-build-type: release + generate-symbols: true + upload-to-storage: ${{ inputs.upload-to-storage }} + secrets: inherit + + publish-arm64: + uses: ./.github/workflows/pipeline-segment-electron-build.yml + needs: checkout-linux with: + build-runs-on: aks-linux-large + build-container: '{"image":"ghcr.io/electron/build:latest","options":"--user root","volumes":["/mnt/cross-instance-cache:/mnt/cross-instance-cache"]}' + target-platform: linux + target-arch: arm64 is-release: true - gn-config: //electron/build/args/release.gn gn-build-type: release generate-symbols: true upload-to-storage: ${{ inputs.upload-to-storage }} diff --git a/.github/workflows/macos-build.yml b/.github/workflows/macos-build.yml deleted file mode 100644 index 5a0c55fde6..0000000000 --- a/.github/workflows/macos-build.yml +++ /dev/null @@ -1,17 +0,0 @@ -name: Build MacOS - -on: - workflow_dispatch: - # push - # pull_request: - -jobs: - build: - uses: ./.github/workflows/macos-pipeline.yml - with: - is-release: false - gn-config: //electron/build/args/testing.gn - gn-build-type: testing - generate-symbols: false - upload-to-storage: '0' - secrets: inherit diff --git a/.github/workflows/macos-pipeline.yml b/.github/workflows/macos-pipeline.yml deleted file mode 100644 index 961f3be1da..0000000000 --- a/.github/workflows/macos-pipeline.yml +++ /dev/null @@ -1,594 +0,0 @@ -name: MacOS Pipeline - -on: - workflow_call: - inputs: - is-release: - description: 'Whether this build job is a release job' - required: true - type: boolean - default: false - gn-config: - description: 'The gn arg configuration to use' - required: true - type: string - default: //electron/build/args/testing.gn - gn-build-type: - description: 'The gn build type - testing or release' - required: true - type: string - default: testing - generate-symbols: - description: 'Whether or not to generate symbols' - required: true - type: boolean - default: false - upload-to-storage: - description: 'Whether or not to upload build artifacts to external storage' - required: true - type: string - default: '0' - -concurrency: - group: ${{ github.workflow }}-${{ github.ref }} - cancel-in-progress: true - -env: - AZURE_AKS_CACHE_STORAGE_ACCOUNT: ${{ secrets.AZURE_AKS_CACHE_STORAGE_ACCOUNT }} - AZURE_AKS_CACHE_SHARE_NAME: ${{ secrets.AZURE_AKS_CACHE_SHARE_NAME }} - ELECTRON_ARTIFACTS_BLOB_STORAGE: ${{ secrets.ELECTRON_ARTIFACTS_BLOB_STORAGE }} - ELECTRON_RBE_JWT: ${{ secrets.ELECTRON_RBE_JWT }} - ELECTRON_GITHUB_TOKEN: ${{ secrets.ELECTRON_GITHUB_TOKEN }} - GN_CONFIG: ${{ inputs.gn-config }} - # Disable pre-compiled headers to reduce out size - only useful for rebuilds - GN_BUILDFLAG_ARGS: 'enable_precompiled_headers=false' - GCLIENT_EXTRA_ARGS: '--custom-var=checkout_mac=True --custom-var=host_os=mac' - # Only disable this in the Asan build - CHECK_DIST_MANIFEST: true - IS_GHA_RELEASE: true - ELECTRON_OUT_DIR: Default - -jobs: - checkout: - runs-on: aks-linux-large - container: - image: ghcr.io/electron/build:latest - options: --user root - volumes: - - /mnt/cross-instance-cache:/mnt/cross-instance-cache - - /var/run/sas:/var/run/sas - steps: - - name: Checkout Electron - uses: actions/checkout@a5ac7e51b41094c92402da3b24376905380afc29 - with: - path: src/electron - fetch-depth: 0 - - name: Checkout & Sync & Save - uses: ./src/electron/.github/actions/checkout - with: - generate-sas-token: 'true' - build: - strategy: - fail-fast: false - matrix: - build-arch: [ arm64, x64 ] - # macos-large is x64, macos-xlarge is arm64 - # More runner information: https://github.com/actions/runner-images/blob/main/README.md#available-images - runs-on: macos-14-xlarge - needs: checkout - env: - TARGET_ARCH: ${{ matrix.build-arch }} - steps: - - name: Load Build Tools - run: | - export BUILD_TOOLS_SHA=ef894bc3cfa99d84a3b731252da0f83f500e4032 - npm i -g @electron/build-tools - e auto-update disable - e init --root=$(pwd) --out=Default ${{ inputs.gn-build-type }} --import ${{ inputs.gn-build-type }} --target-cpu ${{ matrix.build-arch }} - - name: Checkout Electron - uses: actions/checkout@a5ac7e51b41094c92402da3b24376905380afc29 - with: - path: src/electron - fetch-depth: 0 - - name: Setup Node.js/npm - uses: actions/setup-node@60edb5dd545a775178f52524783378180af0d1f8 - with: - node-version: 20.11.x - cache: yarn - cache-dependency-path: src/electron/yarn.lock - - name: Install Dependencies - run: | - cd src/electron - node script/yarn install - brew install azcopy - - name: Load Target Arch & CPU - run: | - echo "target_cpu=${{ matrix.build-arch }}" >> $GITHUB_ENV - echo "host_cpu=${{ matrix.build-arch }}" >> $GITHUB_ENV - - name: Get Depot Tools - timeout-minutes: 5 - run: | - git clone --depth=1 https://chromium.googlesource.com/chromium/tools/depot_tools.git - - # remove ninjalog_uploader_wrapper.py from autoninja since we don't use it and it causes problems - sed -i '' '/ninjalog_uploader_wrapper.py/d' ./depot_tools/autoninja - - # Ensure depot_tools does not update. - test -d depot_tools && cd depot_tools - touch .disable_auto_update - - name: Add Depot Tools to PATH - run: echo "$(pwd)/depot_tools" >> $GITHUB_PATH - - name: Generate DEPS Hash - run: | - node src/electron/script/generate-deps-hash.js && cat src/electron/.depshash-target - DEPSHASH=v1-src-cache-$(shasum src/electron/.depshash | cut -f1 -d' ') - echo "DEPSHASH=$DEPSHASH" >> $GITHUB_ENV - echo "CACHE_PATH=$DEPSHASH.tar" >> $GITHUB_ENV - - name: Obtain SAS Key - uses: actions/cache/restore@v4 - with: - path: | - sas-token - key: sas-key-${{ github.run_number }}-${{ github.run_attempt }} - - name: Download Src Cache from AKS - # The cache will always exist here as a result of the checkout job - # Either it was uploaded to Azure in the checkout job for this commit - # or it was uploaded in the checkout job for a previous commit. - uses: nick-fields/retry@7152eba30c6575329ac0576536151aca5a72780e # v3.0.0 - with: - timeout_minutes: 20 - max_attempts: 3 - retry_on: error - command: | - sas_token=$(cat sas-token) - azcopy copy \ - "https://${{ env.AZURE_AKS_CACHE_STORAGE_ACCOUNT }}.file.core.windows.net/${{ env.AZURE_AKS_CACHE_SHARE_NAME }}/${{ env.CACHE_PATH }}?$sas_token" $DEPSHASH.tar - - name: Clean SAS Key - run: rm -f sas-token - - name: Unzip and Ensure Src Cache - run: | - echo "Downloaded cache is $(du -sh $DEPSHASH.tar | cut -f1)" - mkdir temp-cache - tar -xf $DEPSHASH.tar -C temp-cache - echo "Unzipped cache is $(du -sh temp-cache/src | cut -f1)" - - if [ -d "temp-cache/src" ]; then - echo "Relocating Cache" - rm -rf src - mv temp-cache/src src - - echo "Deleting zip file" - rm -rf $DEPSHASH.tar - fi - - if [ ! -d "src/third_party/blink" ]; then - echo "Cache was not correctly restored - exiting" - exit 1 - fi - - echo "Wiping Electron Directory" - rm -rf src/electron - - name: Checkout Electron - uses: actions/checkout@a5ac7e51b41094c92402da3b24376905380afc29 - with: - path: src/electron - fetch-depth: 0 - - name: Run Electron Only Hooks - run: | - gclient runhooks --spec="solutions=[{'name':'src/electron','url':None,'deps_file':'DEPS','custom_vars':{'process_deps':False},'managed':False}]" - - name: Regenerate DEPS Hash - run: | - (cd src/electron && git checkout .) && node src/electron/script/generate-deps-hash.js && cat src/electron/.depshash-target - echo "DEPSHASH=$(shasum src/electron/.depshash | cut -f1 -d' ')" >> $GITHUB_ENV - - name: Add CHROMIUM_BUILDTOOLS_PATH to env - run: echo "CHROMIUM_BUILDTOOLS_PATH=$(pwd)/src/buildtools" >> $GITHUB_ENV - - name: Fix Sync - # This step is required to correct for differences between "gclient sync" - # on Linux and the expected state on macOS. This requires: - # 1. Fixing Clang Install (wrong binary) - # 2. Fixing esbuild (wrong binary) - # 3. Fixing rustc (wrong binary) - # 4. Fixing gn (wrong binary) - # 5. Fix reclient (wrong binary) - # 6. Fixing dsymutil (wrong binary) - # 7. Ensuring we are using the correct ninja and adding it to PATH - # 8. Fixing angle (wrong remote) - run : | - SEDOPTION="-i ''" - rm -rf src/third_party/llvm-build - python3 src/tools/clang/scripts/update.py - - echo 'infra/3pp/tools/esbuild/${platform}' `gclient getdep --deps-file=src/third_party/devtools-frontend/src/DEPS -r 'third_party/esbuild:infra/3pp/tools/esbuild/${platform}'` > esbuild_ensure_file - # Remove extra output from calling gclient getdep which always calls update_depot_tools - sed -i '' "s/Updating depot_tools... //g" esbuild_ensure_file - cipd ensure --root src/third_party/devtools-frontend/src/third_party/esbuild -ensure-file esbuild_ensure_file - - rm -rf src/third_party/rust-toolchain - python3 src/tools/rust/update_rust.py - - # Prevent calling gclient getdep which always calls update_depot_tools - echo 'gn/gn/mac-${arch}' `gclient getdep --deps-file=src/DEPS -r 'src/buildtools/mac:gn/gn/mac-${arch}'` > gn_ensure_file - sed -i '' "s/Updating depot_tools... //g" gn_ensure_file - cipd ensure --root src/buildtools/mac -ensure-file gn_ensure_file - - # Prevent calling gclient getdep which always calls update_depot_tools - echo 'infra/rbe/client/${platform}' `gclient getdep --deps-file=src/DEPS -r 'src/buildtools/reclient:infra/rbe/client/${platform}'` > gn_ensure_file - sed -i '' "s/Updating depot_tools... //g" gn_ensure_file - cipd ensure --root src/buildtools/reclient -ensure-file gn_ensure_file - python3 src/buildtools/reclient_cfgs/configure_reclient_cfgs.py --rbe_instance "projects/rbe-chrome-untrusted/instances/default_instance" --reproxy_cfg_template reproxy.cfg.template --rewrapper_cfg_project "" --skip_remoteexec_cfg_fetch - - if [ "${{ env.TARGET_ARCH }}" == "arm64" ]; then - DSYM_SHA_FILE=src/tools/clang/dsymutil/bin/dsymutil.arm64.sha1 - else - DSYM_SHA_FILE=src/tools/clang/dsymutil/bin/dsymutil.x64.sha1 - fi - python3 src/third_party/depot_tools/download_from_google_storage.py --no_resume --no_auth --bucket chromium-browser-clang -s $DSYM_SHA_FILE -o src/tools/clang/dsymutil/bin/dsymutil - - echo 'infra/3pp/tools/ninja/${platform}' `gclient getdep --deps-file=src/DEPS -r 'src/third_party/ninja:infra/3pp/tools/ninja/${platform}'` > ninja_ensure_file - sed $SEDOPTION "s/Updating depot_tools... //g" ninja_ensure_file - cipd ensure --root src/third_party/ninja -ensure-file ninja_ensure_file - - echo "$(pwd)/src/third_party/ninja" >> $GITHUB_PATH - - cd src/third_party/angle - rm -f .git/objects/info/alternates - git remote set-url origin https://chromium.googlesource.com/angle/angle.git - cp .git/config .git/config.backup - git remote remove origin - mv .git/config.backup .git/config - git fetch - - name: Install build-tools & Setup RBE - run: | - echo "NUMBER_OF_NINJA_PROCESSES=200" >> $GITHUB_ENV - cd ~/.electron_build_tools - npx yarn --ignore-engines - # Pull down credential helper and print status - node -e "require('./src/utils/reclient.js').downloadAndPrepare({})" - HELPER=$(node -p "require('./src/utils/reclient.js').helperPath({})") - $HELPER login - echo 'RBE_service='`node -e "console.log(require('./src/utils/reclient.js').serviceAddress)"` >> $GITHUB_ENV - echo 'RBE_experimental_credentials_helper='`node -e "console.log(require('./src/utils/reclient.js').helperPath({}))"` >> $GITHUB_ENV - echo 'RBE_experimental_credentials_helper_args=print' >> $GITHUB_ENV - - name: Free Space on MacOS - run: | - sudo mkdir -p $TMPDIR/del-target - - tmpify() { - if [ -d "$1" ]; then - sudo mv "$1" $TMPDIR/del-target/$(echo $1|shasum -a 256|head -n1|cut -d " " -f1) - fi - } - - strip_universal_deep() { - opwd=$(pwd) - cd $1 - f=$(find . -perm +111 -type f) - for fp in $f - do - if [[ $(file "$fp") == *"universal binary"* ]]; then - if [ "`arch`" == "arm64" ]; then - if [[ $(file "$fp") == *"x86_64"* ]]; then - sudo lipo -remove x86_64 "$fp" -o "$fp" || true - fi - else - if [[ $(file "$fp") == *"arm64e)"* ]]; then - sudo lipo -remove arm64e "$fp" -o "$fp" || true - fi - if [[ $(file "$fp") == *"arm64)"* ]]; then - sudo lipo -remove arm64 "$fp" -o "$fp" || true - fi - fi - fi - done - - cd $opwd - } - - tmpify /Library/Developer/CoreSimulator - tmpify ~/Library/Developer/CoreSimulator - tmpify $(xcode-select -p)/Platforms/AppleTVOS.platform - tmpify $(xcode-select -p)/Platforms/iPhoneOS.platform - tmpify $(xcode-select -p)/Platforms/WatchOS.platform - tmpify $(xcode-select -p)/Platforms/WatchSimulator.platform - tmpify $(xcode-select -p)/Platforms/AppleTVSimulator.platform - tmpify $(xcode-select -p)/Platforms/iPhoneSimulator.platform - tmpify $(xcode-select -p)/Toolchains/XcodeDefault.xctoolchain/usr/metal/ios - tmpify $(xcode-select -p)/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift - tmpify $(xcode-select -p)/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift-5.0 - tmpify ~/.rubies - tmpify ~/Library/Caches/Homebrew - tmpify /usr/local/Homebrew - - # the contents of build/linux/strip_binary.gni aren't used, but - # https://chromium-review.googlesource.com/c/chromium/src/+/4278307 - # needs the file to exist. - # mv ~/project/src/build/linux/strip_binary.gni "${TMPDIR}"/ - # tmpify ~/project/src/build/linux/ - # mkdir -p ~/project/src/build/linux - # mv "${TMPDIR}/strip_binary.gni" ~/project/src/build/linux/ - - sudo rm -rf $TMPDIR/del-target - - # sudo rm -rf "/System/Library/Desktop Pictures" - # sudo rm -rf /System/Library/Templates/Data - # sudo rm -rf /System/Library/Speech/Voices - # sudo rm -rf "/System/Library/Screen Savers" - # sudo rm -rf /System/Volumes/Data/Library/Developer/CommandLineTools/SDKs - # sudo rm -rf "/System/Volumes/Data/Library/Application Support/Apple/Photos/Print Products" - # sudo rm -rf /System/Volumes/Data/Library/Developer/CommandLineTools/SDKs/MacOSX10.15.sdk/ - # sudo rm -rf /System/Volumes/Data/Library/Java - # sudo rm -rf /System/Volumes/Data/Library/Ruby - # sudo rm -rf /System/Volumes/Data/Library/Printers - # sudo rm -rf /System/iOSSupport - # sudo rm -rf /System/Applications/*.app - # sudo rm -rf /System/Applications/Utilities/*.app - # sudo rm -rf /System/Library/LinguisticData - # sudo rm -rf /System/Volumes/Data/private/var/db/dyld/* - # sudo rm -rf /System/Library/Fonts/* - # sudo rm -rf /System/Library/PreferencePanes - # sudo rm -rf /System/Library/AssetsV2/* - sudo rm -rf /Applications/Safari.app - sudo rm -rf ~/project/src/third_party/catapult/tracing/test_data - sudo rm -rf ~/project/src/third_party/angle/third_party/VK-GL-CTS - - # lipo off some huge binaries arm64 versions to save space - strip_universal_deep $(xcode-select -p)/../SharedFrameworks - # strip_arm_deep /System/Volumes/Data/Library/Developer/CommandLineTools/usr - - name: Build Electron (darwin) - run: | - cd src/electron - # TODO(codebytere): remove this once we figure out why .git/packed-refs is initially missing - git pack-refs - cd .. - ulimit -n 10000 - sudo launchctl limit maxfiles 65536 200000 - - NINJA_SUMMARIZE_BUILD=1 e build -j $NUMBER_OF_NINJA_PROCESSES - cp out/Default/.ninja_log out/electron_ninja_log - node electron/script/check-symlinks.js - - name: Build Electron dist.zip (darwin) - run: | - cd src - e build electron:electron_dist_zip -j $NUMBER_OF_NINJA_PROCESSES - if [ "${{ env.CHECK_DIST_MANIFEST }}" == "true" ]; then - target_os=mac - electron/script/zip_manifests/check-zip-manifest.py out/Default/dist.zip electron/script/zip_manifests/dist_zip.$target_os.${{ env.TARGET_ARCH }}.manifest - fi - - name: Build Mksnapshot (darwin) - run: | - cd src - e build electron:electron_mksnapshot -j $NUMBER_OF_NINJA_PROCESSES - gn desc out/Default v8:run_mksnapshot_default args > out/Default/mksnapshot_args - # Remove unused args from mksnapshot_args - SEDOPTION="-i ''" - sed $SEDOPTION '/.*builtins-pgo/d' out/Default/mksnapshot_args - sed $SEDOPTION '/--turbo-profiling-input/d' out/Default/mksnapshot_args - sed $SEDOPTION '/The gn arg use_goma=true .*/d' out/Default/mksnapshot_args - e build electron:electron_mksnapshot_zip -j $NUMBER_OF_NINJA_PROCESSES - (cd out/Default; zip mksnapshot.zip mksnapshot_args gen/v8/embedded.S) - - name: Build Chromedriver (darwin) - run: | - cd src - e build electron:electron_chromedriver -j $NUMBER_OF_NINJA_PROCESSES - e build electron:electron_chromedriver_zip - # NOTE (vertedinde): We strip binaries/symbols on the Linux job, not the Mac job - - name: Generate & Zip Symbols (darwin) - run: | - # Generate breakpad symbols on release builds - if [ "${{ inputs.generate-symbols }}" == "true" ]; then - e build electron:electron_symbols - fi - cd src - export BUILD_PATH="$(pwd)/out/Default" - e build electron:licenses - e build electron:electron_version_file - if [ "${{ inputs.is-release }}" == "true" ]; then - DELETE_DSYMS_AFTER_ZIP=1 electron/script/zip-symbols.py -b $BUILD_PATH - else - electron/script/zip-symbols.py -b $BUILD_PATH - fi - - name: Generate FFMpeg (darwin) - if: ${{ inputs.is-release }} - run: | - cd src - gn gen out/ffmpeg --args="import(\"//electron/build/args/ffmpeg.gn\") use_remoteexec=true $GN_EXTRA_ARGS" - autoninja -C out/ffmpeg electron:electron_ffmpeg_zip -j $NUMBER_OF_NINJA_PROCESSES - - name: Generate TypeScript Definitions - if: ${{ inputs.is-release }} - run: | - cd src/electron - node script/yarn create-typescript-definitions - # TODO(vertedinde): These uploads currently point to a different Azure bucket & GitHub Repo - - name: Publish Electron Dist - if: ${{ inputs.is-release }} - run: | - rm -rf src/out/Default/obj - cd src/electron - if [ "${{ inputs.upload-to-storage }}" == "1" ]; then - echo 'Uploading Electron release distribution to Azure' - script/release/uploaders/upload.py --verbose --upload_to_storage - else - echo 'Uploading Electron release distribution to GitHub releases' - script/release/uploaders/upload.py --verbose - fi - # The current generated_artifacts_<< artifact.key >> name was taken from CircleCI - # to ensure we don't break anything, but we may be able to improve that. - - name: Move all Generated Artifacts to Upload Folder - run: ./src/electron/script/actions/move-artifacts.sh - - name: Upload Generated Artifacts - uses: actions/upload-artifact@65462800fd760344b1a7b4382951275a0abb4808 - with: - name: generated_artifacts_darwin_${{ env.TARGET_ARCH }} - path: ./generated_artifacts_darwin_${{ env.TARGET_ARCH }} - - name: Set GN_EXTRA_ARGS for MAS Build - run: | - echo "MAS_BUILD=true" >> $GITHUB_ENV - GN_EXTRA_ARGS='is_mas_build=true' - echo "GN_EXTRA_ARGS=$GN_EXTRA_ARGS" >> $GITHUB_ENV - - name: Build Electron (mas) - run: | - rm -rf "src/out/Default/Electron Framework.framework" - rm -rf src/out/Default/Electron*.app - - cd src/electron - # TODO(codebytere): remove this once we figure out why .git/packed-refs is initially missing - git pack-refs - cd .. - - ulimit -n 10000 - sudo launchctl limit maxfiles 65536 200000 - NINJA_SUMMARIZE_BUILD=1 e build -j $NUMBER_OF_NINJA_PROCESSES - cp out/Default/.ninja_log out/electron_ninja_log - node electron/script/check-symlinks.js - - name: Build Electron dist.zip (mas) - run: | - cd src - e build electron:electron_dist_zip -j $NUMBER_OF_NINJA_PROCESSES - if [ "${{ env.CHECK_DIST_MANIFEST }}" == "true" ]; then - target_os=mac_mas - electron/script/zip_manifests/check-zip-manifest.py out/Default/dist.zip electron/script/zip_manifests/dist_zip.$target_os.${{ env.TARGET_ARCH }}.manifest - fi - - name: Build Mksnapshot (mas) - run: | - cd src - e build electron:electron_mksnapshot -j $NUMBER_OF_NINJA_PROCESSES - gn desc out/Default v8:run_mksnapshot_default args > out/Default/mksnapshot_args - # Remove unused args from mksnapshot_args - SEDOPTION="-i ''" - sed $SEDOPTION '/.*builtins-pgo/d' out/Default/mksnapshot_args - sed $SEDOPTION '/--turbo-profiling-input/d' out/Default/mksnapshot_args - sed $SEDOPTION '/The gn arg use_goma=true .*/d' out/Default/mksnapshot_args - e build electron:electron_mksnapshot_zip -j $NUMBER_OF_NINJA_PROCESSES - (cd out/Default; zip mksnapshot.zip mksnapshot_args gen/v8/embedded.S) - - name: Build Chromedriver (mas) - run: | - cd src - e build electron:electron_chromedriver -j $NUMBER_OF_NINJA_PROCESSES - e build electron:electron_chromedriver_zip - - name: Build Node Headers - run: | - cd src - e build electron:node_headers - - name: Generate & Zip Symbols (mas) - run: | - if [ "${{ inputs.generate-symbols }}" == "true" ]; then - e build electron:electron_symbols - fi - cd src - export BUILD_PATH="$(pwd)/out/Default" - e build electron:licenses - e build electron:electron_version_file - if [ "${{ inputs.is-release }}" == "true" ]; then - DELETE_DSYMS_AFTER_ZIP=1 electron/script/zip-symbols.py -b $BUILD_PATH - else - electron/script/zip-symbols.py -b $BUILD_PATH - fi - - name: Generate FFMpeg (mas) - if: ${{ inputs.is-release }} - run: | - cd src - gn gen out/ffmpeg --args="import(\"//electron/build/args/ffmpeg.gn\") use_remoteexec=true $GN_EXTRA_ARGS" - autoninja -C out/ffmpeg electron:electron_ffmpeg_zip -j $NUMBER_OF_NINJA_PROCESSES - # TODO(vertedinde): These uploads currently point to a different Azure bucket & GitHub Repo - - name: Publish Electron Dist - if: ${{ inputs.is-release }} - run: | - rm -rf src/out/Default/obj - cd src/electron - if [ "${{ inputs.upload-to-storage }}" == "1" ]; then - echo 'Uploading Electron release distribution to Azure' - script/release/uploaders/upload.py --verbose --upload_to_storage - else - echo 'Uploading Electron release distribution to GitHub releases' - script/release/uploaders/upload.py --verbose - fi - - name: Move all Generated Artifacts to Upload Folder (mas) - run: ./src/electron/script/actions/move-artifacts.sh - - name: Upload Generated Artifacts - uses: actions/upload-artifact@65462800fd760344b1a7b4382951275a0abb4808 - with: - name: generated_artifacts_mas_${{ env.TARGET_ARCH }} - path: ./generated_artifacts_mas_${{ env.TARGET_ARCH }} - test: - name: Run Electron Tests - if: ${{ inputs.is-release == false }} - runs-on: macos-14-xlarge - needs: build - strategy: - fail-fast: false - matrix: - build-type: [ darwin, mas ] - target-arch: [ x64, arm64 ] - env: - BUILD_TYPE: ${{ matrix.build-type }} - TARGET_ARCH: ${{ matrix.target-arch }} - steps: - - name: Load Build Tools - run: | - export BUILD_TOOLS_SHA=ef894bc3cfa99d84a3b731252da0f83f500e4032 - npm i -g @electron/build-tools - e auto-update disable - e init --root=$(pwd) --out=Default ${{ inputs.gn-build-type }} --import ${{ inputs.gn-build-type }} --target-cpu ${{ matrix.target-arch }} - - name: Checkout Electron - uses: actions/checkout@a5ac7e51b41094c92402da3b24376905380afc29 - with: - path: src/electron - fetch-depth: 0 - - name: Install Dependencies - run: | - cd src/electron - node script/yarn install - - name: Get Depot Tools - timeout-minutes: 5 - run: | - git clone --depth=1 https://chromium.googlesource.com/chromium/tools/depot_tools.git - if [ "`uname`" == "Darwin" ]; then - # remove ninjalog_uploader_wrapper.py from autoninja since we don't use it and it causes problems - sed -i '' '/ninjalog_uploader_wrapper.py/d' ./depot_tools/autoninja - else - sed -i '/ninjalog_uploader_wrapper.py/d' ./depot_tools/autoninja - # Remove swift-format dep from cipd on macOS until we send a patch upstream. - cd depot_tools - git apply --3way ../src/electron/.github/workflows/config/gclient.diff - fi - # Ensure depot_tools does not update. - test -d depot_tools && cd depot_tools - touch .disable_auto_update - - name: Add Depot Tools to PATH - run: echo "$(pwd)/depot_tools" >> $GITHUB_PATH - - name: Download Generated Artifacts - uses: actions/download-artifact@65a9edc5881444af0b9093a5e628f2fe47ea3b2e - with: - name: generated_artifacts_${{ matrix.build-type }}_${{ matrix.target-arch }} - path: ./generated_artifacts_${{ matrix.build-type }}_${{ matrix.target-arch }} - - name: Restore Generated Artifacts - run: ./src/electron/script/actions/restore-artifacts.sh - - name: Unzip Dist, Mksnapshot & Chromedriver - run: | - cd src/out/Default - unzip -:o dist.zip - unzip -:o chromedriver.zip - unzip -:o mksnapshot.zip - # - name: Import & Trust Self-Signed Codesigning Cert on MacOS - # run: | - # sudo security authorizationdb write com.apple.trust-settings.admin allow - # cd src/electron - # ./script/codesign/generate-identity.sh - - name: Run Electron Tests - env: - MOCHA_REPORTER: mocha-multi-reporters - ELECTRON_TEST_RESULTS_DIR: junit - MOCHA_MULTI_REPORTERS: mocha-junit-reporter, tap - ELECTRON_DISABLE_SECURITY_WARNINGS: 1 - ELECTRON_SKIP_NATIVE_MODULE_TESTS: true - run: | - cd src/electron - node script/yarn test --runners=main --trace-uncaught --enable-logging - - name: Verify mksnapshot - run: | - cd src - python3 electron/script/verify-mksnapshot.py --source-root "$PWD" --build-dir out/Default - - name: Verify ChromeDriver - run: | - cd src - python3 electron/script/verify-chromedriver.py --source-root "$PWD" --build-dir out/Default diff --git a/.github/workflows/macos-publish.yml b/.github/workflows/macos-publish.yml index ffccbfdec7..0efc34855e 100644 --- a/.github/workflows/macos-publish.yml +++ b/.github/workflows/macos-publish.yml @@ -14,11 +14,49 @@ on: default: false jobs: - publish: - uses: ./.github/workflows/macos-pipeline.yml + checkout-macos: + runs-on: aks-linux-large + container: + image: ghcr.io/electron/build:latest + options: --user root + volumes: + - /mnt/cross-instance-cache:/mnt/cross-instance-cache + - /var/run/sas:/var/run/sas + env: + GCLIENT_EXTRA_ARGS: '--custom-var=checkout_mac=True --custom-var=host_os=mac' + steps: + - name: Checkout Electron + uses: actions/checkout@a5ac7e51b41094c92402da3b24376905380afc29 + with: + path: src/electron + fetch-depth: 0 + - name: Checkout & Sync & Save + uses: ./src/electron/.github/actions/checkout + with: + generate-sas-token: 'true' + gclient-extra-args: '--custom-var=checkout_mac=True --custom-var=host_os=mac' + + publish-x64: + uses: ./.github/workflows/pipeline-segment-electron-build.yml + needs: checkout-macos + with: + build-runs-on: macos-14-xlarge + target-platform: macos + target-arch: x64 + is-release: true + gn-build-type: release + generate-symbols: true + upload-to-storage: ${{ inputs.upload-to-storage }} + secrets: inherit + + publish-arm64: + uses: ./.github/workflows/pipeline-segment-electron-build.yml + needs: checkout-macos with: + build-runs-on: macos-14-xlarge + target-platform: macos + target-arch: arm64 is-release: true - gn-config: //electron/build/args/release.gn gn-build-type: release generate-symbols: true upload-to-storage: ${{ inputs.upload-to-storage }} diff --git a/.github/workflows/pipeline-electron-build-and-test-and-nan.yml b/.github/workflows/pipeline-electron-build-and-test-and-nan.yml new file mode 100644 index 0000000000..c1a70b0246 --- /dev/null +++ b/.github/workflows/pipeline-electron-build-and-test-and-nan.yml @@ -0,0 +1,84 @@ +name: Electron Build & Test (+ Node + NaN) Pipeline + +on: + workflow_call: + inputs: + target-platform: + type: string + description: 'Platform to run on, can be macos or linux' + required: true + target-arch: + type: string + description: 'Arch to build for, can be x64, arm64 or arm' + required: true + build-runs-on: + type: string + description: 'What host to run the build' + required: true + test-runs-on: + type: string + description: 'What host to run the tests on' + required: true + build-container: + type: string + description: 'JSON container information for aks runs-on' + required: false + default: '{"image":null}' + is-release: + description: 'Whether this build job is a release job' + required: true + type: boolean + default: false + gn-build-type: + description: 'The gn build type - testing or release' + required: true + type: string + default: testing + generate-symbols: + description: 'Whether or not to generate symbols' + required: true + type: boolean + default: false + upload-to-storage: + description: 'Whether or not to upload build artifacts to external storage' + required: true + type: string + default: '0' + +concurrency: + group: electron-build-and-test-and-nan-${{ inputs.target-platform }}-${{ inputs.target-arch }}-${{ github.ref }} + cancel-in-progress: true + +jobs: + build: + uses: ./.github/workflows/pipeline-segment-electron-build.yml + with: + build-runs-on: ${{ inputs.build-runs-on }} + build-container: ${{ inputs.build-container }} + target-platform: ${{ inputs.target-platform }} + target-arch: ${{ inputs.target-arch }} + is-release: ${{ inputs.is-release }} + gn-build-type: ${{ inputs.gn-build-type }} + generate-symbols: ${{ inputs.generate-symbols }} + upload-to-storage: ${{ inputs.upload-to-storage }} + secrets: inherit + test: + uses: ./.github/workflows/pipeline-segment-electron-test.yml + needs: build + with: + target-arch: ${{ inputs.target-arch }} + target-platform: ${{ inputs.target-platform }} + test-runs-on: ${{ inputs.test-runs-on }} + test-container: ${{ inputs.build-container }} + gn-build-type: ${{ inputs.gn-build-type }} + secrets: inherit + nn-test: + uses: ./.github/workflows/pipeline-segment-node-nan-test.yml + needs: build + with: + target-arch: ${{ inputs.target-arch }} + target-platform: ${{ inputs.target-platform }} + test-runs-on: ${{ inputs.test-runs-on }} + test-container: ${{ inputs.build-container }} + gn-build-type: ${{ inputs.gn-build-type }} + secrets: inherit diff --git a/.github/workflows/pipeline-electron-build-and-test.yml b/.github/workflows/pipeline-electron-build-and-test.yml new file mode 100644 index 0000000000..985733596b --- /dev/null +++ b/.github/workflows/pipeline-electron-build-and-test.yml @@ -0,0 +1,75 @@ +name: Electron Build & Test Pipeline + +on: + workflow_call: + inputs: + target-platform: + type: string + description: 'Platform to run on, can be macos or linux' + required: true + target-arch: + type: string + description: 'Arch to build for, can be x64, arm64 or arm' + required: true + build-runs-on: + type: string + description: 'What host to run the build' + required: true + test-runs-on: + type: string + description: 'What host to run the tests on' + required: true + build-container: + type: string + description: 'JSON container information for aks runs-on' + required: false + default: '{"image":null}' + is-release: + description: 'Whether this build job is a release job' + required: true + type: boolean + default: false + gn-build-type: + description: 'The gn build type - testing or release' + required: true + type: string + default: testing + generate-symbols: + description: 'Whether or not to generate symbols' + required: true + type: boolean + default: false + upload-to-storage: + description: 'Whether or not to upload build artifacts to external storage' + required: true + type: string + default: '0' + +concurrency: + group: electron-build-and-test-${{ inputs.target-platform }}-${{ inputs.target-arch }}-${{ github.ref }} + cancel-in-progress: true + +jobs: + build: + uses: ./.github/workflows/pipeline-segment-electron-build.yml + with: + build-runs-on: ${{ inputs.build-runs-on }} + build-container: ${{ inputs.build-container }} + target-platform: ${{ inputs.target-platform }} + target-arch: ${{ inputs.target-arch }} + is-release: ${{ inputs.is-release }} + gn-build-type: ${{ inputs.gn-build-type }} + generate-symbols: ${{ inputs.generate-symbols }} + upload-to-storage: ${{ inputs.upload-to-storage }} + secrets: inherit + test: + uses: ./.github/workflows/pipeline-segment-electron-test.yml + if: ${{ inputs.target-platform == 'macos' || inputs.target-arch == 'x64' }} + needs: build + with: + target-arch: ${{ inputs.target-arch }} + target-platform: ${{ inputs.target-platform }} + test-runs-on: ${{ inputs.test-runs-on }} + test-container: ${{ inputs.build-container }} + gn-build-type: ${{ inputs.gn-build-type }} + secrets: inherit diff --git a/.github/workflows/pipeline-segment-electron-build.yml b/.github/workflows/pipeline-segment-electron-build.yml new file mode 100644 index 0000000000..ce5af65cdb --- /dev/null +++ b/.github/workflows/pipeline-segment-electron-build.yml @@ -0,0 +1,193 @@ +name: Pipeline Segment - Electron Build + +on: + workflow_call: + inputs: + target-platform: + type: string + description: 'Platform to run on, can be macos or linux' + required: true + target-arch: + type: string + description: 'Arch to build for, can be x64, arm64 or arm' + required: true + build-runs-on: + type: string + description: 'What host to run the build' + required: true + build-container: + type: string + description: 'JSON container information for aks runs-on' + required: false + default: '{"image":null}' + is-release: + description: 'Whether this build job is a release job' + required: true + type: boolean + default: false + gn-build-type: + description: 'The gn build type - testing or release' + required: true + type: string + default: testing + generate-symbols: + description: 'Whether or not to generate symbols' + required: true + type: boolean + default: false + upload-to-storage: + description: 'Whether or not to upload build artifacts to external storage' + required: true + type: string + default: '0' + +concurrency: + group: electron-build-${{ inputs.target-platform }}-${{ inputs.target-arch }}-${{ github.ref }} + cancel-in-progress: true + +env: + AZURE_AKS_CACHE_STORAGE_ACCOUNT: ${{ secrets.AZURE_AKS_CACHE_STORAGE_ACCOUNT }} + AZURE_AKS_CACHE_SHARE_NAME: ${{ secrets.AZURE_AKS_CACHE_SHARE_NAME }} + ELECTRON_ARTIFACTS_BLOB_STORAGE: ${{ secrets.ELECTRON_ARTIFACTS_BLOB_STORAGE }} + ELECTRON_RBE_JWT: ${{ secrets.ELECTRON_RBE_JWT }} + ELECTRON_GITHUB_TOKEN: ${{ secrets.ELECTRON_GITHUB_TOKEN }} + # Disable pre-compiled headers to reduce out size - only useful for rebuilds + GN_BUILDFLAG_ARGS: 'enable_precompiled_headers=false' + GCLIENT_EXTRA_ARGS: ${{ inputs.target-platform == 'macos' && '--custom-var=checkout_mac=True --custom-var=host_os=mac' || '--custom-var=checkout_arm=True --custom-var=checkout_arm64=True' }} + # Only disable this in the Asan build + CHECK_DIST_MANIFEST: true + IS_GHA_RELEASE: true + ELECTRON_OUT_DIR: Default + +jobs: + build: + runs-on: ${{ inputs.build-runs-on }} + container: ${{ fromJSON(inputs.build-container) }} + env: + TARGET_ARCH: ${{ inputs.target-arch }} + steps: + - name: Load Build Tools + run: | + export BUILD_TOOLS_SHA=ef894bc3cfa99d84a3b731252da0f83f500e4032 + npm i -g @electron/build-tools + e auto-update disable + e init --root=$(pwd) --out=Default ${{ inputs.gn-build-type }} --import ${{ inputs.gn-build-type }} --target-cpu ${{ inputs.target-arch }} + - name: Checkout Electron + uses: actions/checkout@a5ac7e51b41094c92402da3b24376905380afc29 + with: + path: src/electron + fetch-depth: 0 + - name: Setup Node.js/npm + if: ${{ inputs.target-platform == 'macos' }} + uses: actions/setup-node@60edb5dd545a775178f52524783378180af0d1f8 + with: + node-version: 20.11.x + cache: yarn + cache-dependency-path: src/electron/yarn.lock + - name: Install Dependencies + run: | + cd src/electron + node script/yarn install + - name: Install AZCopy + if: ${{ inputs.target-platform == 'macos' }} + run: brew install azcopy + - name: Set GN_EXTRA_ARGS for Linux + if: ${{ inputs.target-platform == 'linux' }} + run: | + if [ "${{ inputs.target-arch }}" = "arm" ]; then + GN_EXTRA_ARGS='build_tflite_with_xnnpack=false' + elif [ "${{ inputs.target-arch }}" = "arm64" ]; then + GN_EXTRA_ARGS='fatal_linker_warnings=false enable_linux_installer=false' + fi + echo "GN_EXTRA_ARGS=$GN_EXTRA_ARGS" >> $GITHUB_ENV + - name: Get Depot Tools + timeout-minutes: 5 + run: | + git clone --depth=1 https://chromium.googlesource.com/chromium/tools/depot_tools.git + + SEDOPTION="-i" + if [ "`uname`" = "Darwin" ]; then + SEDOPTION="-i ''" + fi + + # remove ninjalog_uploader_wrapper.py from autoninja since we don't use it and it causes problems + sed $SEDOPTION '/ninjalog_uploader_wrapper.py/d' ./depot_tools/autoninja + + # Ensure depot_tools does not update. + test -d depot_tools && cd depot_tools + if [ "`uname`" = "Linux" ]; then + git apply --3way ../src/electron/.github/workflows/config/gclient.diff + fi + touch .disable_auto_update + - name: Add Depot Tools to PATH + run: echo "$(pwd)/depot_tools" >> $GITHUB_PATH + - name: Generate DEPS Hash + run: | + node src/electron/script/generate-deps-hash.js && cat src/electron/.depshash-target + DEPSHASH=v1-src-cache-$(shasum src/electron/.depshash | cut -f1 -d' ') + echo "DEPSHASH=$DEPSHASH" >> $GITHUB_ENV + echo "CACHE_PATH=$DEPSHASH.tar" >> $GITHUB_ENV + - name: Restore src cache via AZCopy + if: ${{ inputs.target-platform == 'macos' }} + uses: ./src/electron/.github/actions/restore-cache-azcopy + - name: Restore src cache via AKS + if: ${{ inputs.target-platform == 'linux' }} + uses: ./src/electron/.github/actions/restore-cache-aks + - name: Checkout Electron + uses: actions/checkout@a5ac7e51b41094c92402da3b24376905380afc29 + with: + path: src/electron + fetch-depth: 0 + - name: Run Electron Only Hooks + run: | + gclient runhooks --spec="solutions=[{'name':'src/electron','url':None,'deps_file':'DEPS','custom_vars':{'process_deps':False},'managed':False}]" + - name: Regenerate DEPS Hash + run: | + (cd src/electron && git checkout .) && node src/electron/script/generate-deps-hash.js && cat src/electron/.depshash-target + echo "DEPSHASH=$(shasum src/electron/.depshash | cut -f1 -d' ')" >> $GITHUB_ENV + - name: Add CHROMIUM_BUILDTOOLS_PATH to env + run: echo "CHROMIUM_BUILDTOOLS_PATH=$(pwd)/src/buildtools" >> $GITHUB_ENV + - name: Fix Sync (macOS) + if: ${{ inputs.target-platform == 'macos' }} + uses: ./src/electron/.github/actions/fix-sync-macos + - name: Install build-tools & Setup RBE + run: | + echo "NUMBER_OF_NINJA_PROCESSES=${{ inputs.target-platform == 'linux' && '300' || '200' }}" >> $GITHUB_ENV + cd ~/.electron_build_tools + npx yarn --ignore-engines + # Pull down credential helper and print status + node -e "require('./src/utils/reclient.js').downloadAndPrepare({})" + HELPER=$(node -p "require('./src/utils/reclient.js').helperPath({})") + $HELPER login + echo 'RBE_service='`node -e "console.log(require('./src/utils/reclient.js').serviceAddress)"` >> $GITHUB_ENV + echo 'RBE_experimental_credentials_helper='`node -e "console.log(require('./src/utils/reclient.js').helperPath({}))"` >> $GITHUB_ENV + echo 'RBE_experimental_credentials_helper_args=print' >> $GITHUB_ENV + - name: Free up space (macOS) + if: ${{ inputs.target-platform == 'macos' }} + uses: ./src/electron/.github/actions/free-space-macos + - name: Build Electron + uses: ./src/electron/.github/actions/build-electron + with: + target-arch: ${{ inputs.target-arch }} + target-platform: ${{ inputs.target-platform }} + artifact-platform: ${{ inputs.target-platform == 'linux' && 'linux' || 'darwin' }} + is-release: '${{ inputs.is-release }}' + generate-symbols: '${{ inputs.generate-symbols }}' + upload-to-storage: '${{ inputs.upload-to-storage }}' + - name: Set GN_EXTRA_ARGS for MAS Build + if: ${{ inputs.target-platform == 'macos' }} + run: | + echo "MAS_BUILD=true" >> $GITHUB_ENV + GN_EXTRA_ARGS='is_mas_build=true' + echo "GN_EXTRA_ARGS=$GN_EXTRA_ARGS" >> $GITHUB_ENV + - name: Build Electron (MAS) + if: ${{ inputs.target-platform == 'macos' }} + uses: ./src/electron/.github/actions/build-electron + with: + target-arch: ${{ inputs.target-arch }} + target-platform: ${{ inputs.target-platform }} + artifact-platform: 'mas' + is-release: '${{ inputs.is-release }}' + generate-symbols: '${{ inputs.generate-symbols }}' + upload-to-storage: '${{ inputs.upload-to-storage }}' + step-suffix: '(mas)' diff --git a/.github/workflows/pipeline-segment-electron-test.yml b/.github/workflows/pipeline-segment-electron-test.yml new file mode 100644 index 0000000000..5b89e4ff3c --- /dev/null +++ b/.github/workflows/pipeline-segment-electron-test.yml @@ -0,0 +1,120 @@ +name: Pipeline Segment - Electron Test + +on: + workflow_call: + inputs: + target-platform: + type: string + description: 'Platform to run on, can be macos or linux' + required: true + target-arch: + type: string + description: 'Arch to build for, can be x64, arm64 or arm' + required: true + test-runs-on: + type: string + description: 'What host to run the tests on' + required: true + test-container: + type: string + description: 'JSON container information for aks runs-on' + required: false + default: '{"image":null}' + gn-build-type: + description: 'The gn build type - testing or release' + required: true + type: string + default: testing + +concurrency: + group: electron-test-${{ inputs.target-platform }}-${{ inputs.target-arch }}-${{ github.ref }} + cancel-in-progress: true + +env: + ELECTRON_OUT_DIR: Default + ELECTRON_RBE_JWT: ${{ secrets.ELECTRON_RBE_JWT }} + +jobs: + test: + runs-on: ${{ inputs.test-runs-on }} + container: ${{ fromJSON(inputs.test-container) }} + strategy: + fail-fast: false + matrix: + build-type: ${{ inputs.target-platform == 'macos' && fromJSON('["darwin","mas"]') || fromJSON('["linux"]') }} + env: + BUILD_TYPE: ${{ matrix.build-type }} + TARGET_ARCH: ${{ inputs.target-arch }} + steps: + - name: Load Build Tools + run: | + export BUILD_TOOLS_SHA=ef894bc3cfa99d84a3b731252da0f83f500e4032 + npm i -g @electron/build-tools + e auto-update disable + e init --root=$(pwd) --out=Default ${{ inputs.gn-build-type }} --import ${{ inputs.gn-build-type }} --target-cpu ${{ inputs.target-arch }} + - name: Checkout Electron + uses: actions/checkout@a5ac7e51b41094c92402da3b24376905380afc29 + with: + path: src/electron + fetch-depth: 0 + - name: Install Dependencies + run: | + cd src/electron + node script/yarn install + - name: Get Depot Tools + timeout-minutes: 5 + run: | + git clone --depth=1 https://chromium.googlesource.com/chromium/tools/depot_tools.git + if [ "`uname`" = "Darwin" ]; then + # remove ninjalog_uploader_wrapper.py from autoninja since we don't use it and it causes problems + sed -i '' '/ninjalog_uploader_wrapper.py/d' ./depot_tools/autoninja + else + sed -i '/ninjalog_uploader_wrapper.py/d' ./depot_tools/autoninja + # Remove swift-format dep from cipd on macOS until we send a patch upstream. + cd depot_tools + git apply --3way ../src/electron/.github/workflows/config/gclient.diff + fi + # Ensure depot_tools does not update. + test -d depot_tools && cd depot_tools + touch .disable_auto_update + - name: Add Depot Tools to PATH + run: echo "$(pwd)/depot_tools" >> $GITHUB_PATH + - name: Download Generated Artifacts + uses: actions/download-artifact@65a9edc5881444af0b9093a5e628f2fe47ea3b2e + with: + name: generated_artifacts_${{ matrix.build-type }}_${{ inputs.target-arch }} + path: ./generated_artifacts_${{ matrix.build-type }}_${{ inputs.target-arch }} + - name: Restore Generated Artifacts + run: ./src/electron/script/actions/restore-artifacts.sh + - name: Unzip Dist, Mksnapshot & Chromedriver + run: | + cd src/out/Default + unzip -:o dist.zip + unzip -:o chromedriver.zip + unzip -:o mksnapshot.zip + # - name: Import & Trust Self-Signed Codesigning Cert on MacOS + # if: ${{ inputs.target-platform == 'macos' }} + # run: | + # sudo security authorizationdb write com.apple.trust-settings.admin allow + # cd src/electron + # ./script/codesign/generate-identity.sh + - name: Setup for headless testing + if: ${{ inputs.target-platform == 'linux' }} + run: sh -e /etc/init.d/xvfb start + - name: Run Electron Tests + env: + MOCHA_REPORTER: mocha-multi-reporters + ELECTRON_TEST_RESULTS_DIR: junit + MOCHA_MULTI_REPORTERS: mocha-junit-reporter, tap + ELECTRON_DISABLE_SECURITY_WARNINGS: 1 + ELECTRON_SKIP_NATIVE_MODULE_TESTS: true + run: | + cd src/electron + node script/yarn test --runners=main --trace-uncaught --enable-logging + - name: Wait for active SSH sessions + if: always() && !cancelled() + run: | + while [ -f /var/.ssh-lock ] + do + sleep 60 + done \ No newline at end of file diff --git a/.github/workflows/pipeline-segment-node-nan-test.yml b/.github/workflows/pipeline-segment-node-nan-test.yml new file mode 100644 index 0000000000..6c60015b17 --- /dev/null +++ b/.github/workflows/pipeline-segment-node-nan-test.yml @@ -0,0 +1,159 @@ +name: Pipeline Segment - Node/Nan Test + +on: + workflow_call: + inputs: + target-platform: + type: string + description: 'Platform to run on, can be macos or linux' + required: true + target-arch: + type: string + description: 'Arch to build for, can be x64, arm64 or arm' + required: true + test-runs-on: + type: string + description: 'What host to run the tests on' + required: true + test-container: + type: string + description: 'JSON container information for aks runs-on' + required: false + default: '{"image":null}' + gn-build-type: + description: 'The gn build type - testing or release' + required: true + type: string + default: testing + +concurrency: + group: electron-node-nan-test-${{ inputs.target-platform }}-${{ inputs.target-arch }}-${{ github.ref }} + cancel-in-progress: true + +env: + ELECTRON_OUT_DIR: Default + ELECTRON_RBE_JWT: ${{ secrets.ELECTRON_RBE_JWT }} + +jobs: + node-tests: + name: Run Node.js Tests + runs-on: aks-linux-medium + timeout-minutes: 20 + env: + TARGET_ARCH: ${{ inputs.target-arch }} + container: + image: ghcr.io/electron/build:latest + options: --user root + steps: + - name: Load Build Tools + run: | + export BUILD_TOOLS_SHA=ef894bc3cfa99d84a3b731252da0f83f500e4032 + npm i -g @electron/build-tools + e auto-update disable + e init --root=$(pwd) --out=Default ${{ inputs.gn-build-type }} --import ${{ inputs.gn-build-type }} --target-cpu ${{ inputs.target-arch }} + - name: Checkout Electron + uses: actions/checkout@a5ac7e51b41094c92402da3b24376905380afc29 + with: + path: src/electron + fetch-depth: 0 + - name: Install Dependencies + run: | + cd src/electron + node script/yarn install + - name: Get Depot Tools + timeout-minutes: 5 + run: | + git clone --depth=1 https://chromium.googlesource.com/chromium/tools/depot_tools.git + sed -i '/ninjalog_uploader_wrapper.py/d' ./depot_tools/autoninja + cd depot_tools + git apply --3way ../src/electron/.github/workflows/config/gclient.diff + # Ensure depot_tools does not update. + test -d depot_tools && cd depot_tools + touch .disable_auto_update + - name: Add Depot Tools to PATH + run: echo "$(pwd)/depot_tools" >> $GITHUB_PATH + - name: Download Generated Artifacts + uses: actions/download-artifact@65a9edc5881444af0b9093a5e628f2fe47ea3b2e + with: + name: generated_artifacts_linux_${{ env.TARGET_ARCH }} + path: ./generated_artifacts_linux_${{ env.TARGET_ARCH }} + - name: Restore Generated Artifacts + run: ./src/electron/script/actions/restore-artifacts.sh + - name: Unzip Dist + run: | + cd src/out/Default + unzip -:o dist.zip + - name: Setup Linux for Headless Testing + run: sh -e /etc/init.d/xvfb start + - name: Run Node.js Tests + run: | + cd src + node electron/script/node-spec-runner.js --default --jUnitDir=junit + - name: Wait for active SSH sessions + if: always() && !cancelled() + run: | + while [ -f /var/.ssh-lock ] + do + sleep 60 + done + nan-tests: + name: Run Nan Tests + runs-on: aks-linux-medium + timeout-minutes: 20 + env: + TARGET_ARCH: ${{ inputs.target-arch }} + container: + image: ghcr.io/electron/build:latest + options: --user root + steps: + - name: Load Build Tools + run: | + export BUILD_TOOLS_SHA=ef894bc3cfa99d84a3b731252da0f83f500e4032 + npm i -g @electron/build-tools + e auto-update disable + e init --root=$(pwd) --out=Default ${{ inputs.gn-build-type }} + - name: Checkout Electron + uses: actions/checkout@a5ac7e51b41094c92402da3b24376905380afc29 + with: + path: src/electron + fetch-depth: 0 + - name: Install Dependencies + run: | + cd src/electron + node script/yarn install + - name: Get Depot Tools + timeout-minutes: 5 + run: | + git clone --depth=1 https://chromium.googlesource.com/chromium/tools/depot_tools.git + sed -i '/ninjalog_uploader_wrapper.py/d' ./depot_tools/autoninja + cd depot_tools + git apply --3way ../src/electron/.github/workflows/config/gclient.diff + # Ensure depot_tools does not update. + test -d depot_tools && cd depot_tools + touch .disable_auto_update + - name: Add Depot Tools to PATH + run: echo "$(pwd)/depot_tools" >> $GITHUB_PATH + - name: Download Generated Artifacts + uses: actions/download-artifact@65a9edc5881444af0b9093a5e628f2fe47ea3b2e + with: + name: generated_artifacts_linux_${{ env.TARGET_ARCH }} + path: ./generated_artifacts_linux_${{ env.TARGET_ARCH }} + - name: Restore Generated Artifacts + run: ./src/electron/script/actions/restore-artifacts.sh + - name: Unzip Dist + run: | + cd src/out/Default + unzip -:o dist.zip + - name: Setup Linux for Headless Testing + run: sh -e /etc/init.d/xvfb start + - name: Run Node.js Tests + run: | + cd src + node electron/script/nan-spec-runner.js + - name: Wait for active SSH sessions + if: always() && !cancelled() + run: | + while [ -f /var/.ssh-lock ] + do + sleep 60 + done
build
a6b6816beca9433a21e76c5dcd877de8bbf02598
Shelley Vohr
2022-10-05 10:34:53
build: clean up patch linting errors (#35917)
diff --git a/script/lint.js b/script/lint.js index ebc3d41a59..18899f1a38 100755 --- a/script/lint.js +++ b/script/lint.js @@ -181,6 +181,7 @@ const LINTERS = [{ const patchesConfig = path.resolve(patchesDir, 'config.json'); // If the config does not exist, that's a problem if (!fs.existsSync(patchesConfig)) { + console.error(`Patches config file: "${patchesConfig}" does not exist`); process.exit(1); } @@ -188,34 +189,48 @@ const LINTERS = [{ for (const key of Object.keys(config)) { // The directory the config points to should exist const targetPatchesDir = path.resolve(__dirname, '../../..', key); - if (!fs.existsSync(targetPatchesDir)) throw new Error(`target patch directory: "${targetPatchesDir}" does not exist`); + if (!fs.existsSync(targetPatchesDir)) { + console.error(`target patch directory: "${targetPatchesDir}" does not exist`); + process.exit(1); + } // We need a .patches file const dotPatchesPath = path.resolve(targetPatchesDir, '.patches'); - if (!fs.existsSync(dotPatchesPath)) throw new Error(`.patches file: "${dotPatchesPath}" does not exist`); + if (!fs.existsSync(dotPatchesPath)) { + console.error(`.patches file: "${dotPatchesPath}" does not exist`); + process.exit(1); + } // Read the patch list const patchFileList = fs.readFileSync(dotPatchesPath, 'utf8').trim().split('\n'); const patchFileSet = new Set(patchFileList); patchFileList.reduce((seen, file) => { if (seen.has(file)) { - throw new Error(`'${file}' is listed in ${dotPatchesPath} more than once`); + console.error(`'${file}' is listed in ${dotPatchesPath} more than once`); + process.exit(1); } return seen.add(file); }, new Set()); - if (patchFileList.length !== patchFileSet.size) throw new Error('each patch file should only be in the .patches file once'); + + if (patchFileList.length !== patchFileSet.size) { + console.error('Each patch file should only be in the .patches file once'); + process.exit(1); + } + for (const file of fs.readdirSync(targetPatchesDir)) { // Ignore the .patches file and READMEs if (file === '.patches' || file === 'README.md') continue; if (!patchFileSet.has(file)) { - throw new Error(`Expected the .patches file at "${dotPatchesPath}" to contain a patch file ("${file}") present in the directory but it did not`); + console.error(`Expected the .patches file at "${dotPatchesPath}" to contain a patch file ("${file}") present in the directory but it did not`); + process.exit(1); } patchFileSet.delete(file); } // If anything is left in this set, it means it did not exist on disk if (patchFileSet.size > 0) { - throw new Error(`Expected all the patch files listed in the .patches file at "${dotPatchesPath}" to exist but some did not:\n${JSON.stringify([...patchFileSet.values()], null, 2)}`); + console.error(`Expected all the patch files listed in the .patches file at "${dotPatchesPath}" to exist but some did not:\n${JSON.stringify([...patchFileSet.values()], null, 2)}`); + process.exit(1); } }
build
f826506218fc72da8b1792221284a247b09cf800
Shelley Vohr
2024-03-07 15:31:16
fix: `chrome://process-internals` failing to load (#41476) fix: chrome://process-internals failing to load
diff --git a/electron_paks.gni b/electron_paks.gni index 25dd04d407..9c59e52b49 100644 --- a/electron_paks.gni +++ b/electron_paks.gni @@ -77,6 +77,7 @@ template("electron_extra_paks") { "//content:content_resources", "//content/browser/resources/gpu:resources", "//content/browser/resources/media:resources", + "//content/browser/resources/process:resources", "//content/browser/tracing:resources", "//content/browser/webrtc/resources", "//electron:resources", @@ -96,6 +97,7 @@ template("electron_extra_paks") { # New paks should be added here by default. sources += [ "$root_gen_dir/content/browser/devtools/devtools_resources.pak", + "$root_gen_dir/content/process_resources.pak", "$root_gen_dir/ui/resources/webui_resources.pak", ] deps += [ "//content/browser/devtools:devtools_resources" ] diff --git a/spec/chromium-spec.ts b/spec/chromium-spec.ts index 88d433bf8a..5694e7ea11 100644 --- a/spec/chromium-spec.ts +++ b/spec/chromium-spec.ts @@ -2113,7 +2113,8 @@ describe('chromium features', () => { 'chrome://gpu', 'chrome://media-internals', 'chrome://tracing', - 'chrome://webrtc-internals' + 'chrome://webrtc-internals', + 'chrome://process-internals' ]; for (const url of urls) { @@ -2121,8 +2122,9 @@ describe('chromium features', () => { it('loads the page successfully', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL(url); + const host = url.substring('chrome://'.length); const pageExists = await w.webContents.executeJavaScript( - "window.hasOwnProperty('chrome') && window.chrome.hasOwnProperty('send')" + `window.hasOwnProperty('chrome') && window.location.host === '${host}'` ); expect(pageExists).to.be.true(); });
fix
b9c4b27781495224e309eb75554a6cec21981982
Erick Zhao
2024-03-25 03:19:44
docs: backslash escape parametrized TypeScript types (#41575) * docs: backslash escape parametrized TypeScript types * missing instances
diff --git a/docs/api/app.md b/docs/api/app.md index cbd9e42e26..178135e63b 100755 --- a/docs/api/app.md +++ b/docs/api/app.md @@ -32,7 +32,7 @@ In most cases, you should do everything in the `ready` event handler. Returns: * `event` Event -* `launchInfo` Record<string, any> | [NotificationResponse](structures/notification-response.md) _macOS_ +* `launchInfo` Record\<string, any\> | [NotificationResponse](structures/notification-response.md) _macOS_ Emitted once, when Electron has finished initializing. On macOS, `launchInfo` holds the `userInfo` of the [`NSUserNotification`](https://developer.apple.com/documentation/foundation/nsusernotification) @@ -970,7 +970,7 @@ app.setJumpList([ ### `app.requestSingleInstanceLock([additionalData])` -* `additionalData` Record<any, any> (optional) - A JSON object containing additional data to send to the first instance. +* `additionalData` Record\<any, any\> (optional) - A JSON object containing additional data to send to the first instance. Returns `boolean` diff --git a/docs/api/auto-updater.md b/docs/api/auto-updater.md index 80dd7b7d6a..7eb92b415e 100644 --- a/docs/api/auto-updater.md +++ b/docs/api/auto-updater.md @@ -103,7 +103,7 @@ The `autoUpdater` object has the following methods: * `options` Object * `url` string - * `headers` Record<string, string> (optional) _macOS_ - HTTP request headers. + * `headers` Record\<string, string\> (optional) _macOS_ - HTTP request headers. * `serverType` string (optional) _macOS_ - Can be `json` or `default`, see the [Squirrel.Mac][squirrel-mac] README for more information. diff --git a/docs/api/base-window.md b/docs/api/base-window.md index cc7482be10..2a4848da0e 100644 --- a/docs/api/base-window.md +++ b/docs/api/base-window.md @@ -656,7 +656,7 @@ Closes the currently open [Quick Look][quick-look] panel. #### `win.setBounds(bounds[, animate])` -* `bounds` Partial<[Rectangle](structures/rectangle.md)> +* `bounds` Partial\<[Rectangle](structures/rectangle.md)\> * `animate` boolean (optional) _macOS_ Resizes and moves the window to the supplied bounds. Any properties that are not supplied will default to their current values. diff --git a/docs/api/browser-window.md b/docs/api/browser-window.md index ccf434e112..9ee4c92672 100644 --- a/docs/api/browser-window.md +++ b/docs/api/browser-window.md @@ -779,7 +779,7 @@ Closes the currently open [Quick Look][quick-look] panel. #### `win.setBounds(bounds[, animate])` -* `bounds` Partial<[Rectangle](structures/rectangle.md)> +* `bounds` Partial\<[Rectangle](structures/rectangle.md)\> * `animate` boolean (optional) _macOS_ Resizes and moves the window to the supplied bounds. Any properties that are not supplied will default to their current values. @@ -1215,7 +1215,7 @@ win.loadURL('http://localhost:8000/post', { * `filePath` string * `options` Object (optional) - * `query` Record<string, string> (optional) - Passed to `url.format()`. + * `query` Record\<string, string\> (optional) - Passed to `url.format()`. * `search` string (optional) - Passed to `url.format()`. * `hash` string (optional) - Passed to `url.format()`. diff --git a/docs/api/client-request.md b/docs/api/client-request.md index 2d4d4ccac9..440a775267 100644 --- a/docs/api/client-request.md +++ b/docs/api/client-request.md @@ -158,7 +158,7 @@ Returns: * `statusCode` Integer * `method` string * `redirectUrl` string -* `responseHeaders` Record<string, string[]> +* `responseHeaders` Record\<string, string[]\> Emitted when the server returns a redirect response (e.g. 301 Moved Permanently). Calling [`request.followRedirect`](#requestfollowredirect) will diff --git a/docs/api/crash-reporter.md b/docs/api/crash-reporter.md index 8883699db7..26c685f8a4 100644 --- a/docs/api/crash-reporter.md +++ b/docs/api/crash-reporter.md @@ -59,14 +59,14 @@ The `crashReporter` module has the following methods: number of crashes uploaded to 1/hour. Default is `false`. * `compress` boolean (optional) - If true, crash reports will be compressed and uploaded with `Content-Encoding: gzip`. Default is `true`. - * `extra` Record<string, string> (optional) - Extra string key/value + * `extra` Record\<string, string\> (optional) - Extra string key/value annotations that will be sent along with crash reports that are generated in the main process. Only string values are supported. Crashes generated in child processes will not contain these extra parameters to crash reports generated from child processes, call [`addExtraParameter`](#crashreporteraddextraparameterkey-value) from the child process. - * `globalExtra` Record<string, string> (optional) - Extra string key/value + * `globalExtra` Record\<string, string\> (optional) - Extra string key/value annotations that will be sent along with any crash reports generated in any process. These annotations cannot be changed once the crash reporter has been started. If a key is present in both the global extra parameters and diff --git a/docs/api/ipc-main.md b/docs/api/ipc-main.md index 65845218cd..83dd3628a2 100644 --- a/docs/api/ipc-main.md +++ b/docs/api/ipc-main.md @@ -72,7 +72,7 @@ Removes listeners of the specified `channel`. ### `ipcMain.handle(channel, listener)` * `channel` string -* `listener` Function<Promise\<any&#62; | any&#62; +* `listener` Function\<Promise\<any\> | any\> * `event` [IpcMainInvokeEvent][ipc-main-invoke-event] * `...args` any[] @@ -109,7 +109,7 @@ provided to the renderer process. Please refer to ### `ipcMain.handleOnce(channel, listener)` * `channel` string -* `listener` Function<Promise\<any&#62; | any&#62; +* `listener` Function\<Promise\<any\> | any\> * `event` [IpcMainInvokeEvent][ipc-main-invoke-event] * `...args` any[] diff --git a/docs/api/protocol.md b/docs/api/protocol.md index 1a9b446a20..6d2de18751 100644 --- a/docs/api/protocol.md +++ b/docs/api/protocol.md @@ -111,7 +111,7 @@ expect streaming responses. * `scheme` string - scheme to handle, for example `https` or `my-app`. This is the bit before the `:` in a URL. -* `handler` Function<[GlobalResponse](https://nodejs.org/api/globals.html#response) | Promise<GlobalResponse>> +* `handler` Function\<[GlobalResponse](https://nodejs.org/api/globals.html#response) | Promise\<GlobalResponse\>\> * `request` [GlobalRequest](https://nodejs.org/api/globals.html#request) Register a protocol handler for `scheme`. Requests made to URLs with this diff --git a/docs/api/push-notifications.md b/docs/api/push-notifications.md index 4a9d19f09e..01c0e830e5 100644 --- a/docs/api/push-notifications.md +++ b/docs/api/push-notifications.md @@ -27,7 +27,7 @@ The `pushNotification` module emits the following events: Returns: * `event` Event -* `userInfo` Record<String, any> +* `userInfo` Record\<String, any\> Emitted when the app receives a remote notification while running. See: https://developer.apple.com/documentation/appkit/nsapplicationdelegate/1428430-application?language=objc diff --git a/docs/api/session.md b/docs/api/session.md index 0d534b2eee..54a1d160ea 100644 --- a/docs/api/session.md +++ b/docs/api/session.md @@ -1216,7 +1216,7 @@ Returns `Promise<Buffer>` - resolves with blob data. * `url` string * `options` Object (optional) - * `headers` Record<string, string> (optional) - HTTP request headers. + * `headers` Record\<string, string\> (optional) - HTTP request headers. Initiates a download of the resource at `url`. The API will generate a [DownloadItem](download-item.md) that can be accessed diff --git a/docs/api/structures/file-path-with-headers.md b/docs/api/structures/file-path-with-headers.md index e07688eae1..cc55a18fae 100644 --- a/docs/api/structures/file-path-with-headers.md +++ b/docs/api/structures/file-path-with-headers.md @@ -1,4 +1,4 @@ # FilePathWithHeaders Object * `path` string - The path to the file to send. -* `headers` Record<string, string> (optional) - Additional headers to be sent. +* `headers` Record\<string, string\> (optional) - Additional headers to be sent. diff --git a/docs/api/structures/notification-response.md b/docs/api/structures/notification-response.md index 32fff8625e..eb5f1882a5 100644 --- a/docs/api/structures/notification-response.md +++ b/docs/api/structures/notification-response.md @@ -3,5 +3,5 @@ * `actionIdentifier` string - The identifier string of the action that the user selected. * `date` number - The delivery date of the notification. * `identifier` string - The unique identifier for this notification request. -* `userInfo` Record<string, any> - A dictionary of custom information associated with the notification. +* `userInfo` Record\<string, any\> - A dictionary of custom information associated with the notification. * `userText` string (optional) - The text entered or chosen by the user. diff --git a/docs/api/structures/protocol-request.md b/docs/api/structures/protocol-request.md index aacc062f99..586a64bba9 100644 --- a/docs/api/structures/protocol-request.md +++ b/docs/api/structures/protocol-request.md @@ -4,4 +4,4 @@ * `referrer` string * `method` string * `uploadData` [UploadData[]](upload-data.md) (optional) -* `headers` Record<string, string> +* `headers` Record\<string, string\> diff --git a/docs/api/structures/protocol-response.md b/docs/api/structures/protocol-response.md index 21a863240f..6739ca77fb 100644 --- a/docs/api/structures/protocol-response.md +++ b/docs/api/structures/protocol-response.md @@ -10,7 +10,7 @@ `"text/html"`. Setting `mimeType` would implicitly set the `content-type` header in response, but if `content-type` is already set in `headers`, the `mimeType` would be ignored. -* `headers` Record<string, string | string[]> (optional) - An object containing the response headers. The +* `headers` Record\<string, string | string[]\> (optional) - An object containing the response headers. The keys must be string, and values must be either string or Array of string. * `data` (Buffer | string | ReadableStream) (optional) - The response body. When returning stream as response, this is a Node.js readable stream representing diff --git a/docs/api/structures/trace-config.md b/docs/api/structures/trace-config.md index 4160b7121c..fdded661b9 100644 --- a/docs/api/structures/trace-config.md +++ b/docs/api/structures/trace-config.md @@ -19,7 +19,7 @@ include in the trace. If not specified, trace all processes. * `histogram_names` string[] (optional) - a list of [histogram][] names to report with the trace. -* `memory_dump_config` Record<string, any> (optional) - if the +* `memory_dump_config` Record\<string, any\> (optional) - if the `disabled-by-default-memory-infra` category is enabled, this contains optional additional configuration for data collection. See the [Chromium memory-infra docs][memory-infra docs] for more information. diff --git a/docs/api/system-preferences.md b/docs/api/system-preferences.md index 7d61d79cb0..1a4806033a 100644 --- a/docs/api/system-preferences.md +++ b/docs/api/system-preferences.md @@ -36,7 +36,7 @@ Returns `boolean` - Whether the Swipe between pages setting is on. ### `systemPreferences.postNotification(event, userInfo[, deliverImmediately])` _macOS_ * `event` string -* `userInfo` Record<string, any> +* `userInfo` Record\<string, any\> * `deliverImmediately` boolean (optional) - `true` to post notifications immediately even when the subscribing app is inactive. Posts `event` as native notifications of macOS. The `userInfo` is an Object @@ -45,7 +45,7 @@ that contains the user information dictionary sent along with the notification. ### `systemPreferences.postLocalNotification(event, userInfo)` _macOS_ * `event` string -* `userInfo` Record<string, any> +* `userInfo` Record\<string, any\> Posts `event` as native notifications of macOS. The `userInfo` is an Object that contains the user information dictionary sent along with the notification. @@ -53,7 +53,7 @@ that contains the user information dictionary sent along with the notification. ### `systemPreferences.postWorkspaceNotification(event, userInfo)` _macOS_ * `event` string -* `userInfo` Record<string, any> +* `userInfo` Record\<string, any\> Posts `event` as native notifications of macOS. The `userInfo` is an Object that contains the user information dictionary sent along with the notification. @@ -63,7 +63,7 @@ that contains the user information dictionary sent along with the notification. * `event` string | null * `callback` Function * `event` string - * `userInfo` Record<string, unknown> + * `userInfo` Record\<string, unknown\> * `object` string Returns `number` - The ID of this subscription @@ -92,7 +92,7 @@ If `event` is null, the `NSDistributedNotificationCenter` doesn’t use it as cr * `event` string | null * `callback` Function * `event` string - * `userInfo` Record<string, unknown> + * `userInfo` Record\<string, unknown\> * `object` string Returns `number` - The ID of this subscription @@ -107,7 +107,7 @@ If `event` is null, the `NSNotificationCenter` doesn’t use it as criteria for * `event` string | null * `callback` Function * `event` string - * `userInfo` Record<string, unknown> + * `userInfo` Record\<string, unknown\> * `object` string Returns `number` - The ID of this subscription @@ -137,7 +137,7 @@ Same as `unsubscribeNotification`, but removes the subscriber from `NSWorkspace. ### `systemPreferences.registerDefaults(defaults)` _macOS_ -* `defaults` Record<string, string | boolean | number> - a dictionary of (`key: value`) user defaults +* `defaults` Record\<string, string | boolean | number\> - a dictionary of (`key: value`) user defaults Add the specified defaults to your application's `NSUserDefaults`. diff --git a/docs/api/web-contents.md b/docs/api/web-contents.md index 1aef04a308..915c54e6b6 100644 --- a/docs/api/web-contents.md +++ b/docs/api/web-contents.md @@ -237,7 +237,7 @@ See [`window.open()`](window-open.md) for more details and how to use this in co Returns: -* `details` Event<> +* `details` Event\<\> * `url` string - The URL the frame is navigating to. * `isSameDocument` boolean - This event does not fire for same document navigations using window.history api and reference fragment navigations. This property is always set to `false` for this event. @@ -270,7 +270,7 @@ Calling `event.preventDefault()` will prevent the navigation. Returns: -* `details` Event<> +* `details` Event\<\> * `url` string - The URL the frame is navigating to. * `isSameDocument` boolean - This event does not fire for same document navigations using window.history api and reference fragment navigations. This property is always set to `false` for this event. @@ -300,7 +300,7 @@ Calling `event.preventDefault()` will prevent the navigation. Returns: -* `details` Event<> +* `details` Event\<\> * `url` string - The URL the frame is navigating to. * `isSameDocument` boolean - Whether the navigation happened without changing document. Examples of same document navigations are reference fragment @@ -324,7 +324,7 @@ Emitted when any frame (including main) starts navigating. Returns: -* `details` Event<> +* `details` Event\<\> * `url` string - The URL the frame is navigating to. * `isSameDocument` boolean - Whether the navigation happened without changing document. Examples of same document navigations are reference fragment @@ -355,7 +355,7 @@ redirect). Returns: -* `details` Event<> +* `details` Event\<\> * `url` string - The URL the frame is navigating to. * `isSameDocument` boolean - Whether the navigation happened without changing document. Examples of same document navigations are reference fragment @@ -683,7 +683,7 @@ Emitted when media is paused or done playing. Returns: -* `event` Event<> +* `event` Event\<\> * `audible` boolean - True if one or more frames or child `webContents` are emitting audio. Emitted when media becomes audible or inaudible. @@ -900,7 +900,7 @@ Returns: * `webPreferences` [WebPreferences](structures/web-preferences.md) - The web preferences that will be used by the guest page. This object can be modified to adjust the preferences for the guest page. -* `params` Record<string, string> - The other `<webview>` parameters such as the `src` URL. +* `params` Record\<string, string\> - The other `<webview>` parameters such as the `src` URL. This object can be modified to adjust the parameters of the guest page. Emitted when a `<webview>`'s web contents is being attached to this web @@ -1020,7 +1020,7 @@ win.webContents.loadURL('https://github.com', options) * `filePath` string * `options` Object (optional) - * `query` Record<string, string> (optional) - Passed to `url.format()`. + * `query` Record\<string, string\> (optional) - Passed to `url.format()`. * `search` string (optional) - Passed to `url.format()`. * `hash` string (optional) - Passed to `url.format()`. @@ -1051,7 +1051,7 @@ win.loadFile('src/index.html') * `url` string * `options` Object (optional) - * `headers` Record<string, string> (optional) - HTTP request headers. + * `headers` Record\<string, string\> (optional) - HTTP request headers. Initiates a download of the resource at `url` without navigating. The `will-download` event of `session` will be triggered. @@ -1288,7 +1288,7 @@ Ignore application menu shortcuts while this web contents is focused. #### `contents.setWindowOpenHandler(handler)` -* `handler` Function<[WindowOpenHandlerResponse](structures/window-open-handler-response.md)> +* `handler` Function\<[WindowOpenHandlerResponse](structures/window-open-handler-response.md)\> * `details` Object * `url` string - The _resolved_ version of the URL passed to `window.open()`. e.g. opening a window with `window.open('foo')` will yield something like `https://the-origin/the/current/path/foo`. * `frameName` string - Name of the window provided in `window.open()` @@ -1583,7 +1583,7 @@ Returns `Promise<PrinterInfo[]>` - Resolves with a [`PrinterInfo[]`](structures/ * `from` number - Index of the first page to print (0-based). * `to` number - Index of the last page to print (inclusive) (0-based). * `duplexMode` string (optional) - Set the duplex mode of the printed web page. Can be `simplex`, `shortEdge`, or `longEdge`. - * `dpi` Record<string, number> (optional) + * `dpi` Record\<string, number\> (optional) * `horizontal` number (optional) - The horizontal dpi. * `vertical` number (optional) - The vertical dpi. * `header` string (optional) - string to be printed as page header. diff --git a/docs/api/web-request.md b/docs/api/web-request.md index e776bf76dc..232831e780 100644 --- a/docs/api/web-request.md +++ b/docs/api/web-request.md @@ -99,11 +99,11 @@ Some examples of valid `urls`: * `referrer` string * `timestamp` Double * `uploadData` [UploadData[]](structures/upload-data.md) (optional) - * `requestHeaders` Record<string, string> + * `requestHeaders` Record\<string, string\> * `callback` Function * `beforeSendResponse` Object * `cancel` boolean (optional) - * `requestHeaders` Record<string, string | string[]> (optional) - When provided, request will be made + * `requestHeaders` Record\<string, string | string[]\> (optional) - When provided, request will be made with these headers. The `listener` will be called with `listener(details, callback)` before sending @@ -126,7 +126,7 @@ The `callback` has to be called with a `response` object. * `resourceType` string - Can be `mainFrame`, `subFrame`, `stylesheet`, `script`, `image`, `font`, `object`, `xhr`, `ping`, `cspReport`, `media`, `webSocket` or `other`. * `referrer` string * `timestamp` Double - * `requestHeaders` Record<string, string> + * `requestHeaders` Record\<string, string\> The `listener` will be called with `listener(details)` just before a request is going to be sent to the server, modifications of previous `onBeforeSendHeaders` @@ -148,11 +148,11 @@ response are visible by the time this listener is fired. * `timestamp` Double * `statusLine` string * `statusCode` Integer - * `responseHeaders` Record<string, string[]> (optional) + * `responseHeaders` Record\<string, string[]\> (optional) * `callback` Function * `headersReceivedResponse` Object * `cancel` boolean (optional) - * `responseHeaders` Record<string, string | string[]> (optional) - When provided, the server is assumed + * `responseHeaders` Record\<string, string | string[]\> (optional) - When provided, the server is assumed to have responded with these headers. * `statusLine` string (optional) - Should be provided when overriding `responseHeaders` to change header status otherwise original response @@ -177,7 +177,7 @@ The `callback` has to be called with a `response` object. * `resourceType` string - Can be `mainFrame`, `subFrame`, `stylesheet`, `script`, `image`, `font`, `object`, `xhr`, `ping`, `cspReport`, `media`, `webSocket` or `other`. * `referrer` string * `timestamp` Double - * `responseHeaders` Record<string, string[]> (optional) + * `responseHeaders` Record\<string, string[]\> (optional) * `fromCache` boolean - Indicates whether the response was fetched from disk cache. * `statusCode` Integer @@ -207,7 +207,7 @@ and response headers are available. * `ip` string (optional) - The server IP address that the request was actually sent to. * `fromCache` boolean - * `responseHeaders` Record<string, string[]> (optional) + * `responseHeaders` Record\<string, string[]\> (optional) The `listener` will be called with `listener(details)` when a server initiated redirect is about to occur. @@ -226,7 +226,7 @@ redirect is about to occur. * `resourceType` string - Can be `mainFrame`, `subFrame`, `stylesheet`, `script`, `image`, `font`, `object`, `xhr`, `ping`, `cspReport`, `media`, `webSocket` or `other`. * `referrer` string * `timestamp` Double - * `responseHeaders` Record<string, string[]> (optional) + * `responseHeaders` Record\<string, string[]\> (optional) * `fromCache` boolean * `statusCode` Integer * `statusLine` string diff --git a/docs/api/webview-tag.md b/docs/api/webview-tag.md index 232f4a1451..99e740eb39 100644 --- a/docs/api/webview-tag.md +++ b/docs/api/webview-tag.md @@ -287,7 +287,7 @@ e.g. the `http://` or `file://`. * `url` string * `options` Object (optional) - * `headers` Record<string, string> (optional) - HTTP request headers. + * `headers` Record\<string, string\> (optional) - HTTP request headers. Initiates a download of the resource at `url` without navigating. @@ -580,7 +580,7 @@ Stops any `findInPage` request for the `webview` with the provided `action`. * `from` number - Index of the first page to print (0-based). * `to` number - Index of the last page to print (inclusive) (0-based). * `duplexMode` string (optional) - Set the duplex mode of the printed web page. Can be `simplex`, `shortEdge`, or `longEdge`. - * `dpi` Record<string, number> (optional) + * `dpi` Record\<string, number\> (optional) * `horizontal` number (optional) - The horizontal dpi. * `vertical` number (optional) - The vertical dpi. * `header` string (optional) - string to be printed as page header. diff --git a/docs/breaking-changes.md b/docs/breaking-changes.md index 01dd86c794..d16b28ce68 100644 --- a/docs/breaking-changes.md +++ b/docs/breaking-changes.md @@ -1686,7 +1686,7 @@ folder └── file3 ``` -In Electron <=6, this would return a `FileList` with a `File` object for: +In Electron &lt;=6, this would return a `FileList` with a `File` object for: ```console path/to/folder
docs
c35739d60df88b78383af0376cb094566bf5ed55
Charles Kerr
2024-08-09 18:35:18
refactor: use url::DomainIs() to check cookie domains (#43262) * test: add tests to exercise pre-exsiting cookie domain matching behavior * refactor: use url::DomainIs() to match cookie domains * docs: fix typo
diff --git a/docs/api/cookies.md b/docs/api/cookies.md index 8a3576d3fc..5bca7b570f 100644 --- a/docs/api/cookies.md +++ b/docs/api/cookies.md @@ -74,7 +74,7 @@ The following methods are available on instances of `Cookies`: `url`. Empty implies retrieving cookies of all URLs. * `name` string (optional) - Filters cookies by name. * `domain` string (optional) - Retrieves cookies whose domains match or are - subdomains of `domains`. + subdomains of `domain`. * `path` string (optional) - Retrieves cookies whose path matches `path`. * `secure` boolean (optional) - Filters cookies by their Secure property. * `session` boolean (optional) - Filters out session or persistent cookies. diff --git a/shell/browser/api/electron_api_cookies.cc b/shell/browser/api/electron_api_cookies.cc index 8870355084..7873b817c5 100644 --- a/shell/browser/api/electron_api_cookies.cc +++ b/shell/browser/api/electron_api_cookies.cc @@ -30,6 +30,7 @@ #include "shell/common/gin_helper/dictionary.h" #include "shell/common/gin_helper/object_template_builder.h" #include "shell/common/gin_helper/promise.h" +#include "url/url_util.h" namespace gin { @@ -100,25 +101,12 @@ namespace electron::api { namespace { -// Returns whether |domain| matches |filter|. -bool MatchesDomain(std::string filter, const std::string& domain) { - // Add a leading '.' character to the filter domain if it doesn't exist. - if (net::cookie_util::DomainIsHostOnly(filter)) - filter.insert(0, "."); - - std::string sub_domain(domain); +bool DomainIs(std::string_view host, const std::string_view domain) { // Strip any leading '.' character from the input cookie domain. - if (!net::cookie_util::DomainIsHostOnly(sub_domain)) - sub_domain = sub_domain.substr(1); - - // Now check whether the domain argument is a subdomain of the filter domain. - for (sub_domain.insert(0, "."); sub_domain.length() >= filter.length();) { - if (sub_domain == filter) - return true; - const size_t next_dot = sub_domain.find('.', 1); // Skip over leading dot. - sub_domain.erase(0, next_dot); - } - return false; + if (host.starts_with('.')) + host.remove_prefix(1); + + return url::DomainIs(host, domain); } // Returns whether |cookie| matches |filter|. @@ -129,8 +117,7 @@ bool MatchesCookie(const base::Value::Dict& filter, return false; if ((str = filter.FindString("path")) && *str != cookie.Path()) return false; - if ((str = filter.FindString("domain")) && - !MatchesDomain(*str, cookie.Domain())) + if ((str = filter.FindString("domain")) && !DomainIs(cookie.Domain(), *str)) return false; std::optional<bool> secure_filter = filter.FindBool("secure"); if (secure_filter && *secure_filter != cookie.SecureAttribute()) diff --git a/spec/api-session-spec.ts b/spec/api-session-spec.ts index 12ccd9d273..07d47ab299 100644 --- a/spec/api-session-spec.ts +++ b/spec/api-session-spec.ts @@ -1,4 +1,5 @@ import { expect } from 'chai'; +import * as crypto from 'node:crypto'; import * as http from 'node:http'; import * as https from 'node:https'; import * as path from 'node:path'; @@ -126,6 +127,54 @@ describe('session module', () => { expect(cs.some(c => c.name === name && c.value === value)).to.equal(true); }); + it('does not match on empty domain filter strings', async () => { + const { cookies } = session.defaultSession; + const name = crypto.randomBytes(20).toString('hex'); + const value = '1'; + const url = 'https://microsoft.com/'; + + await cookies.set({ url, name, value }); + const cs = await cookies.get({ domain: '' }); + expect(cs.some(c => c.name === name && c.value === value)).to.equal(false); + cookies.remove(url, name); + }); + + it('gets domain-equal cookies', async () => { + const { cookies } = session.defaultSession; + const name = crypto.randomBytes(20).toString('hex'); + const value = '1'; + const url = 'https://microsoft.com/'; + + await cookies.set({ url, name, value }); + const cs = await cookies.get({ domain: 'microsoft.com' }); + expect(cs.some(c => c.name === name && c.value === value)).to.equal(true); + cookies.remove(url, name); + }); + + it('gets domain-inclusive cookies', async () => { + const { cookies } = session.defaultSession; + const name = crypto.randomBytes(20).toString('hex'); + const value = '1'; + const url = 'https://subdomain.microsoft.com/'; + + await cookies.set({ url, name, value }); + const cs = await cookies.get({ domain: 'microsoft.com' }); + expect(cs.some(c => c.name === name && c.value === value)).to.equal(true); + cookies.remove(url, name); + }); + + it('omits domain-exclusive cookies', async () => { + const { cookies } = session.defaultSession; + const name = crypto.randomBytes(20).toString('hex'); + const value = '1'; + const url = 'https://microsoft.com'; + + await cookies.set({ url, name, value }); + const cs = await cookies.get({ domain: 'subdomain.microsoft.com' }); + expect(cs.some(c => c.name === name && c.value === value)).to.equal(false); + cookies.remove(url, name); + }); + it('rejects when setting a cookie with missing required fields', async () => { const { cookies } = session.defaultSession; const name = '1';
refactor
bbd2236bdd4fda6ab702c67fa9a5cec13cc6df01
Shelley Vohr
2023-10-13 22:09:28
fix: ensure MessagePorts get GCed when not referenced (#40189)
diff --git a/patches/chromium/.patches b/patches/chromium/.patches index 58425d281b..0bbfcc0f82 100644 --- a/patches/chromium/.patches +++ b/patches/chromium/.patches @@ -135,3 +135,4 @@ fix_activate_background_material_on_windows.patch fix_move_autopipsettingshelper_behind_branding_buildflag.patch revert_remove_the_allowaggressivethrottlingwithwebsocket_feature.patch fix_handle_no_top_level_aura_window_in_webcontentsimpl.patch +ensure_messageports_get_gced_when_not_referenced.patch diff --git a/patches/chromium/ensure_messageports_get_gced_when_not_referenced.patch b/patches/chromium/ensure_messageports_get_gced_when_not_referenced.patch new file mode 100644 index 0000000000..d4fe394e4f --- /dev/null +++ b/patches/chromium/ensure_messageports_get_gced_when_not_referenced.patch @@ -0,0 +1,73 @@ +From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 +From: Yoav Weiss <[email protected]> +Date: Mon, 9 Oct 2023 14:21:44 +0000 +Subject: Ensure MessagePorts get GCed when not referenced + +[1] regressed MessagePort memory and caused them to no longer be +collected after not being referenced. +This CL fixes that by turning the mutual pointers between attached +MessagePorts to be WeakMembers. + +[1] https://chromium-review.googlesource.com/4919476 + +Bug: 1487835 +Change-Id: Icd7eba09a217ad5d588958504d5c4794d7d8a295 +Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/4919476 +Commit-Queue: Yoav Weiss <[email protected]> +Reviewed-by: Michael Lippautz <[email protected]> +Cr-Commit-Position: refs/heads/main@{#1207067} + +diff --git a/third_party/blink/renderer/core/messaging/message_port.cc b/third_party/blink/renderer/core/messaging/message_port.cc +index 0fd5bbf170efa02d3e710de3cb6733158faec858..15f5f0f6aa05d3b17adae87286c92df9cc26a712 100644 +--- a/third_party/blink/renderer/core/messaging/message_port.cc ++++ b/third_party/blink/renderer/core/messaging/message_port.cc +@@ -162,8 +162,10 @@ MessagePortChannel MessagePort::Disentangle() { + DCHECK(!IsNeutered()); + port_descriptor_.GiveDisentangledHandle(connector_->PassMessagePipe()); + connector_ = nullptr; +- if (initially_entangled_port_) { +- initially_entangled_port_->OnEntangledPortDisconnected(); ++ // Using a variable here places the WeakMember pointer on the stack, ensuring ++ // it doesn't get GCed while it's being used. ++ if (auto* entangled_port = initially_entangled_port_.Get()) { ++ entangled_port->OnEntangledPortDisconnected(); + } + OnEntangledPortDisconnected(); + return MessagePortChannel(std::move(port_descriptor_)); +@@ -340,7 +342,10 @@ bool MessagePort::Accept(mojo::Message* mojo_message) { + // lifetime of this function. + std::unique_ptr<scheduler::TaskAttributionTracker::TaskScope> + task_attribution_scope; +- if (initially_entangled_port_ && message.sender_origin && ++ // Using a variable here places the WeakMember pointer on the stack, ensuring ++ // it doesn't get GCed while it's being used. ++ auto* entangled_port = initially_entangled_port_.Get(); ++ if (entangled_port && message.sender_origin && + message.sender_origin->IsSameOriginWith(context->GetSecurityOrigin()) && + context->IsSameAgentCluster(message.sender_agent_cluster_id) && + context->IsWindow()) { +@@ -364,9 +369,9 @@ bool MessagePort::Accept(mojo::Message* mojo_message) { + ThreadScheduler::Current()->GetTaskAttributionTracker()) { + // Since `initially_entangled_port_` is not nullptr, neither should be + // its `post_message_task_container_`. +- CHECK(initially_entangled_port_->post_message_task_container_); ++ CHECK(entangled_port->post_message_task_container_); + scheduler::TaskAttributionInfo* parent_task = +- initially_entangled_port_->post_message_task_container_ ++ entangled_port->post_message_task_container_ + ->GetAndDecrementPostMessageTask(message.parent_task_id); + task_attribution_scope = tracker->CreateTaskScope( + script_state, parent_task, +diff --git a/third_party/blink/renderer/core/messaging/message_port.h b/third_party/blink/renderer/core/messaging/message_port.h +index 98ed58a9a765f5101d9b421507bf25db4359d7e5..a178d15c11b1e5fb1ff74d182021fe39e9d9b107 100644 +--- a/third_party/blink/renderer/core/messaging/message_port.h ++++ b/third_party/blink/renderer/core/messaging/message_port.h +@@ -195,7 +195,7 @@ class CORE_EXPORT MessagePort : public EventTarget, + + // The entangled port. Only set on initial entanglement, and gets unset as + // soon as the ports are disentangled. +- Member<MessagePort> initially_entangled_port_; ++ WeakMember<MessagePort> initially_entangled_port_; + + Member<PostMessageTaskContainer> post_message_task_container_; + }; diff --git a/spec/api-ipc-spec.ts b/spec/api-ipc-spec.ts index 594148162b..873511b6ea 100644 --- a/spec/api-ipc-spec.ts +++ b/spec/api-ipc-spec.ts @@ -317,11 +317,7 @@ describe('ipc module', () => { await once(ipcMain, 'closed'); }); - // TODO(@vertedinde): This broke upstream in CL https://chromium-review.googlesource.com/c/chromium/src/+/4831380 - // The behavior seems to be an intentional change, we need to either A) implement the task_container_ model in - // our renderer message ports or B) patch how we handle renderer message ports being garbage collected - // crbug: https://bugs.chromium.org/p/chromium/issues/detail?id=1487835 - it.skip('is emitted when the other end of a port is garbage-collected', async () => { + it('is emitted when the other end of a port is garbage-collected', async () => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadURL('about:blank'); await w.webContents.executeJavaScript(`(${async function () {
fix
fac964ac0dc723cd8efd1a89604acac861671579
Charles Kerr
2024-01-10 14:01:49
refactor: migrate deprecated LazyInstance code to NoDestructor (#40927) * refactor: do not use deprecated NoDestructor in javascript_environment.cc * refactor: do not use deprecated NoDestructor in window_list.cc
diff --git a/shell/browser/javascript_environment.cc b/shell/browser/javascript_environment.cc index cd8b0c9df8..6efd69abc3 100644 --- a/shell/browser/javascript_environment.cc +++ b/shell/browser/javascript_environment.cc @@ -14,6 +14,7 @@ #include "base/bits.h" #include "base/command_line.h" #include "base/feature_list.h" +#include "base/no_destructor.h" #include "base/task/current_thread.h" #include "base/task/single_thread_task_runner.h" #include "base/task/thread_pool/initialization_util.h" @@ -184,9 +185,6 @@ class EnabledStateObserverImpl final std::unordered_set<v8::TracingController::TraceStateObserver*> observers_; }; -base::LazyInstance<EnabledStateObserverImpl>::Leaky g_trace_state_dispatcher = - LAZY_INSTANCE_INITIALIZER; - class TracingControllerImpl : public node::tracing::TracingController { public: TracingControllerImpl() = default; @@ -265,11 +263,19 @@ class TracingControllerImpl : public node::tracing::TracingController { TRACE_EVENT_API_UPDATE_TRACE_EVENT_DURATION(category_enabled_flag, name, traceEventHandle); } + void AddTraceStateObserver(TraceStateObserver* observer) override { - g_trace_state_dispatcher.Get().AddObserver(observer); + GetObserverDelegate().AddObserver(observer); } + void RemoveTraceStateObserver(TraceStateObserver* observer) override { - g_trace_state_dispatcher.Get().RemoveObserver(observer); + GetObserverDelegate().RemoveObserver(observer); + } + + private: + static EnabledStateObserverImpl& GetObserverDelegate() { + static base::NoDestructor<EnabledStateObserverImpl> instance; + return *instance; } }; diff --git a/shell/browser/window_list.cc b/shell/browser/window_list.cc index a2555e5a11..78378f3aa9 100644 --- a/shell/browser/window_list.cc +++ b/shell/browser/window_list.cc @@ -7,6 +7,7 @@ #include <algorithm> #include "base/logging.h" +#include "base/no_destructor.h" #include "shell/browser/native_window.h" #include "shell/browser/window_list_observer.h" @@ -24,10 +25,6 @@ std::vector<base::WeakPtr<T>> ConvertToWeakPtrVector(std::vector<T*> raw_ptrs) { namespace electron { -// static -base::LazyInstance<base::ObserverList<WindowListObserver>>::Leaky - WindowList::observers_ = LAZY_INSTANCE_INITIALIZER; - // static WindowList* WindowList::instance_ = nullptr; @@ -55,7 +52,7 @@ void WindowList::AddWindow(NativeWindow* window) { WindowVector& windows = GetInstance()->windows_; windows.push_back(window); - for (WindowListObserver& observer : observers_.Get()) + for (WindowListObserver& observer : GetObservers()) observer.OnWindowAdded(window); } @@ -65,29 +62,29 @@ void WindowList::RemoveWindow(NativeWindow* window) { windows.erase(std::remove(windows.begin(), windows.end(), window), windows.end()); - for (WindowListObserver& observer : observers_.Get()) + for (WindowListObserver& observer : GetObservers()) observer.OnWindowRemoved(window); if (windows.empty()) { - for (WindowListObserver& observer : observers_.Get()) + for (WindowListObserver& observer : GetObservers()) observer.OnWindowAllClosed(); } } // static void WindowList::WindowCloseCancelled(NativeWindow* window) { - for (WindowListObserver& observer : observers_.Get()) + for (WindowListObserver& observer : GetObservers()) observer.OnWindowCloseCancelled(window); } // static void WindowList::AddObserver(WindowListObserver* observer) { - observers_.Get().AddObserver(observer); + GetObservers().AddObserver(observer); } // static void WindowList::RemoveObserver(WindowListObserver* observer) { - observers_.Get().RemoveObserver(observer); + GetObservers().RemoveObserver(observer); } // static @@ -118,4 +115,10 @@ WindowList::WindowList() = default; WindowList::~WindowList() = default; +// static +base::ObserverList<WindowListObserver>& WindowList::GetObservers() { + static base::NoDestructor<base::ObserverList<WindowListObserver>> instance; + return *instance; +} + } // namespace electron diff --git a/shell/browser/window_list.h b/shell/browser/window_list.h index 7d8dd942f4..85d7b7d8ed 100644 --- a/shell/browser/window_list.h +++ b/shell/browser/window_list.h @@ -7,7 +7,6 @@ #include <vector> -#include "base/lazy_instance.h" #include "base/observer_list.h" namespace electron { @@ -49,13 +48,12 @@ class WindowList { WindowList(); ~WindowList(); - // A vector of the windows in this list, in the order they were added. - WindowVector windows_; - // A list of observers which will be notified of every window addition and // removal across all WindowLists. - static base::LazyInstance<base::ObserverList<WindowListObserver>>::Leaky - observers_; + [[nodiscard]] static base::ObserverList<WindowListObserver>& GetObservers(); + + // A vector of the windows in this list, in the order they were added. + WindowVector windows_; static WindowList* instance_; };
refactor
f9d1b9adedd587fcfc822607b2d9e5b3f3b3fdf9
Step Security Bot
2022-11-14 18:39:13
ci: pin some more action versions (#36343) * [StepSecurity] ci: Harden GitHub Actions Signed-off-by: StepSecurity Bot <[email protected]> * Update electron_woa_testing.yml Signed-off-by: StepSecurity Bot <[email protected]> Co-authored-by: Jeremy Rose <[email protected]>
diff --git a/.github/workflows/electron_woa_testing.yml b/.github/workflows/electron_woa_testing.yml index 74192bffb3..a7667da1af 100644 --- a/.github/workflows/electron_woa_testing.yml +++ b/.github/workflows/electron_woa_testing.yml @@ -26,7 +26,7 @@ jobs: checks: write pull-requests: write steps: - - uses: LouisBrunner/[email protected] + - uses: LouisBrunner/checks-action@442ad2296fb110373e3fe01c2a3717b546583631 # tag: v1.1.1 with: token: ${{ secrets.GITHUB_TOKEN }} name: electron-woa-testing @@ -39,7 +39,7 @@ jobs: Remove-Item * -Recurse -Force shell: powershell - name: Checkout - uses: actions/checkout@v3 + uses: actions/checkout@93ea575cb5d8a053eaa0ac8fa3b40d7e05a33cc8 # tag: v3 with: path: src\electron fetch-depth: 0 @@ -134,7 +134,7 @@ jobs: run: | Remove-Item -path $env:APPDATA/Electron* -Recurse -Force -ErrorAction Ignore shell: powershell - - uses: LouisBrunner/[email protected] + - uses: LouisBrunner/checks-action@442ad2296fb110373e3fe01c2a3717b546583631 # tag: v1.1.1 if: ${{ success() }} with: token: ${{ secrets.GITHUB_TOKEN }} @@ -143,7 +143,7 @@ jobs: details_url: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} output: | {"summary":"${{ job.status }}","text_description":"See job details here: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}"} - - uses: LouisBrunner/[email protected] + - uses: LouisBrunner/checks-action@442ad2296fb110373e3fe01c2a3717b546583631 # tag: v1.1.1 if: ${{ success() }} with: token: ${{ secrets.GITHUB_TOKEN }} @@ -152,7 +152,7 @@ jobs: details_url: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} output: | {"summary":"Job Succeeded","text_description":"See job details here: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}"} - - uses: LouisBrunner/[email protected] + - uses: LouisBrunner/checks-action@442ad2296fb110373e3fe01c2a3717b546583631 # tag: v1.1.1 if: ${{ ! success() }} with: token: ${{ secrets.GITHUB_TOKEN }} @@ -160,4 +160,4 @@ jobs: conclusion: "${{ job.status }}" details_url: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} output: | - {"summary":"Job Failed","text_description":"See job details here: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}"} \ No newline at end of file + {"summary":"Job Failed","text_description":"See job details here: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}"}
ci
635d421123b996086f459ec3c6f97513e2e358cf
George Xu
2024-09-04 04:56:26
fix: systemMediaPermissionDenied should not check camera perms when the request is asking for screen share (#43517) * fix: systemMediaPermissionDenied: should check for screen capture perms instead of camera * Revert "fix: systemMediaPermissionDenied: should check for screen capture perms instead of camera" This reverts commit e9cc67216558263402867056ed332f8781da3153. * should only do these checks for audio or video, but not screenshare * no service * oops --------- Co-authored-by: John Kleinschmidt <[email protected]>
diff --git a/shell/browser/web_contents_permission_helper.cc b/shell/browser/web_contents_permission_helper.cc index 40f77feed1..ff3c01c34b 100644 --- a/shell/browser/web_contents_permission_helper.cc +++ b/shell/browser/web_contents_permission_helper.cc @@ -57,7 +57,7 @@ namespace { #if BUILDFLAG(IS_MAC) bool SystemMediaPermissionDenied(const content::MediaStreamRequest& request) { - if (request.audio_type != MediaStreamType::NO_SERVICE) { + if (request.audio_type == MediaStreamType::DEVICE_AUDIO_CAPTURE) { const auto system_audio_permission = system_media_permissions::CheckSystemAudioCapturePermission(); return system_audio_permission == @@ -65,7 +65,7 @@ bool SystemMediaPermissionDenied(const content::MediaStreamRequest& request) { system_audio_permission == system_media_permissions::SystemPermission::kDenied; } - if (request.video_type != MediaStreamType::NO_SERVICE) { + if (request.video_type == MediaStreamType::DEVICE_VIDEO_CAPTURE) { const auto system_video_permission = system_media_permissions::CheckSystemVideoCapturePermission(); return system_video_permission == @@ -73,6 +73,7 @@ bool SystemMediaPermissionDenied(const content::MediaStreamRequest& request) { system_video_permission == system_media_permissions::SystemPermission::kDenied; } + return false; } #endif
fix
f31826f4a0c44756305087f11cf0de794e68c447
Shelley Vohr
2023-01-11 11:55:31
fix: `getUserMedia` duplicate permissions call (#36787) * fix: getUserMedia duplicate permissions call * test: add regression test
diff --git a/patches/chromium/short-circuit_permissions_checks_in_mediastreamdevicescontroller.patch b/patches/chromium/short-circuit_permissions_checks_in_mediastreamdevicescontroller.patch index 33a0542313..2634a5588a 100644 --- a/patches/chromium/short-circuit_permissions_checks_in_mediastreamdevicescontroller.patch +++ b/patches/chromium/short-circuit_permissions_checks_in_mediastreamdevicescontroller.patch @@ -15,60 +15,60 @@ short-circuit all the permissions checks in MSDC for now to allow us to unduplicate this code. diff --git a/components/webrtc/media_stream_devices_controller.cc b/components/webrtc/media_stream_devices_controller.cc -index 7dbbcc13901dcd8b7a9ca9c9bdce4f924c1c6a55..5de44c5c20c92a1793060492f925519d6b8befe5 100644 +index 7dbbcc13901dcd8b7a9ca9c9bdce4f924c1c6a55..f4def7e347aafe30485fd1e6055c97d471b44776 100644 --- a/components/webrtc/media_stream_devices_controller.cc +++ b/components/webrtc/media_stream_devices_controller.cc -@@ -92,10 +92,13 @@ void MediaStreamDevicesController::RequestPermissions( +@@ -56,7 +56,8 @@ bool PermissionIsRequested(blink::PermissionType permission, + void MediaStreamDevicesController::RequestPermissions( + const content::MediaStreamRequest& request, + MediaStreamDeviceEnumerator* enumerator, +- ResultCallback callback) { ++ ResultCallback callback, ++ bool previously_approved) { + content::RenderFrameHost* rfh = content::RenderFrameHost::FromID( + request.render_process_id, request.render_frame_id); + // The RFH may have been destroyed by the time the request is processed. +@@ -92,6 +93,7 @@ void MediaStreamDevicesController::RequestPermissions( std::vector<blink::PermissionType> permission_types; +#if 0 content::PermissionController* permission_controller = web_contents->GetBrowserContext()->GetPermissionController(); -+#endif - if (controller->ShouldRequestAudio()) { -+#if 0 - content::PermissionResult permission_status = - permission_controller->GetPermissionResultForCurrentDocument( - blink::PermissionType::AUDIO_CAPTURE, rfh); -@@ -110,10 +113,12 @@ void MediaStreamDevicesController::RequestPermissions( - content::PermissionStatusSource::FENCED_FRAME); - return; +@@ -152,19 +154,25 @@ void MediaStreamDevicesController::RequestPermissions( + permission_types.push_back(blink::PermissionType::CAMERA_PAN_TILT_ZOOM); } -+#endif - - permission_types.push_back(blink::PermissionType::AUDIO_CAPTURE); } - if (controller->ShouldRequestVideo()) { -+#if 0 - content::PermissionResult permission_status = - permission_controller->GetPermissionResultForCurrentDocument( - blink::PermissionType::VIDEO_CAPTURE, rfh); -@@ -128,6 +133,7 @@ void MediaStreamDevicesController::RequestPermissions( - content::PermissionStatusSource::FENCED_FRAME); - return; - } +#endif - permission_types.push_back(blink::PermissionType::VIDEO_CAPTURE); - -@@ -139,6 +145,7 @@ void MediaStreamDevicesController::RequestPermissions( - // pan-tilt-zoom permission and there are suitable PTZ capable devices - // available. - if (request.request_pan_tilt_zoom_permission && has_pan_tilt_zoom_camera) { -+#if 0 - permission_status = - permission_controller->GetPermissionResultForCurrentDocument( - blink::PermissionType::CAMERA_PAN_TILT_ZOOM, rfh); -@@ -148,6 +155,7 @@ void MediaStreamDevicesController::RequestPermissions( - controller->RunCallback(/*blocked_by_permissions_policy=*/false); - return; - } -+#endif + // It is OK to ignore `request.security_origin` because it will be calculated + // from `render_frame_host` and we always ignore `requesting_origin` for + // `AUDIO_CAPTURE` and `VIDEO_CAPTURE`. + // `render_frame_host->GetMainFrame()->GetLastCommittedOrigin()` will be used + // instead. +- rfh->GetBrowserContext() +- ->GetPermissionController() +- ->RequestPermissionsFromCurrentDocument( +- permission_types, rfh, request.user_gesture, +- base::BindOnce( +- &MediaStreamDevicesController::PromptAnsweredGroupedRequest, +- std::move(controller))); ++ if (previously_approved) { ++ controller->PromptAnsweredGroupedRequest({blink::mojom::PermissionStatus::GRANTED /*audio*/, ++ blink::mojom::PermissionStatus::GRANTED /*video*/}); ++ } else { ++ rfh->GetBrowserContext() ++ ->GetPermissionController() ++ ->RequestPermissionsFromCurrentDocument( ++ permission_types, rfh, request.user_gesture, ++ base::BindOnce( ++ &MediaStreamDevicesController::PromptAnsweredGroupedRequest, ++ std::move(controller))); ++ } + } - permission_types.push_back(blink::PermissionType::CAMERA_PAN_TILT_ZOOM); - } + MediaStreamDevicesController::~MediaStreamDevicesController() { @@ -434,6 +442,7 @@ bool MediaStreamDevicesController::PermissionIsBlockedForReason( return false; } @@ -85,3 +85,17 @@ index 7dbbcc13901dcd8b7a9ca9c9bdce4f924c1c6a55..5de44c5c20c92a1793060492f925519d return false; } +diff --git a/components/webrtc/media_stream_devices_controller.h b/components/webrtc/media_stream_devices_controller.h +index b9cf3f6ad047fa16594393134eae5fc5349e7430..5de5e0bf9b455872f69de47d58dda929f00df12c 100644 +--- a/components/webrtc/media_stream_devices_controller.h ++++ b/components/webrtc/media_stream_devices_controller.h +@@ -48,7 +48,8 @@ class MediaStreamDevicesController { + // synchronously or asynchronously returned via |callback|. + static void RequestPermissions(const content::MediaStreamRequest& request, + MediaStreamDeviceEnumerator* enumerator, +- ResultCallback callback); ++ ResultCallback callback, ++ bool previously_approved = false); + + ~MediaStreamDevicesController(); + diff --git a/shell/browser/web_contents_permission_helper.cc b/shell/browser/web_contents_permission_helper.cc index 0e9b42ecea..01173c2174 100644 --- a/shell/browser/web_contents_permission_helper.cc +++ b/shell/browser/web_contents_permission_helper.cc @@ -119,7 +119,8 @@ void MediaAccessAllowed(const content::MediaStreamRequest& request, blink::mojom::MediaStreamType::DEVICE_AUDIO_CAPTURE) { webrtc::MediaStreamDevicesController::RequestPermissions( request, MediaCaptureDevicesDispatcher::GetInstance(), - base::BindOnce(&OnMediaStreamRequestResponse, std::move(callback))); + base::BindOnce(&OnMediaStreamRequestResponse, std::move(callback)), + allowed); } else if (request.video_type == blink::mojom::MediaStreamType::DISPLAY_VIDEO_CAPTURE || request.video_type == blink::mojom::MediaStreamType:: diff --git a/spec/api-session-spec.ts b/spec/api-session-spec.ts index 019317a510..886f8ed72e 100644 --- a/spec/api-session-spec.ts +++ b/spec/api-session-spec.ts @@ -1053,6 +1053,22 @@ describe('session module', () => { describe('ses.setPermissionRequestHandler(handler)', () => { afterEach(closeAllWindows); + // These tests are done on an http server because navigator.userAgentData + // requires a secure context. + let server: http.Server; + let serverUrl: string; + before(async () => { + server = http.createServer((req, res) => { + res.setHeader('Content-Type', 'text/html'); + res.end(''); + }); + await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve)); + serverUrl = `http://localhost:${(server.address() as any).port}`; + }); + after(() => { + server.close(); + }); + it('cancels any pending requests when cleared', async () => { const w = new BrowserWindow({ show: false, @@ -1085,6 +1101,43 @@ describe('session module', () => { const [, name] = await result; expect(name).to.deep.equal('SecurityError'); }); + + it('successfully resolves when calling legacy getUserMedia', async () => { + const ses = session.fromPartition('' + Math.random()); + ses.setPermissionRequestHandler( + (_webContents, _permission, callback) => { + callback(true); + } + ); + + const w = new BrowserWindow({ show: false, webPreferences: { session: ses } }); + await w.loadURL(serverUrl); + const { ok, message } = await w.webContents.executeJavaScript(` + new Promise((resolve, reject) => navigator.getUserMedia({ + video: true, + audio: true, + }, x => resolve({ok: x instanceof MediaStream}), e => reject({ok: false, message: e.message}))) + `); + expect(ok).to.be.true(message); + }); + + it('successfully rejects when calling legacy getUserMedia', async () => { + const ses = session.fromPartition('' + Math.random()); + ses.setPermissionRequestHandler( + (_webContents, _permission, callback) => { + callback(false); + } + ); + + const w = new BrowserWindow({ show: false, webPreferences: { session: ses } }); + await w.loadURL(serverUrl); + await expect(w.webContents.executeJavaScript(` + new Promise((resolve, reject) => navigator.getUserMedia({ + video: true, + audio: true, + }, x => resolve({ok: x instanceof MediaStream}), e => reject({ok: false, message: e.message}))) + `)).to.eventually.be.rejectedWith('Permission denied'); + }); }); describe('ses.setPermissionCheckHandler(handler)', () => {
fix
b428315c6dd9aea97611ab3ef98145b870ef33ae
Charles Kerr
2024-04-16 18:48:54
perf: remove unnecessary `.c_str()` calls (#41869) * perf: remove unnecessary c_str() call when invoking promise.RejectWithErrorMessage() RejectWithErrorMessage() takes a std::string_view * perf: remove unnecessary c_str() call when invoking Environment::SetVar() the val arg to Environment::SetVar() takes a const std::string& * refactor: use string_view variant of base::UTF8ToWide() * perf: remove unnecessary c_str() call when instantiating a ScopedHString ScopedHString has always taken a StringPiece * refactor: use simpler invocation of base::make_span() * perf: remove unnecessary c_str() call when calling base::CommandLine::HasSwitch() HasSwitch() already takes a string_piece * perf: remove unnecessary c_str() call when calling net::HttpResponseHeaders::AddHeader() AddHeader() already takes a StringPiece arg * perf: omit unnecessary str -> wstr -> str conversion in DesktopCapturer::UpdateSourcesList() this conversion was made redundant by c670e38
diff --git a/shell/browser/api/electron_api_app.cc b/shell/browser/api/electron_api_app.cc index 27d2ec3fa1..01ebe1a544 100644 --- a/shell/browser/api/electron_api_app.cc +++ b/shell/browser/api/electron_api_app.cc @@ -462,8 +462,7 @@ void OnClientCertificateSelected( return; auto certs = net::X509Certificate::CreateCertificateListFromBytes( - base::as_bytes(base::make_span(data.c_str(), data.size())), - net::X509Certificate::FORMAT_AUTO); + base::as_bytes(base::make_span(data)), net::X509Certificate::FORMAT_AUTO); if (!certs.empty()) { scoped_refptr<net::X509Certificate> cert(certs[0].get()); for (auto& identity : *identities) { diff --git a/shell/browser/api/electron_api_desktop_capturer.cc b/shell/browser/api/electron_api_desktop_capturer.cc index be459fb57f..5d9bc96a03 100644 --- a/shell/browser/api/electron_api_desktop_capturer.cc +++ b/shell/browser/api/electron_api_desktop_capturer.cc @@ -399,11 +399,7 @@ void DesktopCapturer::UpdateSourcesList(DesktopMediaList* list) { int device_name_index = 0; for (auto& source : screen_sources) { const auto& device_name = device_names[device_name_index++]; - std::wstring wide_device_name; - base::UTF8ToWide(device_name.c_str(), device_name.size(), - &wide_device_name); - const int64_t device_id = - base::PersistentHash(base::WideToUTF8(wide_device_name.c_str())); + const int64_t device_id = base::PersistentHash(device_name); source.display_id = base::NumberToString(device_id); } } diff --git a/shell/browser/electron_browser_main_parts.cc b/shell/browser/electron_browser_main_parts.cc index 05914ebafc..c843ecbbce 100644 --- a/shell/browser/electron_browser_main_parts.cc +++ b/shell/browser/electron_browser_main_parts.cc @@ -313,7 +313,7 @@ int ElectronBrowserMainParts::PreCreateThreads() { std::string str; if (env->GetVar("LC_ALL", &str)) lc_all.emplace(std::move(str)); - env->SetVar("LC_ALL", locale.c_str()); + env->SetVar("LC_ALL", locale); } #endif diff --git a/shell/browser/net/asar/asar_url_loader.cc b/shell/browser/net/asar/asar_url_loader.cc index c1e83c5d6e..0891df0bfe 100644 --- a/shell/browser/net/asar/asar_url_loader.cc +++ b/shell/browser/net/asar/asar_url_loader.cc @@ -267,7 +267,7 @@ class AsarURLLoader : public network::mojom::URLLoader { } if (head->headers) { head->headers->AddHeader(net::HttpRequestHeaders::kContentType, - head->mime_type.c_str()); + head->mime_type); } client_->OnReceiveResponse(std::move(head), std::move(consumer_handle), std::nullopt); diff --git a/shell/browser/notifications/win/windows_toast_notification.cc b/shell/browser/notifications/win/windows_toast_notification.cc index 9fcdd17d5e..b39eded77f 100644 --- a/shell/browser/notifications/win/windows_toast_notification.cc +++ b/shell/browser/notifications/win/windows_toast_notification.cc @@ -540,7 +540,7 @@ HRESULT WindowsToastNotification::SetXmlImage(IXmlDocument* doc, ComPtr<IXmlNode> src_attr; RETURN_IF_FAILED(attrs->GetNamedItem(src, &src_attr)); - ScopedHString img_path(icon_path.c_str()); + const ScopedHString img_path{icon_path}; if (!img_path.success()) return E_FAIL; diff --git a/shell/common/api/electron_api_command_line.cc b/shell/common/api/electron_api_command_line.cc index dd25183981..5dcd03a550 100644 --- a/shell/common/api/electron_api_command_line.cc +++ b/shell/common/api/electron_api_command_line.cc @@ -14,12 +14,11 @@ namespace { bool HasSwitch(const std::string& name) { - return base::CommandLine::ForCurrentProcess()->HasSwitch(name.c_str()); + return base::CommandLine::ForCurrentProcess()->HasSwitch(name); } base::CommandLine::StringType GetSwitchValue(const std::string& name) { - return base::CommandLine::ForCurrentProcess()->GetSwitchValueNative( - name.c_str()); + return base::CommandLine::ForCurrentProcess()->GetSwitchValueNative(name); } void AppendSwitch(const std::string& switch_string, diff --git a/shell/common/api/electron_api_shell.cc b/shell/common/api/electron_api_shell.cc index b05b5216b5..6881ca7849 100644 --- a/shell/common/api/electron_api_shell.cc +++ b/shell/common/api/electron_api_shell.cc @@ -51,7 +51,7 @@ void OnOpenFinished(gin_helper::Promise<void> promise, if (error.empty()) promise.Resolve(); else - promise.RejectWithErrorMessage(error.c_str()); + promise.RejectWithErrorMessage(error); } v8::Local<v8::Promise> OpenExternal(const GURL& url, gin::Arguments* args) {
perf
c7a64ab994de826ed6e4c300cce75d9fd88efa20
Shelley Vohr
2023-07-06 10:20:34
fix: webview crash when removing in close event (#38996)
diff --git a/shell/browser/api/electron_api_web_contents.cc b/shell/browser/api/electron_api_web_contents.cc index b84ac07250..5f4d985f8b 100644 --- a/shell/browser/api/electron_api_web_contents.cc +++ b/shell/browser/api/electron_api_web_contents.cc @@ -1297,7 +1297,9 @@ void WebContents::CloseContents(content::WebContents* source) { for (ExtendedWebContentsObserver& observer : observers_) observer.OnCloseContents(); - Destroy(); + // This is handled by the embedder frame. + if (!IsGuest()) + Destroy(); } void WebContents::ActivateContents(content::WebContents* source) { diff --git a/spec/fixtures/crash-cases/webview-remove-on-wc-close/index.html b/spec/fixtures/crash-cases/webview-remove-on-wc-close/index.html new file mode 100644 index 0000000000..cbaaf2339d --- /dev/null +++ b/spec/fixtures/crash-cases/webview-remove-on-wc-close/index.html @@ -0,0 +1,32 @@ +<!DOCTYPE html> +<html lang="en"> + +<head> + <meta charset="UTF-8"> + <meta name="viewport" content="width=device-width, initial-scale=1.0"> + <title>Document</title> + <style> + .webview { + border: 1px solid black; + } + </style> +</head> + +<body> + <button class="close-btn">close webview</button> + <webview class="webview" src="./webview.html"></webview> + <script> + const close = document.querySelector('.close-btn') + const webview = document.querySelector('.webview') + + webview.addEventListener('close', () => { + webview.parentNode.removeChild(webview) + }) + + close.addEventListener('click', () => { + webview.executeJavaScript('window.close()', true) + }) + </script> +</body> + +</html> diff --git a/spec/fixtures/crash-cases/webview-remove-on-wc-close/index.js b/spec/fixtures/crash-cases/webview-remove-on-wc-close/index.js new file mode 100644 index 0000000000..6aba842596 --- /dev/null +++ b/spec/fixtures/crash-cases/webview-remove-on-wc-close/index.js @@ -0,0 +1,29 @@ +const { app, BrowserWindow } = require('electron'); + +app.whenReady().then(() => { + const win = new BrowserWindow({ + webPreferences: { + webviewTag: true + } + }); + + win.loadFile('index.html'); + + win.webContents.on('did-attach-webview', (event, contents) => { + contents.on('render-process-gone', () => { + process.exit(1); + }); + + contents.on('destroyed', () => { + process.exit(0); + }); + + contents.on('did-finish-load', () => { + win.webContents.executeJavaScript('document.querySelector(\'.close-btn\').click()'); + }); + + contents.on('will-prevent-unload', event => { + event.preventDefault(); + }); + }); +}); diff --git a/spec/fixtures/crash-cases/webview-remove-on-wc-close/webview.html b/spec/fixtures/crash-cases/webview-remove-on-wc-close/webview.html new file mode 100644 index 0000000000..1402bea99b --- /dev/null +++ b/spec/fixtures/crash-cases/webview-remove-on-wc-close/webview.html @@ -0,0 +1,19 @@ +<!DOCTYPE html> +<html lang="en"> + +<head> + <meta charset="UTF-8"> + <meta name="viewport" content="width=device-width, initial-scale=1.0"> + <title>Document</title> +</head> + +<body> + <h1>webview page</h1> + <script> + window.addEventListener('beforeunload', event => { + event.returnValue = 'test' + }) + </script> +</body> + +</html>
fix
69790f4b2a3d386230480c00ba9653febba2b78b
Charles Kerr
2023-06-07 16:28:35
refactor: remove unused OffScreenRenderWidgetHostView fields (#38623)
diff --git a/shell/browser/osr/osr_render_widget_host_view.cc b/shell/browser/osr/osr_render_widget_host_view.cc index e7fe5132e6..75340ac8cf 100644 --- a/shell/browser/osr/osr_render_widget_host_view.cc +++ b/shell/browser/osr/osr_render_widget_host_view.cc @@ -726,10 +726,8 @@ void OffScreenRenderWidgetHostView::CompositeFrame( } } - paint_callback_running_ = true; callback_.Run(gfx::IntersectRects(gfx::Rect(size_in_pixels), damage_rect), frame); - paint_callback_running_ = false; ReleaseResize(); } diff --git a/shell/browser/osr/osr_render_widget_host_view.h b/shell/browser/osr/osr_render_widget_host_view.h index 4a146ab16b..414b6d463b 100644 --- a/shell/browser/osr/osr_render_widget_host_view.h +++ b/shell/browser/osr/osr_render_widget_host_view.h @@ -19,7 +19,6 @@ #include "base/memory/raw_ptr.h" #include "base/process/kill.h" #include "base/threading/thread.h" -#include "base/time/time.h" #include "components/viz/common/quads/compositor_frame.h" #include "components/viz/common/surfaces/parent_local_surface_id_allocator.h" #include "content/browser/renderer_host/delegated_frame_host.h" // nogncheck @@ -259,9 +258,6 @@ class OffScreenRenderWidgetHostView : public content::RenderWidgetHostViewBase, int frame_rate_ = 0; int frame_rate_threshold_us_ = 0; - base::Time last_time_ = base::Time::Now(); - - gfx::Vector2dF last_scroll_offset_; gfx::Size size_; bool painting_; @@ -272,8 +268,6 @@ class OffScreenRenderWidgetHostView : public content::RenderWidgetHostViewBase, bool hold_resize_ = false; bool pending_resize_ = false; - bool paint_callback_running_ = false; - viz::LocalSurfaceId delegated_frame_host_surface_id_; viz::ParentLocalSurfaceIdAllocator delegated_frame_host_allocator_;
refactor
683235daf0675b2c216eeb1821a4163d5cafb082
Shelley Vohr
2023-05-17 13:17:52
build: combine V8 BUILD.gn patches (#38342) * build: combine V8 BUILD.gn patches * chore: update patches --------- Co-authored-by: PatchUp <73610968+patchup[bot]@users.noreply.github.com>
diff --git a/patches/v8/.patches b/patches/v8/.patches index d4cee9c7f2..6abadfe676 100644 --- a/patches/v8/.patches +++ b/patches/v8/.patches @@ -1,5 +1,4 @@ build_gn.patch -expose_mksnapshot.patch dcheck.patch export_symbols_needed_for_windows_build.patch do_not_export_private_v8_symbols_on_windows.patch diff --git a/patches/v8/build_gn.patch b/patches/v8/build_gn.patch index 3b51c1e81f..ae4343dde6 100644 --- a/patches/v8/build_gn.patch +++ b/patches/v8/build_gn.patch @@ -6,10 +6,10 @@ Subject: build_gn.patch We force V8 into 'shared library' mode so that it exports its symbols, which is necessary for native modules to load. -Also, some fixes relating to mksnapshot on ARM. +Also change visibility on mksnapshot in order to target mksnapshot for mksnapshot zip. diff --git a/BUILD.gn b/BUILD.gn -index d75f44b55a89828845f69f148da147ea29d523e2..4b90367b6a73503ae44c0a68c23d7a2fd606135c 100644 +index d75f44b55a89828845f69f148da147ea29d523e2..3140abb0868eb81976edacafc625bc80159b5aea 100644 --- a/BUILD.gn +++ b/BUILD.gn @@ -714,7 +714,7 @@ config("internal_config") { @@ -30,3 +30,11 @@ index d75f44b55a89828845f69f148da147ea29d523e2..4b90367b6a73503ae44c0a68c23d7a2f deps = [ ":v8_libbase", +@@ -6475,7 +6475,6 @@ if (current_toolchain == v8_generator_toolchain) { + + if (current_toolchain == v8_snapshot_toolchain) { + v8_executable("mksnapshot") { +- visibility = [ ":*" ] # Only targets in this file can depend on this. + + sources = [ + "src/snapshot/embedded/embedded-empty.cc", diff --git a/patches/v8/expose_mksnapshot.patch b/patches/v8/expose_mksnapshot.patch deleted file mode 100644 index 9d5824fbfe..0000000000 --- a/patches/v8/expose_mksnapshot.patch +++ /dev/null @@ -1,19 +0,0 @@ -From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 -From: Shelley Vohr <[email protected]> -Date: Mon, 22 Oct 2018 10:47:13 -0700 -Subject: expose_mksnapshot.patch - -Needed in order to target mksnapshot for mksnapshot zip. - -diff --git a/BUILD.gn b/BUILD.gn -index 4b90367b6a73503ae44c0a68c23d7a2fd606135c..3140abb0868eb81976edacafc625bc80159b5aea 100644 ---- a/BUILD.gn -+++ b/BUILD.gn -@@ -6475,7 +6475,6 @@ if (current_toolchain == v8_generator_toolchain) { - - if (current_toolchain == v8_snapshot_toolchain) { - v8_executable("mksnapshot") { -- visibility = [ ":*" ] # Only targets in this file can depend on this. - - sources = [ - "src/snapshot/embedded/embedded-empty.cc",
build
25f4691e7864be7feb11df7fc4228480fff13960
Shelley Vohr
2024-09-06 11:12:16
fix: ensure version of `xdg-dialog-portal` with `defaultPath` support (#43570) fix: ensure version of xdg-dialog-portal with defaultPath support Closes https://github.com/electron/electron/issues/43310
diff --git a/patches/chromium/feat_add_support_for_missing_dialog_features_to_shell_dialogs.patch b/patches/chromium/feat_add_support_for_missing_dialog_features_to_shell_dialogs.patch index 15dbc706b7..4a6d30939c 100644 --- a/patches/chromium/feat_add_support_for_missing_dialog_features_to_shell_dialogs.patch +++ b/patches/chromium/feat_add_support_for_missing_dialog_features_to_shell_dialogs.patch @@ -199,10 +199,21 @@ index 58985ce62dc569256bad5e94de9c0d125fc470d0..33436784b691c860d58f8b4dfcc6718e &SelectFileDialogLinuxKde::OnSelectSingleFolderDialogResponse, this, parent)); diff --git a/ui/shell_dialogs/select_file_dialog_linux_portal.cc b/ui/shell_dialogs/select_file_dialog_linux_portal.cc -index 61ddcbf7bf57e423099c7d392a19b3ec79b5d03f..8c3f4058ad7e9f6460c8d0516a150db612e8f574 100644 +index 61ddcbf7bf57e423099c7d392a19b3ec79b5d03f..b2d2e11f72dcca5b3791a6dd3e9e5ae930a1f701 100644 --- a/ui/shell_dialogs/select_file_dialog_linux_portal.cc +++ b/ui/shell_dialogs/select_file_dialog_linux_portal.cc -@@ -221,6 +221,8 @@ void SelectFileDialogLinuxPortal::SelectFileImpl( +@@ -44,7 +44,9 @@ constexpr char kMethodStartServiceByName[] = "StartServiceByName"; + constexpr char kXdgPortalService[] = "org.freedesktop.portal.Desktop"; + constexpr char kXdgPortalObject[] = "/org/freedesktop/portal/desktop"; + +-constexpr int kXdgPortalRequiredVersion = 3; ++// Version 4 includes support for current_folder option to the OpenFile method via ++// https://github.com/flatpak/xdg-desktop-portal/commit/71165a5. ++constexpr int kXdgPortalRequiredVersion = 4; + + constexpr char kXdgPortalRequestInterfaceName[] = + "org.freedesktop.portal.Request"; +@@ -221,6 +223,8 @@ void SelectFileDialogLinuxPortal::SelectFileImpl( weak_factory_.GetWeakPtr())); info_->type = type; info_->main_task_runner = base::SequencedTaskRunner::GetCurrentDefault(); @@ -211,7 +222,7 @@ index 61ddcbf7bf57e423099c7d392a19b3ec79b5d03f..8c3f4058ad7e9f6460c8d0516a150db6 if (owning_window) { if (auto* root = owning_window->GetRootWindow()) { -@@ -557,7 +559,9 @@ void SelectFileDialogLinuxPortal::DialogInfo::AppendOptions( +@@ -557,7 +561,9 @@ void SelectFileDialogLinuxPortal::DialogInfo::AppendOptions( response_handle_token); if (type == SelectFileDialog::Type::SELECT_UPLOAD_FOLDER) { @@ -222,7 +233,7 @@ index 61ddcbf7bf57e423099c7d392a19b3ec79b5d03f..8c3f4058ad7e9f6460c8d0516a150db6 l10n_util::GetStringUTF8( IDS_SELECT_UPLOAD_FOLDER_DIALOG_UPLOAD_BUTTON)); } -@@ -566,6 +570,8 @@ void SelectFileDialogLinuxPortal::DialogInfo::AppendOptions( +@@ -566,6 +572,8 @@ void SelectFileDialogLinuxPortal::DialogInfo::AppendOptions( type == SelectFileDialog::Type::SELECT_UPLOAD_FOLDER || type == SelectFileDialog::Type::SELECT_EXISTING_FOLDER) { AppendBoolOption(&options_writer, kFileChooserOptionDirectory, true);
fix
83892ab995fb7a0b60ebc0c8837b2dba35ec5262
Samuel Attard
2023-10-31 14:29:40
refactor: ensure IpcRenderer is not bridgable (#40330) * refactor: ensure IpcRenderer is not bridgable * chore: add notes to breaking-changes * spec: fix test that bridged ipcrenderer
diff --git a/docs/breaking-changes.md b/docs/breaking-changes.md index ddffa5f081..682f1bb554 100644 --- a/docs/breaking-changes.md +++ b/docs/breaking-changes.md @@ -14,6 +14,19 @@ This document uses the following convention to categorize breaking changes: ## Planned Breaking API Changes (29.0) +### Behavior Changed: `ipcRenderer` can no longer be sent over the `contextBridge` + +Attempting to send `ipcRenderer` as an object over the `contextBridge` will now result in +an empty object on the receiving side of the bridge. This change was made to remove / mitigate +a security footgun, you should not directly expose ipcRenderer or it's methods over the bridge. +Instead provide a safe wrapper like below: + +```js +contextBridge.exposeInMainWorld('app', { + onEvent: (cb) => ipcRenderer.on('foo', (e, ...args) => cb(args)) +}) +``` + ### Removed: `renderer-process-crashed` event on `app` The `renderer-process-crashed` event on `app` has been removed. diff --git a/lib/renderer/api/ipc-renderer.ts b/lib/renderer/api/ipc-renderer.ts index b637f19271..c82f862123 100644 --- a/lib/renderer/api/ipc-renderer.ts +++ b/lib/renderer/api/ipc-renderer.ts @@ -3,30 +3,30 @@ import { EventEmitter } from 'events'; const { ipc } = process._linkedBinding('electron_renderer_ipc'); const internal = false; +class IpcRenderer extends EventEmitter implements Electron.IpcRenderer { + send (channel: string, ...args: any[]) { + return ipc.send(internal, channel, args); + } -const ipcRenderer = new EventEmitter() as Electron.IpcRenderer; -ipcRenderer.send = function (channel, ...args) { - return ipc.send(internal, channel, args); -}; - -ipcRenderer.sendSync = function (channel, ...args) { - return ipc.sendSync(internal, channel, args); -}; + sendSync (channel: string, ...args: any[]) { + return ipc.sendSync(internal, channel, args); + } -ipcRenderer.sendToHost = function (channel, ...args) { - return ipc.sendToHost(channel, args); -}; + sendToHost (channel: string, ...args: any[]) { + return ipc.sendToHost(channel, args); + } -ipcRenderer.invoke = async function (channel, ...args) { - const { error, result } = await ipc.invoke(internal, channel, args); - if (error) { - throw new Error(`Error invoking remote method '${channel}': ${error}`); + async invoke (channel: string, ...args: any[]) { + const { error, result } = await ipc.invoke(internal, channel, args); + if (error) { + throw new Error(`Error invoking remote method '${channel}': ${error}`); + } + return result; } - return result; -}; -ipcRenderer.postMessage = function (channel: string, message: any, transferables: any) { - return ipc.postMessage(channel, message, transferables); -}; + postMessage (channel: string, message: any, transferables: any) { + return ipc.postMessage(channel, message, transferables); + } +} -export default ipcRenderer; +export default new IpcRenderer(); diff --git a/lib/renderer/ipc-renderer-internal.ts b/lib/renderer/ipc-renderer-internal.ts index f37ea0d724..da832d2e47 100644 --- a/lib/renderer/ipc-renderer-internal.ts +++ b/lib/renderer/ipc-renderer-internal.ts @@ -4,20 +4,22 @@ const { ipc } = process._linkedBinding('electron_renderer_ipc'); const internal = true; -export const ipcRendererInternal = new EventEmitter() as any as ElectronInternal.IpcRendererInternal; +class IpcRendererInternal extends EventEmitter implements ElectronInternal.IpcRendererInternal { + send (channel: string, ...args: any[]) { + return ipc.send(internal, channel, args); + } -ipcRendererInternal.send = function (channel, ...args) { - return ipc.send(internal, channel, args); -}; + sendSync (channel: string, ...args: any[]) { + return ipc.sendSync(internal, channel, args); + } -ipcRendererInternal.sendSync = function (channel, ...args) { - return ipc.sendSync(internal, channel, args); -}; + async invoke<T> (channel: string, ...args: any[]) { + const { error, result } = await ipc.invoke<T>(internal, channel, args); + if (error) { + throw new Error(`Error invoking remote method '${channel}': ${error}`); + } + return result; + }; +} -ipcRendererInternal.invoke = async function<T> (channel: string, ...args: any[]) { - const { error, result } = await ipc.invoke<T>(internal, channel, args); - if (error) { - throw new Error(`Error invoking remote method '${channel}': ${error}`); - } - return result; -}; +export const ipcRendererInternal = new IpcRendererInternal(); diff --git a/spec/fixtures/apps/libuv-hang/preload.js b/spec/fixtures/apps/libuv-hang/preload.js index 2629549fbf..d788aec429 100644 --- a/spec/fixtures/apps/libuv-hang/preload.js +++ b/spec/fixtures/apps/libuv-hang/preload.js @@ -1,7 +1,8 @@ const { contextBridge, ipcRenderer } = require('electron'); contextBridge.exposeInMainWorld('api', { - ipcRenderer, + // This is not safe, do not copy this code into your app + invoke: (...args) => ipcRenderer.invoke(...args), run: async () => { const { promises: fs } = require('node:fs'); for (let i = 0; i < 10; i++) { diff --git a/spec/fixtures/apps/libuv-hang/renderer.js b/spec/fixtures/apps/libuv-hang/renderer.js index cdbc4aab4d..eb822ca519 100644 --- a/spec/fixtures/apps/libuv-hang/renderer.js +++ b/spec/fixtures/apps/libuv-hang/renderer.js @@ -1,6 +1,6 @@ -const { run, ipcRenderer } = window.api; +const { run, invoke } = window.api; run().then(async () => { - const count = await ipcRenderer.invoke('reload-successful'); + const count = await invoke('reload-successful'); if (count < 3) location.reload(); }).catch(console.log);
refactor
caf24ef417365d0a65c10b1285520de7fb051483
George Xu
2024-12-17 15:20:44
fix: add patch to fix desktopCapturer.getSources not returning electron windows on Windows (#45000) * fix: add patch to fix desktopCapturer.getSources not returning electron window on Windows * add chromium link * Update patches/chromium/fix_desktop_capturer_show_own_window.patch Co-authored-by: Keeley Hammond <[email protected]> * fix on electron side * set flag to true * wrong capturer --------- Co-authored-by: Keeley Hammond <[email protected]>
diff --git a/shell/browser/api/electron_api_desktop_capturer.cc b/shell/browser/api/electron_api_desktop_capturer.cc index 74e71b0bbb..b7d7177bf4 100644 --- a/shell/browser/api/electron_api_desktop_capturer.cc +++ b/shell/browser/api/electron_api_desktop_capturer.cc @@ -286,7 +286,7 @@ void DesktopCapturer::StartHandling(bool capture_window, capture_screen_ = false; capture_window_ = capture_window; window_capturer_ = std::make_unique<NativeDesktopMediaList>( - DesktopMediaList::Type::kWindow, std::move(capturer)); + DesktopMediaList::Type::kWindow, std::move(capturer), true, true); window_capturer_->SetThumbnailSize(thumbnail_size); OnceCallback update_callback = base::BindOnce( @@ -322,7 +322,7 @@ void DesktopCapturer::StartHandling(bool capture_window, auto capturer = MakeWindowCapturer(); if (capturer) { window_capturer_ = std::make_unique<NativeDesktopMediaList>( - DesktopMediaList::Type::kWindow, std::move(capturer)); + DesktopMediaList::Type::kWindow, std::move(capturer), true, true); window_capturer_->SetThumbnailSize(thumbnail_size); #if BUILDFLAG(IS_MAC) window_capturer_->skip_next_refresh_ =
fix
c4abaec56ac91a53341bc486dcd05f733348326e
Keeley Hammond
2024-06-10 16:58:29
build: fix upload script defaults (#42430)
diff --git a/script/lib/util.py b/script/lib/util.py index 2e91ad6afa..1446b99b82 100644 --- a/script/lib/util.py +++ b/script/lib/util.py @@ -158,7 +158,7 @@ def azput(prefix, key_prefix, files): print(output) def get_out_dir(): - out_dir = 'Debug' + out_dir = 'Default' override = os.environ.get('ELECTRON_OUT_DIR') if override is not None: out_dir = override diff --git a/script/release/uploaders/upload.py b/script/release/uploaders/upload.py index c431d1cc37..cb6c788941 100755 --- a/script/release/uploaders/upload.py +++ b/script/release/uploaders/upload.py @@ -48,7 +48,7 @@ def main(): if args.verbose: enable_verbose_mode() if args.upload_to_storage: - utcnow = datetime.datetime.utcnow() + utcnow = datetime.datetime.now(datetime.UTC) args.upload_timestamp = utcnow.strftime('%Y%m%d') build_version = get_electron_build_version()
build
ee4460ac686511b21a235cd6e9f3d29e3588e1d8
Shelley Vohr
2023-07-19 00:20:11
build: correct codespaces devcontainer extensions settings (#39123)
diff --git a/.devcontainer/devcontainer.json b/.devcontainer/devcontainer.json index 605c3eaf9a..3743ea60ae 100644 --- a/.devcontainer/devcontainer.json +++ b/.devcontainer/devcontainer.json @@ -4,37 +4,6 @@ "onCreateCommand": ".devcontainer/on-create-command.sh", "updateContentCommand": ".devcontainer/update-content-command.sh", "workspaceFolder": "/workspaces/gclient/src/electron", - "extensions": [ - "joeleinbinder.mojom-language", - "rafaelmaiolla.diff", - "surajbarkale.ninja", - "ms-vscode.cpptools", - "mutantdino.resourcemonitor", - "dbaeumer.vscode-eslint", - "shakram02.bash-beautify", - "marshallofsound.gnls-electron", - "CircleCI.circleci" - ], - "settings": { - "editor.tabSize": 2, - "bashBeautify.tabSize": 2, - "typescript.tsdk": "node_modules/typescript/lib", - "[gn]": { - "editor.formatOnSave": true - }, - "[javascript]": { - "editor.codeActionsOnSave": { - "source.fixAll.eslint": true - } - }, - "[typescript]": { - "editor.codeActionsOnSave": { - "source.fixAll.eslint": true - } - }, - "javascript.preferences.quoteStyle": "single", - "typescript.preferences.quoteStyle": "single" - }, "forwardPorts": [8088, 6080, 5901], "portsAttributes": { "8088": { @@ -60,6 +29,38 @@ "openFiles": [ ".devcontainer/README.md" ] + }, + "vscode": { + "extensions": ["joeleinbinder.mojom-language", + "rafaelmaiolla.diff", + "surajbarkale.ninja", + "ms-vscode.cpptools", + "mutantdino.resourcemonitor", + "dbaeumer.vscode-eslint", + "shakram02.bash-beautify", + "marshallofsound.gnls-electron", + "CircleCI.circleci" + ], + "settings": { + "editor.tabSize": 2, + "bashBeautify.tabSize": 2, + "typescript.tsdk": "node_modules/typescript/lib", + "[gn]": { + "editor.formatOnSave": true + }, + "[javascript]": { + "editor.codeActionsOnSave": { + "source.fixAll.eslint": true + } + }, + "[typescript]": { + "editor.codeActionsOnSave": { + "source.fixAll.eslint": true + } + }, + "javascript.preferences.quoteStyle": "single", + "typescript.preferences.quoteStyle": "single" + } } } } \ No newline at end of file
build
c9bae5da8ef280e310d4c1d03ee94a169c704357
Milan Burda
2023-07-27 16:53:45
refactor: use optional catch binding (#39232)
diff --git a/spec/api-app-spec.ts b/spec/api-app-spec.ts index 79c3388cb1..87b6e61648 100644 --- a/spec/api-app-spec.ts +++ b/spec/api-app-spec.ts @@ -345,7 +345,7 @@ describe('app module', () => { expectedAdditionalData: undefined }); assert(false); - } catch (e) { + } catch { // This is expected. } }); diff --git a/spec/api-auto-updater-spec.ts b/spec/api-auto-updater-spec.ts index ec0da4b9bd..e558dbf517 100644 --- a/spec/api-auto-updater-spec.ts +++ b/spec/api-auto-updater-spec.ts @@ -32,7 +32,7 @@ ifdescribe(!process.mas)('autoUpdater module', function () { const url = 'http://electronjs.org'; try { (autoUpdater.setFeedURL as any)(url, { header: 'val' }); - } catch (err) { /* ignore */ } + } catch { /* ignore */ } expect(autoUpdater.getFeedURL()).to.equal(url); }); @@ -44,7 +44,7 @@ ifdescribe(!process.mas)('autoUpdater module', function () { const url = 'http://mymagicurl.local'; try { autoUpdater.setFeedURL({ url }); - } catch (err) { /* ignore */ } + } catch { /* ignore */ } expect(autoUpdater.getFeedURL()).to.equal(url); }); diff --git a/spec/api-crash-reporter-spec.ts b/spec/api-crash-reporter-spec.ts index e7232573df..bc7afe2cdd 100644 --- a/spec/api-crash-reporter-spec.ts +++ b/spec/api-crash-reporter-spec.ts @@ -116,7 +116,7 @@ function waitForNewFileInDir (dir: string): Promise<string[]> { function readdirIfPresent (dir: string): string[] { try { return fs.readdirSync(dir); - } catch (e) { + } catch { return []; } } @@ -402,7 +402,7 @@ ifdescribe(!isLinuxOnArm && !process.mas && !process.env.DISABLE_CRASH_REPORTER_ try { fs.rmdirSync(dir, { recursive: true }); fs.mkdirSync(dir); - } catch (e) { /* ignore */ } + } catch { /* ignore */ } // 1. start the crash reporter. await remotely((port: number) => { diff --git a/spec/api-debugger-spec.ts b/spec/api-debugger-spec.ts index 311b7ec6c6..057f39e418 100644 --- a/spec/api-debugger-spec.ts +++ b/spec/api-debugger-spec.ts @@ -32,7 +32,7 @@ describe('debugger module', () => { it('fails when protocol version is not supported', done => { try { w.webContents.debugger.attach('2.0'); - } catch (err) { + } catch { expect(w.webContents.debugger.isAttached()).to.be.false(); done(); } diff --git a/spec/api-net-log-spec.ts b/spec/api-net-log-spec.ts index eb5957e825..fc570f2297 100644 --- a/spec/api-net-log-spec.ts +++ b/spec/api-net-log-spec.ts @@ -55,7 +55,7 @@ describe('netLog module', () => { if (fs.existsSync(dumpFileDynamic)) { fs.unlinkSync(dumpFileDynamic); } - } catch (e) { + } catch { // Ignore error } expect(testNetLog().currentlyLogging).to.be.false('currently logging'); diff --git a/spec/api-process-spec.ts b/spec/api-process-spec.ts index a5d1326a66..7ae874c7fe 100644 --- a/spec/api-process-spec.ts +++ b/spec/api-process-spec.ts @@ -99,7 +99,7 @@ describe('process module', () => { defer(() => { try { fs.unlinkSync(filePath); - } catch (e) { + } catch { // ignore error } }); @@ -211,7 +211,7 @@ describe('process module', () => { defer(() => { try { fs.unlinkSync(filePath); - } catch (e) { + } catch { // ignore error } }); diff --git a/spec/api-protocol-spec.ts b/spec/api-protocol-spec.ts index 90b07b7074..72dfe18fe8 100644 --- a/spec/api-protocol-spec.ts +++ b/spec/api-protocol-spec.ts @@ -104,7 +104,7 @@ describe('protocol module', () => { try { callback(text); callback(''); - } catch (error) { + } catch { // Ignore error } }); @@ -557,7 +557,7 @@ describe('protocol module', () => { try { callback(text); callback(''); - } catch (error) { + } catch { // Ignore error } }); @@ -1106,7 +1106,7 @@ describe('protocol module', () => { // In case of failure, make sure we unhandle. But we should succeed // :) protocol.unhandle('test-scheme'); - } catch (_ignored) { /* ignore */ } + } catch { /* ignore */ } }); const resp1 = await net.fetch('test-scheme://foo'); expect(resp1.status).to.equal(200); diff --git a/spec/api-web-contents-spec.ts b/spec/api-web-contents-spec.ts index 7445111b63..aeb2a11349 100644 --- a/spec/api-web-contents-spec.ts +++ b/spec/api-web-contents-spec.ts @@ -1786,7 +1786,7 @@ describe('webContents module', () => { const cleanup = () => { try { fs.unlinkSync(filePath); - } catch (e) { + } catch { // ignore error } }; diff --git a/spec/fixtures/api/default-menu/main.js b/spec/fixtures/api/default-menu/main.js index 16e84badc9..28cad7a293 100644 --- a/spec/fixtures/api/default-menu/main.js +++ b/spec/fixtures/api/default-menu/main.js @@ -22,11 +22,11 @@ try { setImmediate(() => { try { output(Menu.getApplicationMenu() === expectedMenu); - } catch (error) { + } catch { output(null); } }); }); -} catch (error) { +} catch { output(null); } diff --git a/spec/fixtures/module/echo-renamed.js b/spec/fixtures/module/echo-renamed.js index 6dfa05f914..d81f922c21 100644 --- a/spec/fixtures/module/echo-renamed.js +++ b/spec/fixtures/module/echo-renamed.js @@ -1,7 +1,7 @@ let echo; try { echo = require('@electron-ci/echo'); -} catch (e) { +} catch { process.exit(1); } process.exit(echo(0)); diff --git a/spec/webview-spec.ts b/spec/webview-spec.ts index 51c2ab952b..06ad8c527f 100644 --- a/spec/webview-spec.ts +++ b/spec/webview-spec.ts @@ -2032,7 +2032,7 @@ describe('<webview> tag', function () { // Values can be 0,2,3,4, or 6. We want 6, which is RGB + Alpha expect(imgBuffer[25]).to.equal(6); return; - } catch (e) { + } catch { /* drop the error */ } }
refactor
92db4f0b8a196601ae888b983f91dea42044418d
Shelley Vohr
2024-06-10 10:34:36
build: fix `generate_gn_filenames_json.py` (#42389) build: fix generate_gn_filenames_json.py
diff --git a/patches/node/build_add_gn_build_files.patch b/patches/node/build_add_gn_build_files.patch index 9ca484febc..a688391250 100644 --- a/patches/node/build_add_gn_build_files.patch +++ b/patches/node/build_add_gn_build_files.patch @@ -1256,10 +1256,10 @@ index 0000000000000000000000000000000000000000..af9cbada10203b387fb9732b346583b1 +} diff --git a/filenames.json b/filenames.json new file mode 100644 -index 0000000000000000000000000000000000000000..1a9cba024f1762b0dfe31da92213b51e112101ec +index 0000000000000000000000000000000000000000..fd42e2a5e6163ff70db0f716d2f9a32f13cdf668 --- /dev/null +++ b/filenames.json -@@ -0,0 +1,739 @@ +@@ -0,0 +1,734 @@ +// This file is automatically generated by generate_gn_filenames_json.py +// DO NOT EDIT +{ @@ -1292,7 +1292,7 @@ index 0000000000000000000000000000000000000000..1a9cba024f1762b0dfe31da92213b51e + ] + }, + { -+ "dest_dir": "include/node//", ++ "dest_dir": "include/node/./", + "files": [ + "//v8/include/v8-array-buffer.h", + "//v8/include/v8-callbacks.h", @@ -1346,11 +1346,12 @@ index 0000000000000000000000000000000000000000..1a9cba024f1762b0dfe31da92213b51e + "//v8/include/v8-wasm.h", + "//v8/include/v8-weak-callback-info.h", + "//v8/include/v8.h", -+ "//v8/include/v8config.h" ++ "//v8/include/v8config.h", ++ "deps/uv/include/uv.h" + ] + }, + { -+ "dest_dir": "include/node//libplatform/", ++ "dest_dir": "include/node/libplatform/", + "files": [ + "//v8/include/libplatform/libplatform-export.h", + "//v8/include/libplatform/libplatform.h", @@ -1358,7 +1359,7 @@ index 0000000000000000000000000000000000000000..1a9cba024f1762b0dfe31da92213b51e + ] + }, + { -+ "dest_dir": "include/node//cppgc/", ++ "dest_dir": "include/node/cppgc/", + "files": [ + "//v8/include/cppgc/allocation.h", + "//v8/include/cppgc/common.h", @@ -1391,7 +1392,7 @@ index 0000000000000000000000000000000000000000..1a9cba024f1762b0dfe31da92213b51e + ] + }, + { -+ "dest_dir": "include/node//cppgc/internal/", ++ "dest_dir": "include/node/cppgc/internal/", + "files": [ + "//v8/include/cppgc/internal/api-constants.h", + "//v8/include/cppgc/internal/atomic-entry-flag.h", @@ -1410,13 +1411,7 @@ index 0000000000000000000000000000000000000000..1a9cba024f1762b0dfe31da92213b51e + ] + }, + { -+ "dest_dir": "include/node//", -+ "files": [ -+ "deps/uv/include/uv.h" -+ ] -+ }, -+ { -+ "dest_dir": "include/node//uv/", ++ "dest_dir": "include/node/uv/", + "files": [ + "deps/uv/include/uv/aix.h", + "deps/uv/include/uv/bsd.h", @@ -1891,7 +1886,7 @@ index 0000000000000000000000000000000000000000..1a9cba024f1762b0dfe31da92213b51e + "src/dataqueue/queue.h", + "src/debug_utils.h", + "src/debug_utils-inl.h", -+ "src/embeded_data.h", ++ "src/embedded_data.h", + "src/encoding_binding.h", + "src/env_properties.h", + "src/env.h", @@ -2243,10 +2238,10 @@ index 75a7f3dd89e096d13ad7d70ed29d301cd56315b5..9a20a275fbe5df9f384b7b1d1d26806e // bootstrap scripts, whose source are bundled into the binary as static data. diff --git a/tools/generate_gn_filenames_json.py b/tools/generate_gn_filenames_json.py new file mode 100755 -index 0000000000000000000000000000000000000000..7848ddb1841b6d4f36e9376c73564eb4ff6d7c08 +index 0000000000000000000000000000000000000000..37c16859003e61636fe2f1a4040b1e904c472d0b --- /dev/null +++ b/tools/generate_gn_filenames_json.py -@@ -0,0 +1,90 @@ +@@ -0,0 +1,117 @@ +#!/usr/bin/env python3 +import json +import os @@ -2276,6 +2271,14 @@ index 0000000000000000000000000000000000000000..7848ddb1841b6d4f36e9376c73564eb4 +// DO NOT EDIT +'''.lstrip() + ++SRC_DIR = os.path.abspath(os.path.join(__file__, '..', '..', '..', '..')) ++ ++def get_out_dir(): ++ out_dir = 'Testing' ++ override = os.environ.get('ELECTRON_OUT_DIR') ++ if override is not None: ++ out_dir = override ++ return os.path.join(SRC_DIR, 'out', out_dir) + +if __name__ == '__main__': + node_root_dir = os.path.dirname(os.path.dirname(__file__)) @@ -2294,18 +2297,25 @@ index 0000000000000000000000000000000000000000..7848ddb1841b6d4f36e9376c73564eb4 + } + + def filter_v8_files(files): -+ if any(f.startswith('deps/v8/') for f in files): -+ files = [f.replace('deps/v8/', '../../v8/', 1) if f.endswith('js') else f.replace('deps/v8/', '//v8/') for f in files] -+ -+ if any(f == '<@(node_builtin_shareable_builtins)' for f in files): -+ files.remove('<@(node_builtin_shareable_builtins)') ++ v8_files = [f for f in files if f.startswith('deps/v8/')] ++ other_files = [f for f in files if not f.startswith('deps/v8/')] ++ ++ for i, f in enumerate(v8_files): ++ if not f.startswith('deps/v8/tools'): ++ if f.endswith('js'): ++ v8_files[i] = f.replace('deps/v8/', '../../v8/', 1) ++ else: ++ v8_files[i] = f.replace('deps/v8/', '//v8/') ++ ++ if any(f == '<@(node_builtin_shareable_builtins)' for f in other_files): ++ other_files.remove('<@(node_builtin_shareable_builtins)') + shared_builtins = ['deps/cjs-module-lexer/lexer.js', 'deps/cjs-module-lexer/dist/lexer.js', 'deps/undici/undici.js'] -+ files.extend(shared_builtins) ++ other_files.extend(shared_builtins) + -+ return files ++ return v8_files + other_files + + def filter_fs_files(files): -+ return [f for f in files if f.startswith('lib/internal/fs/')] + ['lib/fs.js'] ++ return [f for f in files if f.startswith('lib/internal/fs/')] + ['lib/fs.js'] + ['lib/fs/promises.js'] + + lib_files = SearchFiles('lib', 'js') + out['library_files'] = filter_v8_files(lib_files) @@ -2322,17 +2332,29 @@ index 0000000000000000000000000000000000000000..7848ddb1841b6d4f36e9376c73564eb4 + out['node_sources'] += filter_v8_files(blocklisted_sources) + + out['headers'] = [] -+ def add_headers(files, dest_dir): ++ def add_headers(options, files, dest_dir): + if 'src/node.h' in files: + files = [f for f in files if f.endswith('.h') and f != 'src/node_version.h'] + elif any(f.startswith('../../v8/') for f in files): + files = [f.replace('../../v8/', '//v8/', 1) for f in files] + if files: -+ hs = {'files': sorted(files), 'dest_dir': dest_dir} -+ out['headers'].append(hs) -+ -+ install.variables = {'node_shared_libuv': 'false'} -+ install.headers(add_headers) ++ dir_index = next((i for i, d in enumerate(out['headers']) if d['dest_dir'] == dest_dir), -1) ++ if (dir_index != -1): ++ out['headers'][dir_index]['files'] += sorted(files) ++ else: ++ hs = {'files': sorted(files), 'dest_dir': dest_dir} ++ out['headers'].append(hs) ++ ++ config_gypi_path = os.path.join(get_out_dir(), 'gen', 'config.gypi') ++ root_gen_dir = os.path.join(node_root_dir, 'out', 'Release', 'gen') ++ ++ options = install.parse_options(['install', '--v8-dir', '../../v8', '--config-gypi-path', config_gypi_path, '--headers-only']) ++ options.variables['node_use_openssl'] = 'false' ++ options.variables['node_shared_libuv'] = 'false' ++ # We generate zlib headers in Electron's BUILD.gn. ++ options.variables['node_shared_zlib'] = '' ++ ++ install.headers(options, add_headers) + with open(os.path.join(node_root_dir, 'filenames.json'), 'w') as f: + f.write(FILENAMES_JSON_HEADER) + f.write(json.dumps(out, sort_keys=True, indent=2, separators=(',', ': '))) @@ -2363,18 +2385,27 @@ index 0000000000000000000000000000000000000000..9be3ac447f9a4dde23fefc26e0b922b4 + transformed_f.write(transformed_contents) + diff --git a/tools/install.py b/tools/install.py -index b132c7bf26c02886a7ab341a1973bf449744ba0f..171b383a4b6c2528d11dd5f89a6837fd071bcf4b 100755 +index b132c7bf26c02886a7ab341a1973bf449744ba0f..757e3e60a7be01fac55c5fbb010dbbae00b1bfca 100755 --- a/tools/install.py +++ b/tools/install.py -@@ -284,6 +284,7 @@ def headers(options, action): +@@ -264,6 +264,7 @@ def headers(options, action): + 'include/v8-forward.h', + 'include/v8-function-callback.h', + 'include/v8-function.h', ++ 'include/v8-handle-base.h', + 'include/v8-initialization.h', + 'include/v8-internal.h', + 'include/v8-isolate.h', +@@ -284,6 +285,8 @@ def headers(options, action): 'include/v8-promise.h', 'include/v8-proxy.h', 'include/v8-regexp.h', + "include/v8-sandbox.h", ++ "include/v8-source-location.h", 'include/v8-script.h', 'include/v8-snapshot.h', 'include/v8-statistics.h', -@@ -390,7 +391,7 @@ def parse_options(args): +@@ -390,7 +393,7 @@ def parse_options(args): parser.add_argument('--build-dir', help='the location of built binaries', default='out/Release') parser.add_argument('--v8-dir', help='the location of V8',
build
85e2622b6852b4528ee43282cadc2ab4db67c447
Charles Kerr
2024-11-20 15:24:59
refactor: use gdk_display_beep() on Linux (#44734) * refactor: use gdk_display_beep() to beep on Linux * chore: make a stub declaration for gdk_display_beep() * chore: remove unused file electron_gtk.sigs * chore: remove unused #includes to make gn check happy
diff --git a/BUILD.gn b/BUILD.gn index 1e61506b29..fdd722ea68 100644 --- a/BUILD.gn +++ b/BUILD.gn @@ -84,7 +84,10 @@ if (is_linux) { # from the gtk library. Function signatures for which stubs are # required should be declared in the sig files. generate_stubs("electron_gtk_stubs") { - sigs = [ "shell/browser/ui/electron_gdk_pixbuf.sigs" ] + sigs = [ + "shell/browser/ui/electron_gdk.sigs", + "shell/browser/ui/electron_gdk_pixbuf.sigs", + ] extra_header = "shell/browser/ui/electron_gtk.fragment" output_name = "electron_gtk_stubs" public_deps = [ "//ui/gtk:gtk_config" ] diff --git a/shell/browser/ui/electron_gdk.sigs b/shell/browser/ui/electron_gdk.sigs new file mode 100644 index 0000000000..cf8fb7dee2 --- /dev/null +++ b/shell/browser/ui/electron_gdk.sigs @@ -0,0 +1 @@ +void gdk_display_beep(GdkDisplay* display); diff --git a/shell/browser/ui/electron_gtk.sigs b/shell/browser/ui/electron_gtk.sigs deleted file mode 100644 index 41f3890096..0000000000 --- a/shell/browser/ui/electron_gtk.sigs +++ /dev/null @@ -1,7 +0,0 @@ -GtkFileChooserNative* gtk_file_chooser_native_new(const gchar* title, GtkWindow* parent, GtkFileChooserAction action, const gchar* accept_label, const gchar* cancel_label); -void gtk_native_dialog_set_modal(GtkNativeDialog* self, gboolean modal); -void gtk_native_dialog_show(GtkNativeDialog* self); -void gtk_native_dialog_hide(GtkNativeDialog* self); -gint gtk_native_dialog_run(GtkNativeDialog* self); -void gtk_native_dialog_destroy(GtkNativeDialog* self); -GType gtk_native_dialog_get_type(void); diff --git a/shell/common/platform_util_linux.cc b/shell/common/platform_util_linux.cc index 6bd80cc15b..125b4d037a 100644 --- a/shell/common/platform_util_linux.cc +++ b/shell/common/platform_util_linux.cc @@ -11,6 +11,8 @@ #include <string> #include <vector> +#include <gdk/gdk.h> + #include "base/cancelable_callback.h" #include "base/containers/contains.h" #include "base/environment.h" @@ -32,6 +34,7 @@ #include "dbus/bus.h" #include "dbus/message.h" #include "dbus/object_proxy.h" + #include "shell/common/platform_util_internal.h" #include "url/gurl.h" @@ -408,15 +411,8 @@ bool PlatformTrashItem(const base::FilePath& full_path, std::string* error) { } // namespace internal void Beep() { - // echo '\a' > /dev/console - FILE* fp = fopen("/dev/console", "a"); - if (fp == nullptr) { - fp = fopen("/dev/tty", "a"); - } - if (fp != nullptr) { - fprintf(fp, "\a"); - fclose(fp); - } + auto* display = gdk_display_get_default(); + gdk_display_beep(display); } bool GetDesktopName(std::string* setme) {
refactor
6fdfca6e499656806d9b924a5e9fed1b66faa362
Will Anderson
2025-02-11 03:56:05
build: make gen-libc++-filenames.js produce the same results on Windows (#45556)
diff --git a/script/gen-libc++-filenames.js b/script/gen-libc++-filenames.js index 84cb2b2e3b..fb258cf896 100644 --- a/script/gen-libc++-filenames.js +++ b/script/gen-libc++-filenames.js @@ -7,6 +7,7 @@ const check = process.argv.includes('--check'); function findAllHeaders (basePath) { const allFiles = fs.readdirSync(basePath); + allFiles.sort(); const toReturn = []; for (const file of allFiles) { const absPath = path.resolve(basePath, file); @@ -48,7 +49,7 @@ for (const folder of ['libc++', 'libc++abi']) { const libcxxIncludeDir = path.resolve(__dirname, '..', '..', 'third_party', folder, 'src', 'include'); const gclientPath = `third_party/${folder}/src/include`; - const headers = findAllHeaders(libcxxIncludeDir).map(absPath => path.relative(path.resolve(__dirname, '../..', gclientPath), absPath)); + const headers = findAllHeaders(libcxxIncludeDir).map(absPath => path.relative(path.resolve(__dirname, '../..', gclientPath), absPath).replaceAll('\\', '/')); const newHeaders = headers.map(f => `//${path.posix.join(gclientPath, f)}`); const content = `${prettyName}_headers = [
build
f4b7e59b2d4ec7e6c15574d476feae5a862ee498
Shelley Vohr
2023-04-25 11:30:16
fix: crash on missing `RenderWidgetHostView` (#38100) chore: fix crash on missing RenderWidgetHostView
diff --git a/shell/browser/ui/cocoa/electron_inspectable_web_contents_view.mm b/shell/browser/ui/cocoa/electron_inspectable_web_contents_view.mm index 1790ed8887..3c8a73fe01 100644 --- a/shell/browser/ui/cocoa/electron_inspectable_web_contents_view.mm +++ b/shell/browser/ui/cocoa/electron_inspectable_web_contents_view.mm @@ -287,12 +287,14 @@ // Temporarily pretend that the WebContents is fully non-draggable while we // re-send the mouse event. This allows the re-dispatched event to "land" // on the WebContents, instead of "falling through" back to the window. - api_contents->SetForceNonDraggable(true); - BaseView* contentsView = (BaseView*)contents->GetRenderWidgetHostView() - ->GetNativeView() - .GetNativeNSView(); - [contentsView mouseEvent:event]; - api_contents->SetForceNonDraggable(false); + auto* rwhv = contents->GetRenderWidgetHostView(); + if (rwhv) { + api_contents->SetForceNonDraggable(true); + BaseView* contentsView = + (BaseView*)rwhv->GetNativeView().GetNativeNSView(); + [contentsView mouseEvent:event]; + api_contents->SetForceNonDraggable(false); + } } }
fix
9fe1b0502516cb17b75982a88032164d06cf926f
Shelley Vohr
2024-06-13 16:35:13
build: upload separate artifact for src files (#42486)
diff --git a/.github/actions/build-electron/action.yml b/.github/actions/build-electron/action.yml index 90d6d1dea2..587c7ccec3 100644 --- a/.github/actions/build-electron/action.yml +++ b/.github/actions/build-electron/action.yml @@ -184,4 +184,9 @@ runs: uses: actions/upload-artifact@65462800fd760344b1a7b4382951275a0abb4808 with: name: generated_artifacts_${{ inputs.artifact-platform }}_${{ env.TARGET_ARCH }} - path: ./generated_artifacts_${{ inputs.artifact-platform }}_${{ env.TARGET_ARCH }} \ No newline at end of file + path: ./generated_artifacts_${{ inputs.artifact-platform }}_${{ env.TARGET_ARCH }} + - name: Upload Src Artifacts ${{ inputs.step-suffix }} + uses: actions/upload-artifact@65462800fd760344b1a7b4382951275a0abb4808 + with: + name: src_artifacts_${{ inputs.artifact-platform }}_${{ env.TARGET_ARCH }} + path: ./src_artifacts_${{ inputs.artifact-platform }}_${{ env.TARGET_ARCH }} diff --git a/.github/workflows/pipeline-segment-electron-test.yml b/.github/workflows/pipeline-segment-electron-test.yml index 8f49a1bd15..0f28524887 100644 --- a/.github/workflows/pipeline-segment-electron-test.yml +++ b/.github/workflows/pipeline-segment-electron-test.yml @@ -81,6 +81,11 @@ jobs: with: name: generated_artifacts_${{ matrix.build-type }}_${{ inputs.target-arch }} path: ./generated_artifacts_${{ matrix.build-type }}_${{ inputs.target-arch }} + - name: Download Src Artifacts + uses: actions/download-artifact@65a9edc5881444af0b9093a5e628f2fe47ea3b2e + with: + name: src_artifacts_${{ matrix.build-type }}_${{ env.TARGET_ARCH }} + path: ./src_artifacts_${{ matrix.build-type }}_${{ env.TARGET_ARCH }} - name: Restore Generated Artifacts run: ./src/electron/script/actions/restore-artifacts.sh - name: Unzip Dist, Mksnapshot & Chromedriver diff --git a/.github/workflows/pipeline-segment-node-nan-test.yml b/.github/workflows/pipeline-segment-node-nan-test.yml index 103ed5ce9b..b9cca6fa6f 100644 --- a/.github/workflows/pipeline-segment-node-nan-test.yml +++ b/.github/workflows/pipeline-segment-node-nan-test.yml @@ -75,6 +75,11 @@ jobs: with: name: generated_artifacts_linux_${{ env.TARGET_ARCH }} path: ./generated_artifacts_linux_${{ env.TARGET_ARCH }} + - name: Download Src Artifacts + uses: actions/download-artifact@65a9edc5881444af0b9093a5e628f2fe47ea3b2e + with: + name: src_artifacts_linux_${{ env.TARGET_ARCH }} + path: ./src_artifacts_linux_${{ env.TARGET_ARCH }} - name: Restore Generated Artifacts run: ./src/electron/script/actions/restore-artifacts.sh - name: Unzip Dist @@ -134,6 +139,11 @@ jobs: with: name: generated_artifacts_linux_${{ env.TARGET_ARCH }} path: ./generated_artifacts_linux_${{ env.TARGET_ARCH }} + - name: Download Src Artifacts + uses: actions/download-artifact@65a9edc5881444af0b9093a5e628f2fe47ea3b2e + with: + name: src_artifacts_linux_${{ env.TARGET_ARCH }} + path: ./src_artifacts_linux_${{ env.TARGET_ARCH }} - name: Restore Generated Artifacts run: ./src/electron/script/actions/restore-artifacts.sh - name: Unzip Dist diff --git a/script/actions/move-artifacts.sh b/script/actions/move-artifacts.sh index c08192f3c5..e4030b300c 100755 --- a/script/actions/move-artifacts.sh +++ b/script/actions/move-artifacts.sh @@ -19,6 +19,12 @@ echo Creating $GENERATED_ARTIFACTS... rm -rf $GENERATED_ARTIFACTS mkdir $GENERATED_ARTIFACTS +SRC_ARTIFACTS="src_artifacts_${BUILD_TYPE}_${TARGET_ARCH}" + +echo Creating $SRC_ARTIFACTS... +rm -rf $SRC_ARTIFACTS +mkdir $SRC_ARTIFACTS + mv_if_exist() { if [ -f "$1" ] || [ -d "$1" ]; then echo Storing $1 @@ -37,8 +43,8 @@ cp_if_exist() { fi } -tar_src_dirs_if_exist() { - mkdir build_artifacts +move_src_dirs_if_exist() { + mkdir src_artifacts for dir in \ src/out/Default/gen/node_headers \ @@ -60,14 +66,15 @@ tar_src_dirs_if_exist() { src/v8/tools/builtins-pgo do if [ -d "$dir" ]; then - mkdir -p build_artifacts/$(dirname $dir) - cp -r $dir/ build_artifacts/$dir + mkdir -p src_artifacts/$(dirname $dir) + cp -r $dir/ src_artifacts/$dir fi done - tar -C build_artifacts -cf build_artifacts.tar ./ + tar -C src_artifacts -cf src_artifacts.tar ./ - mv_if_exist build_artifacts.tar + echo Storing src_artifacts.tar + mv src_artifacts.tar $SRC_ARTIFACTS } # Generated Artifacts @@ -82,4 +89,4 @@ mv_if_exist src/cross-arch-snapshots cp_if_exist src/out/electron_ninja_log cp_if_exist src/out/Default/.ninja_log -tar_src_dirs_if_exist +move_src_dirs_if_exist diff --git a/script/actions/restore-artifacts.sh b/script/actions/restore-artifacts.sh index 35210a908c..a4eed010d1 100755 --- a/script/actions/restore-artifacts.sh +++ b/script/actions/restore-artifacts.sh @@ -14,6 +14,7 @@ else fi GENERATED_ARTIFACTS="generated_artifacts_${BUILD_TYPE}_${TARGET_ARCH}" +SRC_ARTIFACTS="src_artifacts_${BUILD_TYPE}_${TARGET_ARCH}" mv_if_exist() { if [ -f "${GENERATED_ARTIFACTS}/$1" ] || [ -d "${GENERATED_ARTIFACTS}/$1" ]; then @@ -26,9 +27,9 @@ mv_if_exist() { } untar_if_exist() { - if [ -f "${GENERATED_ARTIFACTS}/$1" ] || [ -d "${GENERATED_ARTIFACTS}/$1" ]; then + if [ -f "${SRC_ARTIFACTS}/$1" ] || [ -d "${SRC_ARTIFACTS}/$1" ]; then echo Restoring $1 to current directory - tar -xf ${GENERATED_ARTIFACTS}/$1 + tar -xf ${SRC_ARTIFACTS}/$1 else echo Skipping $1 - It is not present on disk fi @@ -46,5 +47,7 @@ mv_if_exist ffmpeg.zip src/out/ffmpeg mv_if_exist hunspell_dictionaries.zip src/out/Default mv_if_exist cross-arch-snapshots src -# Restore build artifacts -untar_if_exist build_artifacts.tar +echo Restoring artifacts from $SRC_ARTIFACTS + +# Restore src artifacts +untar_if_exist src_artifacts.tar
build
8b8fbd0408c95487afcee28fa18b2a8b2270f713
David Sanders
2023-10-08 16:46:56
test: add back smoke test for removed API (#40132)
diff --git a/spec/ts-smoke/electron/main.ts b/spec/ts-smoke/electron/main.ts index 7e30c40f07..6c770d35cf 100644 --- a/spec/ts-smoke/electron/main.ts +++ b/spec/ts-smoke/electron/main.ts @@ -382,6 +382,8 @@ if (process.platform === 'darwin') { // @ts-expect-error Removed API systemPreferences.setAppLevelAppearance('dark'); // @ts-expect-error Removed API + console.log(systemPreferences.appLevelAppearance); + // @ts-expect-error Removed API console.log(systemPreferences.getColor('alternate-selected-control-text')); }
test
a0ae691a9c1da400904934803818d345c64cd258
Erick Zhao
2023-09-27 17:07:04
docs: document type-specific module aliases (#39685)
diff --git a/docs/tutorial/process-model.md b/docs/tutorial/process-model.md index 06c56e02d3..f0f896170b 100644 --- a/docs/tutorial/process-model.md +++ b/docs/tutorial/process-model.md @@ -228,6 +228,23 @@ channel with a renderer process using [`MessagePort`][]s. An Electron app can always prefer the [UtilityProcess][] API over Node.js [`child_process.fork`][] API when there is need to fork a child process from the main process. +## Process-specific module aliases (TypeScript) + +Electron's npm package also exports subpaths that contain a subset of +Electron's TypeScript type definitions. + +- `electron/main` includes types for all main process modules. +- `electron/renderer` includes types for all renderer process modules. +- `electron/common` includes types for modules that can run in main and renderer processes. + +These aliases have no impact on runtime, but can be used for typechecking +and autocomplete. + +```js title="Usage example" +const { app } = require('electron/main') +const { shell } = require('electron/common') +``` + [window-mdn]: https://developer.mozilla.org/en-US/docs/Web/API/Window [`MessagePort`]: https://developer.mozilla.org/en-US/docs/Web/API/MessagePort [`child_process.fork`]: https://nodejs.org/dist/latest-v16.x/docs/api/child_process.html#child_processforkmodulepath-args-options diff --git a/docs/tutorial/tutorial-2-first-app.md b/docs/tutorial/tutorial-2-first-app.md index 8f0fd17977..7537dce7a5 100644 --- a/docs/tutorial/tutorial-2-first-app.md +++ b/docs/tutorial/tutorial-2-first-app.md @@ -222,14 +222,26 @@ with CommonJS module syntax: - [app][app], which controls your application's event lifecycle. - [BrowserWindow][browser-window], which creates and manages app windows. -:::info Capitalization conventions +<details><summary>Module capitalization conventions</summary> You might have noticed the capitalization difference between the **a**pp and **B**rowser**W**indow modules. Electron follows typical JavaScript conventions here, where PascalCase modules are instantiable class constructors (e.g. BrowserWindow, Tray, Notification) whereas camelCase modules are not instantiable (e.g. app, ipcRenderer, webContents). -::: +</details> + +<details><summary>Typed import aliases</summary> + +For better type checking when writing TypeScript code, you can choose to import +main process modules from <code>electron/main</code>. + +```js +const { app, BrowserWindow } = require('electron/main') +``` + +For more information, see the [Process Model docs](../tutorial/process-model.md#process-specific-module-aliases-typescript). +</details> :::warning ES Modules in Electron
docs
82456c691524e5944bd475d367a429d21bb4c159
Yureka
2023-03-13 22:16:23
refactor: DEPS: remove squirrel.mac from recursedeps (#37496) DEPS: remove squirrel.mac from recursedeps squirrel.mac repository does not contain a gclient DEPS file, so recursing into it is useless
diff --git a/DEPS b/DEPS index aca88df604..69539906f3 100644 --- a/DEPS +++ b/DEPS @@ -149,5 +149,4 @@ hooks = [ recursedeps = [ 'src', - 'src/third_party/squirrel.mac', ]
refactor
b5227b4a1760a0966fc74e177d58633587556365
Charles Kerr
2024-10-09 09:12:48
fix: -Wunsafe-buffer-usage warnings in GetNextZoomLevel() (#44149) fixup e8948397 really fix the warning this time
diff --git a/shell/browser/ui/inspectable_web_contents.cc b/shell/browser/ui/inspectable_web_contents.cc index 4c7d1717d9..fa1b054f46 100644 --- a/shell/browser/ui/inspectable_web_contents.cc +++ b/shell/browser/ui/inspectable_web_contents.cc @@ -118,20 +118,20 @@ void SetZoomLevelForWebContents(content::WebContents* web_contents, content::HostZoomMap::SetZoomLevel(web_contents, level); } -double GetNextZoomLevel(const double level, const bool out) { +double GetNextZoomLevel(double level, bool out) { static constexpr std::array<double, 16U> kPresetFactors{ 0.25, 0.333, 0.5, 0.666, 0.75, 0.9, 1.0, 1.1, 1.25, 1.5, 1.75, 2.0, 2.5, 3.0, 4.0, 5.0}; - static constexpr auto kBegin = kPresetFactors.begin(); - static constexpr auto kEnd = kPresetFactors.end(); + static constexpr size_t size = std::size(kPresetFactors); const double factor = blink::ZoomLevelToZoomFactor(level); - auto matches = [=](auto val) { return blink::ZoomValuesEqual(factor, val); }; - if (auto iter = std::find_if(kBegin, kEnd, matches); iter != kEnd) { - if (out && iter != kBegin) - return blink::ZoomFactorToZoomLevel(*--iter); - if (!out && ++iter != kEnd) - return blink::ZoomFactorToZoomLevel(*iter); + for (size_t i = 0U; i < size; ++i) { + if (!blink::ZoomValuesEqual(kPresetFactors[i], factor)) + continue; + if (out && i > 0U) + return blink::ZoomFactorToZoomLevel(kPresetFactors[i - 1U]); + if (!out && i + 1U < size) + return blink::ZoomFactorToZoomLevel(kPresetFactors[i + 1U]); } return level; }
fix
f943b8c940386f196a10cf490ad9122d83ec59f5
Bruno Henrique da Silva
2023-09-27 11:42:46
fix: set window contents as opaque to decrease DWM GPU usage (#39895) * set window contents as opaque to decrease DWM GPU usage * chore: add more context to ShouldWindowContentsBeTransparent
diff --git a/shell/browser/ui/win/electron_desktop_window_tree_host_win.cc b/shell/browser/ui/win/electron_desktop_window_tree_host_win.cc index dbed46d56e..d60675f31f 100644 --- a/shell/browser/ui/win/electron_desktop_window_tree_host_win.cc +++ b/shell/browser/ui/win/electron_desktop_window_tree_host_win.cc @@ -133,4 +133,14 @@ void ElectronDesktopWindowTreeHostWin::OnNativeThemeUpdated( } } +bool ElectronDesktopWindowTreeHostWin::ShouldWindowContentsBeTransparent() + const { + // Window should be marked as opaque if no transparency setting has been set, + // otherwise videos rendered in the window will trigger a DirectComposition + // redraw for every frame. + // https://github.com/electron/electron/pull/39895 + return native_window_view_->GetOpacity() < 1.0 || + native_window_view_->transparent(); +} + } // namespace electron diff --git a/shell/browser/ui/win/electron_desktop_window_tree_host_win.h b/shell/browser/ui/win/electron_desktop_window_tree_host_win.h index 1901cad02f..2c627ceeb0 100644 --- a/shell/browser/ui/win/electron_desktop_window_tree_host_win.h +++ b/shell/browser/ui/win/electron_desktop_window_tree_host_win.h @@ -40,6 +40,7 @@ class ElectronDesktopWindowTreeHostWin : public views::DesktopWindowTreeHostWin, // ui::NativeThemeObserver: void OnNativeThemeUpdated(ui::NativeTheme* observed_theme) override; + bool ShouldWindowContentsBeTransparent() const override; private: raw_ptr<NativeWindowViews> native_window_view_; // weak ref
fix
16aec702b407af24aab4632c97a21d24c2015acc
Samuel Attard
2023-09-11 11:51:14
fix: ensure app load is limited to real asar files when appropriate (#39788)
diff --git a/lib/asar/fs-wrapper.ts b/lib/asar/fs-wrapper.ts index 2427c9473f..0d7b8e8cec 100644 --- a/lib/asar/fs-wrapper.ts +++ b/lib/asar/fs-wrapper.ts @@ -27,7 +27,7 @@ const cachedArchives = new Map<string, NodeJS.AsarArchive>(); const getOrCreateArchive = (archivePath: string) => { const isCached = cachedArchives.has(archivePath); if (isCached) { - return cachedArchives.get(archivePath); + return cachedArchives.get(archivePath)!; } try { @@ -39,6 +39,8 @@ const getOrCreateArchive = (archivePath: string) => { } }; +process._getOrCreateArchive = getOrCreateArchive; + const asarRe = /\.asar/i; const { getValidatedPath } = __non_webpack_require__('internal/fs/utils'); diff --git a/lib/browser/init.ts b/lib/browser/init.ts index 8359971653..cdd5135ff3 100644 --- a/lib/browser/init.ts +++ b/lib/browser/init.ts @@ -84,11 +84,20 @@ const v8Util = process._linkedBinding('electron_common_v8_util'); let packagePath = null; let packageJson = null; const searchPaths: string[] = v8Util.getHiddenValue(global, 'appSearchPaths'); +const searchPathsOnlyLoadASAR: boolean = v8Util.getHiddenValue(global, 'appSearchPathsOnlyLoadASAR'); +// Borrow the _getOrCreateArchive asar helper +const getOrCreateArchive = process._getOrCreateArchive; +delete process._getOrCreateArchive; if (process.resourcesPath) { for (packagePath of searchPaths) { try { packagePath = path.join(process.resourcesPath, packagePath); + if (searchPathsOnlyLoadASAR) { + if (!getOrCreateArchive?.(packagePath)) { + continue; + } + } packageJson = Module._load(path.join(packagePath, 'package.json')); break; } catch { diff --git a/shell/common/node_bindings.cc b/shell/common/node_bindings.cc index 87c32167d3..9a6092364e 100644 --- a/shell/common/node_bindings.cc +++ b/shell/common/node_bindings.cc @@ -586,6 +586,13 @@ std::shared_ptr<node::Environment> NodeBindings::CreateEnvironment( electron::fuses::IsOnlyLoadAppFromAsarEnabled() ? app_asar_search_paths : search_paths)); + context->Global()->SetPrivate( + context, + v8::Private::ForApi( + isolate, gin::ConvertToV8(isolate, "appSearchPathsOnlyLoadASAR") + .As<v8::String>()), + gin::ConvertToV8(isolate, + electron::fuses::IsOnlyLoadAppFromAsarEnabled())); } base::FilePath resources_path = GetResourcesPath(); diff --git a/typings/internal-ambient.d.ts b/typings/internal-ambient.d.ts index 9fa99fb932..6f6eaafb62 100644 --- a/typings/internal-ambient.d.ts +++ b/typings/internal-ambient.d.ts @@ -254,6 +254,7 @@ declare namespace NodeJS { // Additional properties _firstFileName?: string; _serviceStartupScript: string; + _getOrCreateArchive?: (path: string) => NodeJS.AsarArchive | null; helperExecPath: string; mainModule?: NodeJS.Module | undefined;
fix
38dc43f6497018cc1e6807fea398f89c6d63175b
Samuel Attard
2023-06-08 23:56:26
build: actually use m1.large for publish job (#38706)
diff --git a/.circleci/config/base.yml b/.circleci/config/base.yml index 480331c1d2..a5cef3c2b5 100644 --- a/.circleci/config/base.yml +++ b/.circleci/config/base.yml @@ -52,7 +52,7 @@ executors: size: description: "macOS executor size" type: enum - enum: ["macos.x86.medium.gen2", "macos.m1.medium.gen1"] + enum: ["macos.x86.medium.gen2", "macos.m1.large.gen1", "macos.m1.medium.gen1"] version: description: "xcode version" type: enum @@ -1930,7 +1930,7 @@ jobs: osx-publish-arm64: executor: name: macos - size: macos.m1.medium.gen1 + size: macos.m1.large.gen1 environment: <<: *env-mac-large-release <<: *env-release-build @@ -2011,7 +2011,7 @@ jobs: mas-publish-arm64: executor: name: macos - size: macos.m1.medium.gen1 + size: macos.m1.large.gen1 environment: <<: *env-mac-large-release <<: *env-mas-apple-silicon
build
e4cd162433927de69943fab3ad13bd9b9c396ec6
Sam Maddock
2025-02-10 10:13:11
docs: fix powerMonitor event types (#45518) * fix: powerMonitor event types * fix: thermal-state-change missing Returns
diff --git a/docs/api/power-monitor.md b/docs/api/power-monitor.md index 0801f81a07..83289e0739 100644 --- a/docs/api/power-monitor.md +++ b/docs/api/power-monitor.md @@ -26,7 +26,10 @@ Emitted when system changes to battery power. ### Event: 'thermal-state-change' _macOS_ -* `state` string - The system's new thermal state. Can be `unknown`, `nominal`, `fair`, `serious`, `critical`. +Returns: + +* `details` Event\<\> + * `state` string - The system's new thermal state. Can be `unknown`, `nominal`, `fair`, `serious`, `critical`. Emitted when the thermal state of the system changes. Notification of a change in the thermal status of the system, such as entering a critical temperature @@ -44,7 +47,8 @@ See https://developer.apple.com/library/archive/documentation/Performance/Concep Returns: -* `limit` number - The operating system's advertised speed limit for CPUs, in percent. +* `details` Event\<\> + * `limit` number - The operating system's advertised speed limit for CPUs, in percent. Notification of a change in the operating system's advertised speed limit for CPUs, in percent. Values below 100 indicate that the system is impairing
docs
f7a7085019bf757700df3c2f8714e0de356203cd
Sergei Chestakov
2023-08-16 06:26:02
docs: fix typo in open-url API docs (#39513) * Fix typo in open-url API docs * Update app.md
diff --git a/docs/api/app.md b/docs/api/app.md index 23cf19e5f4..1364ed2664 100755 --- a/docs/api/app.md +++ b/docs/api/app.md @@ -128,9 +128,8 @@ Emitted when the user wants to open a URL with the application. Your application set `NSPrincipalClass` to `AtomApplication`. As with the `open-file` event, be sure to register a listener for the `open-url` -event early in your application startup to detect if the the application being -is being opened to handle a URL. If you register the listener in response to a -`ready` event, you'll miss URLs that trigger the launch of your application. +event early in your application startup to detect if the application is being opened to handle a URL. +If you register the listener in response to a `ready` event, you'll miss URLs that trigger the launch of your application. ### Event: 'activate' _macOS_
docs
5cf15cdab7f3d055a225dbc50c53d62614250468
Milan Burda
2022-09-15 19:29:10
build: fix building with enable_basic_printing false (#35687) Co-authored-by: Milan Burda <[email protected]>
diff --git a/shell/browser/api/electron_api_web_contents.cc b/shell/browser/api/electron_api_web_contents.cc old mode 100755 new mode 100644 index fe53806541..49a690976e --- a/shell/browser/api/electron_api_web_contents.cc +++ b/shell/browser/api/electron_api_web_contents.cc @@ -144,6 +144,10 @@ #include "shell/browser/osr/osr_web_contents_view.h" #endif +#if BUILDFLAG(IS_WIN) +#include "shell/browser/native_window_views.h" +#endif + #if !BUILDFLAG(IS_MAC) #include "ui/aura/window.h" #else @@ -176,9 +180,8 @@ #if BUILDFLAG(IS_WIN) #include "printing/backend/win_helper.h" -#include "shell/browser/native_window_views.h" -#endif #endif +#endif // BUILDFLAG(ENABLE_PRINTING) #if BUILDFLAG(ENABLE_PICTURE_IN_PICTURE) #include "chrome/browser/picture_in_picture/picture_in_picture_window_manager.h"
build
ed9fec7da413533788d57a48c97e36dedfc6003c
Jeremy Rose
2024-04-19 06:43:01
fix: `nativeImage.createThumbnailFromPath` and `shell.openExternal` in renderer (#41875) * fix: nativeImage.createThumbnailFromPath in renderer * also fix shell.openExternal
diff --git a/shell/common/api/electron_api_native_image_mac.mm b/shell/common/api/electron_api_native_image_mac.mm index cf9c6cdcfa..e45eaae9a9 100644 --- a/shell/common/api/electron_api_native_image_mac.mm +++ b/shell/common/api/electron_api_native_image_mac.mm @@ -14,6 +14,7 @@ #include "base/apple/foundation_util.h" #include "base/strings/sys_string_conversions.h" +#include "base/task/bind_post_task.h" #include "gin/arguments.h" #include "shell/common/gin_converters/image_converter.h" #include "shell/common/gin_helper/promise.h" @@ -38,6 +39,23 @@ double safeShift(double in, double def) { return def; } +void ReceivedThumbnailResult(CGSize size, + gin_helper::Promise<gfx::Image> p, + QLThumbnailRepresentation* thumbnail, + NSError* error) { + if (error || !thumbnail) { + std::string err_msg([error.localizedDescription UTF8String]); + p.RejectWithErrorMessage("unable to retrieve thumbnail preview " + "image for the given path: " + + err_msg); + } else { + NSImage* result = [[NSImage alloc] initWithCGImage:[thumbnail CGImage] + size:size]; + gfx::Image image(result); + p.Resolve(image); + } +} + // static v8::Local<v8::Promise> NativeImage::CreateThumbnailFromPath( v8::Isolate* isolate, @@ -70,31 +88,15 @@ v8::Local<v8::Promise> NativeImage::CreateThumbnailFromPath( size:cg_size scale:[screen backingScaleFactor] representationTypes:QLThumbnailGenerationRequestRepresentationTypeAll]); - __block gin_helper::Promise<gfx::Image> p = std::move(promise); + __block auto block_callback = base::BindPostTaskToCurrentDefault( + base::BindOnce(&ReceivedThumbnailResult, cg_size, std::move(promise))); + auto completionHandler = + ^(QLThumbnailRepresentation* thumbnail, NSError* error) { + std::move(block_callback).Run(thumbnail, error); + }; [[QLThumbnailGenerator sharedGenerator] generateBestRepresentationForRequest:request - completionHandler:^( - QLThumbnailRepresentation* thumbnail, - NSError* error) { - if (error || !thumbnail) { - std::string err_msg( - [error.localizedDescription UTF8String]); - dispatch_async(dispatch_get_main_queue(), ^{ - p.RejectWithErrorMessage( - "unable to retrieve thumbnail preview " - "image for the given path: " + - err_msg); - }); - } else { - NSImage* result = [[NSImage alloc] - initWithCGImage:[thumbnail CGImage] - size:cg_size]; - gfx::Image image(result); - dispatch_async(dispatch_get_main_queue(), ^{ - p.Resolve(image); - }); - } - }]; + completionHandler:completionHandler]; return handle; } diff --git a/shell/common/platform_util_mac.mm b/shell/common/platform_util_mac.mm index 60419c7b28..32972a5dfe 100644 --- a/shell/common/platform_util_mac.mm +++ b/shell/common/platform_util_mac.mm @@ -15,11 +15,15 @@ #include "base/apple/osstatus_logging.h" #include "base/files/file_path.h" #include "base/files/file_util.h" +#include "base/functional/bind.h" #include "base/functional/callback.h" #include "base/logging.h" #include "base/mac/scoped_aedesc.h" #include "base/strings/stringprintf.h" #include "base/strings/sys_string_conversions.h" +#include "base/task/thread_pool.h" +#include "content/public/browser/browser_task_traits.h" +#include "content/public/browser/browser_thread.h" #include "net/base/apple/url_conversions.h" #include "ui/views/widget/widget.h" #include "url/gurl.h" @@ -183,15 +187,12 @@ void OpenExternal(const GURL& url, return; } - bool activate = options.activate; - __block OpenCallback c = std::move(callback); - dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), - ^{ - __block std::string error = OpenURL(ns_url, activate); - dispatch_async(dispatch_get_main_queue(), ^{ - std::move(c).Run(error); - }); - }); + base::ThreadPool::PostTaskAndReplyWithResult( + FROM_HERE, + {base::MayBlock(), base::WithBaseSyncPrimitives(), + base::TaskPriority::USER_BLOCKING, + base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN}, + base::BindOnce(&OpenURL, ns_url, options.activate), std::move(callback)); } bool MoveItemToTrashWithError(const base::FilePath& full_path, diff --git a/spec/api-native-image-spec.ts b/spec/api-native-image-spec.ts index 7e055dd6a1..d498214942 100644 --- a/spec/api-native-image-spec.ts +++ b/spec/api-native-image-spec.ts @@ -1,6 +1,6 @@ import { expect } from 'chai'; import { nativeImage } from 'electron/common'; -import { ifdescribe, ifit } from './lib/spec-helpers'; +import { ifdescribe, ifit, itremote, useRemoteContext } from './lib/spec-helpers'; import * as path from 'node:path'; describe('nativeImage module', () => { @@ -426,6 +426,8 @@ describe('nativeImage module', () => { }); ifdescribe(process.platform !== 'linux')('createThumbnailFromPath(path, size)', () => { + useRemoteContext({ webPreferences: { contextIsolation: false, nodeIntegration: true } }); + it('throws when invalid size is passed', async () => { const badSize = { width: -1, height: -1 }; @@ -473,6 +475,13 @@ describe('nativeImage module', () => { const result = await nativeImage.createThumbnailFromPath(imgPath, maxSize); expect(result.getSize()).to.deep.equal(maxSize); }); + + itremote('works in the renderer', async (path: string) => { + const { nativeImage } = require('electron'); + const goodSize = { width: 100, height: 100 }; + const result = await nativeImage.createThumbnailFromPath(path, goodSize); + expect(result.isEmpty()).to.equal(false); + }, [path.join(fixturesPath, 'assets', 'logo.png')]); }); describe('addRepresentation()', () => { diff --git a/spec/api-shell-spec.ts b/spec/api-shell-spec.ts index 749677311b..a2e9cef96f 100644 --- a/spec/api-shell-spec.ts +++ b/spec/api-shell-spec.ts @@ -31,7 +31,7 @@ describe('shell module', () => { }); afterEach(closeAllWindows); - it('opens an external link', async () => { + async function urlOpened () { let url = 'http://127.0.0.1'; let requestReceived: Promise<any>; if (process.platform === 'linux') { @@ -53,12 +53,26 @@ describe('shell module', () => { url = (await listen(server)).url; requestReceived = new Promise<void>(resolve => server.on('connection', () => resolve())); } + return { url, requestReceived }; + } + it('opens an external link', async () => { + const { url, requestReceived } = await urlOpened(); await Promise.all<void>([ shell.openExternal(url), requestReceived ]); }); + + it('opens an external link in the renderer', async () => { + const { url, requestReceived } = await urlOpened(); + const w = new BrowserWindow({ show: false, webPreferences: { sandbox: false, contextIsolation: false, nodeIntegration: true } }); + await w.loadURL('about:blank'); + await Promise.all<void>([ + w.webContents.executeJavaScript(`require("electron").shell.openExternal(${JSON.stringify(url)})`), + requestReceived + ]); + }); }); describe('shell.trashItem()', () => {
fix
18f517d8a6245135d0109d5f040114f09c84224d
David Sanders
2023-09-25 03:43:57
test: vendor node-is-valid-window (#39965)
diff --git a/spec/api-browser-window-spec.ts b/spec/api-browser-window-spec.ts index 0c11ccf204..d194e7c385 100644 --- a/spec/api-browser-window-spec.ts +++ b/spec/api-browser-window-spec.ts @@ -5891,9 +5891,7 @@ describe('BrowserWindow module', () => { afterEach(closeAllWindows); it('returns valid handle', () => { const w = new BrowserWindow({ show: false }); - // The module's source code is hosted at - // https://github.com/electron/node-is-valid-window - const isValidWindow = require('is-valid-window'); + const isValidWindow = require('@electron-ci/is-valid-window'); expect(isValidWindow(w.getNativeWindowHandle())).to.be.true('is valid window'); }); }); diff --git a/spec/is-valid-window/.gitignore b/spec/is-valid-window/.gitignore new file mode 100644 index 0000000000..41912cdec3 --- /dev/null +++ b/spec/is-valid-window/.gitignore @@ -0,0 +1,7 @@ +/node_modules +/build +*.swp +*.log +*~ +.node-version +package-lock.json diff --git a/spec/is-valid-window/README.md b/spec/is-valid-window/README.md new file mode 100644 index 0000000000..6727360b6a --- /dev/null +++ b/spec/is-valid-window/README.md @@ -0,0 +1,8 @@ +# is-valid-window + +Validates if a pointer to window is valid. Used by Electron to validate the +result of `TopLevelWindow.getNativeWindowHandle`. + +## License + +Public domain. diff --git a/spec/is-valid-window/binding.gyp b/spec/is-valid-window/binding.gyp new file mode 100644 index 0000000000..0de7c1f9d1 --- /dev/null +++ b/spec/is-valid-window/binding.gyp @@ -0,0 +1,41 @@ +{ + 'target_defaults': { + 'conditions': [ + ['OS=="win"', { + 'msvs_disabled_warnings': [ + 4530, # C++ exception handler used, but unwind semantics are not enabled + 4506, # no definition for inline function + ], + }], + ], + }, + 'targets': [ + { + 'target_name': 'is_valid_window', + 'sources': [ + 'src/impl.h', + 'src/main.cc', + ], + 'conditions': [ + ['OS=="win"', { + 'sources': [ + 'src/impl_win.cc', + ], + }], + ['OS=="mac"', { + 'sources': [ + 'src/impl_darwin.mm', + ], + 'libraries': [ + '$(SDKROOT)/System/Library/Frameworks/AppKit.framework', + ], + }], + ['OS not in ["mac", "win"]', { + 'sources': [ + 'src/impl_posix.cc', + ], + }], + ], + } + ] +} diff --git a/spec/is-valid-window/lib/is-valid-window.js b/spec/is-valid-window/lib/is-valid-window.js new file mode 100644 index 0000000000..e3154cbc30 --- /dev/null +++ b/spec/is-valid-window/lib/is-valid-window.js @@ -0,0 +1 @@ +module.exports = require('../build/Release/is_valid_window.node').isValidWindow; diff --git a/spec/is-valid-window/package.json b/spec/is-valid-window/package.json new file mode 100644 index 0000000000..40e5c92145 --- /dev/null +++ b/spec/is-valid-window/package.json @@ -0,0 +1,9 @@ +{ + "main": "./lib/is-valid-window.js", + "name": "is-valid-window", + "version": "0.0.5", + "licenses": "Public Domain", + "dependencies": { + "nan": "2.x" + } +} diff --git a/spec/is-valid-window/src/impl.h b/spec/is-valid-window/src/impl.h new file mode 100644 index 0000000000..b211ff05dc --- /dev/null +++ b/spec/is-valid-window/src/impl.h @@ -0,0 +1,12 @@ +#ifndef SRC_IMPL_H_ +#define SRC_IMPL_H_ + +#include <cstddef> + +namespace impl { + +bool IsValidWindow(char* handle, size_t size); + +} // namespace impl + +#endif // SRC_IMPL_H_ diff --git a/spec/is-valid-window/src/impl_darwin.mm b/spec/is-valid-window/src/impl_darwin.mm new file mode 100644 index 0000000000..ef71aed162 --- /dev/null +++ b/spec/is-valid-window/src/impl_darwin.mm @@ -0,0 +1,14 @@ +#include "impl.h" + +#include <Cocoa/Cocoa.h> + +namespace impl { + +bool IsValidWindow(char* handle, size_t size) { + if (size != sizeof(NSView*)) + return false; + NSView* view = *reinterpret_cast<NSView**>(handle); + return [view isKindOfClass:[NSView class]]; +} + +} // namespace impl diff --git a/spec/is-valid-window/src/impl_posix.cc b/spec/is-valid-window/src/impl_posix.cc new file mode 100644 index 0000000000..6c582b6ffb --- /dev/null +++ b/spec/is-valid-window/src/impl_posix.cc @@ -0,0 +1,9 @@ +#include "impl.h" + +namespace impl { + +bool IsValidWindow(char* handle, size_t size) { + return true; +} + +} // namespace impl diff --git a/spec/is-valid-window/src/impl_win.cc b/spec/is-valid-window/src/impl_win.cc new file mode 100644 index 0000000000..91d272bdc5 --- /dev/null +++ b/spec/is-valid-window/src/impl_win.cc @@ -0,0 +1,14 @@ +#include "impl.h" + +#include <windows.h> + +namespace impl { + +bool IsValidWindow(char* handle, size_t size) { + if (size != sizeof(HWND)) + return false; + HWND window = *reinterpret_cast<HWND*>(handle); + return ::IsWindow(window); +} + +} // namespace impl diff --git a/spec/is-valid-window/src/main.cc b/spec/is-valid-window/src/main.cc new file mode 100644 index 0000000000..b14e38b7d3 --- /dev/null +++ b/spec/is-valid-window/src/main.cc @@ -0,0 +1,56 @@ +#include <js_native_api.h> +#include <node_api.h> + +#include "impl.h" + +namespace { + +napi_value IsValidWindow(napi_env env, napi_callback_info info) { + size_t argc = 1; + napi_value args[1], result; + napi_status status; + + status = napi_get_cb_info(env, info, &argc, args, NULL, NULL); + if (status != napi_ok) + return NULL; + + bool is_buffer; + status = napi_is_buffer(env, args[0], &is_buffer); + if (status != napi_ok) + return NULL; + + if (!is_buffer) { + napi_throw_error(env, NULL, "First argument must be Buffer"); + return NULL; + } + + char* data; + size_t length; + status = napi_get_buffer_info(env, args[0], (void**)&data, &length); + if (status != napi_ok) + return NULL; + + status = napi_get_boolean(env, impl::IsValidWindow(data, length), &result); + if (status != napi_ok) + return NULL; + + return result; +} + +napi_value Init(napi_env env, napi_value exports) { + napi_status status; + napi_property_descriptor descriptors[] = {{"isValidWindow", NULL, + IsValidWindow, NULL, NULL, NULL, + napi_default, NULL}}; + + status = napi_define_properties( + env, exports, sizeof(descriptors) / sizeof(*descriptors), descriptors); + if (status != napi_ok) + return NULL; + + return exports; +} + +} // namespace + +NAPI_MODULE(NODE_GYP_MODULE_NAME, Init) diff --git a/spec/package.json b/spec/package.json index 34e7e5ee0e..4bb3c0b6fe 100644 --- a/spec/package.json +++ b/spec/package.json @@ -8,6 +8,7 @@ }, "devDependencies": { "@electron-ci/echo": "file:./fixtures/native-addon/echo", + "@electron-ci/is-valid-window": "file:./is-valid-window", "@electron-ci/uv-dlopen": "file:./fixtures/native-addon/uv-dlopen/", "@marshallofsound/mocha-appveyor-reporter": "^0.4.3", "@types/sinon": "^9.0.4", @@ -20,7 +21,6 @@ "dbus-native": "github:nornagon/dbus-native#master", "dirty-chai": "^2.0.1", "graceful-fs": "^4.1.15", - "is-valid-window": "0.0.5", "mkdirp": "^0.5.1", "mocha": "^10.0.0", "mocha-junit-reporter": "^1.18.0", diff --git a/spec/yarn.lock b/spec/yarn.lock index b97e450d38..86dbabf976 100644 --- a/spec/yarn.lock +++ b/spec/yarn.lock @@ -5,6 +5,11 @@ "@electron-ci/echo@file:./fixtures/native-addon/echo": version "0.0.1" +"@electron-ci/is-valid-window@file:./is-valid-window": + version "0.0.5" + dependencies: + nan "2.x" + "@electron-ci/uv-dlopen@file:./fixtures/native-addon/uv-dlopen": version "0.0.1" @@ -703,13 +708,6 @@ is-unicode-supported@^0.1.0: resolved "https://registry.yarnpkg.com/is-unicode-supported/-/is-unicode-supported-0.1.0.tgz#3f26c76a809593b52bfa2ecb5710ed2779b522a7" integrity sha512-knxG2q4UC3u8stRGyAVJCOdxFmv5DZiRcdlIaAQXAbSfJya+OhopNotLQrstBhququ4ZpuKbDc/8S6mgXgPFPw== [email protected]: - version "0.0.5" - resolved "https://registry.yarnpkg.com/is-valid-window/-/is-valid-window-0.0.5.tgz#57935b35b8c3f30f077b16d54fe5c0d0e4ba8a03" - integrity sha512-bs7tIvCJyJ9BOFZP+U3yGWH9mMQVBDxtWTokrpvpSzEQfMHX+hlhuKqltbYnVkEfj+YSgQJgAW/Klx0qQH7zbQ== - dependencies: - nan "2.x" - [email protected]: version "0.0.1" resolved "https://registry.yarnpkg.com/isarray/-/isarray-0.0.1.tgz#8a18acfca9a8f4177e09abfc6038939b05d1eedf" @@ -897,9 +895,9 @@ [email protected]: resolved "https://registry.yarnpkg.com/ms/-/ms-2.1.3.tgz#574c8138ce1d2b5861f0b44579dbadd60c6615b2" integrity sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA== [email protected], nan@^2.12.1, "nan@github:jkleinsc/nan#remove_accessor_signature": - version "2.16.0" - resolved "https://codeload.github.com/jkleinsc/nan/tar.gz/6a2f95a6a2209d8aa7542fb18099fd808a802059" [email protected], nan@^2.12.1, nan@nodejs/nan#e14bdcd1f72d62bca1d541b66da43130384ec213: + version "2.18.0" + resolved "https://codeload.github.com/nodejs/nan/tar.gz/e14bdcd1f72d62bca1d541b66da43130384ec213" [email protected]: version "3.3.3"
test
0d8dd61257b6d5d73d313016d2f77310205fd4d8
Milan Burda
2023-02-19 10:25:40
test: use expect(dir).to.be.an.instanceof(fs.Dirent); (#37331)
diff --git a/spec/asar-spec.ts b/spec/asar-spec.ts index 248010ad97..827b1d612f 100644 --- a/spec/asar-spec.ts +++ b/spec/asar-spec.ts @@ -899,7 +899,7 @@ describe('asar package', function () { const p = path.join(asarDir, 'a.asar'); const dirs = fs.readdirSync(p, { withFileTypes: true }); for (const dir of dirs) { - expect(dir instanceof fs.Dirent).to.be.true(); + expect(dir).to.be.an.instanceof(fs.Dirent); } const names = dirs.map(a => a.name); expect(names).to.deep.equal(['dir1', 'dir2', 'dir3', 'file1', 'file2', 'file3', 'link1', 'link2', 'ping.js']); @@ -909,7 +909,7 @@ describe('asar package', function () { const p = path.join(asarDir, 'a.asar', 'dir3'); const dirs = fs.readdirSync(p, { withFileTypes: true }); for (const dir of dirs) { - expect(dir instanceof fs.Dirent).to.be.true(); + expect(dir).to.be.an.instanceof(fs.Dirent); } const names = dirs.map(a => a.name); expect(names).to.deep.equal(['file1', 'file2', 'file3']); @@ -941,7 +941,7 @@ describe('asar package', function () { const dirs = await promisify(fs.readdir)(p, { withFileTypes: true }); for (const dir of dirs) { - expect(dir instanceof fs.Dirent).to.be.true(); + expect(dir).to.be.an.instanceof(fs.Dirent); } const names = dirs.map((a: any) => a.name); @@ -1004,7 +1004,7 @@ describe('asar package', function () { const p = path.join(asarDir, 'a.asar'); const dirs = await fs.promises.readdir(p, { withFileTypes: true }); for (const dir of dirs) { - expect(dir instanceof fs.Dirent).to.be.true(); + expect(dir).to.be.an.instanceof(fs.Dirent); } const names = dirs.map(a => a.name); expect(names).to.deep.equal(['dir1', 'dir2', 'dir3', 'file1', 'file2', 'file3', 'link1', 'link2', 'ping.js']);
test
296a558c322567104cb2f47771855e7bf8eaf92b
David Sanders
2024-07-22 01:45:49
build: update @electron/lint-roller to 2.3.0 (#42950)
diff --git a/package.json b/package.json index 577b78d1dc..42e13783f1 100644 --- a/package.json +++ b/package.json @@ -9,7 +9,7 @@ "@electron/docs-parser": "^1.2.0", "@electron/fiddle-core": "^1.0.4", "@electron/github-app-auth": "^2.0.0", - "@electron/lint-roller": "^2.2.0", + "@electron/lint-roller": "^2.3.0", "@electron/typescript-definitions": "^8.15.2", "@octokit/rest": "^19.0.7", "@primer/octicons": "^10.0.0", diff --git a/yarn.lock b/yarn.lock index 8f4a9f43d8..3b6a72139e 100644 --- a/yarn.lock +++ b/yarn.lock @@ -199,14 +199,16 @@ "@octokit/auth-app" "^4.0.13" "@octokit/rest" "^19.0.11" -"@electron/lint-roller@^2.2.0": - version "2.2.0" - resolved "https://registry.yarnpkg.com/@electron/lint-roller/-/lint-roller-2.2.0.tgz#3390ea37868b1ac35863cd393ddf776d049a2e3c" - integrity sha512-gYOwL7p3vXJjzndzW0ewnYuBz+WcNOGCbqNBJLmoVwimHGdNJ7cdh9/AwAggcjHEPO/zpRMfpfhUM7shNPagCQ== +"@electron/lint-roller@^2.3.0": + version "2.3.0" + resolved "https://registry.yarnpkg.com/@electron/lint-roller/-/lint-roller-2.3.0.tgz#4b7702f7275020e75ecda87869c7bfe7ae9aa12c" + integrity sha512-sENX/utPp6lhN2OWH4VcIP+zpjgM/sTX0fnaB36hTnWTSRs7JX7qGNS9jZK9jsgGup1UjPFUr5L9zawk5ivHkw== dependencies: "@dsanders11/vscode-markdown-languageservice" "^0.3.0" + ajv "^8.16.0" balanced-match "^2.0.0" glob "^8.1.0" + hast-util-from-html "^2.0.1" markdown-it "^13.0.1" markdownlint-cli "^0.40.0" mdast-util-from-markdown "^1.3.0" @@ -217,6 +219,7 @@ vscode-languageserver "^8.1.0" vscode-languageserver-textdocument "^1.0.8" vscode-uri "^3.0.7" + yaml "^2.4.5" "@electron/typescript-definitions@^8.15.2": version "8.15.6" @@ -819,6 +822,13 @@ "@types/minimatch" "*" "@types/node" "*" +"@types/hast@^3.0.0": + version "3.0.4" + resolved "https://registry.yarnpkg.com/@types/hast/-/hast-3.0.4.tgz#1d6b39993b82cea6ad783945b0508c25903e15aa" + integrity sha512-WPs+bbQw5aCj+x6laNGWLH3wviHtoCv/P3+otBhbOhJgG8qtpdAMlTCxLtsTWA7LH1Oh/bFCHsBn0TPS5m30EQ== + dependencies: + "@types/unist" "*" + "@types/http-cache-semantics@*": version "4.0.1" resolved "https://registry.yarnpkg.com/@types/http-cache-semantics/-/http-cache-semantics-4.0.1.tgz#0ea7b61496902b95890dc4c3a116b60cb8dae812" @@ -1080,6 +1090,11 @@ resolved "https://registry.yarnpkg.com/@types/unist/-/unist-2.0.3.tgz#9c088679876f374eb5983f150d4787aa6fb32d7e" integrity sha512-FvUupuM3rlRsRtCN+fDudtmytGO6iHJuuRKS1Ss0pG5z8oX0diNEw94UEL7hgDbpN94rgaK5R7sWm6RrSkZuAQ== +"@types/unist@^3.0.0": + version "3.0.2" + resolved "https://registry.yarnpkg.com/@types/unist/-/unist-3.0.2.tgz#6dd61e43ef60b34086287f83683a5c1b2dc53d20" + integrity sha512-dqId9J8K/vGi5Zr7oo212BGii5m3q5Hxlkwy3WpYuKPklmBEvsbMYYyLxAQpSffdLl/gdW0XUpKWFvYmyoWCoQ== + "@types/uuid@^3.4.6": version "3.4.6" resolved "https://registry.yarnpkg.com/@types/uuid/-/uuid-3.4.6.tgz#d2c4c48eb85a757bf2927f75f939942d521e3016" @@ -1401,6 +1416,16 @@ ajv@^6.10.0, ajv@^6.12.2, ajv@^6.12.4, ajv@^6.12.5: json-schema-traverse "^0.4.1" uri-js "^4.2.2" +ajv@^8.16.0: + version "8.17.1" + resolved "https://registry.yarnpkg.com/ajv/-/ajv-8.17.1.tgz#37d9a5c776af6bc92d7f4f9510eba4c0a60d11a6" + integrity sha512-B/gBuNg5SiMTrPkC+A2+cW0RszwxYmn6VYxB/inlBStS5nx6xHIt/ehKRhIMhqusl7a8LjQoZnjCs5vhwxOQ1g== + dependencies: + fast-deep-equal "^3.1.3" + fast-uri "^3.0.1" + json-schema-traverse "^1.0.0" + require-from-string "^2.0.2" + ansi-colors@^4.1.1: version "4.1.1" resolved "https://registry.yarnpkg.com/ansi-colors/-/ansi-colors-4.1.1.tgz#cbb9ae256bf750af1eab344f229aa27fe94ba348" @@ -1974,6 +1999,11 @@ combined-stream@^1.0.8: dependencies: delayed-stream "~1.0.0" +comma-separated-tokens@^2.0.0: + version "2.0.3" + resolved "https://registry.yarnpkg.com/comma-separated-tokens/-/comma-separated-tokens-2.0.3.tgz#4e89c9458acb61bc8fef19f4529973b2392839ee" + integrity sha512-Fu4hJdvzeylCfQPp9SGWidpzrMs7tTrlu6Vb8XGaRGck8QSNZJJp538Wrb60Lax4fPwR64ViY468OIUTbRlGZg== + commander@^2.20.0, commander@^2.9.0: version "2.20.3" resolved "https://registry.yarnpkg.com/commander/-/commander-2.20.3.tgz#fd485e84c03eb4881c20722ba48035e8531aeb33" @@ -2171,6 +2201,13 @@ detect-node@^2.0.4: resolved "https://registry.yarnpkg.com/detect-node/-/detect-node-2.1.0.tgz#c9c70775a49c3d03bc2c06d9a73be550f978f8b1" integrity sha512-T0NIuQpnTvFDATNuHN5roPwSBG83rFsuO+MXXH9/3N1eFbn4wcPjttvjMLEPWJ0RGUYgQE7cGgS3tNxbqCGM7g== +devlop@^1.0.0, devlop@^1.1.0: + version "1.1.0" + resolved "https://registry.yarnpkg.com/devlop/-/devlop-1.1.0.tgz#4db7c2ca4dc6e0e834c30be70c94bbc976dc7018" + integrity sha512-RWmIqhcFf1lRYBvNmr7qTNuyCt/7/ns2jbpp1+PalgE/rDQcBT0fioSMUpJ93irlUhC5hrg4cYqe6U+0ImW0rA== + dependencies: + dequal "^2.0.0" + diff@^3.1.0: version "3.5.0" resolved "https://registry.yarnpkg.com/diff/-/diff-3.5.0.tgz#800c0dd1e0a8bfbc95835c202ad220fe317e5a12" @@ -2908,6 +2945,11 @@ fast-levenshtein@^2.0.6: resolved "https://registry.yarnpkg.com/fast-levenshtein/-/fast-levenshtein-2.0.6.tgz#3d8a5c66883a16a30ca8643e851f19baa7797917" integrity sha1-PYpcZog6FqMMqGQ+hR8Zuqd5eRc= +fast-uri@^3.0.1: + version "3.0.1" + resolved "https://registry.yarnpkg.com/fast-uri/-/fast-uri-3.0.1.tgz#cddd2eecfc83a71c1be2cc2ef2061331be8a7134" + integrity sha512-MWipKbbYiYI0UC7cl8m/i/IWTqfC8YXsqjzybjddLsFjStroQzsHXkc73JutMvBiXmOvapk+axIl79ig5t55Bw== + fastest-levenshtein@^1.0.12: version "1.0.14" resolved "https://registry.yarnpkg.com/fastest-levenshtein/-/fastest-levenshtein-1.0.14.tgz#9054384e4b7a78c88d01a4432dc18871af0ac859" @@ -3390,6 +3432,50 @@ has@^1.0.3: dependencies: function-bind "^1.1.1" +hast-util-from-html@^2.0.1: + version "2.0.1" + resolved "https://registry.yarnpkg.com/hast-util-from-html/-/hast-util-from-html-2.0.1.tgz#9cd38ee81bf40b2607368b92a04b0905fa987488" + integrity sha512-RXQBLMl9kjKVNkJTIO6bZyb2n+cUH8LFaSSzo82jiLT6Tfc+Pt7VQCS+/h3YwG4jaNE2TA2sdJisGWR+aJrp0g== + dependencies: + "@types/hast" "^3.0.0" + devlop "^1.1.0" + hast-util-from-parse5 "^8.0.0" + parse5 "^7.0.0" + vfile "^6.0.0" + vfile-message "^4.0.0" + +hast-util-from-parse5@^8.0.0: + version "8.0.1" + resolved "https://registry.yarnpkg.com/hast-util-from-parse5/-/hast-util-from-parse5-8.0.1.tgz#654a5676a41211e14ee80d1b1758c399a0327651" + integrity sha512-Er/Iixbc7IEa7r/XLtuG52zoqn/b3Xng/w6aZQ0xGVxzhw5xUFxcRqdPzP6yFi/4HBYRaifaI5fQ1RH8n0ZeOQ== + dependencies: + "@types/hast" "^3.0.0" + "@types/unist" "^3.0.0" + devlop "^1.0.0" + hastscript "^8.0.0" + property-information "^6.0.0" + vfile "^6.0.0" + vfile-location "^5.0.0" + web-namespaces "^2.0.0" + +hast-util-parse-selector@^4.0.0: + version "4.0.0" + resolved "https://registry.yarnpkg.com/hast-util-parse-selector/-/hast-util-parse-selector-4.0.0.tgz#352879fa86e25616036037dd8931fb5f34cb4a27" + integrity sha512-wkQCkSYoOGCRKERFWcxMVMOcYE2K1AaNLU8DXS9arxnLOUEWbOXKXiJUNzEpqZ3JOKpnha3jkFrumEjVliDe7A== + dependencies: + "@types/hast" "^3.0.0" + +hastscript@^8.0.0: + version "8.0.0" + resolved "https://registry.yarnpkg.com/hastscript/-/hastscript-8.0.0.tgz#4ef795ec8dee867101b9f23cc830d4baf4fd781a" + integrity sha512-dMOtzCEd3ABUeSIISmrETiKuyydk1w0pa+gE/uormcTpSYuaNJPbX1NU3JLyscSLjwAQM8bWMhhIlnCqnRvDTw== + dependencies: + "@types/hast" "^3.0.0" + comma-separated-tokens "^2.0.0" + hast-util-parse-selector "^4.0.0" + property-information "^6.0.0" + space-separated-tokens "^2.0.0" + hosted-git-info@^2.1.4: version "2.8.9" resolved "https://registry.yarnpkg.com/hosted-git-info/-/hosted-git-info-2.8.9.tgz#dffc0bf9a21c02209090f2aa69429e1414daf3f9" @@ -3891,6 +3977,11 @@ json-schema-traverse@^0.4.1: resolved "https://registry.yarnpkg.com/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz#69f6a87d9513ab8bb8fe63bdb0979c448e684660" integrity sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg== +json-schema-traverse@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz#ae7bcb3656ab77a73ba5c49bf654f38e6b6860e2" + integrity sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug== + json-stable-stringify-without-jsonify@^1.0.1: version "1.0.1" resolved "https://registry.yarnpkg.com/json-stable-stringify-without-jsonify/-/json-stable-stringify-without-jsonify-1.0.1.tgz#9db7b59496ad3f3cfef30a75142d2d930ad72651" @@ -5111,6 +5202,13 @@ parse-ms@^2.1.0: resolved "https://registry.yarnpkg.com/parse-ms/-/parse-ms-2.1.0.tgz#348565a753d4391fa524029956b172cb7753097d" integrity sha512-kHt7kzLoS9VBZfUsiKjv43mr91ea+U05EyKkEtqp7vNbHxmaVuEqN7XxeEVnGrMtYOAxGrDElSi96K7EgO1zCA== +parse5@^7.0.0: + version "7.1.2" + resolved "https://registry.yarnpkg.com/parse5/-/parse5-7.1.2.tgz#0736bebbfd77793823240a23b7fc5e010b7f8e32" + integrity sha512-Czj1WaSVpaoj0wbhMzLmWD69anp2WH7FXMB9n1Sy8/ZFF9jolSQVMu1Ij5WIyGmcBmhk7EOndpO4mIpihVqAXw== + dependencies: + entities "^4.4.0" + parseurl@~1.3.3: version "1.3.3" resolved "https://registry.yarnpkg.com/parseurl/-/parseurl-1.3.3.tgz#9da19e7bee8d12dff0513ed5b76957793bc2e8d4" @@ -5286,6 +5384,11 @@ prop-types@^15.8.1: object-assign "^4.1.1" react-is "^16.13.1" +property-information@^6.0.0: + version "6.5.0" + resolved "https://registry.yarnpkg.com/property-information/-/property-information-6.5.0.tgz#6212fbb52ba757e92ef4fb9d657563b933b7ffec" + integrity sha512-PgTgs/BlvHxOu8QuEN7wi5A0OmXaBcHpmCSTehcs6Uuu9IkDIEo13Hy7n898RHfrQ49vKCoGeWZSaAK01nwVig== + proxy-addr@~2.0.7: version "2.0.7" resolved "https://registry.yarnpkg.com/proxy-addr/-/proxy-addr-2.0.7.tgz#f19fe69ceab311eeb94b42e70e8c2070f9ba1025" @@ -5995,6 +6098,11 @@ repeat-string@^1.0.0: resolved "https://registry.yarnpkg.com/repeat-string/-/repeat-string-1.6.1.tgz#8dcae470e1c88abc2d600fff4a776286da75e637" integrity sha1-jcrkcOHIirwtYA//Sndihtp15jc= +require-from-string@^2.0.2: + version "2.0.2" + resolved "https://registry.yarnpkg.com/require-from-string/-/require-from-string-2.0.2.tgz#89a7fdd938261267318eafe14f9c32e598c36909" + integrity sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw== + resolve-alpn@^1.0.0: version "1.2.1" resolved "https://registry.yarnpkg.com/resolve-alpn/-/resolve-alpn-1.2.1.tgz#b7adbdac3546aaaec20b45e7d8265927072726f9" @@ -6391,6 +6499,11 @@ source-map@^0.6.0: resolved "https://registry.yarnpkg.com/source-map/-/source-map-0.6.1.tgz#74722af32e9614e9c287a8d0bbde48b5e2f1a263" integrity sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g== +space-separated-tokens@^2.0.0: + version "2.0.2" + resolved "https://registry.yarnpkg.com/space-separated-tokens/-/space-separated-tokens-2.0.2.tgz#1ecd9d2350a3844572c3f4a312bceb018348859f" + integrity sha512-PEGlAwrG8yXGXRjW32fGbg66JAlOAwbObuqVoJpv/mRgoWDQfgH1wDPvtzWyUSNAXBGSk8h755YDbbcEy3SH2Q== + spdx-correct@^3.0.0: version "3.2.0" resolved "https://registry.yarnpkg.com/spdx-correct/-/spdx-correct-3.2.0.tgz#4f5ab0668f0059e34f9c00dce331784a12de4e9c" @@ -7090,6 +7203,13 @@ unist-util-stringify-position@^3.0.0: dependencies: "@types/unist" "^2.0.0" +unist-util-stringify-position@^4.0.0: + version "4.0.0" + resolved "https://registry.yarnpkg.com/unist-util-stringify-position/-/unist-util-stringify-position-4.0.0.tgz#449c6e21a880e0855bf5aabadeb3a740314abac2" + integrity sha512-0ASV06AAoKCDkS2+xw5RXJywruurpbC4JZSm7nr7MOt1ojAzvyyaO+UxZf18j8FCF6kmzCZKcAgN/yu2gm2XgQ== + dependencies: + "@types/unist" "^3.0.0" + unist-util-visit-parents@^3.0.0: version "3.1.1" resolved "https://registry.yarnpkg.com/unist-util-visit-parents/-/unist-util-visit-parents-3.1.1.tgz#65a6ce698f78a6b0f56aa0e88f13801886cdaef6" @@ -7223,6 +7343,14 @@ vfile-location@^3.0.0: resolved "https://registry.yarnpkg.com/vfile-location/-/vfile-location-3.2.0.tgz#d8e41fbcbd406063669ebf6c33d56ae8721d0f3c" integrity sha512-aLEIZKv/oxuCDZ8lkJGhuhztf/BW4M+iHdCwglA/eWc+vtuRFJj8EtgceYFX4LRjOhCAAiNHsKGssC6onJ+jbA== +vfile-location@^5.0.0: + version "5.0.3" + resolved "https://registry.yarnpkg.com/vfile-location/-/vfile-location-5.0.3.tgz#cb9eacd20f2b6426d19451e0eafa3d0a846225c3" + integrity sha512-5yXvWDEgqeiYiBe1lbxYF7UMAIm/IcopxMHrMQDq3nvKcjPKIhZklUKL+AE7J7uApI4kwe2snsK+eI6UTj9EHg== + dependencies: + "@types/unist" "^3.0.0" + vfile "^6.0.0" + vfile-message@^3.0.0: version "3.0.1" resolved "https://registry.yarnpkg.com/vfile-message/-/vfile-message-3.0.1.tgz#b9bcf87cb5525e61777e0c6df07e816a577588a3" @@ -7231,6 +7359,14 @@ vfile-message@^3.0.0: "@types/unist" "^2.0.0" unist-util-stringify-position "^3.0.0" +vfile-message@^4.0.0: + version "4.0.2" + resolved "https://registry.yarnpkg.com/vfile-message/-/vfile-message-4.0.2.tgz#c883c9f677c72c166362fd635f21fc165a7d1181" + integrity sha512-jRDZ1IMLttGj41KcZvlrYAaI3CfqpLpfpf+Mfig13viT6NKvRzWZ+lXz0Y5D60w6uJIBAOGq9mSHf0gktF0duw== + dependencies: + "@types/unist" "^3.0.0" + unist-util-stringify-position "^4.0.0" + vfile-reporter@^7.0.0: version "7.0.1" resolved "https://registry.yarnpkg.com/vfile-reporter/-/vfile-reporter-7.0.1.tgz#759bfebb995f3dc8c644284cb88ac4b310ebd168" @@ -7269,6 +7405,15 @@ vfile@^5.0.0: unist-util-stringify-position "^3.0.0" vfile-message "^3.0.0" +vfile@^6.0.0: + version "6.0.2" + resolved "https://registry.yarnpkg.com/vfile/-/vfile-6.0.2.tgz#ef49548ea3d270097a67011921411130ceae7deb" + integrity sha512-zND7NlS8rJYb/sPqkb13ZvbbUoExdbi4w3SfRrMq6R3FvnLQmmfpajJNITuuYm6AZ5uao9vy4BAos3EXBPf2rg== + dependencies: + "@types/unist" "^3.0.0" + unist-util-stringify-position "^4.0.0" + vfile-message "^4.0.0" + [email protected]: version "8.1.0" resolved "https://registry.yarnpkg.com/vscode-jsonrpc/-/vscode-jsonrpc-8.1.0.tgz#cb9989c65e219e18533cc38e767611272d274c94" @@ -7342,6 +7487,11 @@ wcwidth@^1.0.1: dependencies: defaults "^1.0.3" +web-namespaces@^2.0.0: + version "2.0.1" + resolved "https://registry.yarnpkg.com/web-namespaces/-/web-namespaces-2.0.1.tgz#1010ff7c650eccb2592cebeeaf9a1b253fd40692" + integrity sha512-bKr1DkiNa2krS7qxNtdrtHAmzuYGFQLiQ13TsorsdT6ULTkPLKuu5+GsFpDlg6JFjUTwX2DyhMPG2be8uPrqsQ== + webidl-conversions@^3.0.0: version "3.0.1" resolved "https://registry.yarnpkg.com/webidl-conversions/-/webidl-conversions-3.0.1.tgz#24534275e2a7bc6be7bc86611cc16ae0a5654871" @@ -7541,6 +7691,11 @@ yaml@^1.7.2: resolved "https://registry.yarnpkg.com/yaml/-/yaml-1.10.0.tgz#3b593add944876077d4d683fee01081bd9fff31e" integrity sha512-yr2icI4glYaNG+KWONODapy2/jDdMSDnrONSjblABjD9B4Z5LgiircSt8m8sRZFNi08kG9Sm0uSHtEmP3zaEGg== +yaml@^2.4.5: + version "2.4.5" + resolved "https://registry.yarnpkg.com/yaml/-/yaml-2.4.5.tgz#60630b206dd6d84df97003d33fc1ddf6296cca5e" + integrity sha512-aBx2bnqDzVOyNKfsysjA2ms5ZlnjSAW2eG3/L5G/CSujfjLJTJsEw1bGw8kCf04KodQWk1pxlGnZ56CRxiawmg== + yauzl@^2.10.0: version "2.10.0" resolved "https://registry.yarnpkg.com/yauzl/-/yauzl-2.10.0.tgz#c7eb17c93e112cb1086fa6d8e51fb0667b79a5f9"
build
df7f07a8af35a7b96c892374f0b51f3d432fc705
Shelley Vohr
2024-01-18 09:59:54
fix: modal rounding on nonmodal windows (#41003) * fix: modal rounding on nonmodal windows * chore: feedback from review
diff --git a/shell/browser/native_window_mac.mm b/shell/browser/native_window_mac.mm index a13d5488e2..14438b7eb2 100644 --- a/shell/browser/native_window_mac.mm +++ b/shell/browser/native_window_mac.mm @@ -1402,14 +1402,15 @@ void NativeWindowMac::UpdateVibrancyRadii(bool fullscreen) { if (vibrantView != nil && !vibrancy_type_.empty()) { const bool no_rounded_corner = !HasStyleMask(NSWindowStyleMaskTitled); const int macos_version = base::mac::MacOSMajorVersion(); + const bool modal = is_modal(); - // Modal window corners are rounded on macOS >= 11 or higher if the user - // hasn't passed noRoundedCorners. + // If the window is modal, its corners are rounded on macOS >= 11 or higher + // unless the user has explicitly passed noRoundedCorners. bool should_round_modal = - !no_rounded_corner && (macos_version >= 11 ? true : !is_modal()); - // Nonmodal window corners are rounded if they're frameless and the user - // hasn't passed noRoundedCorners. - bool should_round_nonmodal = !no_rounded_corner && !has_frame(); + !no_rounded_corner && macos_version >= 11 && modal; + // If the window is nonmodal, its corners are rounded if it is frameless and + // the user hasn't passed noRoundedCorners. + bool should_round_nonmodal = !no_rounded_corner && !modal && !has_frame(); if (should_round_nonmodal || should_round_modal) { CGFloat radius;
fix
cee51785e1ed057fa5c78b2fc7bb1e8a5b91053d
Charles Kerr
2024-02-09 03:29:14
refactor: inline simple getters, pt . 2 (#41254) * refactor: inline AutofillPopup::line_count() refactor: inline AutofillPopup::value_at() refactor: inline AutofillPopup::label_at() * refactor: inline NativeWindow::aspect_ratio() refactor: inline NativeWindow::aspect_ratio_extra_size() * refactor: inline BrowserProcessImpl::linux_storage_backend() * refactor: inline ElectronMenuModel::sharing_item() * refactor: inline Browser::badge_count() * refactor: inline WebContents::is_guest() refactor: inline InspectableWebContents::is_guest() * refactor: inline InspectableWebContents::dev_tool_bounds() * refactor: inline WebContents::type()
diff --git a/shell/browser/api/electron_api_app.cc b/shell/browser/api/electron_api_app.cc index 8558fc74db..734c4959e6 100644 --- a/shell/browser/api/electron_api_app.cc +++ b/shell/browser/api/electron_api_app.cc @@ -1681,7 +1681,7 @@ gin::ObjectTemplateBuilder App::GetObjectTemplateBuilder(v8::Isolate* isolate) { .SetMethod("setBadgeCount", base::BindRepeating(&Browser::SetBadgeCount, browser)) .SetMethod("getBadgeCount", - base::BindRepeating(&Browser::GetBadgeCount, browser)) + base::BindRepeating(&Browser::badge_count, browser)) .SetMethod("getLoginItemSettings", &App::GetLoginItemSettings) .SetMethod("setLoginItemSettings", base::BindRepeating(&Browser::SetLoginItemSettings, browser)) diff --git a/shell/browser/api/electron_api_safe_storage.cc b/shell/browser/api/electron_api_safe_storage.cc index 1eaddeb112..2bbf774c2b 100644 --- a/shell/browser/api/electron_api_safe_storage.cc +++ b/shell/browser/api/electron_api_safe_storage.cc @@ -31,7 +31,7 @@ bool IsEncryptionAvailable() { return OSCrypt::IsEncryptionAvailable() || (use_password_v10 && static_cast<BrowserProcessImpl*>(g_browser_process) - ->GetLinuxStorageBackend() == "basic_text"); + ->linux_storage_backend() == "basic_text"); #else return OSCrypt::IsEncryptionAvailable(); #endif @@ -46,7 +46,7 @@ std::string GetSelectedLinuxBackend() { if (!Browser::Get()->is_ready()) return "unknown"; return static_cast<BrowserProcessImpl*>(g_browser_process) - ->GetLinuxStorageBackend(); + ->linux_storage_backend(); } #endif diff --git a/shell/browser/api/electron_api_web_contents.cc b/shell/browser/api/electron_api_web_contents.cc index e90532aa24..d966a357b6 100644 --- a/shell/browser/api/electron_api_web_contents.cc +++ b/shell/browser/api/electron_api_web_contents.cc @@ -852,7 +852,7 @@ WebContents::WebContents(v8::Isolate* isolate, session_.Reset(isolate, session.ToV8()); std::unique_ptr<content::WebContents> web_contents; - if (IsGuest()) { + if (is_guest()) { scoped_refptr<content::SiteInstance> site_instance = content::SiteInstance::CreateForURL(session->browser_context(), GURL("chrome-guest://fake-host")); @@ -922,7 +922,7 @@ void WebContents::InitWithSessionAndOptions( const gin_helper::Dictionary& options) { Observe(owned_web_contents.get()); InitWithWebContents(std::move(owned_web_contents), session->browser_context(), - IsGuest()); + is_guest()); inspectable_web_contents_->GetView()->SetDelegate(this); @@ -982,7 +982,7 @@ void WebContents::InitWithSessionAndOptions( SetUserAgent(GetBrowserContext()->GetUserAgent()); - if (IsGuest()) { + if (is_guest()) { NativeWindow* owner_window = nullptr; if (embedder_) { // New WebContents's owner_window is the embedder's owner_window. @@ -1017,7 +1017,7 @@ void WebContents::InitWithExtensionView(v8::Isolate* isolate, // Allow toggling DevTools for background pages Observe(web_contents); InitWithWebContents(std::unique_ptr<content::WebContents>(web_contents), - GetBrowserContext(), IsGuest()); + GetBrowserContext(), is_guest()); inspectable_web_contents_->GetView()->SetDelegate(this); } #endif @@ -1066,7 +1066,7 @@ WebContents::~WebContents() { // For guest view based on OOPIF, the WebContents is released by the embedder // frame, and we need to clear the reference to the memory. - bool not_owned_by_this = IsGuest() && attached_; + bool not_owned_by_this = is_guest() && attached_; #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) // And background pages are owned by extensions::ExtensionHost. if (type_ == Type::kBackgroundPage) @@ -1096,7 +1096,7 @@ void WebContents::DeleteThisIfAlive() { void WebContents::Destroy() { // The content::WebContents should be destroyed asynchronously when possible // as user may choose to destroy WebContents during an event of it. - if (Browser::Get()->is_shutting_down() || IsGuest()) { + if (Browser::Get()->is_shutting_down() || is_guest()) { DeleteThisIfAlive(); } else { content::GetUIThreadTaskRunner({})->PostTask( @@ -2155,7 +2155,7 @@ void WebContents::DidFinishNavigation( Emit("did-navigate", url, http_response_code, http_status_text); } } - if (IsGuest()) + if (is_guest()) Emit("load-commit", url, is_main_frame); } else { auto url = navigation_handle->GetURL(); @@ -2374,10 +2374,6 @@ base::ProcessId WebContents::GetOSProcessID() const { return base::GetProcId(process_handle); } -WebContents::Type WebContents::GetType() const { - return type_; -} - bool WebContents::Equal(const WebContents* web_contents) const { return ID() == web_contents->ID(); } @@ -3371,7 +3367,7 @@ bool WebContents::IsFocused() const { if (!view) return false; - if (GetType() != Type::kBackgroundPage) { + if (type() != Type::kBackgroundPage) { auto* window = web_contents()->GetNativeView()->GetToplevelWindow(); if (window && !window->IsVisible()) return false; @@ -3567,10 +3563,6 @@ void WebContents::OnCursorChanged(const ui::Cursor& cursor) { } } -bool WebContents::IsGuest() const { - return type_ == Type::kWebView; -} - void WebContents::AttachToIframe(content::WebContents* embedder_web_contents, int embedder_frame_id) { attached_ = true; @@ -3782,7 +3774,7 @@ void WebContents::SetImageAnimationPolicy(const std::string& new_policy) { } void WebContents::SetBackgroundColor(std::optional<SkColor> maybe_color) { - SkColor color = maybe_color.value_or((IsGuest() && guest_transparent_) || + SkColor color = maybe_color.value_or((is_guest() && guest_transparent_) || type_ == Type::kBrowserView ? SK_ColorTRANSPARENT : SK_ColorWHITE); @@ -4304,7 +4296,7 @@ void WebContents::UpdateHtmlApiFullscreen(bool fullscreen) { } // Make sure all child webviews quit html fullscreen. - if (!fullscreen && !IsGuest()) { + if (!fullscreen && !is_guest()) { auto* manager = WebViewManager::GetWebViewManager(web_contents()); manager->ForEachGuest(web_contents(), [&](content::WebContents* guest) { WebContents* api_web_contents = WebContents::From(guest); @@ -4416,7 +4408,7 @@ void WebContents::FillObjectTemplate(v8::Isolate* isolate, .SetMethod("getZoomLevel", &WebContents::GetZoomLevel) .SetMethod("setZoomFactor", &WebContents::SetZoomFactor) .SetMethod("getZoomFactor", &WebContents::GetZoomFactor) - .SetMethod("getType", &WebContents::GetType) + .SetMethod("getType", &WebContents::type) .SetMethod("_getPreloadPaths", &WebContents::GetPreloadPaths) .SetMethod("getLastWebPreferences", &WebContents::GetLastWebPreferences) .SetMethod("getOwnerBrowserWindow", &WebContents::GetOwnerBrowserWindow) diff --git a/shell/browser/api/electron_api_web_contents.h b/shell/browser/api/electron_api_web_contents.h index a2021c6203..98c8d227c3 100644 --- a/shell/browser/api/electron_api_web_contents.h +++ b/shell/browser/api/electron_api_web_contents.h @@ -173,7 +173,7 @@ class WebContents : public ExclusiveAccessContext, void SetBackgroundThrottling(bool allowed); int GetProcessID() const; base::ProcessId GetOSProcessID() const; - Type GetType() const; + [[nodiscard]] Type type() const { return type_; } bool Equal(const WebContents* web_contents) const; void LoadURL(const GURL& url, const gin_helper::Dictionary& options); void Reload(); @@ -292,7 +292,7 @@ class WebContents : public ExclusiveAccessContext, v8::Local<v8::Promise> CapturePage(gin::Arguments* args); // Methods for creating <webview>. - bool IsGuest() const; + [[nodiscard]] bool is_guest() const { return type_ == Type::kWebView; } void AttachToIframe(content::WebContents* embedder_web_contents, int embedder_frame_id); void DetachFromOuterFrame(); diff --git a/shell/browser/api/electron_api_web_contents_mac.mm b/shell/browser/api/electron_api_web_contents_mac.mm index bf1c69dbf5..f27ab28a93 100644 --- a/shell/browser/api/electron_api_web_contents_mac.mm +++ b/shell/browser/api/electron_api_web_contents_mac.mm @@ -24,7 +24,7 @@ bool WebContents::IsFocused() const { if (!view) return false; - if (GetType() != Type::kBackgroundPage) { + if (type() != Type::kBackgroundPage) { auto window = [web_contents()->GetNativeView().GetNativeNSView() window]; // On Mac the render widget host view does not lose focus when the window // loses focus so check if the top level window is the key window. diff --git a/shell/browser/browser.cc b/shell/browser/browser.cc index df6fff168e..2d8a831765 100644 --- a/shell/browser/browser.cc +++ b/shell/browser/browser.cc @@ -159,10 +159,6 @@ void Browser::SetName(const std::string& name) { OverriddenApplicationName() = name; } -int Browser::GetBadgeCount() { - return badge_count_; -} - bool Browser::OpenFile(const std::string& file_path) { bool prevent_default = false; for (BrowserObserver& observer : observers_) diff --git a/shell/browser/browser.h b/shell/browser/browser.h index 8b0434cf06..cb82f9a061 100644 --- a/shell/browser/browser.h +++ b/shell/browser/browser.h @@ -110,7 +110,7 @@ class Browser : public WindowListObserver { // Set/Get the badge count. bool SetBadgeCount(std::optional<int> count); - int GetBadgeCount(); + [[nodiscard]] int badge_count() const { return badge_count_; } #if BUILDFLAG(IS_WIN) struct LaunchItem { diff --git a/shell/browser/browser_process_impl.cc b/shell/browser/browser_process_impl.cc index 49999ad547..f33455d992 100644 --- a/shell/browser/browser_process_impl.cc +++ b/shell/browser/browser_process_impl.cc @@ -340,10 +340,6 @@ void BrowserProcessImpl::SetLinuxStorageBackend( break; } } - -const std::string& BrowserProcessImpl::GetLinuxStorageBackend() const { - return selected_linux_storage_backend_; -} #endif // BUILDFLAG(IS_LINUX) void BrowserProcessImpl::SetApplicationLocale(const std::string& locale) { diff --git a/shell/browser/browser_process_impl.h b/shell/browser/browser_process_impl.h index a5c1e24a32..fd34bb8f96 100644 --- a/shell/browser/browser_process_impl.h +++ b/shell/browser/browser_process_impl.h @@ -59,7 +59,9 @@ class BrowserProcessImpl : public BrowserProcess { #if BUILDFLAG(IS_LINUX) void SetLinuxStorageBackend(os_crypt::SelectedLinuxBackend selected_backend); - const std::string& GetLinuxStorageBackend() const; + [[nodiscard]] const std::string& linux_storage_backend() const { + return selected_linux_storage_backend_; + } #endif void EndSession() override {} diff --git a/shell/browser/native_window.cc b/shell/browser/native_window.cc index 46a0c7fc49..e171ce303f 100644 --- a/shell/browser/native_window.cc +++ b/shell/browser/native_window.cc @@ -520,14 +520,6 @@ bool NativeWindow::IsMenuBarVisible() const { return true; } -double NativeWindow::GetAspectRatio() const { - return aspect_ratio_; -} - -gfx::Size NativeWindow::GetAspectRatioExtraSize() const { - return aspect_ratio_extraSize_; -} - void NativeWindow::SetAspectRatio(double aspect_ratio, const gfx::Size& extra_size) { aspect_ratio_ = aspect_ratio; diff --git a/shell/browser/native_window.h b/shell/browser/native_window.h index 1b907eae7f..29c0abd4fb 100644 --- a/shell/browser/native_window.h +++ b/shell/browser/native_window.h @@ -264,8 +264,10 @@ class NativeWindow : public base::SupportsUserData, virtual bool IsMenuBarVisible() const; // Set the aspect ratio when resizing window. - double GetAspectRatio() const; - gfx::Size GetAspectRatioExtraSize() const; + [[nodiscard]] double aspect_ratio() const { return aspect_ratio_; } + [[nodiscard]] gfx::Size aspect_ratio_extra_size() const { + return aspect_ratio_extraSize_; + } virtual void SetAspectRatio(double aspect_ratio, const gfx::Size& extra_size); // File preview APIs. diff --git a/shell/browser/native_window_mac.mm b/shell/browser/native_window_mac.mm index 3d13a2008a..412f8a99f1 100644 --- a/shell/browser/native_window_mac.mm +++ b/shell/browser/native_window_mac.mm @@ -641,7 +641,7 @@ bool NativeWindowMac::IsMaximized() const { if (HasStyleMask(NSWindowStyleMaskResizable) != 0) return [window_ isZoomed]; - NSRect rectScreen = GetAspectRatio() > 0.0 + NSRect rectScreen = aspect_ratio() > 0.0 ? default_frame_for_zoom() : [[NSScreen mainScreen] visibleFrame]; diff --git a/shell/browser/ui/autofill_popup.cc b/shell/browser/ui/autofill_popup.cc index f45e76a023..5b051098fb 100644 --- a/shell/browser/ui/autofill_popup.cc +++ b/shell/browser/ui/autofill_popup.cc @@ -231,7 +231,7 @@ void AutofillPopup::SetItems(const std::vector<std::u16string>& values, void AutofillPopup::AcceptSuggestion(int index) { mojo::AssociatedRemote<mojom::ElectronAutofillAgent> autofill_agent; frame_host_->GetRemoteAssociatedInterfaces()->GetInterface(&autofill_agent); - autofill_agent->AcceptDataListSuggestion(GetValueAt(index)); + autofill_agent->AcceptDataListSuggestion(value_at(index)); } void AutofillPopup::UpdatePopupBounds() { @@ -272,11 +272,10 @@ int AutofillPopup::GetDesiredPopupWidth() { int popup_width = element_bounds_.width(); for (size_t i = 0; i < values_.size(); ++i) { - int row_size = - kEndPadding + 2 * kPopupBorderThickness + - gfx::GetStringWidth(GetValueAt(i), GetValueFontListForRow(i)) + - gfx::GetStringWidth(GetLabelAt(i), GetLabelFontListForRow(i)); - if (!GetLabelAt(i).empty()) + int row_size = kEndPadding + 2 * kPopupBorderThickness + + gfx::GetStringWidth(value_at(i), GetValueFontListForRow(i)) + + gfx::GetStringWidth(label_at(i), GetLabelFontListForRow(i)); + if (!label_at(i).empty()) row_size += kNamePadding + kEndPadding; popup_width = std::max(popup_width, row_size); @@ -307,18 +306,6 @@ ui::ColorId AutofillPopup::GetBackgroundColorIDForRow(int index) const { : ui::kColorResultsTableNormalBackground; } -int AutofillPopup::GetLineCount() { - return values_.size(); -} - -std::u16string AutofillPopup::GetValueAt(int i) { - return values_.at(i); -} - -std::u16string AutofillPopup::GetLabelAt(int i) { - return labels_.at(i); -} - int AutofillPopup::LineFromY(int y) const { int current_height = kPopupBorderThickness; diff --git a/shell/browser/ui/autofill_popup.h b/shell/browser/ui/autofill_popup.h index 59fa7d0425..88dadd3147 100644 --- a/shell/browser/ui/autofill_popup.h +++ b/shell/browser/ui/autofill_popup.h @@ -57,9 +57,9 @@ class AutofillPopup : public views::ViewObserver { const gfx::FontList& GetLabelFontListForRow(int index) const; ui::ColorId GetBackgroundColorIDForRow(int index) const; - int GetLineCount(); - std::u16string GetValueAt(int i); - std::u16string GetLabelAt(int i); + int line_count() const { return values_.size(); } + const std::u16string& value_at(int i) const { return values_.at(i); } + const std::u16string& label_at(int i) const { return labels_.at(i); } int LineFromY(int y) const; int selected_index_; diff --git a/shell/browser/ui/cocoa/electron_inspectable_web_contents_view.mm b/shell/browser/ui/cocoa/electron_inspectable_web_contents_view.mm index c4ab6a9f6d..809ca9a9f8 100644 --- a/shell/browser/ui/cocoa/electron_inspectable_web_contents_view.mm +++ b/shell/browser/ui/cocoa/electron_inspectable_web_contents_view.mm @@ -27,7 +27,7 @@ devtools_is_first_responder_ = NO; attached_to_window_ = NO; - if (inspectableWebContentsView_->inspectable_web_contents()->IsGuest()) { + if (inspectableWebContentsView_->inspectable_web_contents()->is_guest()) { fake_view_ = [[NSView alloc] init]; [fake_view_ setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable]; [self addSubview:fake_view_]; diff --git a/shell/browser/ui/cocoa/electron_menu_controller.mm b/shell/browser/ui/cocoa/electron_menu_controller.mm index ef4f17ab25..26affca39f 100644 --- a/shell/browser/ui/cocoa/electron_menu_controller.mm +++ b/shell/browser/ui/cocoa/electron_menu_controller.mm @@ -493,8 +493,8 @@ NSArray* ConvertSharingItemToNS(const SharingItem& item) { if (menu_) return menu_; - if (model_ && model_->GetSharingItem()) { - NSMenu* menu = [self createShareMenuForItem:*model_->GetSharingItem()]; + if (model_ && model_->sharing_item()) { + NSMenu* menu = [self createShareMenuForItem:*model_->sharing_item()]; menu_ = menu; } else { menu_ = [[NSMenu alloc] initWithTitle:@""]; diff --git a/shell/browser/ui/cocoa/electron_ns_window_delegate.mm b/shell/browser/ui/cocoa/electron_ns_window_delegate.mm index f23f987dcc..e15687a942 100644 --- a/shell/browser/ui/cocoa/electron_ns_window_delegate.mm +++ b/shell/browser/ui/cocoa/electron_ns_window_delegate.mm @@ -76,7 +76,7 @@ using FullScreenTransitionState = - (NSRect)windowWillUseStandardFrame:(NSWindow*)window defaultFrame:(NSRect)frame { if (!shell_->zoom_to_page_width()) { - if (shell_->GetAspectRatio() > 0.0) + if (shell_->aspect_ratio() > 0.0) shell_->set_default_frame_for_zoom(frame); return frame; } @@ -104,7 +104,7 @@ using FullScreenTransitionState = // Set the width. Don't touch y or height. frame.size.width = zoomed_width; - if (shell_->GetAspectRatio() > 0.0) + if (shell_->aspect_ratio() > 0.0) shell_->set_default_frame_for_zoom(frame); return frame; @@ -139,13 +139,12 @@ using FullScreenTransitionState = - (NSSize)windowWillResize:(NSWindow*)sender toSize:(NSSize)frameSize { NSSize newSize = frameSize; - double aspectRatio = shell_->GetAspectRatio(); NSWindow* window = shell_->GetNativeWindow().GetNativeNSWindow(); - if (aspectRatio > 0.0) { - gfx::Size windowSize = shell_->GetSize(); - gfx::Size contentSize = shell_->GetContentSize(); - gfx::Size extraSize = shell_->GetAspectRatioExtraSize(); + if (const double aspectRatio = shell_->aspect_ratio(); aspectRatio > 0.0) { + const gfx::Size windowSize = shell_->GetSize(); + const gfx::Size contentSize = shell_->GetContentSize(); + const gfx::Size extraSize = shell_->aspect_ratio_extra_size(); double titleBarHeight = windowSize.height() - contentSize.height(); double extraWidthPlusFrame = diff --git a/shell/browser/ui/electron_menu_model.cc b/shell/browser/ui/electron_menu_model.cc index d85de9d907..bc2456c8f4 100644 --- a/shell/browser/ui/electron_menu_model.cc +++ b/shell/browser/ui/electron_menu_model.cc @@ -99,11 +99,6 @@ bool ElectronMenuModel::GetSharingItemAt(size_t index, void ElectronMenuModel::SetSharingItem(SharingItem item) { sharing_item_.emplace(std::move(item)); } - -const std::optional<ElectronMenuModel::SharingItem>& -ElectronMenuModel::GetSharingItem() const { - return sharing_item_; -} #endif void ElectronMenuModel::MenuWillClose() { diff --git a/shell/browser/ui/electron_menu_model.h b/shell/browser/ui/electron_menu_model.h index 297b302288..db168d2df9 100644 --- a/shell/browser/ui/electron_menu_model.h +++ b/shell/browser/ui/electron_menu_model.h @@ -98,7 +98,10 @@ class ElectronMenuModel : public ui::SimpleMenuModel { bool GetSharingItemAt(size_t index, SharingItem* item) const; // Set/Get the SharingItem of this menu. void SetSharingItem(SharingItem item); - const std::optional<SharingItem>& GetSharingItem() const; + [[nodiscard]] const std::optional<SharingItem>& sharing_item() const { + return sharing_item_; + } + #endif // ui::SimpleMenuModel: diff --git a/shell/browser/ui/inspectable_web_contents.cc b/shell/browser/ui/inspectable_web_contents.cc index b69628e328..f7d3ec2577 100644 --- a/shell/browser/ui/inspectable_web_contents.cc +++ b/shell/browser/ui/inspectable_web_contents.cc @@ -384,10 +384,6 @@ InspectableWebContentsDelegate* InspectableWebContents::GetDelegate() const { return delegate_; } -bool InspectableWebContents::IsGuest() const { - return is_guest_; -} - void InspectableWebContents::ReleaseWebContents() { web_contents_.release(); WebContentsDestroyed(); @@ -454,7 +450,7 @@ void InspectableWebContents::CloseDevTools() { managed_devtools_web_contents_.reset(); } embedder_message_dispatcher_.reset(); - if (!IsGuest()) + if (!is_guest()) web_contents_->Focus(); } } @@ -516,10 +512,6 @@ void InspectableWebContents::CallClientFunction( std::move(arguments), std::move(cb)); } -gfx::Rect InspectableWebContents::GetDevToolsBounds() const { - return devtools_bounds_; -} - void InspectableWebContents::SaveDevToolsBounds(const gfx::Rect& bounds) { pref_service_->Set(kDevToolsBoundsPref, base::Value{RectToDictionary(bounds)}); diff --git a/shell/browser/ui/inspectable_web_contents.h b/shell/browser/ui/inspectable_web_contents.h index 1bbd2bde79..57f59eb625 100644 --- a/shell/browser/ui/inspectable_web_contents.h +++ b/shell/browser/ui/inspectable_web_contents.h @@ -55,7 +55,7 @@ class InspectableWebContents void SetDelegate(InspectableWebContentsDelegate* delegate); InspectableWebContentsDelegate* GetDelegate() const; - bool IsGuest() const; + [[nodiscard]] bool is_guest() const { return is_guest_; } void ReleaseWebContents(); void SetDevToolsWebContents(content::WebContents* devtools); void SetDockState(const std::string& state); @@ -76,7 +76,9 @@ class InspectableWebContents void InspectElement(int x, int y); // Return the last position and size of devtools window. - gfx::Rect GetDevToolsBounds() const; + [[nodiscard]] const gfx::Rect& dev_tools_bounds() const { + return devtools_bounds_; + } void SaveDevToolsBounds(const gfx::Rect& bounds); // Return the last set zoom level of devtools window. diff --git a/shell/browser/ui/views/autofill_popup_view.cc b/shell/browser/ui/views/autofill_popup_view.cc index 9919b1504c..164a282a86 100644 --- a/shell/browser/ui/views/autofill_popup_view.cc +++ b/shell/browser/ui/views/autofill_popup_view.cc @@ -124,7 +124,7 @@ void AutofillPopupView::OnSuggestionsChanged() { return; CreateChildViews(); - if (popup_->GetLineCount() == 0) { + if (popup_->line_count() == 0) { popup_->Hide(); return; } @@ -177,28 +177,28 @@ void AutofillPopupView::DrawAutofillEntry(gfx::Canvas* canvas, int x_align_left = value_rect.x(); const int value_width = gfx::GetStringWidth( - popup_->GetValueAt(index), popup_->GetValueFontListForRow(index)); + popup_->value_at(index), popup_->GetValueFontListForRow(index)); int value_x_align_left = x_align_left; value_x_align_left = is_rtl ? value_rect.right() - value_width : value_rect.x(); canvas->DrawStringRectWithFlags( - popup_->GetValueAt(index), popup_->GetValueFontListForRow(index), + popup_->value_at(index), popup_->GetValueFontListForRow(index), GetColorProvider()->GetColor(ui::kColorResultsTableNormalText), gfx::Rect(value_x_align_left, value_rect.y(), value_width, value_rect.height()), text_align); // Draw the label text, if one exists. - if (!popup_->GetLabelAt(index).empty()) { - const int label_width = gfx::GetStringWidth( - popup_->GetLabelAt(index), popup_->GetLabelFontListForRow(index)); + if (auto const& label = popup_->label_at(index); !label.empty()) { + const int label_width = + gfx::GetStringWidth(label, popup_->GetLabelFontListForRow(index)); int label_x_align_left = x_align_left; label_x_align_left = is_rtl ? value_rect.x() : value_rect.right() - label_width; canvas->DrawStringRectWithFlags( - popup_->GetLabelAt(index), popup_->GetLabelFontListForRow(index), + label, popup_->GetLabelFontListForRow(index), GetColorProvider()->GetColor(ui::kColorResultsTableDimmedText), gfx::Rect(label_x_align_left, entry_rect.y(), label_width, entry_rect.height()), @@ -212,8 +212,8 @@ void AutofillPopupView::CreateChildViews() { RemoveAllChildViews(); - for (int i = 0; i < popup_->GetLineCount(); ++i) { - auto* child_view = new AutofillPopupChildView(popup_->GetValueAt(i)); + for (int i = 0; i < popup_->line_count(); ++i) { + auto* child_view = new AutofillPopupChildView(popup_->value_at(i)); child_view->set_drag_controller(this); AddChildView(child_view); } @@ -234,8 +234,7 @@ void AutofillPopupView::DoUpdateBoundsAndRedrawPopup() { } void AutofillPopupView::OnPaint(gfx::Canvas* canvas) { - if (!popup_ || - static_cast<size_t>(popup_->GetLineCount()) != children().size()) + if (!popup_ || static_cast<size_t>(popup_->line_count()) != children().size()) return; gfx::Canvas* draw_canvas = canvas; SkBitmap bitmap; @@ -252,7 +251,7 @@ void AutofillPopupView::OnPaint(gfx::Canvas* canvas) { GetColorProvider()->GetColor(ui::kColorResultsTableNormalBackground)); OnPaintBorder(draw_canvas); - for (int i = 0; i < popup_->GetLineCount(); ++i) { + for (int i = 0; i < popup_->line_count(); ++i) { gfx::Rect line_rect = popup_->GetRowBounds(i); DrawAutofillEntry(draw_canvas, i, line_rect); @@ -381,7 +380,7 @@ bool AutofillPopupView::HandleKeyPressEvent( SetSelectedLine(0); return true; case ui::VKEY_NEXT: // Page down. - SetSelectedLine(popup_->GetLineCount() - 1); + SetSelectedLine(popup_->line_count() - 1); return true; case ui::VKEY_ESCAPE: popup_->Hide(); @@ -421,7 +420,7 @@ void AutofillPopupView::AcceptSuggestion(int index) { } bool AutofillPopupView::AcceptSelectedLine() { - if (!selected_line_ || selected_line_.value() >= popup_->GetLineCount()) + if (!selected_line_ || selected_line_.value() >= popup_->line_count()) return false; AcceptSuggestion(selected_line_.value()); @@ -441,7 +440,7 @@ void AutofillPopupView::SetSelectedLine(std::optional<int> selected_line) { return; if (selected_line_ == selected_line) return; - if (selected_line && selected_line.value() >= popup_->GetLineCount()) + if (selected_line && selected_line.value() >= popup_->line_count()) return; auto previous_selected_line(selected_line_); @@ -461,7 +460,7 @@ void AutofillPopupView::SelectNextLine() { return; int new_selected_line = selected_line_ ? *selected_line_ + 1 : 0; - if (new_selected_line >= popup_->GetLineCount()) + if (new_selected_line >= popup_->line_count()) new_selected_line = 0; SetSelectedLine(new_selected_line); @@ -473,7 +472,7 @@ void AutofillPopupView::SelectPreviousLine() { int new_selected_line = selected_line_.value_or(0) - 1; if (new_selected_line < 0) - new_selected_line = popup_->GetLineCount() - 1; + new_selected_line = popup_->line_count() - 1; SetSelectedLine(new_selected_line); } diff --git a/shell/browser/ui/views/inspectable_web_contents_view_views.cc b/shell/browser/ui/views/inspectable_web_contents_view_views.cc index cf9e7f47d7..db3bc463a7 100644 --- a/shell/browser/ui/views/inspectable_web_contents_view_views.cc +++ b/shell/browser/ui/views/inspectable_web_contents_view_views.cc @@ -83,7 +83,7 @@ InspectableWebContentsViewViews::InspectableWebContentsViewViews( : InspectableWebContentsView(inspectable_web_contents), devtools_web_view_(new views::WebView(nullptr)), title_(u"Developer Tools") { - if (!inspectable_web_contents_->IsGuest() && + if (!inspectable_web_contents_->is_guest() && inspectable_web_contents_->GetWebContents()->GetNativeView()) { auto* contents_web_view = new views::WebView(nullptr); contents_web_view->SetWebContents( @@ -116,8 +116,7 @@ void InspectableWebContentsViewViews::ShowDevTools(bool activate) { if (devtools_window_) { devtools_window_web_view_->SetWebContents( inspectable_web_contents_->GetDevToolsWebContents()); - devtools_window_->SetBounds( - inspectable_web_contents()->GetDevToolsBounds()); + devtools_window_->SetBounds(inspectable_web_contents()->dev_tools_bounds()); if (activate) { devtools_window_->Show(); } else { @@ -182,7 +181,7 @@ void InspectableWebContentsViewViews::SetIsDocked(bool docked, bool activate) { views::Widget::InitParams params; params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; params.delegate = devtools_window_delegate_; - params.bounds = inspectable_web_contents()->GetDevToolsBounds(); + params.bounds = inspectable_web_contents()->dev_tools_bounds(); #if BUILDFLAG(IS_LINUX) params.wm_role_name = "devtools";
refactor
1e1dc22e167a9b7313aaa914fb400a19edbbeb7f
Robo
2024-07-15 17:46:24
fix: crash when resolving proxy due to network service restart (#42878)
diff --git a/shell/browser/browser_process_impl.cc b/shell/browser/browser_process_impl.cc index f43d20475f..727baccccc 100644 --- a/shell/browser/browser_process_impl.cc +++ b/shell/browser/browser_process_impl.cc @@ -329,7 +329,7 @@ const std::string& BrowserProcessImpl::GetSystemLocale() const { electron::ResolveProxyHelper* BrowserProcessImpl::GetResolveProxyHelper() { if (!resolve_proxy_helper_) { resolve_proxy_helper_ = base::MakeRefCounted<electron::ResolveProxyHelper>( - system_network_context_manager()->GetContext()); + nullptr /* browser_context */); } return resolve_proxy_helper_.get(); } diff --git a/shell/browser/electron_browser_context.cc b/shell/browser/electron_browser_context.cc index f373ad6b54..779a76573d 100644 --- a/shell/browser/electron_browser_context.cc +++ b/shell/browser/electron_browser_context.cc @@ -609,8 +609,7 @@ ElectronBrowserContext::GetFileSystemAccessPermissionContext() { ResolveProxyHelper* ElectronBrowserContext::GetResolveProxyHelper() { if (!resolve_proxy_helper_) { - resolve_proxy_helper_ = base::MakeRefCounted<ResolveProxyHelper>( - GetDefaultStoragePartition()->GetNetworkContext()); + resolve_proxy_helper_ = base::MakeRefCounted<ResolveProxyHelper>(this); } return resolve_proxy_helper_.get(); } diff --git a/shell/browser/net/resolve_proxy_helper.cc b/shell/browser/net/resolve_proxy_helper.cc index 3f54212b54..85f425edbf 100644 --- a/shell/browser/net/resolve_proxy_helper.cc +++ b/shell/browser/net/resolve_proxy_helper.cc @@ -8,17 +8,20 @@ #include "base/functional/bind.h" #include "content/public/browser/browser_thread.h" +#include "content/public/browser/storage_partition.h" #include "mojo/public/cpp/bindings/pending_remote.h" #include "net/base/network_anonymization_key.h" #include "net/proxy_resolution/proxy_info.h" +#include "services/network/public/mojom/network_context.mojom.h" +#include "shell/browser/electron_browser_context.h" +#include "shell/browser/net/system_network_context_manager.h" using content::BrowserThread; namespace electron { -ResolveProxyHelper::ResolveProxyHelper( - network::mojom::NetworkContext* network_context) - : network_context_(network_context) {} +ResolveProxyHelper::ResolveProxyHelper(ElectronBrowserContext* browser_context) + : browser_context_(browser_context) {} ResolveProxyHelper::~ResolveProxyHelper() { DCHECK_CURRENTLY_ON(BrowserThread::UI); @@ -52,9 +55,18 @@ void ResolveProxyHelper::StartPendingRequest() { receiver_.set_disconnect_handler( base::BindOnce(&ResolveProxyHelper::OnProxyLookupComplete, base::Unretained(this), net::ERR_ABORTED, std::nullopt)); - network_context_->LookUpProxyForURL(pending_requests_.front().url, - net::NetworkAnonymizationKey(), - std::move(proxy_lookup_client)); + network::mojom::NetworkContext* network_context = nullptr; + if (browser_context_) { + network_context = + browser_context_->GetDefaultStoragePartition()->GetNetworkContext(); + } else { + DCHECK(SystemNetworkContextManager::GetInstance()); + network_context = SystemNetworkContextManager::GetInstance()->GetContext(); + } + CHECK(network_context); + network_context->LookUpProxyForURL(pending_requests_.front().url, + net::NetworkAnonymizationKey(), + std::move(proxy_lookup_client)); } void ResolveProxyHelper::OnProxyLookupComplete( diff --git a/shell/browser/net/resolve_proxy_helper.h b/shell/browser/net/resolve_proxy_helper.h index d12b64acc7..20c998be26 100644 --- a/shell/browser/net/resolve_proxy_helper.h +++ b/shell/browser/net/resolve_proxy_helper.h @@ -12,19 +12,20 @@ #include "base/memory/raw_ptr.h" #include "base/memory/ref_counted.h" #include "mojo/public/cpp/bindings/receiver.h" -#include "services/network/public/mojom/network_context.mojom.h" #include "services/network/public/mojom/proxy_lookup_client.mojom.h" #include "url/gurl.h" namespace electron { +class ElectronBrowserContext; + class ResolveProxyHelper : public base::RefCountedThreadSafe<ResolveProxyHelper>, network::mojom::ProxyLookupClient { public: using ResolveProxyCallback = base::OnceCallback<void(std::string)>; - explicit ResolveProxyHelper(network::mojom::NetworkContext* network_context); + explicit ResolveProxyHelper(ElectronBrowserContext* browser_context); void ResolveProxy(const GURL& url, ResolveProxyCallback callback); @@ -70,7 +71,7 @@ class ResolveProxyHelper mojo::Receiver<network::mojom::ProxyLookupClient> receiver_{this}; // Weak Ref - raw_ptr<network::mojom::NetworkContext> network_context_ = nullptr; + raw_ptr<ElectronBrowserContext> browser_context_; }; } // namespace electron
fix
115d37477e03c4dd78884967210e07867c9a2f87
Shelley Vohr
2023-05-31 15:52:13
build: shrink unnecessary test changes in patch revert (#38505) build: shrink unneccesary test changes in patch revert
diff --git a/patches/boringssl/revert_track_ssl_error_zero_return_explicitly.patch b/patches/boringssl/revert_track_ssl_error_zero_return_explicitly.patch index 8626416c64..82a3bae972 100644 --- a/patches/boringssl/revert_track_ssl_error_zero_return_explicitly.patch +++ b/patches/boringssl/revert_track_ssl_error_zero_return_explicitly.patch @@ -47,42 +47,3 @@ index 838761af5cb8498d8bcb66b1a7a6f9c1a233cac7..b9bda24dd4d372485622ff99873ee34e void SSL_CTX_set_tmp_rsa_callback(SSL_CTX *ctx, RSA *(*cb)(SSL *ssl, int is_export, -diff --git a/ssl/ssl_test.cc b/ssl/ssl_test.cc -index be00e7c342759d3059d77cbfd938438df96b5c33..6e551c4d48d1633509dbb95a9619abaa84f84cb2 100644 ---- a/ssl/ssl_test.cc -+++ b/ssl/ssl_test.cc -@@ -8558,11 +8558,6 @@ TEST(SSLTest, ErrorSyscallAfterCloseNotify) { - EXPECT_EQ(ret, 0); - EXPECT_EQ(SSL_get_error(client.get(), ret), SSL_ERROR_ZERO_RETURN); - -- // Further calls to |SSL_read| continue to report |SSL_ERROR_ZERO_RETURN|. -- ret = SSL_read(client.get(), buf, sizeof(buf)); -- EXPECT_EQ(ret, 0); -- EXPECT_EQ(SSL_get_error(client.get(), ret), SSL_ERROR_ZERO_RETURN); -- - // Although the client has seen close_notify, it should continue to report - // |SSL_ERROR_SYSCALL| when its writes fail. - ret = SSL_write(client.get(), data, sizeof(data)); -@@ -8570,22 +8565,6 @@ TEST(SSLTest, ErrorSyscallAfterCloseNotify) { - EXPECT_EQ(SSL_get_error(client.get(), ret), SSL_ERROR_SYSCALL); - EXPECT_TRUE(write_failed); - write_failed = false; -- -- // Cause |BIO_write| to fail with a return value of zero instead. -- // |SSL_get_error| should not misinterpret this as a close_notify. -- // -- // This is not actually a correct implementation of |BIO_write|, but the rest -- // of the code treats zero from |BIO_write| as an error, so ensure it does so -- // correctly. Fixing https://crbug.com/boringssl/503 will make this case moot. -- BIO_meth_set_write(method.get(), [](BIO *, const char *, int) -> int { -- write_failed = true; -- return 0; -- }); -- ret = SSL_write(client.get(), data, sizeof(data)); -- EXPECT_EQ(ret, 0); -- EXPECT_EQ(SSL_get_error(client.get(), ret), SSL_ERROR_SYSCALL); -- EXPECT_TRUE(write_failed); -- write_failed = false; - } - - // Test that |SSL_shutdown|, when quiet shutdown is enabled, simulates receiving
build
58fd8825d224c855cc8290f0a9985c21d4f3c326
Valentin Hăloiu
2023-09-20 21:21:23
fix: add support for ELECTRON_OZONE_PLATFORM_HINT env var (#39792) Co-authored-by: John Kleinschmidt <[email protected]>
diff --git a/docs/api/environment-variables.md b/docs/api/environment-variables.md index ba3d5cf99e..fa6d1e13fc 100644 --- a/docs/api/environment-variables.md +++ b/docs/api/environment-variables.md @@ -111,6 +111,16 @@ Options: * `kioclient5` * `kioclient` +### `ELECTRON_OZONE_PLATFORM_HINT` _Linux_ + +Selects the preferred platform backend used on Linux. The default one is `x11`. `auto` selects Wayland if possible, X11 otherwise. + +Options: + +* `auto` +* `wayland` +* `x11` + ## Development Variables The following environment variables are intended primarily for development and diff --git a/shell/browser/electron_browser_main_parts_linux.cc b/shell/browser/electron_browser_main_parts_linux.cc index 2ad25d3116..49408910c8 100644 --- a/shell/browser/electron_browser_main_parts_linux.cc +++ b/shell/browser/electron_browser_main_parts_linux.cc @@ -15,6 +15,9 @@ #include "shell/common/thread_restrictions.h" #endif +constexpr base::StringPiece kElectronOzonePlatformHint( + "ELECTRON_OZONE_PLATFORM_HINT"); + #if BUILDFLAG(OZONE_PLATFORM_WAYLAND) constexpr char kPlatformWayland[] = "wayland"; @@ -115,17 +118,20 @@ std::string MaybeFixPlatformName(const std::string& ozone_platform_hint) { } // namespace void ElectronBrowserMainParts::DetectOzonePlatform() { + auto const env = base::Environment::Create(); auto* const command_line = base::CommandLine::ForCurrentProcess(); if (!command_line->HasSwitch(switches::kOzonePlatform)) { - const auto ozone_platform_hint = + auto ozone_platform_hint = command_line->GetSwitchValueASCII(switches::kOzonePlatformHint); + if (ozone_platform_hint.empty()) { + env->GetVar(kElectronOzonePlatformHint, &ozone_platform_hint); + } if (!ozone_platform_hint.empty()) { command_line->AppendSwitchASCII( switches::kOzonePlatform, MaybeFixPlatformName(ozone_platform_hint)); } } - auto env = base::Environment::Create(); std::string desktop_startup_id; if (env->GetVar("DESKTOP_STARTUP_ID", &desktop_startup_id)) command_line->AppendSwitchASCII("desktop-startup-id", desktop_startup_id);
fix
6aa9a003c8e3df7459dc09cdf987e59a44c3ac56
lauren n. liberda
2024-04-15 19:32:48
fix: stop using std::vector<const uint8_t> in ProcessingSingleton (#41832)
diff --git a/patches/chromium/feat_add_data_parameter_to_processsingleton.patch b/patches/chromium/feat_add_data_parameter_to_processsingleton.patch index a1a044cd1d..a0ccf4b049 100644 --- a/patches/chromium/feat_add_data_parameter_to_processsingleton.patch +++ b/patches/chromium/feat_add_data_parameter_to_processsingleton.patch @@ -13,7 +13,7 @@ app.requestSingleInstanceLock API so that users can pass in a JSON object for the second instance to send to the first instance. diff --git a/chrome/browser/process_singleton.h b/chrome/browser/process_singleton.h -index 31f5b160e4cd755cfb56a62b04261ee1bee80277..191d43392d1ca76882e9da32548fd8e6a713e701 100644 +index 31f5b160e4cd755cfb56a62b04261ee1bee80277..8dbc5ac458481d2f805f90101069f02adcfe4090 100644 --- a/chrome/browser/process_singleton.h +++ b/chrome/browser/process_singleton.h @@ -18,6 +18,7 @@ @@ -30,7 +30,7 @@ index 31f5b160e4cd755cfb56a62b04261ee1bee80277..191d43392d1ca76882e9da32548fd8e6 base::RepeatingCallback<bool(base::CommandLine command_line, - const base::FilePath& current_directory)>; + const base::FilePath& current_directory, -+ const std::vector<const uint8_t> additional_data)>; ++ const std::vector<uint8_t> additional_data)>; #if BUILDFLAG(IS_WIN) ProcessSingleton(const std::string& program_name, @@ -63,14 +63,14 @@ index 31f5b160e4cd755cfb56a62b04261ee1bee80277..191d43392d1ca76882e9da32548fd8e6 #if BUILDFLAG(IS_WIN) bool EscapeVirtualization(const base::FilePath& user_data_dir); diff --git a/chrome/browser/process_singleton_posix.cc b/chrome/browser/process_singleton_posix.cc -index 298c9c81fa110ad7900d0bd6822136bb57f0382e..da7aaed23e4e0cdc037490bbe8beaea705b48df5 100644 +index 298c9c81fa110ad7900d0bd6822136bb57f0382e..f662580a6fc23d06c5e4795d5e7d41e788c8f90d 100644 --- a/chrome/browser/process_singleton_posix.cc +++ b/chrome/browser/process_singleton_posix.cc @@ -610,6 +610,7 @@ class ProcessSingleton::LinuxWatcher // |reader| is for sending back ACK message. void HandleMessage(const std::string& current_dir, const std::vector<std::string>& argv, -+ const std::vector<const uint8_t> additional_data, ++ const std::vector<uint8_t> additional_data, SocketReader* reader); // Called when the ProcessSingleton that owns this class is about to be @@ -81,7 +81,7 @@ index 298c9c81fa110ad7900d0bd6822136bb57f0382e..da7aaed23e4e0cdc037490bbe8beaea7 - const std::string& current_dir, const std::vector<std::string>& argv, + const std::string& current_dir, + const std::vector<std::string>& argv, -+ const std::vector<const uint8_t> additional_data, ++ const std::vector<uint8_t> additional_data, SocketReader* reader) { DCHECK(ui_task_runner_->BelongsToCurrentThread()); DCHECK(reader); @@ -112,7 +112,7 @@ index 298c9c81fa110ad7900d0bd6822136bb57f0382e..da7aaed23e4e0cdc037490bbe8beaea7 + base::StringToSizeT(tokens[0], &num_args); + std::vector<std::string> command_line(tokens.begin() + 1, tokens.begin() + 1 + num_args); + -+ std::vector<const uint8_t> additional_data; ++ std::vector<uint8_t> additional_data; + if (tokens.size() >= 3 + num_args) { + size_t additional_data_size; + base::StringToSizeT(tokens[1 + num_args], &additional_data_size); @@ -121,7 +121,7 @@ index 298c9c81fa110ad7900d0bd6822136bb57f0382e..da7aaed23e4e0cdc037490bbe8beaea7 + std::string(1, kTokenDelimiter)); + const uint8_t* additional_data_bits = + reinterpret_cast<const uint8_t*>(remaining_args.c_str()); -+ additional_data = std::vector<const uint8_t>( ++ additional_data = std::vector<uint8_t>( + additional_data_bits, additional_data_bits + additional_data_size); + } + @@ -178,7 +178,7 @@ index 298c9c81fa110ad7900d0bd6822136bb57f0382e..da7aaed23e4e0cdc037490bbe8beaea7 if (!WriteToSocket(socket.fd(), to_send.data(), to_send.length())) { // Try to kill the other process, because it might have been dead. diff --git a/chrome/browser/process_singleton_win.cc b/chrome/browser/process_singleton_win.cc -index 11f35769cc53b4aa111a319d155a3916f0040fa7..8e3e870eaac14ce6886878b027c7cf2eba19a759 100644 +index 11f35769cc53b4aa111a319d155a3916f0040fa7..4a87d6c425aa27fb8dcec91287f8714e39b2c429 100644 --- a/chrome/browser/process_singleton_win.cc +++ b/chrome/browser/process_singleton_win.cc @@ -80,10 +80,12 @@ BOOL CALLBACK BrowserWindowEnumeration(HWND window, LPARAM param) { @@ -187,7 +187,7 @@ index 11f35769cc53b4aa111a319d155a3916f0040fa7..8e3e870eaac14ce6886878b027c7cf2e base::CommandLine* parsed_command_line, - base::FilePath* current_directory) { + base::FilePath* current_directory, -+ std::vector<const uint8_t>* parsed_additional_data) { ++ std::vector<uint8_t>* parsed_additional_data) { // We should have enough room for the shortest command (min_message_size) // and also be a multiple of wchar_t bytes. The shortest command - // possible is L"START\0\0" (empty current directory and command line). @@ -228,7 +228,7 @@ index 11f35769cc53b4aa111a319d155a3916f0040fa7..8e3e870eaac14ce6886878b027c7cf2e + msg.substr(fourth_null + 1, fifth_null - fourth_null); + const uint8_t* additional_data_bytes = + reinterpret_cast<const uint8_t*>(additional_data.c_str()); -+ *parsed_additional_data = std::vector<const uint8_t>(additional_data_bytes, ++ *parsed_additional_data = std::vector<uint8_t>(additional_data_bytes, + additional_data_bytes + additional_data_length); + return true; @@ -239,7 +239,7 @@ index 11f35769cc53b4aa111a319d155a3916f0040fa7..8e3e870eaac14ce6886878b027c7cf2e base::CommandLine parsed_command_line(base::CommandLine::NO_PROGRAM); base::FilePath current_directory; - if (!ParseCommandLine(cds, &parsed_command_line, &current_directory)) { -+ std::vector<const uint8_t> additional_data; ++ std::vector<uint8_t> additional_data; + if (!ParseCommandLine(cds, &parsed_command_line, &current_directory, &additional_data)) { *result = TRUE; return true; diff --git a/shell/browser/api/electron_api_app.cc b/shell/browser/api/electron_api_app.cc index cad66ef5e8..4881834a7b 100644 --- a/shell/browser/api/electron_api_app.cc +++ b/shell/browser/api/electron_api_app.cc @@ -407,10 +407,10 @@ bool NotificationCallbackWrapper( const base::RepeatingCallback< void(base::CommandLine command_line, const base::FilePath& current_directory, - const std::vector<const uint8_t> additional_data)>& callback, + const std::vector<uint8_t> additional_data)>& callback, base::CommandLine cmd, const base::FilePath& cwd, - const std::vector<const uint8_t> additional_data) { + const std::vector<uint8_t> additional_data) { // Make sure the callback is called after app gets ready. if (Browser::Get()->is_ready()) { callback.Run(std::move(cmd), cwd, std::move(additional_data)); @@ -987,7 +987,7 @@ std::string App::GetLocaleCountryCode() { void App::OnSecondInstance(base::CommandLine cmd, const base::FilePath& cwd, - const std::vector<const uint8_t> additional_data) { + const std::vector<uint8_t> additional_data) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope handle_scope(isolate); v8::Local<v8::Value> data_value = diff --git a/shell/browser/api/electron_api_app.h b/shell/browser/api/electron_api_app.h index be9b7af97b..96f47b273a 100644 --- a/shell/browser/api/electron_api_app.h +++ b/shell/browser/api/electron_api_app.h @@ -196,7 +196,7 @@ class App : public ElectronBrowserClient::Delegate, std::string GetSystemLocale(gin_helper::ErrorThrower thrower) const; void OnSecondInstance(base::CommandLine cmd, const base::FilePath& cwd, - const std::vector<const uint8_t> additional_data); + const std::vector<uint8_t> additional_data); bool HasSingleInstanceLock() const; bool RequestSingleInstanceLock(gin::Arguments* args); void ReleaseSingleInstanceLock();
fix
ce56d614a373fee7d412143825e13d9bbbfb69b0
Eugene Nesvetaev
2023-01-12 15:32:56
chore: fix typo in promise rejection (#36763)
diff --git a/lib/browser/api/web-contents.ts b/lib/browser/api/web-contents.ts index 7ca4b09e8b..43f9158058 100644 --- a/lib/browser/api/web-contents.ts +++ b/lib/browser/api/web-contents.ts @@ -272,7 +272,7 @@ WebContents.prototype.printToPDF = async function (options) { if (options.pageRanges !== undefined) { if (typeof options.pageRanges !== 'string') { - return Promise.reject(new Error('printBackground must be a String')); + return Promise.reject(new Error('pageRanges must be a String')); } printSettings.pageRanges = options.pageRanges; }
chore
2a7d0a84c0c0e18b98e94816f2655cd69eeac471
Robo
2023-01-12 01:59:03
fix: missing libcxx headers (#36863) * chore: add libcxx script to precommit hook * chore: run gen-libc++-filename.js
diff --git a/filenames.libcxx.gni b/filenames.libcxx.gni index 3437fdf91f..992f8b69c6 100644 --- a/filenames.libcxx.gni +++ b/filenames.libcxx.gni @@ -271,6 +271,10 @@ libcxx_headers = [ "//buildtools/third_party/libc++/trunk/include/__debug", "//buildtools/third_party/libc++/trunk/include/__debug_utils/randomize_range.h", "//buildtools/third_party/libc++/trunk/include/__errc", + "//buildtools/third_party/libc++/trunk/include/__expected/bad_expected_access.h", + "//buildtools/third_party/libc++/trunk/include/__expected/expected.h", + "//buildtools/third_party/libc++/trunk/include/__expected/unexpect.h", + "//buildtools/third_party/libc++/trunk/include/__expected/unexpected.h", "//buildtools/third_party/libc++/trunk/include/__filesystem/copy_options.h", "//buildtools/third_party/libc++/trunk/include/__filesystem/directory_entry.h", "//buildtools/third_party/libc++/trunk/include/__filesystem/directory_iterator.h", @@ -290,6 +294,7 @@ libcxx_headers = [ "//buildtools/third_party/libc++/trunk/include/__format/buffer.h", "//buildtools/third_party/libc++/trunk/include/__format/concepts.h", "//buildtools/third_party/libc++/trunk/include/__format/enable_insertable.h", + "//buildtools/third_party/libc++/trunk/include/__format/escaped_output_table.h", "//buildtools/third_party/libc++/trunk/include/__format/extended_grapheme_cluster_table.h", "//buildtools/third_party/libc++/trunk/include/__format/format_arg.h", "//buildtools/third_party/libc++/trunk/include/__format/format_arg_store.h", @@ -311,6 +316,7 @@ libcxx_headers = [ "//buildtools/third_party/libc++/trunk/include/__format/formatter_pointer.h", "//buildtools/third_party/libc++/trunk/include/__format/formatter_string.h", "//buildtools/third_party/libc++/trunk/include/__format/parser_std_format_spec.h", + "//buildtools/third_party/libc++/trunk/include/__format/range_default_formatter.h", "//buildtools/third_party/libc++/trunk/include/__format/unicode.h", "//buildtools/third_party/libc++/trunk/include/__functional/binary_function.h", "//buildtools/third_party/libc++/trunk/include/__functional/binary_negate.h", @@ -343,8 +349,10 @@ libcxx_headers = [ "//buildtools/third_party/libc++/trunk/include/__fwd/array.h", "//buildtools/third_party/libc++/trunk/include/__fwd/get.h", "//buildtools/third_party/libc++/trunk/include/__fwd/hash.h", + "//buildtools/third_party/libc++/trunk/include/__fwd/memory_resource.h", "//buildtools/third_party/libc++/trunk/include/__fwd/pair.h", "//buildtools/third_party/libc++/trunk/include/__fwd/span.h", + "//buildtools/third_party/libc++/trunk/include/__fwd/string.h", "//buildtools/third_party/libc++/trunk/include/__fwd/string_view.h", "//buildtools/third_party/libc++/trunk/include/__fwd/tuple.h", "//buildtools/third_party/libc++/trunk/include/__hash_table", @@ -395,6 +403,7 @@ libcxx_headers = [ "//buildtools/third_party/libc++/trunk/include/__memory/allocation_guard.h", "//buildtools/third_party/libc++/trunk/include/__memory/allocator.h", "//buildtools/third_party/libc++/trunk/include/__memory/allocator_arg_t.h", + "//buildtools/third_party/libc++/trunk/include/__memory/allocator_destructor.h", "//buildtools/third_party/libc++/trunk/include/__memory/allocator_traits.h", "//buildtools/third_party/libc++/trunk/include/__memory/assume_aligned.h", "//buildtools/third_party/libc++/trunk/include/__memory/auto_ptr.h", @@ -414,7 +423,14 @@ libcxx_headers = [ "//buildtools/third_party/libc++/trunk/include/__memory/uninitialized_algorithms.h", "//buildtools/third_party/libc++/trunk/include/__memory/unique_ptr.h", "//buildtools/third_party/libc++/trunk/include/__memory/uses_allocator.h", + "//buildtools/third_party/libc++/trunk/include/__memory/uses_allocator_construction.h", "//buildtools/third_party/libc++/trunk/include/__memory/voidify.h", + "//buildtools/third_party/libc++/trunk/include/__memory_resource/memory_resource.h", + "//buildtools/third_party/libc++/trunk/include/__memory_resource/monotonic_buffer_resource.h", + "//buildtools/third_party/libc++/trunk/include/__memory_resource/polymorphic_allocator.h", + "//buildtools/third_party/libc++/trunk/include/__memory_resource/pool_options.h", + "//buildtools/third_party/libc++/trunk/include/__memory_resource/synchronized_pool_resource.h", + "//buildtools/third_party/libc++/trunk/include/__memory_resource/unsynchronized_pool_resource.h", "//buildtools/third_party/libc++/trunk/include/__mutex_base", "//buildtools/third_party/libc++/trunk/include/__node_handle", "//buildtools/third_party/libc++/trunk/include/__numeric/accumulate.h", @@ -476,12 +492,14 @@ libcxx_headers = [ "//buildtools/third_party/libc++/trunk/include/__ranges/dangling.h", "//buildtools/third_party/libc++/trunk/include/__ranges/data.h", "//buildtools/third_party/libc++/trunk/include/__ranges/drop_view.h", + "//buildtools/third_party/libc++/trunk/include/__ranges/drop_while_view.h", "//buildtools/third_party/libc++/trunk/include/__ranges/empty.h", "//buildtools/third_party/libc++/trunk/include/__ranges/empty_view.h", "//buildtools/third_party/libc++/trunk/include/__ranges/enable_borrowed_range.h", "//buildtools/third_party/libc++/trunk/include/__ranges/enable_view.h", "//buildtools/third_party/libc++/trunk/include/__ranges/filter_view.h", "//buildtools/third_party/libc++/trunk/include/__ranges/iota_view.h", + "//buildtools/third_party/libc++/trunk/include/__ranges/istream_view.h", "//buildtools/third_party/libc++/trunk/include/__ranges/join_view.h", "//buildtools/third_party/libc++/trunk/include/__ranges/lazy_split_view.h", "//buildtools/third_party/libc++/trunk/include/__ranges/non_propagating_cache.h", @@ -495,6 +513,7 @@ libcxx_headers = [ "//buildtools/third_party/libc++/trunk/include/__ranges/size.h", "//buildtools/third_party/libc++/trunk/include/__ranges/subrange.h", "//buildtools/third_party/libc++/trunk/include/__ranges/take_view.h", + "//buildtools/third_party/libc++/trunk/include/__ranges/take_while_view.h", "//buildtools/third_party/libc++/trunk/include/__ranges/transform_view.h", "//buildtools/third_party/libc++/trunk/include/__ranges/view_interface.h", "//buildtools/third_party/libc++/trunk/include/__ranges/views.h", @@ -614,6 +633,7 @@ libcxx_headers = [ "//buildtools/third_party/libc++/trunk/include/__type_traits/is_scoped_enum.h", "//buildtools/third_party/libc++/trunk/include/__type_traits/is_signed.h", "//buildtools/third_party/libc++/trunk/include/__type_traits/is_signed_integer.h", + "//buildtools/third_party/libc++/trunk/include/__type_traits/is_specialization.h", "//buildtools/third_party/libc++/trunk/include/__type_traits/is_standard_layout.h", "//buildtools/third_party/libc++/trunk/include/__type_traits/is_swappable.h", "//buildtools/third_party/libc++/trunk/include/__type_traits/is_trivial.h", @@ -654,6 +674,7 @@ libcxx_headers = [ "//buildtools/third_party/libc++/trunk/include/__type_traits/remove_reference.h", "//buildtools/third_party/libc++/trunk/include/__type_traits/remove_volatile.h", "//buildtools/third_party/libc++/trunk/include/__type_traits/result_of.h", + "//buildtools/third_party/libc++/trunk/include/__type_traits/strip_signature.h", "//buildtools/third_party/libc++/trunk/include/__type_traits/type_identity.h", "//buildtools/third_party/libc++/trunk/include/__type_traits/type_list.h", "//buildtools/third_party/libc++/trunk/include/__type_traits/underlying_type.h", @@ -726,6 +747,7 @@ libcxx_headers = [ "//buildtools/third_party/libc++/trunk/include/errno.h", "//buildtools/third_party/libc++/trunk/include/exception", "//buildtools/third_party/libc++/trunk/include/execution", + "//buildtools/third_party/libc++/trunk/include/expected", "//buildtools/third_party/libc++/trunk/include/experimental/__config", "//buildtools/third_party/libc++/trunk/include/experimental/__memory", "//buildtools/third_party/libc++/trunk/include/experimental/algorithm", @@ -767,6 +789,7 @@ libcxx_headers = [ "//buildtools/third_party/libc++/trunk/include/istream", "//buildtools/third_party/libc++/trunk/include/iterator", "//buildtools/third_party/libc++/trunk/include/latch", + "//buildtools/third_party/libc++/trunk/include/libcxx.imp", "//buildtools/third_party/libc++/trunk/include/limits", "//buildtools/third_party/libc++/trunk/include/limits.h", "//buildtools/third_party/libc++/trunk/include/list", @@ -775,6 +798,7 @@ libcxx_headers = [ "//buildtools/third_party/libc++/trunk/include/map", "//buildtools/third_party/libc++/trunk/include/math.h", "//buildtools/third_party/libc++/trunk/include/memory", + "//buildtools/third_party/libc++/trunk/include/memory_resource", "//buildtools/third_party/libc++/trunk/include/module.modulemap.in", "//buildtools/third_party/libc++/trunk/include/mutex", "//buildtools/third_party/libc++/trunk/include/new", diff --git a/package.json b/package.json index 786172fd79..8ccdee44cf 100644 --- a/package.json +++ b/package.json @@ -143,7 +143,8 @@ "ts-node script/check-patch-diff.ts" ], "DEPS": [ - "node script/gen-hunspell-filenames.js" + "node script/gen-hunspell-filenames.js", + "node script/gen-libc++-filenames.js" ] }, "resolutions": {
fix
f82a863f654b12846bab783677f20d0842add13f
Jeremy Rose
2022-09-27 14:47:46
feat: replace scroll-touch* with generic input-event (#35531)
diff --git a/docs/api/browser-window.md b/docs/api/browser-window.md index 16a005cd35..859b1876a1 100644 --- a/docs/api/browser-window.md +++ b/docs/api/browser-window.md @@ -652,18 +652,36 @@ The following app commands are explicitly supported on Linux: * `browser-backward` * `browser-forward` -#### Event: 'scroll-touch-begin' _macOS_ +#### Event: 'scroll-touch-begin' _macOS_ _Deprecated_ Emitted when scroll wheel event phase has begun. -#### Event: 'scroll-touch-end' _macOS_ +> **Note** +> This event is deprecated beginning in Electron 22.0.0. See [Breaking +> Changes](breaking-changes.md#deprecated-browserwindow-scroll-touch--events) +> for details of how to migrate to using the [WebContents +> `input-event`](api/web-contents.md#event-input-event) event. + +#### Event: 'scroll-touch-end' _macOS_ _Deprecated_ Emitted when scroll wheel event phase has ended. -#### Event: 'scroll-touch-edge' _macOS_ +> **Note** +> This event is deprecated beginning in Electron 22.0.0. See [Breaking +> Changes](breaking-changes.md#deprecated-browserwindow-scroll-touch--events) +> for details of how to migrate to using the [WebContents +> `input-event`](api/web-contents.md#event-input-event) event. + +#### Event: 'scroll-touch-edge' _macOS_ _Deprecated_ Emitted when scroll wheel event phase filed upon reaching the edge of element. +> **Note** +> This event is deprecated beginning in Electron 22.0.0. See [Breaking +> Changes](breaking-changes.md#deprecated-browserwindow-scroll-touch--events) +> for details of how to migrate to using the [WebContents +> `input-event`](api/web-contents.md#event-input-event) event. + #### Event: 'swipe' _macOS_ Returns: diff --git a/docs/api/structures/input-event.md b/docs/api/structures/input-event.md index 21efec36d3..a68a9304df 100644 --- a/docs/api/structures/input-event.md +++ b/docs/api/structures/input-event.md @@ -1,5 +1,16 @@ # InputEvent Object +* `type` string - Can be `undefined`, `mouseDown`, `mouseUp`, `mouseMove`, + `mouseEnter`, `mouseLeave`, `contextMenu`, `mouseWheel`, `rawKeyDown`, + `keyDown`, `keyUp`, `char`, `gestureScrollBegin`, `gestureScrollEnd`, + `gestureScrollUpdate`, `gestureFlingStart`, `gestureFlingCancel`, + `gesturePinchBegin`, `gesturePinchEnd`, `gesturePinchUpdate`, + `gestureTapDown`, `gestureShowPress`, `gestureTap`, `gestureTapCancel`, + `gestureShortPress`, `gestureLongPress`, `gestureLongTap`, + `gestureTwoFingerTap`, `gestureTapUnconfirmed`, `gestureDoubleTap`, + `touchStart`, `touchMove`, `touchEnd`, `touchCancel`, `touchScrollStarted`, + `pointerDown`, `pointerUp`, `pointerMove`, `pointerRawUpdate`, + `pointerCancel` or `pointerCausedUaAction`. * `modifiers` string[] (optional) - An array of modifiers of the event, can be `shift`, `control`, `ctrl`, `alt`, `meta`, `command`, `cmd`, `isKeypad`, `isAutoRepeat`, `leftButtonDown`, `middleButtonDown`, `rightButtonDown`, diff --git a/docs/api/structures/keyboard-input-event.md b/docs/api/structures/keyboard-input-event.md index de7bef2d77..3f8b4b5e8d 100644 --- a/docs/api/structures/keyboard-input-event.md +++ b/docs/api/structures/keyboard-input-event.md @@ -1,6 +1,6 @@ # KeyboardInputEvent Object extends `InputEvent` -* `type` string - The type of the event, can be `keyDown`, `keyUp` or `char`. +* `type` string - The type of the event, can be `rawKeyDown`, `keyDown`, `keyUp` or `char`. * `keyCode` string - The character that will be sent as the keyboard event. Should only use the valid key codes in [Accelerator](../accelerator.md). diff --git a/docs/api/web-contents.md b/docs/api/web-contents.md index 1f0df82f98..17084a7c7c 100644 --- a/docs/api/web-contents.md +++ b/docs/api/web-contents.md @@ -411,6 +411,16 @@ Emitted when a plugin process has crashed. Emitted when `webContents` is destroyed. +#### Event: 'input-event' + +Returns: + +* `event` Event +* `inputEvent` [InputEvent](structures/input-event.md) + +Emitted when an input event is sent to the WebContents. See +[InputEvent](structures/input-event.md) for details. + #### Event: 'before-input-event' Returns: diff --git a/docs/breaking-changes.md b/docs/breaking-changes.md index f7bea50260..03d12a6232 100644 --- a/docs/breaking-changes.md +++ b/docs/breaking-changes.md @@ -12,6 +12,32 @@ This document uses the following convention to categorize breaking changes: * **Deprecated:** An API was marked as deprecated. The API will continue to function, but will emit a deprecation warning, and will be removed in a future release. * **Removed:** An API or feature was removed, and is no longer supported by Electron. +## Planned Breaking API Changes (23.0) + +### Removed: BrowserWindow `scroll-touch-*` events + +The deprecated `scroll-touch-begin`, `scroll-touch-end` and `scroll-touch-edge` +events on BrowserWindow have been removed. Instead, use the newly available +[`input-event` event](api/web-contents.md#event-input-event) on WebContents. + +```js +// Removed in Electron 23.0 +win.on('scroll-touch-begin', scrollTouchBegin) +win.on('scroll-touch-edge', scrollTouchEdge) +win.on('scroll-touch-end', scrollTouchEnd) + +// Replace with +win.webContents.on('input-event', (_, event) => { + if (event.type === 'gestureScrollBegin') { + scrollTouchBegin() + } else if (event.type === 'gestureScrollUpdate') { + scrollTouchEdge() + } else if (event.type === 'gestureScrollEnd') { + scrollTouchEnd() + } +}) +``` + ## Planned Breaking API Changes (22.0) ### Removed: WebContents `new-window` event @@ -30,6 +56,30 @@ webContents.setWindowOpenHandler((details) => { }) ``` +### Deprecated: BrowserWindow `scroll-touch-*` events + +The `scroll-touch-begin`, `scroll-touch-end` and `scroll-touch-edge` events on +BrowserWindow are deprecated. Instead, use the newly available [`input-event` +event](api/web-contents.md#event-input-event) on WebContents. + +```js +// Deprecated +win.on('scroll-touch-begin', scrollTouchBegin) +win.on('scroll-touch-edge', scrollTouchEdge) +win.on('scroll-touch-end', scrollTouchEnd) + +// Replace with +win.webContents.on('input-event', (_, event) => { + if (event.type === 'gestureScrollBegin') { + scrollTouchBegin() + } else if (event.type === 'gestureScrollUpdate') { + scrollTouchEdge() + } else if (event.type === 'gestureScrollEnd') { + scrollTouchEnd() + } +}) +``` + ## Planned Breaking API Changes (20.0) ### Behavior Changed: V8 Memory Cage enabled diff --git a/lib/browser/api/browser-window.ts b/lib/browser/api/browser-window.ts index 053e09ab63..605c65e2ff 100644 --- a/lib/browser/api/browser-window.ts +++ b/lib/browser/api/browser-window.ts @@ -1,5 +1,6 @@ import { BaseWindow, WebContents, Event, BrowserView, TouchBar } from 'electron/main'; import type { BrowserWindow as BWT } from 'electron/main'; +import * as deprecate from '@electron/internal/common/deprecate'; const { BrowserWindow } = process._linkedBinding('electron_browser_window') as { BrowserWindow: typeof BWT }; Object.setPrototypeOf(BrowserWindow.prototype, BaseWindow.prototype); @@ -44,6 +45,28 @@ BrowserWindow.prototype._init = function (this: BWT) { this.on(event as any, visibilityChanged); } + const warn = deprecate.warnOnceMessage('\'scroll-touch-{begin,end,edge}\' are deprecated and will be removed. Please use the WebContents \'input-event\' event instead.'); + this.webContents.on('input-event', (_, e) => { + if (e.type === 'gestureScrollBegin') { + if (this.listenerCount('scroll-touch-begin') !== 0) { + warn(); + this.emit('scroll-touch-edge'); + this.emit('scroll-touch-begin'); + } + } else if (e.type === 'gestureScrollUpdate') { + if (this.listenerCount('scroll-touch-edge') !== 0) { + warn(); + this.emit('scroll-touch-edge'); + } + } else if (e.type === 'gestureScrollEnd') { + if (this.listenerCount('scroll-touch-end') !== 0) { + warn(); + this.emit('scroll-touch-edge'); + this.emit('scroll-touch-end'); + } + } + }); + // Notify the creation of the window. const event = process._linkedBinding('electron_browser_event').createEmpty(); app.emit('browser-window-created', event, this); diff --git a/lib/common/deprecate.ts b/lib/common/deprecate.ts index b9c42c3cc0..dc6d9d0eb9 100644 --- a/lib/common/deprecate.ts +++ b/lib/common/deprecate.ts @@ -3,10 +3,13 @@ type DeprecationHandler = (message: string) => void; let deprecationHandler: DeprecationHandler | null = null; export function warnOnce (oldName: string, newName?: string) { - let warned = false; - const msg = newName + return warnOnceMessage(newName ? `'${oldName}' is deprecated and will be removed. Please use '${newName}' instead.` - : `'${oldName}' is deprecated and will be removed.`; + : `'${oldName}' is deprecated and will be removed.`); +} + +export function warnOnceMessage (msg: string) { + let warned = false; return () => { if (!warned && !process.noDeprecation) { warned = true; diff --git a/shell/browser/api/electron_api_base_window.cc b/shell/browser/api/electron_api_base_window.cc index 0a933a0487..6aa498923e 100644 --- a/shell/browser/api/electron_api_base_window.cc +++ b/shell/browser/api/electron_api_base_window.cc @@ -247,14 +247,6 @@ void BaseWindow::OnWindowLeaveFullScreen() { Emit("leave-full-screen"); } -void BaseWindow::OnWindowScrollTouchBegin() { - Emit("scroll-touch-begin"); -} - -void BaseWindow::OnWindowScrollTouchEnd() { - Emit("scroll-touch-end"); -} - void BaseWindow::OnWindowSwipe(const std::string& direction) { Emit("swipe", direction); } diff --git a/shell/browser/api/electron_api_base_window.h b/shell/browser/api/electron_api_base_window.h index 8ec83b0947..5500006939 100644 --- a/shell/browser/api/electron_api_base_window.h +++ b/shell/browser/api/electron_api_base_window.h @@ -68,8 +68,6 @@ class BaseWindow : public gin_helper::TrackableObject<BaseWindow>, bool* prevent_default) override; void OnWindowMove() override; void OnWindowMoved() override; - void OnWindowScrollTouchBegin() override; - void OnWindowScrollTouchEnd() override; void OnWindowSwipe(const std::string& direction) override; void OnWindowRotateGesture(float rotation) override; void OnWindowSheetBegin() override; diff --git a/shell/browser/api/electron_api_browser_window.cc b/shell/browser/api/electron_api_browser_window.cc index 422512af1e..ea30dba67f 100644 --- a/shell/browser/api/electron_api_browser_window.cc +++ b/shell/browser/api/electron_api_browser_window.cc @@ -106,10 +106,6 @@ BrowserWindow::BrowserWindow(gin::Arguments* args, // Associate with BrowserWindow. web_contents->SetOwnerWindow(window()); - auto* host = web_contents->web_contents()->GetRenderViewHost(); - if (host) - host->GetWidget()->AddInputEventObserver(this); - InitWithArgs(args); // Install the content view after BaseWindow's JS code is initialized. @@ -128,9 +124,6 @@ BrowserWindow::~BrowserWindow() { if (api_web_contents_) { // Cleanup the observers if user destroyed this instance directly instead of // gracefully closing content::WebContents. - auto* host = web_contents()->GetRenderViewHost(); - if (host) - host->GetWidget()->RemoveInputEventObserver(this); api_web_contents_->RemoveObserver(this); // Destroy the WebContents. OnCloseContents(); @@ -138,26 +131,6 @@ BrowserWindow::~BrowserWindow() { } } -void BrowserWindow::OnInputEvent(const blink::WebInputEvent& event) { - switch (event.GetType()) { - case blink::WebInputEvent::Type::kGestureScrollBegin: - case blink::WebInputEvent::Type::kGestureScrollUpdate: - case blink::WebInputEvent::Type::kGestureScrollEnd: - Emit("scroll-touch-edge"); - break; - default: - break; - } -} - -void BrowserWindow::RenderViewHostChanged(content::RenderViewHost* old_host, - content::RenderViewHost* new_host) { - if (old_host) - old_host->GetWidget()->RemoveInputEventObserver(this); - if (new_host) - new_host->GetWidget()->AddInputEventObserver(this); -} - void BrowserWindow::BeforeUnloadDialogCancelled() { WindowList::WindowCloseCancelled(window()); // Cancel unresponsive event when window close is cancelled. diff --git a/shell/browser/api/electron_api_browser_window.h b/shell/browser/api/electron_api_browser_window.h index 94a21f813d..83ea70bbb5 100644 --- a/shell/browser/api/electron_api_browser_window.h +++ b/shell/browser/api/electron_api_browser_window.h @@ -17,7 +17,6 @@ namespace electron::api { class BrowserWindow : public BaseWindow, - public content::RenderWidgetHost::InputEventObserver, public content::WebContentsObserver, public ExtendedWebContentsObserver { public: @@ -43,12 +42,7 @@ class BrowserWindow : public BaseWindow, BrowserWindow(gin::Arguments* args, const gin_helper::Dictionary& options); ~BrowserWindow() override; - // content::RenderWidgetHost::InputEventObserver: - void OnInputEvent(const blink::WebInputEvent& event) override; - // content::WebContentsObserver: - void RenderViewHostChanged(content::RenderViewHost* old_host, - content::RenderViewHost* new_host) override; void BeforeUnloadDialogCancelled() override; void OnRendererUnresponsive(content::RenderProcessHost*) override; void OnRendererResponsive( diff --git a/shell/browser/api/electron_api_web_contents.cc b/shell/browser/api/electron_api_web_contents.cc index 3349fb7a2d..a5c9a93c0f 100644 --- a/shell/browser/api/electron_api_web_contents.cc +++ b/shell/browser/api/electron_api_web_contents.cc @@ -820,6 +820,12 @@ void WebContents::InitZoomController(content::WebContents* web_contents, double zoom_factor; if (options.Get(options::kZoomFactor, &zoom_factor)) zoom_controller_->SetDefaultZoomFactor(zoom_factor); + + // Nothing to do with ZoomController, but this function gets called in all + // init cases! + content::RenderViewHost* host = web_contents->GetRenderViewHost(); + if (host) + host->GetWidget()->AddInputEventObserver(this); } void WebContents::InitWithSessionAndOptions( @@ -957,6 +963,12 @@ void WebContents::InitWithWebContents( } WebContents::~WebContents() { + if (web_contents()) { + content::RenderViewHost* host = web_contents()->GetRenderViewHost(); + if (host) + host->GetWidget()->RemoveInputEventObserver(this); + } + if (!inspectable_web_contents_) { WebContentsDestroyed(); return; @@ -1273,7 +1285,12 @@ content::KeyboardEventProcessingResult WebContents::PreHandleKeyboardEvent( if (event.GetType() == blink::WebInputEvent::Type::kRawKeyDown || event.GetType() == blink::WebInputEvent::Type::kKeyUp) { - bool prevent_default = Emit("before-input-event", event); + // For backwards compatibility, pretend that `kRawKeyDown` events are + // actually `kKeyDown`. + content::NativeWebKeyboardEvent tweaked_event(event); + if (event.GetType() == blink::WebInputEvent::Type::kRawKeyDown) + tweaked_event.SetType(blink::WebInputEvent::Type::kKeyDown); + bool prevent_default = Emit("before-input-event", tweaked_event); if (prevent_default) { return content::KeyboardEventProcessingResult::HANDLED; } @@ -1684,6 +1701,14 @@ void WebContents::OnWebContentsLostFocus( Emit("blur"); } +void WebContents::RenderViewHostChanged(content::RenderViewHost* old_host, + content::RenderViewHost* new_host) { + if (old_host) + old_host->GetWidget()->RemoveInputEventObserver(this); + if (new_host) + new_host->GetWidget()->AddInputEventObserver(this); +} + void WebContents::DOMContentLoaded( content::RenderFrameHost* render_frame_host) { auto* web_frame = WebFrameMain::FromRenderFrameHost(render_frame_host); @@ -3060,6 +3085,9 @@ void WebContents::SendInputEvent(v8::Isolate* isolate, blink::WebKeyboardEvent::Type::kRawKeyDown, blink::WebInputEvent::Modifiers::kNoModifiers, ui::EventTimeForNow()); if (gin::ConvertFromV8(isolate, input_event, &keyboard_event)) { + // For backwards compatibility, convert `kKeyDown` to `kRawKeyDown`. + if (keyboard_event.GetType() == blink::WebKeyboardEvent::Type::kKeyDown) + keyboard_event.SetType(blink::WebKeyboardEvent::Type::kRawKeyDown); rwh->ForwardKeyboardEvent(keyboard_event); return; } @@ -3466,6 +3494,10 @@ void WebContents::SetImageAnimationPolicy(const std::string& new_policy) { web_contents()->OnWebPreferencesChanged(); } +void WebContents::OnInputEvent(const blink::WebInputEvent& event) { + Emit("input-event", event); +} + v8::Local<v8::Promise> WebContents::GetProcessMemoryInfo(v8::Isolate* isolate) { gin_helper::Promise<gin_helper::Dictionary> promise(isolate); v8::Local<v8::Promise> handle = promise.GetHandle(); diff --git a/shell/browser/api/electron_api_web_contents.h b/shell/browser/api/electron_api_web_contents.h index 6aeb8b9375..79f1182672 100644 --- a/shell/browser/api/electron_api_web_contents.h +++ b/shell/browser/api/electron_api_web_contents.h @@ -103,6 +103,7 @@ class WebContents : public ExclusiveAccessContext, public gin_helper::CleanedUpAtExit, public content::WebContentsObserver, public content::WebContentsDelegate, + public content::RenderWidgetHost::InputEventObserver, public InspectableWebContentsDelegate, public InspectableWebContentsViewDelegate { public: @@ -433,6 +434,9 @@ class WebContents : public ExclusiveAccessContext, void SetImageAnimationPolicy(const std::string& new_policy); + // content::RenderWidgetHost::InputEventObserver: + void OnInputEvent(const blink::WebInputEvent& event) override; + // disable copy WebContents(const WebContents&) = delete; WebContents& operator=(const WebContents&) = delete; @@ -616,6 +620,8 @@ class WebContents : public ExclusiveAccessContext, content::RenderWidgetHost* render_widget_host) override; void OnWebContentsLostFocus( content::RenderWidgetHost* render_widget_host) override; + void RenderViewHostChanged(content::RenderViewHost* old_host, + content::RenderViewHost* new_host) override; // InspectableWebContentsDelegate: void DevToolsReloadPage() override; diff --git a/shell/browser/native_window.cc b/shell/browser/native_window.cc index 2440658ba1..37aff64f57 100755 --- a/shell/browser/native_window.cc +++ b/shell/browser/native_window.cc @@ -603,16 +603,6 @@ void NativeWindow::NotifyWindowEnterFullScreen() { observer.OnWindowEnterFullScreen(); } -void NativeWindow::NotifyWindowScrollTouchBegin() { - for (NativeWindowObserver& observer : observers_) - observer.OnWindowScrollTouchBegin(); -} - -void NativeWindow::NotifyWindowScrollTouchEnd() { - for (NativeWindowObserver& observer : observers_) - observer.OnWindowScrollTouchEnd(); -} - void NativeWindow::NotifyWindowSwipe(const std::string& direction) { for (NativeWindowObserver& observer : observers_) observer.OnWindowSwipe(direction); diff --git a/shell/browser/native_window.h b/shell/browser/native_window.h index 6568f03127..e81da9619e 100644 --- a/shell/browser/native_window.h +++ b/shell/browser/native_window.h @@ -291,8 +291,6 @@ class NativeWindow : public base::SupportsUserData, void NotifyWindowResized(); void NotifyWindowWillMove(const gfx::Rect& new_bounds, bool* prevent_default); void NotifyWindowMoved(); - void NotifyWindowScrollTouchBegin(); - void NotifyWindowScrollTouchEnd(); void NotifyWindowSwipe(const std::string& direction); void NotifyWindowRotateGesture(float rotation); void NotifyWindowSheetBegin(); diff --git a/shell/browser/native_window_mac.h b/shell/browser/native_window_mac.h index ef5ab1b10e..390c2997b2 100644 --- a/shell/browser/native_window_mac.h +++ b/shell/browser/native_window_mac.h @@ -228,9 +228,6 @@ class NativeWindowMac : public NativeWindow, base::scoped_nsobject<ElectronPreviewItem> preview_item_; base::scoped_nsobject<ElectronTouchBar> touch_bar_; - // Event monitor for scroll wheel event. - id wheel_event_monitor_; - // The NSView that used as contentView of window. // // For frameless window it would fill the whole window. diff --git a/shell/browser/native_window_mac.mm b/shell/browser/native_window_mac.mm index 2bb5e3a4c5..e66745a547 100644 --- a/shell/browser/native_window_mac.mm +++ b/shell/browser/native_window_mac.mm @@ -418,32 +418,6 @@ NativeWindowMac::NativeWindowMac(const gin_helper::Dictionary& options, options.Get(options::kDisableAutoHideCursor, &disableAutoHideCursor); [window_ setDisableAutoHideCursor:disableAutoHideCursor]; - // Use an NSEvent monitor to listen for the wheel event. - BOOL __block began = NO; - wheel_event_monitor_ = [NSEvent - addLocalMonitorForEventsMatchingMask:NSEventMaskScrollWheel - handler:^(NSEvent* event) { - if ([[event window] windowNumber] != - [window_ windowNumber]) - return event; - - if (!began && (([event phase] == - NSEventPhaseMayBegin) || - ([event phase] == - NSEventPhaseBegan))) { - this->NotifyWindowScrollTouchBegin(); - began = YES; - } else if (began && - (([event phase] == - NSEventPhaseEnded) || - ([event phase] == - NSEventPhaseCancelled))) { - this->NotifyWindowScrollTouchEnd(); - began = NO; - } - return event; - }]; - // Set maximizable state last to ensure zoom button does not get reset // by calls to other APIs. SetMaximizable(maximizable); @@ -1725,10 +1699,6 @@ void NativeWindowMac::Cleanup() { DCHECK(!IsClosed()); ui::NativeTheme::GetInstanceForNativeUi()->RemoveObserver(this); display::Screen::GetScreen()->RemoveObserver(this); - if (wheel_event_monitor_) { - [NSEvent removeMonitor:wheel_event_monitor_]; - wheel_event_monitor_ = nil; - } } void NativeWindowMac::OverrideNSWindowContentView() { diff --git a/shell/browser/native_window_observer.h b/shell/browser/native_window_observer.h index 6cbc941450..2c24406375 100644 --- a/shell/browser/native_window_observer.h +++ b/shell/browser/native_window_observer.h @@ -81,8 +81,6 @@ class NativeWindowObserver : public base::CheckedObserver { bool* prevent_default) {} virtual void OnWindowMove() {} virtual void OnWindowMoved() {} - virtual void OnWindowScrollTouchBegin() {} - virtual void OnWindowScrollTouchEnd() {} virtual void OnWindowSwipe(const std::string& direction) {} virtual void OnWindowRotateGesture(float rotation) {} virtual void OnWindowSheetBegin() {} diff --git a/shell/common/gin_converters/blink_converter.cc b/shell/common/gin_converters/blink_converter.cc index 68ba0307dc..bda0113c05 100644 --- a/shell/common/gin_converters/blink_converter.cc +++ b/shell/common/gin_converters/blink_converter.cc @@ -11,6 +11,7 @@ #include "base/strings/string_util.h" #include "base/strings/utf_string_conversions.h" #include "gin/converter.h" +#include "gin/data_object_builder.h" #include "shell/common/gin_converters/gfx_converter.h" #include "shell/common/gin_converters/gurl_converter.h" #include "shell/common/gin_converters/value_converter.h" @@ -56,43 +57,73 @@ struct Converter<char16_t> { } }; -template <> -struct Converter<blink::WebInputEvent::Type> { - static bool FromV8(v8::Isolate* isolate, - v8::Handle<v8::Value> val, - blink::WebInputEvent::Type* out) { - std::string type = base::ToLowerASCII(gin::V8ToString(isolate, val)); - if (type == "mousedown") - *out = blink::WebInputEvent::Type::kMouseDown; - else if (type == "mouseup") - *out = blink::WebInputEvent::Type::kMouseUp; - else if (type == "mousemove") - *out = blink::WebInputEvent::Type::kMouseMove; - else if (type == "mouseenter") - *out = blink::WebInputEvent::Type::kMouseEnter; - else if (type == "mouseleave") - *out = blink::WebInputEvent::Type::kMouseLeave; - else if (type == "contextmenu") - *out = blink::WebInputEvent::Type::kContextMenu; - else if (type == "mousewheel") - *out = blink::WebInputEvent::Type::kMouseWheel; - else if (type == "keydown") - *out = blink::WebInputEvent::Type::kRawKeyDown; - else if (type == "keyup") - *out = blink::WebInputEvent::Type::kKeyUp; - else if (type == "char") - *out = blink::WebInputEvent::Type::kChar; - else if (type == "touchstart") - *out = blink::WebInputEvent::Type::kTouchStart; - else if (type == "touchmove") - *out = blink::WebInputEvent::Type::kTouchMove; - else if (type == "touchend") - *out = blink::WebInputEvent::Type::kTouchEnd; - else if (type == "touchcancel") - *out = blink::WebInputEvent::Type::kTouchCancel; - return true; +#define BLINK_EVENT_TYPES() \ + CASE_TYPE(kUndefined, "undefined") \ + CASE_TYPE(kMouseDown, "mouseDown") \ + CASE_TYPE(kMouseUp, "mouseUp") \ + CASE_TYPE(kMouseMove, "mouseMove") \ + CASE_TYPE(kMouseEnter, "mouseEnter") \ + CASE_TYPE(kMouseLeave, "mouseLeave") \ + CASE_TYPE(kContextMenu, "contextMenu") \ + CASE_TYPE(kMouseWheel, "mouseWheel") \ + CASE_TYPE(kRawKeyDown, "rawKeyDown") \ + CASE_TYPE(kKeyDown, "keyDown") \ + CASE_TYPE(kKeyUp, "keyUp") \ + CASE_TYPE(kChar, "char") \ + CASE_TYPE(kGestureScrollBegin, "gestureScrollBegin") \ + CASE_TYPE(kGestureScrollEnd, "gestureScrollEnd") \ + CASE_TYPE(kGestureScrollUpdate, "gestureScrollUpdate") \ + CASE_TYPE(kGestureFlingStart, "gestureFlingStart") \ + CASE_TYPE(kGestureFlingCancel, "gestureFlingCancel") \ + CASE_TYPE(kGesturePinchBegin, "gesturePinchBegin") \ + CASE_TYPE(kGesturePinchEnd, "gesturePinchEnd") \ + CASE_TYPE(kGesturePinchUpdate, "gesturePinchUpdate") \ + CASE_TYPE(kGestureTapDown, "gestureTapDown") \ + CASE_TYPE(kGestureShowPress, "gestureShowPress") \ + CASE_TYPE(kGestureTap, "gestureTap") \ + CASE_TYPE(kGestureTapCancel, "gestureTapCancel") \ + CASE_TYPE(kGestureShortPress, "gestureShortPress") \ + CASE_TYPE(kGestureLongPress, "gestureLongPress") \ + CASE_TYPE(kGestureLongTap, "gestureLongTap") \ + CASE_TYPE(kGestureTwoFingerTap, "gestureTwoFingerTap") \ + CASE_TYPE(kGestureTapUnconfirmed, "gestureTapUnconfirmed") \ + CASE_TYPE(kGestureDoubleTap, "gestureDoubleTap") \ + CASE_TYPE(kTouchStart, "touchStart") \ + CASE_TYPE(kTouchMove, "touchMove") \ + CASE_TYPE(kTouchEnd, "touchEnd") \ + CASE_TYPE(kTouchCancel, "touchCancel") \ + CASE_TYPE(kTouchScrollStarted, "touchScrollStarted") \ + CASE_TYPE(kPointerDown, "pointerDown") \ + CASE_TYPE(kPointerUp, "pointerUp") \ + CASE_TYPE(kPointerMove, "pointerMove") \ + CASE_TYPE(kPointerRawUpdate, "pointerRawUpdate") \ + CASE_TYPE(kPointerCancel, "pointerCancel") \ + CASE_TYPE(kPointerCausedUaAction, "pointerCausedUaAction") + +bool Converter<blink::WebInputEvent::Type>::FromV8( + v8::Isolate* isolate, + v8::Handle<v8::Value> val, + blink::WebInputEvent::Type* out) { + std::string type = gin::V8ToString(isolate, val); +#define CASE_TYPE(event_type, js_name) \ + if (base::EqualsCaseInsensitiveASCII(type, js_name)) { \ + *out = blink::WebInputEvent::Type::event_type; \ + return true; \ } -}; + BLINK_EVENT_TYPES() +#undef CASE_TYPE + return false; +} + +v8::Local<v8::Value> Converter<blink::WebInputEvent::Type>::ToV8( + v8::Isolate* isolate, + const blink::WebInputEvent::Type& in) { +#define CASE_TYPE(event_type, js_name) \ + case blink::WebInputEvent::Type::event_type: \ + return StringToV8(isolate, js_name); + switch (in) { BLINK_EVENT_TYPES() } +#undef CASE_TYPE +} template <> struct Converter<blink::WebMouseEvent::Button> { @@ -207,6 +238,19 @@ bool Converter<blink::WebInputEvent>::FromV8(v8::Isolate* isolate, return true; } +v8::Local<v8::Value> Converter<blink::WebInputEvent>::ToV8( + v8::Isolate* isolate, + const blink::WebInputEvent& in) { + if (blink::WebInputEvent::IsKeyboardEventType(in.GetType())) + return gin::ConvertToV8(isolate, + *static_cast<const blink::WebKeyboardEvent*>(&in)); + return gin::DataObjectBuilder(isolate) + .Set("type", in.GetType()) + .Set("modifiers", ModifiersToArray(in.GetModifiers())) + .Set("_modifiers", in.GetModifiers()) + .Build(); +} + bool Converter<blink::WebKeyboardEvent>::FromV8(v8::Isolate* isolate, v8::Local<v8::Value> val, blink::WebKeyboardEvent* out) { @@ -276,10 +320,7 @@ v8::Local<v8::Value> Converter<blink::WebKeyboardEvent>::ToV8( const blink::WebKeyboardEvent& in) { gin_helper::Dictionary dict = gin::Dictionary::CreateEmpty(isolate); - if (in.GetType() == blink::WebInputEvent::Type::kRawKeyDown) - dict.Set("type", "keyDown"); - else if (in.GetType() == blink::WebInputEvent::Type::kKeyUp) - dict.Set("type", "keyUp"); + dict.Set("type", in.GetType()); dict.Set("key", ui::KeycodeConverter::DomKeyToKeyString(in.dom_key)); dict.Set("code", ui::KeycodeConverter::DomCodeToCodeString( static_cast<ui::DomCode>(in.dom_code))); diff --git a/shell/common/gin_converters/blink_converter.h b/shell/common/gin_converters/blink_converter.h index 8ae85d7506..38017310fb 100644 --- a/shell/common/gin_converters/blink_converter.h +++ b/shell/common/gin_converters/blink_converter.h @@ -24,11 +24,22 @@ namespace gin { blink::WebInputEvent::Type GetWebInputEventType(v8::Isolate* isolate, v8::Local<v8::Value> val); +template <> +struct Converter<blink::WebInputEvent::Type> { + static bool FromV8(v8::Isolate* isolate, + v8::Local<v8::Value> val, + blink::WebInputEvent::Type* out); + static v8::Local<v8::Value> ToV8(v8::Isolate* isolate, + const blink::WebInputEvent::Type& in); +}; + template <> struct Converter<blink::WebInputEvent> { static bool FromV8(v8::Isolate* isolate, v8::Local<v8::Value> val, blink::WebInputEvent* out); + static v8::Local<v8::Value> ToV8(v8::Isolate* isolate, + const blink::WebInputEvent& in); }; template <>
feat
7529ebfe0e20ff0456aaab29c22346e35cf074ce
John Kleinschmidt
2022-11-17 17:49:12
fix: remove unneeded --turbo-profiling-input arg from mksnapshot_args (#36378) fix: remove unneeded --turbo-profiling-input args from mksnapshot_args
diff --git a/.circleci/config/base.yml b/.circleci/config/base.yml index 368fc15d6e..bfd6567296 100644 --- a/.circleci/config/base.yml +++ b/.circleci/config/base.yml @@ -701,6 +701,13 @@ step-mksnapshot-build: &step-mksnapshot-build if [ "$USE_PREBUILT_V8_CONTEXT_SNAPSHOT" != "1" ]; then ninja -C out/Default electron:electron_mksnapshot -j $NUMBER_OF_NINJA_PROCESSES gn desc out/Default v8:run_mksnapshot_default args > out/Default/mksnapshot_args + # Remove unused args from mksnapshot_args + SEDOPTION= + if [ "`uname`" == "Darwin" ]; then + SEDOPTION="-i ''" + fi + sed $SEDOPTION '/.*builtins-pgo/d' out/Default/mksnapshot_args + sed $SEDOPTION '/--turbo-profiling-input/d' out/Default/mksnapshot_args fi if [ "`uname`" != "Darwin" ]; then if [ "$TARGET_ARCH" == "arm" ]; then @@ -1216,6 +1223,13 @@ commands: ninja -C out/Default electron:electron_mksnapshot_zip -j $NUMBER_OF_NINJA_PROCESSES ninja -C out/Default tools/v8_context_snapshot -j $NUMBER_OF_NINJA_PROCESSES gn desc out/Default v8:run_mksnapshot_default args > out/Default/mksnapshot_args + # Remove unused args from mksnapshot_args + SEDOPTION= + if [ "`uname`" == "Darwin" ]; then + SEDOPTION="-i ''" + fi + sed $SEDOPTION '/.*builtins-pgo/d' out/Default/mksnapshot_args + sed $SEDOPTION '/--turbo-profiling-input/d' out/Default/mksnapshot_args (cd out/Default; zip mksnapshot.zip mksnapshot_args clang_x64_v8_arm64/gen/v8/embedded.S) if [ "<< parameters.clean-prebuilt-snapshot >>" == "true" ]; then rm -rf out/Default/clang_x64_v8_arm64/gen diff --git a/appveyor.yml b/appveyor.yml index 914b9f8826..86dcc96ea8 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -179,7 +179,11 @@ for: - ninja -C out/ffmpeg electron:electron_ffmpeg_zip - ninja -C out/Default electron:electron_dist_zip - ninja -C out/Default shell_browser_ui_unittests - - gn desc out/Default v8:run_mksnapshot_default args > out/Default/mksnapshot_args + - gn desc out/Default v8:run_mksnapshot_default args > out/Default/default_mksnapshot_args + - ps: >- + # Remove unused args from mksnapshot_args + + Get-Content out/Default/default_mksnapshot_args | Where-Object { -not $_.Contains('--turbo-profiling-input') -And -not $_.Contains('builtins-pgo') } | Set-Content out/Default/mksnapshot_args - ninja -C out/Default electron:electron_mksnapshot_zip - cd out\Default - 7z a mksnapshot.zip mksnapshot_args gen\v8\embedded.S @@ -190,7 +194,6 @@ for: - python %LOCAL_GOMA_DIR%\goma_ctl.py stat - python3 electron/build/profile_toolchain.py --output-json=out/Default/windows_toolchain_profile.json - 7z a node_headers.zip out\Default\gen\node_headers - - 7z a builtins-pgo.zip v8\tools\builtins-pgo - ps: >- if ($env:GN_CONFIG -eq 'release') { # Needed for msdia140.dll on 64-bit windows @@ -235,7 +238,6 @@ for: - if exist out\Default\mksnapshot.zip (appveyor-retry appveyor PushArtifact out\Default\mksnapshot.zip) - if exist out\Default\hunspell_dictionaries.zip (appveyor-retry appveyor PushArtifact out\Default\hunspell_dictionaries.zip) - if exist out\Default\electron.lib (appveyor-retry appveyor PushArtifact out\Default\electron.lib) - - if exist builtins-pgo.zip (appveyor-retry appveyor PushArtifact builtins-pgo.zip) - ps: >- if ((Test-Path "pdb.zip") -And ($env:GN_CONFIG -ne 'release')) { appveyor-retry appveyor PushArtifact pdb.zip @@ -269,7 +271,7 @@ for: # Download build artifacts $apiUrl = 'https://ci.appveyor.com/api' $build_info = Invoke-RestMethod -Method Get -Uri "$apiUrl/projects/$env:APPVEYOR_ACCOUNT_NAME/$env:APPVEYOR_PROJECT_SLUG/builds/$env:APPVEYOR_BUILD_ID" - $artifacts_to_download = @('dist.zip','shell_browser_ui_unittests.exe','chromedriver.zip','ffmpeg.zip','node_headers.zip','mksnapshot.zip','electron.lib','builtins-pgo.zip') + $artifacts_to_download = @('dist.zip','shell_browser_ui_unittests.exe','chromedriver.zip','ffmpeg.zip','node_headers.zip','mksnapshot.zip','electron.lib') foreach ($job in $build_info.build.jobs) { if ($job.name -eq "Build") { $jobId = $job.jobId @@ -290,7 +292,6 @@ for: } - ps: 7z x -y -osrc\out\ffmpeg ffmpeg.zip - ps: 7z x -y -osrc node_headers.zip - - ps: 7z x -y -osrc builtins-pgo.zip test_script: # Workaround for https://github.com/appveyor/ci/issues/2420
fix
db27b9f433f6681c42c9f22910d5908e172a67fe
David Sanders
2023-04-05 06:42:20
chore: initial linting fixes for JS in docs/fiddles (#37689)
diff --git a/docs/fiddles/features/drag-and-drop/main.js b/docs/fiddles/features/drag-and-drop/main.js index 9ad158beaf..db617ba27d 100644 --- a/docs/fiddles/features/drag-and-drop/main.js +++ b/docs/fiddles/features/drag-and-drop/main.js @@ -1,9 +1,9 @@ -const { app, BrowserWindow, ipcMain, nativeImage, NativeImage } = require('electron') +const { app, BrowserWindow, ipcMain } = require('electron') const path = require('path') const fs = require('fs') const https = require('https') -function createWindow() { +function createWindow () { const win = new BrowserWindow({ width: 800, height: 600, @@ -15,23 +15,23 @@ function createWindow() { win.loadFile('index.html') } -const iconName = path.join(__dirname, 'iconForDragAndDrop.png'); -const icon = fs.createWriteStream(iconName); +const iconName = path.join(__dirname, 'iconForDragAndDrop.png') +const icon = fs.createWriteStream(iconName) // Create a new file to copy - you can also copy existing files. fs.writeFileSync(path.join(__dirname, 'drag-and-drop-1.md'), '# First file to test drag and drop') fs.writeFileSync(path.join(__dirname, 'drag-and-drop-2.md'), '# Second file to test drag and drop') https.get('https://img.icons8.com/ios/452/drag-and-drop.png', (response) => { - response.pipe(icon); -}); + response.pipe(icon) +}) app.whenReady().then(createWindow) ipcMain.on('ondragstart', (event, filePath) => { event.sender.startDrag({ file: path.join(__dirname, filePath), - icon: iconName, + icon: iconName }) }) diff --git a/docs/fiddles/features/keyboard-shortcuts/global/main.js b/docs/fiddles/features/keyboard-shortcuts/global/main.js index 24b2d343fb..8b43433a4a 100644 --- a/docs/fiddles/features/keyboard-shortcuts/global/main.js +++ b/docs/fiddles/features/keyboard-shortcuts/global/main.js @@ -3,7 +3,7 @@ const { app, BrowserWindow, globalShortcut } = require('electron') function createWindow () { const win = new BrowserWindow({ width: 800, - height: 600, + height: 600 }) win.loadFile('index.html') diff --git a/docs/fiddles/features/keyboard-shortcuts/local/main.js b/docs/fiddles/features/keyboard-shortcuts/local/main.js index c583469df4..6abd81b1be 100644 --- a/docs/fiddles/features/keyboard-shortcuts/local/main.js +++ b/docs/fiddles/features/keyboard-shortcuts/local/main.js @@ -3,7 +3,7 @@ const { app, BrowserWindow, Menu, MenuItem } = require('electron') function createWindow () { const win = new BrowserWindow({ width: 800, - height: 600, + height: 600 }) win.loadFile('index.html') diff --git a/docs/fiddles/features/keyboard-shortcuts/web-apis/main.js b/docs/fiddles/features/keyboard-shortcuts/web-apis/main.js index 876d7632b2..7803cd859d 100644 --- a/docs/fiddles/features/keyboard-shortcuts/web-apis/main.js +++ b/docs/fiddles/features/keyboard-shortcuts/web-apis/main.js @@ -1,17 +1,15 @@ // Modules to control application life and create native browser window -const {app, BrowserWindow} = require('electron') -const path = require('path') +const { app, BrowserWindow } = require('electron') function createWindow () { // Create the browser window. const mainWindow = new BrowserWindow({ width: 800, - height: 600, + height: 600 }) // and load the index.html of the app. mainWindow.loadFile('index.html') - } // This method will be called when Electron has finished diff --git a/docs/fiddles/features/keyboard-shortcuts/web-apis/renderer.js b/docs/fiddles/features/keyboard-shortcuts/web-apis/renderer.js index 7f7e406c4b..e3e0520920 100644 --- a/docs/fiddles/features/keyboard-shortcuts/web-apis/renderer.js +++ b/docs/fiddles/features/keyboard-shortcuts/web-apis/renderer.js @@ -1,6 +1,6 @@ function handleKeyPress (event) { // You can put code here to handle the keypress. - document.getElementById("last-keypress").innerText = event.key + document.getElementById('last-keypress').innerText = event.key console.log(`You pressed ${event.key}`) } diff --git a/docs/fiddles/features/macos-dock-menu/main.js b/docs/fiddles/features/macos-dock-menu/main.js index f7f86a2361..7809e5459c 100644 --- a/docs/fiddles/features/macos-dock-menu/main.js +++ b/docs/fiddles/features/macos-dock-menu/main.js @@ -3,7 +3,7 @@ const { app, BrowserWindow, Menu } = require('electron') function createWindow () { const win = new BrowserWindow({ width: 800, - height: 600, + height: 600 }) win.loadFile('index.html') diff --git a/docs/fiddles/features/notifications/renderer/renderer.js b/docs/fiddles/features/notifications/renderer/renderer.js index a6c88f9a79..3b782f1f17 100644 --- a/docs/fiddles/features/notifications/renderer/renderer.js +++ b/docs/fiddles/features/notifications/renderer/renderer.js @@ -3,4 +3,4 @@ const NOTIFICATION_BODY = 'Notification from the Renderer process. Click to log const CLICK_MESSAGE = 'Notification clicked!' new Notification(NOTIFICATION_TITLE, { body: NOTIFICATION_BODY }) - .onclick = () => document.getElementById("output").innerText = CLICK_MESSAGE + .onclick = () => document.getElementById('output').innerText = CLICK_MESSAGE diff --git a/docs/fiddles/features/represented-file/main.js b/docs/fiddles/features/represented-file/main.js index 204a3fc458..387047b5d0 100644 --- a/docs/fiddles/features/represented-file/main.js +++ b/docs/fiddles/features/represented-file/main.js @@ -1,5 +1,5 @@ const { app, BrowserWindow } = require('electron') -const os = require('os'); +const os = require('os') function createWindow () { const win = new BrowserWindow({ diff --git a/docs/fiddles/features/web-bluetooth/main.js b/docs/fiddles/features/web-bluetooth/main.js index 4d6e6d38e2..e5fd0110ba 100644 --- a/docs/fiddles/features/web-bluetooth/main.js +++ b/docs/fiddles/features/web-bluetooth/main.js @@ -1,4 +1,4 @@ -const {app, BrowserWindow, ipcMain} = require('electron') +const { app, BrowserWindow, ipcMain } = require('electron') const path = require('path') let bluetoothPinCallback @@ -38,7 +38,6 @@ function createWindow () { }) mainWindow.webContents.session.setBluetoothPairingHandler((details, callback) => { - bluetoothPinCallback = callback // Send a message to the renderer to prompt the user to confirm the pairing. mainWindow.webContents.send('bluetooth-pairing-request', details) diff --git a/docs/fiddles/features/web-bluetooth/preload.js b/docs/fiddles/features/web-bluetooth/preload.js index a8d3056036..d10666b7ee 100644 --- a/docs/fiddles/features/web-bluetooth/preload.js +++ b/docs/fiddles/features/web-bluetooth/preload.js @@ -4,4 +4,4 @@ contextBridge.exposeInMainWorld('electronAPI', { cancelBluetoothRequest: (callback) => ipcRenderer.send('cancel-bluetooth-request', callback), bluetoothPairingRequest: (callback) => ipcRenderer.on('bluetooth-pairing-request', callback), bluetoothPairingResponse: (response) => ipcRenderer.send('bluetooth-pairing-response', response) -}) \ No newline at end of file +}) diff --git a/docs/fiddles/features/web-bluetooth/renderer.js b/docs/fiddles/features/web-bluetooth/renderer.js index 241c253de0..24f8cec1fc 100644 --- a/docs/fiddles/features/web-bluetooth/renderer.js +++ b/docs/fiddles/features/web-bluetooth/renderer.js @@ -1,11 +1,11 @@ -async function testIt() { +async function testIt () { const device = await navigator.bluetooth.requestDevice({ acceptAllDevices: true }) document.getElementById('device-name').innerHTML = device.name || `ID: ${device.id}` } -document.getElementById('clickme').addEventListener('click',testIt) +document.getElementById('clickme').addEventListener('click', testIt) function cancelRequest() { window.electronAPI.cancelBluetoothRequest() @@ -37,4 +37,4 @@ window.electronAPI.bluetoothPairingRequest((event, details) => { } window.electronAPI.bluetoothPairingResponse(response) -}) \ No newline at end of file +}) diff --git a/docs/fiddles/features/web-hid/main.js b/docs/fiddles/features/web-hid/main.js index 5626a919be..b5dcb5aea4 100644 --- a/docs/fiddles/features/web-hid/main.js +++ b/docs/fiddles/features/web-hid/main.js @@ -1,5 +1,4 @@ -const {app, BrowserWindow} = require('electron') -const path = require('path') +const { app, BrowserWindow } = require('electron') function createWindow () { const mainWindow = new BrowserWindow({ @@ -8,16 +7,16 @@ function createWindow () { }) mainWindow.webContents.session.on('select-hid-device', (event, details, callback) => { - //Add events to handle devices being added or removed before the callback on - //`select-hid-device` is called. + // Add events to handle devices being added or removed before the callback on + // `select-hid-device` is called. mainWindow.webContents.session.on('hid-device-added', (event, device) => { console.log('hid-device-added FIRED WITH', device) - //Optionally update details.deviceList + // Optionally update details.deviceList }) mainWindow.webContents.session.on('hid-device-removed', (event, device) => { console.log('hid-device-removed FIRED WITH', device) - //Optionally update details.deviceList + // Optionally update details.deviceList }) event.preventDefault() diff --git a/docs/fiddles/features/web-hid/renderer.js b/docs/fiddles/features/web-hid/renderer.js index 54bda3f977..cbb00ab08f 100644 --- a/docs/fiddles/features/web-hid/renderer.js +++ b/docs/fiddles/features/web-hid/renderer.js @@ -1,4 +1,4 @@ -async function testIt() { +async function testIt () { const grantedDevices = await navigator.hid.getDevices() let grantedDeviceList = '' grantedDevices.forEach(device => { @@ -10,10 +10,10 @@ async function testIt() { }) grantedDeviceList = '' - grantedDevices2.forEach(device => { + grantedDevices2.forEach(device => { grantedDeviceList += `<hr>${device.productName}</hr>` }) document.getElementById('granted-devices2').innerHTML = grantedDeviceList } -document.getElementById('clickme').addEventListener('click',testIt) +document.getElementById('clickme').addEventListener('click', testIt) diff --git a/docs/fiddles/features/web-serial/main.js b/docs/fiddles/features/web-serial/main.js index e88c509fc4..55d40d2038 100644 --- a/docs/fiddles/features/web-serial/main.js +++ b/docs/fiddles/features/web-serial/main.js @@ -1,5 +1,4 @@ -const {app, BrowserWindow} = require('electron') -const path = require('path') +const { app, BrowserWindow } = require('electron') function createWindow () { const mainWindow = new BrowserWindow({ @@ -8,24 +7,23 @@ function createWindow () { }) mainWindow.webContents.session.on('select-serial-port', (event, portList, webContents, callback) => { - - //Add listeners to handle ports being added or removed before the callback for `select-serial-port` - //is called. + // Add listeners to handle ports being added or removed before the callback for `select-serial-port` + // is called. mainWindow.webContents.session.on('serial-port-added', (event, port) => { console.log('serial-port-added FIRED WITH', port) - //Optionally update portList to add the new port + // Optionally update portList to add the new port }) mainWindow.webContents.session.on('serial-port-removed', (event, port) => { console.log('serial-port-removed FIRED WITH', port) - //Optionally update portList to remove the port + // Optionally update portList to remove the port }) event.preventDefault() if (portList && portList.length > 0) { callback(portList[0].portId) } else { - callback('') //Could not find any matching devices + callback('') // Could not find any matching devices } }) diff --git a/docs/fiddles/features/web-serial/renderer.js b/docs/fiddles/features/web-serial/renderer.js index 1d684d2192..2c5eb36980 100644 --- a/docs/fiddles/features/web-serial/renderer.js +++ b/docs/fiddles/features/web-serial/renderer.js @@ -1,11 +1,11 @@ -async function testIt() { +async function testIt () { const filters = [ { usbVendorId: 0x2341, usbProductId: 0x0043 }, { usbVendorId: 0x2341, usbProductId: 0x0001 } - ]; + ] try { - const port = await navigator.serial.requestPort({filters}); - const portInfo = port.getInfo(); + const port = await navigator.serial.requestPort({ filters }) + const portInfo = port.getInfo() document.getElementById('device-name').innerHTML = `vendorId: ${portInfo.usbVendorId} | productId: ${portInfo.usbProductId} ` } catch (ex) { if (ex.name === 'NotFoundError') { @@ -16,4 +16,4 @@ async function testIt() { } } -document.getElementById('clickme').addEventListener('click',testIt) +document.getElementById('clickme').addEventListener('click', testIt) diff --git a/docs/fiddles/features/web-usb/main.js b/docs/fiddles/features/web-usb/main.js index 14983093c6..2534ae97cb 100644 --- a/docs/fiddles/features/web-usb/main.js +++ b/docs/fiddles/features/web-usb/main.js @@ -1,5 +1,4 @@ -const {app, BrowserWindow} = require('electron') -const path = require('path') +const { app, BrowserWindow } = require('electron') function createWindow () { const mainWindow = new BrowserWindow({ @@ -10,22 +9,22 @@ function createWindow () { let grantedDeviceThroughPermHandler mainWindow.webContents.session.on('select-usb-device', (event, details, callback) => { - //Add events to handle devices being added or removed before the callback on - //`select-usb-device` is called. + // Add events to handle devices being added or removed before the callback on + // `select-usb-device` is called. mainWindow.webContents.session.on('usb-device-added', (event, device) => { console.log('usb-device-added FIRED WITH', device) - //Optionally update details.deviceList + // Optionally update details.deviceList }) mainWindow.webContents.session.on('usb-device-removed', (event, device) => { console.log('usb-device-removed FIRED WITH', device) - //Optionally update details.deviceList + // Optionally update details.deviceList }) event.preventDefault() if (details.deviceList && details.deviceList.length > 0) { - const deviceToReturn = details.deviceList.find((device) => { - if (!grantedDeviceThroughPermHandler || (device.deviceId != grantedDeviceThroughPermHandler.deviceId)) { + const deviceToReturn = details.deviceList.find((device) => { + if (!grantedDeviceThroughPermHandler || (device.deviceId !== grantedDeviceThroughPermHandler.deviceId)) { return true } }) diff --git a/docs/fiddles/features/web-usb/renderer.js b/docs/fiddles/features/web-usb/renderer.js index 8544353f0f..d55b0ccef7 100644 --- a/docs/fiddles/features/web-usb/renderer.js +++ b/docs/fiddles/features/web-usb/renderer.js @@ -1,8 +1,8 @@ -function getDeviceDetails(device) { +function getDeviceDetails (device) { return device.productName || `Unknown device ${device.deviceId}` } -async function testIt() { +async function testIt () { const noDevicesFoundMsg = 'No devices found' const grantedDevices = await navigator.usb.getDevices() let grantedDeviceList = '' @@ -21,7 +21,6 @@ async function testIt() { filters: [] }) grantedDeviceList += `<hr>${getDeviceDetails(device)}</hr>` - } catch (ex) { if (ex.name === 'NotFoundError') { grantedDeviceList = noDevicesFoundMsg @@ -30,4 +29,4 @@ async function testIt() { document.getElementById('granted-devices2').innerHTML = grantedDeviceList } -document.getElementById('clickme').addEventListener('click',testIt) +document.getElementById('clickme').addEventListener('click', testIt) diff --git a/docs/fiddles/ipc/pattern-1/main.js b/docs/fiddles/ipc/pattern-1/main.js index c561edc783..567baf4029 100644 --- a/docs/fiddles/ipc/pattern-1/main.js +++ b/docs/fiddles/ipc/pattern-1/main.js @@ -1,4 +1,4 @@ -const {app, BrowserWindow, ipcMain} = require('electron') +const { app, BrowserWindow, ipcMain } = require('electron') const path = require('path') function createWindow () { diff --git a/docs/fiddles/ipc/pattern-1/preload.js b/docs/fiddles/ipc/pattern-1/preload.js index 822f4ed516..50b3f3d4b1 100644 --- a/docs/fiddles/ipc/pattern-1/preload.js +++ b/docs/fiddles/ipc/pattern-1/preload.js @@ -1,5 +1,5 @@ const { contextBridge, ipcRenderer } = require('electron') contextBridge.exposeInMainWorld('electronAPI', { - setTitle: (title) => ipcRenderer.send('set-title', title) + setTitle: (title) => ipcRenderer.send('set-title', title) }) diff --git a/docs/fiddles/ipc/pattern-1/renderer.js b/docs/fiddles/ipc/pattern-1/renderer.js index c44f59a8df..67b775fa53 100644 --- a/docs/fiddles/ipc/pattern-1/renderer.js +++ b/docs/fiddles/ipc/pattern-1/renderer.js @@ -1,6 +1,6 @@ const setButton = document.getElementById('btn') const titleInput = document.getElementById('title') setButton.addEventListener('click', () => { - const title = titleInput.value - window.electronAPI.setTitle(title) -}); + const title = titleInput.value + window.electronAPI.setTitle(title) +}) diff --git a/docs/fiddles/ipc/pattern-2/main.js b/docs/fiddles/ipc/pattern-2/main.js index 5492a7d159..7257ab117b 100644 --- a/docs/fiddles/ipc/pattern-2/main.js +++ b/docs/fiddles/ipc/pattern-2/main.js @@ -1,10 +1,10 @@ -const {app, BrowserWindow, ipcMain, dialog} = require('electron') +const { app, BrowserWindow, ipcMain, dialog } = require('electron') const path = require('path') -async function handleFileOpen() { +async function handleFileOpen () { const { canceled, filePaths } = await dialog.showOpenDialog() if (canceled) { - return + } else { return filePaths[0] } diff --git a/docs/fiddles/ipc/pattern-2/preload.js b/docs/fiddles/ipc/pattern-2/preload.js index cb78f84230..5f2f6e2205 100644 --- a/docs/fiddles/ipc/pattern-2/preload.js +++ b/docs/fiddles/ipc/pattern-2/preload.js @@ -1,5 +1,5 @@ const { contextBridge, ipcRenderer } = require('electron') -contextBridge.exposeInMainWorld('electronAPI',{ +contextBridge.exposeInMainWorld('electronAPI', { openFile: () => ipcRenderer.invoke('dialog:openFile') }) diff --git a/docs/fiddles/ipc/pattern-3/main.js b/docs/fiddles/ipc/pattern-3/main.js index 4f1e1b4bf1..4c2334dfb0 100644 --- a/docs/fiddles/ipc/pattern-3/main.js +++ b/docs/fiddles/ipc/pattern-3/main.js @@ -1,4 +1,4 @@ -const {app, BrowserWindow, Menu, ipcMain} = require('electron') +const { app, BrowserWindow, Menu, ipcMain } = require('electron') const path = require('path') function createWindow () { @@ -12,14 +12,14 @@ function createWindow () { { label: app.name, submenu: [ - { - click: () => mainWindow.webContents.send('update-counter', 1), - label: 'Increment', - }, - { - click: () => mainWindow.webContents.send('update-counter', -1), - label: 'Decrement', - } + { + click: () => mainWindow.webContents.send('update-counter', 1), + label: 'Increment' + }, + { + click: () => mainWindow.webContents.send('update-counter', -1), + label: 'Decrement' + } ] } diff --git a/docs/fiddles/ipc/pattern-3/renderer.js b/docs/fiddles/ipc/pattern-3/renderer.js index 04fd4bca89..d7316a5d87 100644 --- a/docs/fiddles/ipc/pattern-3/renderer.js +++ b/docs/fiddles/ipc/pattern-3/renderer.js @@ -1,8 +1,8 @@ const counter = document.getElementById('counter') window.electronAPI.handleCounter((event, value) => { - const oldValue = Number(counter.innerText) - const newValue = oldValue + value - counter.innerText = newValue - event.sender.send('counter-value', newValue) + const oldValue = Number(counter.innerText) + const newValue = oldValue + value + counter.innerText = newValue + event.sender.send('counter-value', newValue) }) diff --git a/docs/fiddles/native-ui/dialogs/error-dialog/renderer.js b/docs/fiddles/native-ui/dialogs/error-dialog/renderer.js index 4011066587..a0221af5ef 100644 --- a/docs/fiddles/native-ui/dialogs/error-dialog/renderer.js +++ b/docs/fiddles/native-ui/dialogs/error-dialog/renderer.js @@ -15,4 +15,4 @@ Array.prototype.forEach.call(links, (link) => { shell.openExternal(url) }) } -}) \ No newline at end of file +}) diff --git a/docs/fiddles/native-ui/dialogs/information-dialog/main.js b/docs/fiddles/native-ui/dialogs/information-dialog/main.js index 3e81a57820..e30f8c378b 100644 --- a/docs/fiddles/native-ui/dialogs/information-dialog/main.js +++ b/docs/fiddles/native-ui/dialogs/information-dialog/main.js @@ -52,7 +52,6 @@ app.on('activate', function () { } }) - ipcMain.on('open-information-dialog', event => { const options = { type: 'info', @@ -65,6 +64,5 @@ ipcMain.on('open-information-dialog', event => { }) }) - // In this file you can include the rest of your app's specific main process // code. You can also put them in separate files and require them here. diff --git a/docs/fiddles/native-ui/dialogs/information-dialog/renderer.js b/docs/fiddles/native-ui/dialogs/information-dialog/renderer.js index 69ea9cdb1a..5e46971b27 100644 --- a/docs/fiddles/native-ui/dialogs/information-dialog/renderer.js +++ b/docs/fiddles/native-ui/dialogs/information-dialog/renderer.js @@ -22,4 +22,4 @@ Array.prototype.forEach.call(links, (link) => { shell.openExternal(url) }) } -}) \ No newline at end of file +}) diff --git a/docs/fiddles/native-ui/dialogs/open-file-or-directory/main.js b/docs/fiddles/native-ui/dialogs/open-file-or-directory/main.js index 24b9164dab..b3f4b42926 100644 --- a/docs/fiddles/native-ui/dialogs/open-file-or-directory/main.js +++ b/docs/fiddles/native-ui/dialogs/open-file-or-directory/main.js @@ -52,7 +52,6 @@ app.on('activate', function () { } }) - ipcMain.on('open-file-dialog', event => { dialog.showOpenDialog( { diff --git a/docs/fiddles/native-ui/dialogs/save-dialog/renderer.js b/docs/fiddles/native-ui/dialogs/save-dialog/renderer.js index 9f6da55469..db9bb5c1d4 100644 --- a/docs/fiddles/native-ui/dialogs/save-dialog/renderer.js +++ b/docs/fiddles/native-ui/dialogs/save-dialog/renderer.js @@ -20,4 +20,4 @@ Array.prototype.forEach.call(links, (link) => { shell.openExternal(url) }) } -}) \ No newline at end of file +}) diff --git a/docs/fiddles/quick-start/main.js b/docs/fiddles/quick-start/main.js index 519a67947c..ba8a65d05d 100644 --- a/docs/fiddles/quick-start/main.js +++ b/docs/fiddles/quick-start/main.js @@ -28,4 +28,3 @@ app.on('window-all-closed', () => { app.quit() } }) - diff --git a/docs/fiddles/quick-start/preload.js b/docs/fiddles/quick-start/preload.js index 7674d01224..d5f73597ee 100644 --- a/docs/fiddles/quick-start/preload.js +++ b/docs/fiddles/quick-start/preload.js @@ -8,4 +8,3 @@ window.addEventListener('DOMContentLoaded', () => { replaceText(`${type}-version`, process.versions[type]) } }) - diff --git a/docs/fiddles/system/protocol-handler/launch-app-from-URL-in-another-app/main.js b/docs/fiddles/system/protocol-handler/launch-app-from-URL-in-another-app/main.js index fafb18143d..154ba38020 100644 --- a/docs/fiddles/system/protocol-handler/launch-app-from-URL-in-another-app/main.js +++ b/docs/fiddles/system/protocol-handler/launch-app-from-URL-in-another-app/main.js @@ -2,14 +2,14 @@ const { app, BrowserWindow, ipcMain, shell, dialog } = require('electron') const path = require('path') -let mainWindow; +let mainWindow if (process.defaultApp) { if (process.argv.length >= 2) { app.setAsDefaultProtocolClient('electron-fiddle', process.execPath, [path.resolve(process.argv[1])]) } } else { - app.setAsDefaultProtocolClient('electron-fiddle') + app.setAsDefaultProtocolClient('electron-fiddle') } const gotTheLock = app.requestSingleInstanceLock() @@ -24,7 +24,7 @@ if (!gotTheLock) { mainWindow.focus() } - dialog.showErrorBox('Welcome Back', `You arrived from: ${commandLine.pop().slice(0,-1)}`) + dialog.showErrorBox('Welcome Back', `You arrived from: ${commandLine.pop().slice(0, -1)}`) }) // Create mainWindow, load the rest of the app, etc... @@ -43,7 +43,7 @@ function createWindow () { width: 800, height: 600, webPreferences: { - preload: path.join(__dirname, 'preload.js'), + preload: path.join(__dirname, 'preload.js') } }) diff --git a/docs/fiddles/system/protocol-handler/launch-app-from-URL-in-another-app/preload.js b/docs/fiddles/system/protocol-handler/launch-app-from-URL-in-another-app/preload.js index 1eebf784ad..13e803ad9c 100644 --- a/docs/fiddles/system/protocol-handler/launch-app-from-URL-in-another-app/preload.js +++ b/docs/fiddles/system/protocol-handler/launch-app-from-URL-in-another-app/preload.js @@ -6,6 +6,6 @@ const { contextBridge, ipcRenderer } = require('electron') contextBridge.exposeInMainWorld( 'shell', { - open: () => ipcRenderer.send('shell:open'), + open: () => ipcRenderer.send('shell:open') } -) \ No newline at end of file +) diff --git a/docs/fiddles/system/protocol-handler/launch-app-from-URL-in-another-app/renderer.js b/docs/fiddles/system/protocol-handler/launch-app-from-URL-in-another-app/renderer.js index 525f25ff2e..a933c04e70 100644 --- a/docs/fiddles/system/protocol-handler/launch-app-from-URL-in-another-app/renderer.js +++ b/docs/fiddles/system/protocol-handler/launch-app-from-URL-in-another-app/renderer.js @@ -4,5 +4,5 @@ // Binds the buttons to the context bridge API. document.getElementById('open-in-browser').addEventListener('click', () => { - shell.open(); -}); \ No newline at end of file + window.shell.open() +}) diff --git a/docs/fiddles/system/system-app-user-information/app-information/main.js b/docs/fiddles/system/system-app-user-information/app-information/main.js index 64141f98e8..97e612c4b2 100644 --- a/docs/fiddles/system/system-app-user-information/app-information/main.js +++ b/docs/fiddles/system/system-app-user-information/app-information/main.js @@ -1,5 +1,5 @@ -const {app, ipcMain} = require('electron') +const { app, ipcMain } = require('electron') ipcMain.on('get-app-path', (event) => { event.sender.send('got-app-path', app.getAppPath()) -}) \ No newline at end of file +}) diff --git a/docs/fiddles/system/system-app-user-information/app-information/renderer.js b/docs/fiddles/system/system-app-user-information/app-information/renderer.js index 3f971abcab..6a348da871 100644 --- a/docs/fiddles/system/system-app-user-information/app-information/renderer.js +++ b/docs/fiddles/system/system-app-user-information/app-information/renderer.js @@ -1,4 +1,4 @@ -const {ipcRenderer} = require('electron') +const { ipcRenderer } = require('electron') const appInfoBtn = document.getElementById('app-info') const electron_doc_link = document.querySelectorAll('a[href]') @@ -15,4 +15,4 @@ ipcRenderer.on('got-app-path', (event, path) => { electron_doc_link.addEventListener('click', (e) => { e.preventDefault() shell.openExternal(url) -}) \ No newline at end of file +}) diff --git a/docs/fiddles/tutorial-first-app/main.js b/docs/fiddles/tutorial-first-app/main.js index 10d57a0696..fdb092a9d4 100644 --- a/docs/fiddles/tutorial-first-app/main.js +++ b/docs/fiddles/tutorial-first-app/main.js @@ -1,26 +1,26 @@ -const { app, BrowserWindow } = require('electron'); +const { app, BrowserWindow } = require('electron') const createWindow = () => { const win = new BrowserWindow({ width: 800, - height: 600, - }); + height: 600 + }) - win.loadFile('index.html'); -}; + win.loadFile('index.html') +} app.whenReady().then(() => { - createWindow(); + createWindow() app.on('activate', () => { if (BrowserWindow.getAllWindows().length === 0) { - createWindow(); + createWindow() } - }); -}); + }) +}) app.on('window-all-closed', () => { if (process.platform !== 'darwin') { - app.quit(); + app.quit() } -}); +}) diff --git a/docs/fiddles/tutorial-preload/main.js b/docs/fiddles/tutorial-preload/main.js index 6b7184900e..7b854f5ec2 100644 --- a/docs/fiddles/tutorial-preload/main.js +++ b/docs/fiddles/tutorial-preload/main.js @@ -1,30 +1,30 @@ -const { app, BrowserWindow } = require('electron'); -const path = require('path'); +const { app, BrowserWindow } = require('electron') +const path = require('path') const createWindow = () => { const win = new BrowserWindow({ width: 800, height: 600, webPreferences: { - preload: path.join(__dirname, 'preload.js'), - }, - }); + preload: path.join(__dirname, 'preload.js') + } + }) - win.loadFile('index.html'); -}; + win.loadFile('index.html') +} app.whenReady().then(() => { - createWindow(); + createWindow() app.on('activate', () => { if (BrowserWindow.getAllWindows().length === 0) { - createWindow(); + createWindow() } - }); -}); + }) +}) app.on('window-all-closed', () => { if (process.platform !== 'darwin') { - app.quit(); + app.quit() } -}); +}) diff --git a/docs/fiddles/tutorial-preload/preload.js b/docs/fiddles/tutorial-preload/preload.js index e0dbdce1b8..4d0213eedb 100644 --- a/docs/fiddles/tutorial-preload/preload.js +++ b/docs/fiddles/tutorial-preload/preload.js @@ -1,7 +1,7 @@ -const { contextBridge } = require('electron'); +const { contextBridge } = require('electron') contextBridge.exposeInMainWorld('versions', { node: () => process.versions.node, chrome: () => process.versions.chrome, - electron: () => process.versions.electron, -}); + electron: () => process.versions.electron +}) diff --git a/docs/fiddles/tutorial-preload/renderer.js b/docs/fiddles/tutorial-preload/renderer.js index 7585229a91..df60659df2 100644 --- a/docs/fiddles/tutorial-preload/renderer.js +++ b/docs/fiddles/tutorial-preload/renderer.js @@ -1,2 +1,2 @@ -const information = document.getElementById('info'); -information.innerText = `This app is using Chrome (v${versions.chrome()}), Node.js (v${versions.node()}), and Electron (v${versions.electron()})`; +const information = document.getElementById('info') +information.innerText = `This app is using Chrome (v${versions.chrome()}), Node.js (v${versions.node()}), and Electron (v${versions.electron()})` diff --git a/docs/fiddles/windows/manage-windows/create-frameless-window/main.js b/docs/fiddles/windows/manage-windows/create-frameless-window/main.js index 05d530736a..9090767da9 100644 --- a/docs/fiddles/windows/manage-windows/create-frameless-window/main.js +++ b/docs/fiddles/windows/manage-windows/create-frameless-window/main.js @@ -1,6 +1,6 @@ const { app, BrowserWindow, ipcMain } = require('electron') -ipcMain.on('create-frameless-window', (event, {url}) => { +ipcMain.on('create-frameless-window', (event, { url }) => { const win = new BrowserWindow({ frame: false }) win.loadURL(url) }) diff --git a/docs/fiddles/windows/manage-windows/frameless-window/main.js b/docs/fiddles/windows/manage-windows/frameless-window/main.js index d7925cd7ff..60a9c08d4f 100644 --- a/docs/fiddles/windows/manage-windows/frameless-window/main.js +++ b/docs/fiddles/windows/manage-windows/frameless-window/main.js @@ -1,7 +1,7 @@ // Modules to control application life and create native browser window -const { app, BrowserWindow } = require('electron') +const { app, BrowserWindow, ipcMain } = require('electron') -ipcMain.on('create-frameless-window', (event, {url}) => { +ipcMain.on('create-frameless-window', (event, { url }) => { const win = new BrowserWindow({ frame: false }) win.loadURL(url) }) diff --git a/docs/fiddles/windows/manage-windows/manage-window-state/main.js b/docs/fiddles/windows/manage-windows/manage-window-state/main.js index 166ff0fa62..81bb22fdde 100644 --- a/docs/fiddles/windows/manage-windows/manage-window-state/main.js +++ b/docs/fiddles/windows/manage-windows/manage-window-state/main.js @@ -4,7 +4,7 @@ const { app, BrowserWindow, ipcMain } = require('electron') ipcMain.on('create-demo-window', (event) => { const win = new BrowserWindow({ width: 400, height: 275 }) - function updateReply() { + function updateReply () { event.sender.send('bounds-changed', { size: win.getSize(), position: win.getPosition() diff --git a/docs/fiddles/windows/manage-windows/new-window/renderer.js b/docs/fiddles/windows/manage-windows/new-window/renderer.js index ccb8b22643..0b5288d4f9 100644 --- a/docs/fiddles/windows/manage-windows/new-window/renderer.js +++ b/docs/fiddles/windows/manage-windows/new-window/renderer.js @@ -5,10 +5,10 @@ const link = document.getElementById('browser-window-link') newWindowBtn.addEventListener('click', (event) => { const url = 'https://electronjs.org' - ipcRenderer.send('new-window', { url, width: 400, height: 320 }); + ipcRenderer.send('new-window', { url, width: 400, height: 320 }) }) link.addEventListener('click', (e) => { e.preventDefault() - shell.openExternal("https://electronjs.org/docs/api/browser-window") + shell.openExternal('https://electronjs.org/docs/api/browser-window') }) diff --git a/package.json b/package.json index eee8766562..7d90e783cb 100644 --- a/package.json +++ b/package.json @@ -95,6 +95,7 @@ "lint:py": "node ./script/lint.js --py", "lint:gn": "node ./script/lint.js --gn", "lint:docs": "remark docs -qf && npm run lint:js-in-markdown && npm run create-typescript-definitions && npm run lint:docs-relative-links && npm run lint:markdownlint", + "lint:docs-fiddles": "standard \"docs/fiddles/**/*.js\"", "lint:docs-relative-links": "ts-node script/lint-docs-links.ts", "lint:markdownlint": "markdownlint -r ./script/markdownlint-emd001.js \"*.md\" \"docs/**/*.md\"", "lint:js-in-markdown": "standard-markdown docs",
chore
3d45429667c7e98e4db9c9c3325e0083ca3d7909
Milan Burda
2023-08-07 11:30:15
refactor: use `for-of` instead of `for` simple array iteration (#39338)
diff --git a/lib/browser/api/dialog.ts b/lib/browser/api/dialog.ts index e155ab3074..3ec49b8bc2 100644 --- a/lib/browser/api/dialog.ts +++ b/lib/browser/api/dialog.ts @@ -194,8 +194,8 @@ const messageBox = (sync: boolean, window: BrowserWindow | null, options?: Messa if (cancelId == null) { // If the defaultId is set to 0, ensure the cancel button is a different index (1) cancelId = (defaultId === 0 && buttons.length > 1) ? 1 : 0; - for (let i = 0; i < buttons.length; i++) { - const text = buttons[i].toLowerCase(); + for (const [i, button] of buttons.entries()) { + const text = button.toLowerCase(); if (text === 'cancel' || text === 'no') { cancelId = i; break; diff --git a/spec/api-desktop-capturer-spec.ts b/spec/api-desktop-capturer-spec.ts index 55dcaf4205..b7729ac748 100644 --- a/spec/api-desktop-capturer-spec.ts +++ b/spec/api-desktop-capturer-spec.ts @@ -60,8 +60,8 @@ ifdescribe(!process.arch.includes('arm') && process.platform !== 'win32')('deskt const sources = await desktopCapturer.getSources({ types: ['screen'] }); expect(sources).to.be.an('array').of.length(displays.length); - for (let i = 0; i < sources.length; i++) { - expect(sources[i].display_id).to.equal(displays[i].id.toString()); + for (const [i, source] of sources.entries()) { + expect(source.display_id).to.equal(displays[i].id.toString()); } }); diff --git a/spec/api-subframe-spec.ts b/spec/api-subframe-spec.ts index c5e5b50302..1a56612695 100644 --- a/spec/api-subframe-spec.ts +++ b/spec/api-subframe-spec.ts @@ -133,14 +133,14 @@ describe('renderer nodeIntegrationInSubFrames', () => { const generateConfigs = (webPreferences: any, ...permutations: {name: string, webPreferences: any}[]) => { const configs = [{ webPreferences, names: [] as string[] }]; - for (let i = 0; i < permutations.length; i++) { + for (const permutation of permutations) { const length = configs.length; for (let j = 0; j < length; j++) { const newConfig = Object.assign({}, configs[j]); newConfig.webPreferences = Object.assign({}, - newConfig.webPreferences, permutations[i].webPreferences); + newConfig.webPreferences, permutation.webPreferences); newConfig.names = newConfig.names.slice(0); - newConfig.names.push(permutations[i].name); + newConfig.names.push(permutation.name); configs.push(newConfig); } } diff --git a/spec/lib/video-helpers.js b/spec/lib/video-helpers.js index c376b1598d..b2ff78a6de 100644 --- a/spec/lib/video-helpers.js +++ b/spec/lib/video-helpers.js @@ -313,16 +313,16 @@ function bitsToBuffer (bits) { function generateEBML (json) { const ebml = []; - for (let i = 0; i < json.length; i++) { - if (!('id' in json[i])) { + for (const item of json) { + if (!('id' in item)) { // already encoded blob or byteArray - ebml.push(json[i]); + ebml.push(item); continue; } - let data = json[i].data; + let data = item.data; if (typeof data === 'object') data = generateEBML(data); - if (typeof data === 'number') data = ('size' in json[i]) ? numToFixedBuffer(data, json[i].size) : bitsToBuffer(data.toString(2)); + if (typeof data === 'number') data = ('size' in item) ? numToFixedBuffer(data, item.size) : bitsToBuffer(data.toString(2)); if (typeof data === 'string') data = strToBuffer(data); const len = data.size || data.byteLength || data.length; @@ -335,7 +335,7 @@ function generateEBML (json) { // going to fix this, i'm probably just going to write some hacky thing which // converts that string into a buffer-esque thing - ebml.push(numToBuffer(json[i].id)); + ebml.push(numToBuffer(item.id)); ebml.push(bitsToBuffer(size)); ebml.push(data); } @@ -349,13 +349,13 @@ function toFlatArray (arr, outBuffer) { if (outBuffer == null) { outBuffer = []; } - for (let i = 0; i < arr.length; i++) { - if (typeof arr[i] === 'object') { + for (const item of arr) { + if (typeof item === 'object') { // an array - toFlatArray(arr[i], outBuffer); + toFlatArray(item, outBuffer); } else { // a simple element - outBuffer.push(arr[i]); + outBuffer.push(item); } } return outBuffer; diff --git a/spec/ts-smoke/electron/renderer.ts b/spec/ts-smoke/electron/renderer.ts index 8fc55790d0..16d0f9c02b 100644 --- a/spec/ts-smoke/electron/renderer.ts +++ b/spec/ts-smoke/electron/renderer.ts @@ -74,14 +74,14 @@ crashReporter.start({ // https://github.com/electron/electron/blob/main/docs/api/desktop-capturer.md getSources({ types: ['window', 'screen'] }).then(sources => { - for (let i = 0; i < sources.length; ++i) { - if (sources[i].name === 'Electron') { + for (const source of sources) { + if (source.name === 'Electron') { (navigator as any).webkitGetUserMedia({ audio: false, video: { mandatory: { chromeMediaSource: 'desktop', - chromeMediaSourceId: sources[i].id, + chromeMediaSourceId: source.id, minWidth: 1280, maxWidth: 1280, minHeight: 720,
refactor
f8b05bc127a0bdca54ecf0ef004d07ceab782a80
Shelley Vohr
2023-08-03 17:38:31
feat: support `minimum_chrome_version` manifest key (#39256) feat: support minimum_chrome_version extension key
diff --git a/electron_paks.gni b/electron_paks.gni index 1ee2e16639..c3a257ab0f 100644 --- a/electron_paks.gni +++ b/electron_paks.gni @@ -174,6 +174,7 @@ template("electron_paks") { } source_patterns = [ + "${root_gen_dir}/chrome/chromium_strings_", "${root_gen_dir}/chrome/locale_settings_", "${root_gen_dir}/chrome/platform_locale_settings_", "${root_gen_dir}/chrome/generated_resources_", @@ -189,6 +190,7 @@ template("electron_paks") { "${root_gen_dir}/ui/strings/ui_strings_", ] deps = [ + "//chrome/app:chromium_strings", "//chrome/app:generated_resources", "//chrome/app/resources:locale_settings", "//chrome/app/resources:platform_locale_settings", diff --git a/shell/common/extensions/api/_manifest_features.json b/shell/common/extensions/api/_manifest_features.json index 7fdabc8a37..b860cc40e2 100644 --- a/shell/common/extensions/api/_manifest_features.json +++ b/shell/common/extensions/api/_manifest_features.json @@ -14,5 +14,9 @@ "devtools_page": { "channel": "stable", "extension_types": ["extension"] + }, + "minimum_chrome_version": { + "channel": "stable", + "extension_types": ["extension"] } } diff --git a/shell/common/extensions/electron_extensions_api_provider.cc b/shell/common/extensions/electron_extensions_api_provider.cc index a5aea27f0d..36cf3f8957 100644 --- a/shell/common/extensions/electron_extensions_api_provider.cc +++ b/shell/common/extensions/electron_extensions_api_provider.cc @@ -10,6 +10,7 @@ #include "base/containers/span.h" #include "base/strings/utf_string_conversions.h" #include "chrome/common/extensions/chrome_manifest_url_handlers.h" +#include "chrome/common/extensions/manifest_handlers/minimum_chrome_version_checker.h" #include "electron/buildflags/buildflags.h" #include "electron/shell/common/extensions/api/generated_schemas.h" #include "extensions/common/alias.h" @@ -99,6 +100,8 @@ void ElectronExtensionsAPIProvider::RegisterManifestHandlers() { extensions::ManifestHandlerRegistry::Get(); registry->RegisterHandler( std::make_unique<extensions::DevToolsPageHandler>()); + registry->RegisterHandler( + std::make_unique<extensions::MinimumChromeVersionChecker>()); } } // namespace electron diff --git a/spec/extensions-spec.ts b/spec/extensions-spec.ts index b5a43fcd95..5a0f5ddff2 100644 --- a/spec/extensions-spec.ts +++ b/spec/extensions-spec.ts @@ -69,6 +69,25 @@ describe('chrome extensions', () => { `)).to.eventually.have.property('id'); }); + it('supports minimum_chrome_version manifest key', async () => { + const customSession = session.fromPartition(`persist:${require('uuid').v4()}`); + const w = new BrowserWindow({ + show: false, + webPreferences: { + session: customSession, + sandbox: true + } + }); + + await w.loadURL('about:blank'); + + const extPath = path.join(fixtures, 'extensions', 'chrome-too-low-version'); + const load = customSession.loadExtension(extPath); + await expect(load).to.eventually.be.rejectedWith( + `Loading extension at ${extPath} failed with: This extension requires Chromium version 999 or greater.` + ); + }); + it('can open WebSQLDatabase in a background page', async () => { const customSession = session.fromPartition(`persist:${require('uuid').v4()}`); const w = new BrowserWindow({ show: false, webPreferences: { session: customSession, sandbox: true } }); diff --git a/spec/fixtures/extensions/chrome-too-low-version/main.js b/spec/fixtures/extensions/chrome-too-low-version/main.js new file mode 100644 index 0000000000..d58117c501 --- /dev/null +++ b/spec/fixtures/extensions/chrome-too-low-version/main.js @@ -0,0 +1 @@ +document.documentElement.style.backgroundColor = 'blue'; diff --git a/spec/fixtures/extensions/chrome-too-low-version/manifest.json b/spec/fixtures/extensions/chrome-too-low-version/manifest.json new file mode 100644 index 0000000000..c65bced2f5 --- /dev/null +++ b/spec/fixtures/extensions/chrome-too-low-version/manifest.json @@ -0,0 +1,14 @@ +{ + "name": "chrome-too-low-version", + "version": "1.0", + "minimum_chrome_version": "999", + "content_scripts": [ + { + "matches": ["<all_urls>"], + "js": ["main.js"], + "run_at": "document_start" + } + ], + "permissions": ["storage"], + "manifest_version": 3 +}
feat
54ff706b710363bac1e00a5316737805f4a57f4c
Milan Burda
2023-10-24 09:25:30
test: add spec for `app.getAppMetrics()` for utility process (#40306)
diff --git a/spec/api-utility-process-spec.ts b/spec/api-utility-process-spec.ts index b87920d354..e6c15aaf95 100644 --- a/spec/api-utility-process-spec.ts +++ b/spec/api-utility-process-spec.ts @@ -6,6 +6,7 @@ import { ifit } from './lib/spec-helpers'; import { closeWindow } from './lib/window-helpers'; import { once } from 'node:events'; import { pathToFileURL } from 'node:url'; +import { setImmediate } from 'node:timers/promises'; const fixturesPath = path.resolve(__dirname, 'fixtures', 'api', 'utility-process'); const isWindowsOnArm = process.platform === 'win32' && process.arch === 'arm64'; @@ -113,6 +114,36 @@ describe('utilityProcess module', () => { }); }); + describe('app.getAppMetrics()', () => { + it('with default serviceName', async () => { + const child = utilityProcess.fork(path.join(fixturesPath, 'endless.js')); + await once(child, 'spawn'); + expect(child.pid).to.not.be.null(); + + await setImmediate(); + + const details = app.getAppMetrics().find(item => item.pid === child.pid)!; + expect(details).to.be.an('object'); + expect(details.type).to.equal('Utility'); + expect(details.serviceName).to.to.equal('node.mojom.NodeService'); + expect(details.name).to.equal('Node Utility Process'); + }); + + it('with custom serviceName', async () => { + const child = utilityProcess.fork(path.join(fixturesPath, 'endless.js'), [], { serviceName: 'Hello World!' }); + await once(child, 'spawn'); + expect(child.pid).to.not.be.null(); + + await setImmediate(); + + const details = app.getAppMetrics().find(item => item.pid === child.pid)!; + expect(details).to.be.an('object'); + expect(details.type).to.equal('Utility'); + expect(details.serviceName).to.to.equal('node.mojom.NodeService'); + expect(details.name).to.equal('Hello World!'); + }); + }); + describe('kill() API', () => { it('terminates the child process gracefully', async () => { const child = utilityProcess.fork(path.join(fixturesPath, 'endless.js'), [], {
test
61f619a5e66601f33ac698027d3581e933a46f39
Shelley Vohr
2024-01-15 19:48:10
ci: correctly export RBE_experimental_credentials_helper_args (#40997)
diff --git a/.circleci/config/base.yml b/.circleci/config/base.yml index c29c61381e..31a6b34681 100644 --- a/.circleci/config/base.yml +++ b/.circleci/config/base.yml @@ -357,6 +357,7 @@ step-setup-rbe-for-build: &step-setup-rbe-for-build $HELPER login echo 'export RBE_service='`node -e "console.log(require('./src/utils/reclient.js').serviceAddress)"` >> $BASH_ENV echo 'export RBE_experimental_credentials_helper='`node -e "console.log(require('./src/utils/reclient.js').helperPath)"` >> $BASH_ENV + echo 'export RBE_experimental_credentials_helper_args="print"' >> $BASH_ENV step-restore-brew-cache: &step-restore-brew-cache restore_cache: diff --git a/appveyor-woa.yml b/appveyor-woa.yml index ad487a4fbd..3e162cc27a 100644 --- a/appveyor-woa.yml +++ b/appveyor-woa.yml @@ -113,6 +113,8 @@ for: $env:RBE_service = node -e "console.log(require('./src/utils/reclient.js').serviceAddress)" - ps: >- $env:RBE_experimental_credentials_helper = $env:RECLIENT_HELPER + - ps: >- + $env:RBE_experimental_credentials_helper_args = "print" - cd ..\.. - ps: $env:CHROMIUM_BUILDTOOLS_PATH="$pwd\src\buildtools" - ps: >- diff --git a/appveyor.yml b/appveyor.yml index 682a5f5600..85adf464cc 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -111,6 +111,8 @@ for: $env:RBE_service = node -e "console.log(require('./src/utils/reclient.js').serviceAddress)" - ps: >- $env:RBE_experimental_credentials_helper = $env:RECLIENT_HELPER + - ps: >- + $env:RBE_experimental_credentials_helper_args = "print" - cd ..\.. - ps: $env:CHROMIUM_BUILDTOOLS_PATH="$pwd\src\buildtools" - ps: >-
ci