before_code stringlengths 14 465k | reviewer_comment stringlengths 16 64.5k | after_code stringlengths 9 467k | diff_context stringlengths 0 97k | file_path stringlengths 5 226 | comment_line int32 0 26 | language stringclasses 37
values | quality_score float32 0.07 1 | comment_type stringclasses 9
values | comment_length int32 16 64.5k | before_lines int32 1 17.2k | after_lines int32 1 12.1k | is_negative bool 2
classes | pr_title stringlengths 1 308 | pr_number int32 1 299k | repo_name stringclasses 533
values | repo_stars int64 321 419k | repo_language stringclasses 27
values | reviewer_username stringlengths 0 39 | author_username stringlengths 2 39 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
label = ngettext(
# Translators: The label to use when displaying the number of items
# in a list, e.g. "1 image" or "2 images".
"%(count)d %(item_name)s",
"%(count)d %(item_name_plural)s",
self.count,
)
return label % {
"co... | No issues found. | label = ngettext(
# Translators: The label to use when displaying the number of items
# in a list, e.g. "1 image" or "2 images".
"%(count)d %(item_name)s",
"%(count)d %(item_name_plural)s",
self.count,
)
return label % {
"co... | @@ -0,0 +1,104 @@
+from django.core.paginator import EmptyPage, PageNotAnInteger, Paginator
+from django.utils.functional import cached_property
+from django.utils.translation import gettext as _
+from django.utils.translation import ngettext
+
+
+class WagtailPaginator(Paginator):
+ num_page_buttons = 6
+
+ @cac... | wagtail/admin/paginator.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | Implement new and improved pagination controls | 13,042 | wagtail/wagtail | 16,097 | Python | laymonage | |
import { ChooserModal } from '../../includes/chooserModal';
import { Chooser, ChooserFactory } from '.';
class SnippetChooserModal extends ChooserModal {
// left as is for backwards compatibility.
}
export class SnippetChooser extends Chooser {
titleStateKey = 'string';
chooserModalClass = SnippetChooserModal;
... | No issues found. | import { ChooserModal } from '../../includes/chooserModal';
import { Chooser, ChooserFactory } from '.';
class SnippetChooserModal extends ChooserModal {
// left as is for backwards compatibility.
}
export class SnippetChooser extends Chooser {
titleStateKey = 'string';
chooserModalClass = SnippetChooserModal;
... | @@ -1,19 +1,8 @@
import { ChooserModal } from '../../includes/chooserModal';
import { Chooser, ChooserFactory } from '.';
-import { WAGTAIL_CONFIG } from '../../config/wagtailConfig';
class SnippetChooserModal extends ChooserModal {
- getURLParams(opts) {
- const params = super.getURLParams(opts);
- if (WAG... | client/src/components/ChooserWidget/SnippetChooserWidget.js | 0 | JavaScript | 1 | none | 16 | 17 | 17 | true | Improve locale filter in all choosers | 13,043 | wagtail/wagtail | 16,097 | Python | zerolab | |
class Migration(migrations.Migration):
dependencies = [
("tests", "0054_delete_notyetregisteredgenericsetting_and_more"),
("wagtailcore", "0094_alter_page_locale"),
]
operations = [
migrations.CreateModel(
name="PreviewableGenericSetting",
fields=[
... | No issues found. |
class Migration(migrations.Migration):
dependencies = [
("tests", "0054_delete_notyetregisteredgenericsetting_and_more"),
("wagtailcore", "0094_alter_page_locale"),
]
operations = [
migrations.CreateModel(
name="PreviewableGenericSetting",
fields=[
... | @@ -0,0 +1,62 @@
+# Generated by Django 5.1.3 on 2025-04-21 10:43
+
+from django.db import migrations, models
+
+import wagtail.models.preview
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("tests", "0054_delete_notyetregisteredgenericsetting_and_more"),
+ ("wagtailcore", "0094_alt... | wagtail/test/testapp/migrations/0055_previewable_settings.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | PreviewableMixin compatibility for settings | 13,050 | wagtail/wagtail | 16,097 | Python | SebCorbin | |
(
"en",
"English",
), # Note: Current value is displayed even though it's in use
("fr", "French"),
],
)
url_finder = AdminURLFinder(self.user)
expected_url = "/admin/locales/edit/%d/" % self.eng... | No issues found. | (
"en",
"English",
), # Note: Current value is displayed even though it's in use
("fr", "French"),
],
)
url_finder = AdminURLFinder(self.user)
expected_url = "/admin/locales/edit/%d/" % self.eng... | @@ -13,8 +13,13 @@
class TestLocaleIndexView(AdminTemplateTestUtils, WagtailTestUtils, TestCase):
+ @classmethod
+ def setUpTestData(cls):
+ cls.user = cls.create_test_user()
+ cls.add_url = reverse("wagtaillocales:add")
+
def setUp(self):
- self.login()
+ self.login(user=sel... | wagtail/locales/tests.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | Hide add locale button when no more languages are available | 13,051 | wagtail/wagtail | 16,097 | Python | zerolab | |
from django.db import migrations, models
import wagtail.fields
class Migration(migrations.Migration):
dependencies = [
("tests", "0052_variousondeletemodel_protected_page_and_user"),
]
operations = [
migrations.AddField(
model_name="pagewithexcludedcopyfield",
na... | No issues found. | from django.db import migrations, models
import wagtail.fields
class Migration(migrations.Migration):
dependencies = [
("tests", "0052_variousondeletemodel_protected_page_and_user"),
]
operations = [
migrations.AddField(
model_name="pagewithexcludedcopyfield",
na... | @@ -0,0 +1,57 @@
+# Generated by Django 5.2.1 on 2025-05-16 10:44
+
+import django.db.models.deletion
+import modelcluster.fields
+from django.db import migrations, models
+
+import wagtail.fields
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("tests", "0052_variousondeletemodel_protected... | wagtail/test/testapp/migrations/0053_pagewithexcludedcopyfield_special_stream_and_more.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | Handle non-JSON-safe fields in exclude_fields_in_copy | 13,082 | wagtail/wagtail | 16,097 | Python | gasman | |
with hooks.register_temporarily(
"construct_wagtail_userbar",
self.get_hook(CustomContextAccessibilityItem),
):
config = self.get_config()
self.assertEqual(
config["context"],
{
# Override via class attr... | No issues found. |
with hooks.register_temporarily(
"construct_wagtail_userbar",
self.get_hook(CustomContextAccessibilityItem),
):
config = self.get_config()
self.assertEqual(
config["context"],
{
# Override via class attr... | @@ -177,11 +177,15 @@ def setUp(self):
self.request = get_dummy_request()
self.request.user = self.user
- def get_script(self):
- template = Template("{% load wagtailuserbar %}{% wagtailuserbar %}")
+ def get_content(self, position="bottom-right"):
+ template = Template(
+ ... | wagtail/admin/tests/test_userbar.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | Adjust accessibility dialog position based on userbar's position | 13,122 | wagtail/wagtail | 16,097 | Python | laymonage | |
f"""
<img sizes="100vw" src="{filename35}"
srcset="{filename35} 35.0w, {filename55} 55.0w" width="35.0" height="35.0"
alt="Test SVG image">
""",
)
def test_raster_srcset_image_with_preserve_svg(self):
"""Test that prese... | No issues found. | f"""
<img sizes="100vw" src="{filename35}"
srcset="{filename35} 35.0w, {filename55} 55.0w" width="35.0" height="35.0"
alt="Test SVG image">
""",
)
def test_raster_srcset_image_with_preserve_svg(self):
"""Test that prese... | @@ -4,6 +4,7 @@
from wagtail.images.tests.utils import (
get_test_image_file,
get_test_image_file_svg,
+ get_test_image_filename,
)
from wagtail.test.utils import WagtailTestUtils
@@ -41,9 +42,12 @@ def test_image_with_raster_image(self):
html = self.render(
'{{ image(img, "width... | wagtail/images/tests/test_jinja2_svg.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | Handle preserve-svg for multiple renditions | 13,125 | wagtail/wagtail | 16,097 | Python | gasman | |
from django import template
from wagtail.admin.userbar import Userbar
from wagtail.models import PAGE_TEMPLATE_VAR, Page
register = template.Library()
def get_page_instance(context):
"""
Given a template context, try and find a Page variable in the common
places. Returns None if a page can not be found.... | No issues found. | from django import template
from wagtail.admin.userbar import Userbar
from wagtail.models import PAGE_TEMPLATE_VAR, Page
register = template.Library()
def get_page_instance(context):
"""
Given a template context, try and find a Page variable in the common
places. Returns None if a page can not be found.... | @@ -1,17 +1,7 @@
from django import template
-from django.template.loader import render_to_string
-from django.utils import translation
-from wagtail.admin.userbar import (
- AccessibilityItem,
- AddPageItem,
- AdminItem,
- EditPageItem,
- ExplorePageItem,
- apply_userbar_hooks,
-)
-from wagtail.mo... | wagtail/admin/templatetags/wagtailuserbar.py | 0 | Python | 1 | none | 16 | 43 | 43 | true | Extract Userbar component from template tag code | 13,149 | wagtail/wagtail | 16,097 | Python | laymonage | |
return embed_to_frontend_html(self.url, self.max_width, self.max_height)
def __str__(self):
return self.html
class EmbedBlock(blocks.URLBlock):
def get_default(self):
# Allow specifying the default for an EmbedBlock as either an EmbedValue or a string (or None).
if not self.me... | No issues found. | return embed_to_frontend_html(self.url, self.max_width, self.max_height)
def __str__(self):
return self.html
class EmbedBlock(blocks.URLBlock):
def get_default(self):
# Allow specifying the default for an EmbedBlock as either an EmbedValue or a string (or None).
if not self.me... | @@ -87,8 +87,11 @@ def clean(self, value):
def normalize(self, value):
if isinstance(value, EmbedValue):
- return value
- return EmbedValue(value)
+ return value if value.url else None
+ elif value:
+ return EmbedValue(value)
+ else:
+ ret... | wagtail/embeds/blocks.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | Fix saving of empty values in EmbedBlock | 13,160 | wagtail/wagtail | 16,097 | Python | gasman | |
response = self.get()
self.assertContains(response, "Page 1 of 3")
self.assertEqual(response.status_code, 200)
def test_filter_by_tag(self):
for i in range(0, 10):
image = Image.objects.create(
title="Test image %d is even better than the last one" % i,
... | No issues found. | response = self.get()
self.assertContains(response, "Page 1 of 3")
self.assertEqual(response.status_code, 200)
def test_filter_by_tag(self):
for i in range(0, 10):
image = Image.objects.create(
title="Test image %d is even better than the last one" % i,
... | @@ -21,9 +21,10 @@
from willow.registry import registry
from wagtail.admin.admin_url_finder import AdminURLFinder
+from wagtail.admin.ui.tables import Table
from wagtail.images import get_image_model
from wagtail.images.utils import generate_signature
-from wagtail.images.views.images import ImagesFilterSet
+from... | wagtail/images/tests/test_admin_views.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | List View for Image Listing | 13,172 | wagtail/wagtail | 16,097 | Python | joelwilliam2005 | |
# required, and no cache hits are made
self._test_get_renditions_performance(0, prefetch_all=True)
def test_create_renditions(self):
filter_list = [Filter(spec) for spec in self.SPECS]
# When no renditions exist, there should be one query for
# 'clash identification', and an... | No issues found. | # required, and no cache hits are made
self._test_get_renditions_performance(0, prefetch_all=True)
def test_create_renditions(self):
filter_list = [Filter(spec) for spec in self.SPECS]
# When no renditions exist, there should be one query for
# 'clash identification', and an... | @@ -908,6 +908,10 @@ def test_focal_point(self):
rendition.background_position_style, "background-position: 15% 41%;"
)
+ # Individual background position properties
+ self.assertEqual(rendition.background_position_x, "15%")
+ self.assertEqual(rendition.background_position_y... | wagtail/images/tests/test_models.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | refactor background_position_style into x & y methods | 13,173 | wagtail/wagtail | 16,097 | Python | Chiemezuo | |
// should send the preview data to the preview URL
await jest.advanceTimersByTime(1000);
expect(global.fetch).toHaveBeenCalledWith(url, {
body: expect.any(Object),
method: 'POST',
});
expect(global.fetch).toHaveBeenCalledTimes(1);
expect(events.update).toHaveLength(2)... | No issues found. | // should send the preview data to the preview URL
await jest.advanceTimersByTime(1000);
expect(global.fetch).toHaveBeenCalledWith(url, {
body: expect.any(Object),
method: 'POST',
});
expect(global.fetch).toHaveBeenCalledTimes(1);
expect(events.update).toHaveLength(2)... | @@ -16,15 +16,6 @@ jest.mock('axe-core', () => {
};
});
-function mockAxeResults(runResults, contentChecksResults) {
- axe.run.mockResolvedValueOnce(runResults);
- axe.utils.sendCommandToFrame.mockImplementationOnce(
- (frame, options, callback) => {
- callback(contentChecksResults);
- },
- );
-}
-
... | client/src/controllers/PreviewController.test.js | 0 | JavaScript | 1 | none | 16 | 51 | 51 | true | Add API for extracting preview page content | 13,197 | wagtail/wagtail | 16,097 | Python | laymonage | |
expect(document.body.innerHTML).toMatchSnapshot();
const select = document.querySelector('select');
expect(select.options[select.selectedIndex].value).toBe('red');
const selectedOptions = document.querySelector('select').selectedOptions;
expect(selectedOptions.length).toBe(2);
expect(selectedOpt... | No issues found. | expect(document.body.innerHTML).toMatchSnapshot();
const select = document.querySelector('select');
expect(select.options[select.selectedIndex].value).toBe('red');
const selectedOptions = document.querySelector('select').selectedOptions;
expect(selectedOptions.length).toBe(2);
expect(selectedOpt... | @@ -61,6 +61,17 @@ describe('telepath: wagtail.widgets.Widget', () => {
expect(document.querySelector('input').value).toBe('The new Value');
});
+ test('setInvalid() sets aria-invalid attribute', () => {
+ boundWidget.setInvalid(true);
+ expect(document.querySelector('input').getAttribute('aria-invalid... | client/src/entrypoints/admin/telepath/widgets.test.js | 0 | JavaScript | 1 | none | 16 | 51 | 51 | true | Set `aria-invalid` on StreamField widgets input when there is an error | 13,204 | wagtail/wagtail | 16,097 | Python | laymonage | |
},
)
def test_adapt_with_classname_via_class_meta(self):
"""form_classname from meta to be used as an additional class when rendering list block"""
class LinkBlock(blocks.StructBlock):
title = blocks.CharBlock()
link = blocks.URLBlock()
class Cu... | No issues found. | },
)
def test_adapt_with_classname_via_class_meta(self):
"""form_classname from meta to be used as an additional class when rendering list block"""
class LinkBlock(blocks.StructBlock):
title = blocks.CharBlock()
link = blocks.URLBlock()
class Cu... | @@ -191,6 +191,7 @@ def test_charblock_adapter(self):
"blockDefId": block.definition_prefix,
"isPreviewable": block.is_previewable,
"classname": "w-field w-field--char_field w-field--text_input",
+ "attrs": {},
"showAddCommentButton": Tr... | wagtail/tests/test_blocks.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | Add `form_attrs` support to all StreamField blocks | 13,211 | wagtail/wagtail | 16,097 | Python | laymonage | |
"/admin/documents/multiple/%d/" % response.context["doc"].id,
)
self.assertEqual(
response.context["delete_action"],
"/admin/documents/multiple/%d/delete/" % response.context["doc"].id,
)
# check that it is in the root collection
doc = get_doc... | No issues found. | "/admin/documents/multiple/%d/" % response.context["doc"].id,
)
self.assertEqual(
response.context["delete_action"],
"/admin/documents/multiple/%d/delete/" % response.context["doc"].id,
)
# check that it is in the root collection
doc = get_doc... | @@ -2118,6 +2118,32 @@ def test_usage_count_zero_appears(self):
response = self.client.get(reverse("wagtaildocs:edit", args=(1,)))
self.assertContains(response, "Used 0 times")
+ def test_usage_count_column_with_document_usage(self):
+ with self.captureOnCommitCallbacks(execute=True):
+ ... | wagtail/documents/tests/test_admin_views.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | Usage count column for media listings | 13,234 | wagtail/wagtail | 16,097 | Python | joelwilliam2005 | |
# Generated by Django 5.1.6 on 2025-07-14 16:16
import django.db.models.deletion
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("tests", "0057_featurecompletetoy_sort_order"),
]
operations = [
migrations.CreateModel(
name="C... | No issues found. | # Generated by Django 5.1.6 on 2025-07-14 16:16
import django.db.models.deletion
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("tests", "0057_featurecompletetoy_sort_order"),
]
operations = [
migrations.CreateModel(
name="C... | @@ -0,0 +1,31 @@
+# Generated by Django 5.1.6 on 2025-07-14 16:16
+
+import django.db.models.deletion
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("tests", "0057_featurecompletetoy_sort_order"),
+ ]
+
+ operations = [
+ migrations.C... | wagtail/test/testapp/migrations/0058_customlocktask.py | 0 | Python | 1 | none | 16 | 32 | 32 | true | Allow defining custom `WorkflowLock` subclasses on workflow `Task`s | 13,239 | wagtail/wagtail | 16,097 | Python | zerolab | |
# Generated by Django 5.2.3 on 2025-07-23 16:12
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("wagtailusers", "0014_userprofile_contrast"),
]
operations = [
migrations.AddField(
model_name="userprofile",
name="k... | No issues found. | # Generated by Django 5.2.3 on 2025-07-23 16:12
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("wagtailusers", "0014_userprofile_contrast"),
]
operations = [
migrations.AddField(
model_name="userprofile",
name="k... | @@ -0,0 +1,22 @@
+# Generated by Django 5.2.3 on 2025-07-23 16:12
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("wagtailusers", "0014_userprofile_contrast"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="us... | wagtail/users/migrations/0015_userprofile_keyboard_shortcuts.py | 0 | Python | 1 | none | 16 | 23 | 23 | true | Added user account setting for disabling custom keyboard shortcuts | 13,258 | wagtail/wagtail | 16,097 | Python | dhruvipatel14 | |
}
/**
* JavaScript equivalent of the {% panel %} template tag.
*/
export class CollapsiblePanel {
declare props: PanelProps;
constructor(props: PanelProps) {
this.props = props;
}
render() {
const template = document.createElement('template');
const {
panelId,
headingId,
conte... | No issues found. | }
/**
* JavaScript equivalent of the {% panel %} template tag.
*/
export class CollapsiblePanel {
declare props: PanelProps;
constructor(props: PanelProps) {
this.props = props;
}
render() {
const template = document.createElement('template');
const {
panelId,
headingId,
conte... | @@ -51,13 +51,13 @@ export class CollapsiblePanel {
</svg>
</button>
<h2 class="w-panel__heading w-panel__heading--label" aria-level="3" id="${headingId}" data-panel-heading>
- <span data-panel-heading-text class="c-sf-block__title"></span>
<span clas... | client/src/components/StreamField/blocks/CollapsiblePanel.ts | 0 | TypeScript | 1 | none | 16 | 51 | 51 | true | Always show block types in StreamField UI | 13,263 | wagtail/wagtail | 16,097 | Python | thibaudcolas | |
)
# no collection chooser when only one collection exists
self.assertNotContains(response, "id_adddocument_collection")
self.check_form_media_in_response(response)
def test_add_with_collections(self):
root_collection = Collection.get_first_root_node()
root_collecti... | No issues found. | )
# no collection chooser when only one collection exists
self.assertNotContains(response, "id_adddocument_collection")
self.check_form_media_in_response(response)
def test_add_with_collections(self):
root_collection = Collection.get_first_root_node()
root_collecti... | @@ -301,6 +301,96 @@ def test_tag_filtering_preserves_other_params(self):
"?p=3&tag=even" in response_body or "?tag=even&p=3" in response_body
)
+ def test_usage_count_column(self):
+ used_document = models.Document.objects.create(title="Used document")
+ unused_document... | wagtail/documents/tests/test_admin_views.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | Added Usage Count Filter | 13,291 | wagtail/wagtail | 16,097 | Python | joelwilliam2005 | |
myst_url_schemes = {
"https": None,
"http": None,
"mailto": None,
"client": {
"url": "/reference/ui/client/{{path}}.html#{{fragment}}",
"title": "{{path}}",
"classes": ["pre"],
},
"controller": {
"url": "/reference/ui/client/classes/controllers_{{path}}.{{path}}.... | No issues found. |
myst_url_schemes = {
"https": None,
"http": None,
"mailto": None,
"client": {
"url": "/reference/ui/client/{{path}}.html#{{fragment}}",
"title": "{{path}}",
"classes": ["pre"],
},
"controller": {
"url": "/reference/ui/client/classes/controllers_{{path}}.{{path}}.... | @@ -190,6 +190,16 @@
"https": None,
"http": None,
"mailto": None,
+ "client": {
+ "url": "/reference/ui/client/{{path}}.html#{{fragment}}",
+ "title": "{{path}}",
+ "classes": ["pre"],
+ },
+ "controller": {
+ "url": "/reference/ui/client/classes/controllers_{{path}}.... | docs/conf.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | Add docs for programmatic access to the editor's form element and the preview panel | 13,296 | wagtail/wagtail | 16,097 | Python | laymonage | |
)
self.assertContainsActiveFilter(
response,
"Page type: Simple page",
f"content_type={page_type_pk}",
)
# "Page" should not be listed as a content type
soup = self.get_soup(response.content)
page_type_labels = {
list(label... | No issues found. | )
self.assertContainsActiveFilter(
response,
"Page type: Simple page",
f"content_type={page_type_pk}",
)
# "Page" should not be listed as a content type
soup = self.get_soup(response.content)
page_type_labels = {
list(label... | @@ -11,7 +11,9 @@
from wagtail.models import GroupPagePermission, Locale, Page, Site, Workflow
from wagtail.test.testapp.models import (
CustomPermissionPage,
+ SimpleChildPage,
SimplePage,
+ SimpleParentPage,
SingleEventPage,
StandardIndex,
)
@@ -915,6 +917,29 @@ def test_explore_custom_pe... | wagtail/admin/tests/pages/test_explorer_view.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | Check if subpage models can be created in can_add_subpage | 13,297 | wagtail/wagtail | 16,097 | Python | lasse-cs | |
expect(simulateKey({ key: 'j' })).toHaveProperty('keypress', false);
expect(buttonClickMock).toHaveBeenCalledTimes(1);
expect(buttonClickMock.mock.contexts).toEqual([
document.getElementById('btn'),
]);
});
it('should call the click event when `ctrl+j` is pressed after being re... | No issues found. | expect(simulateKey({ key: 'j' })).toHaveProperty('keypress', false);
expect(buttonClickMock).toHaveBeenCalledTimes(1);
expect(buttonClickMock.mock.contexts).toEqual([
document.getElementById('btn'),
]);
});
it('should call the click event when `ctrl+j` is pressed after being re... | @@ -3,12 +3,6 @@ import Mousetrap from 'mousetrap';
import { KeyboardController } from './KeyboardController';
-jest.mock('../config/wagtailConfig', () => ({
- WAGTAIL_CONFIG: {
- KEYBOARD_SHORTCUTS_ENABLED: true,
- },
-}));
-
describe('KeyboardController', () => {
let app;
const buttonClickMock = jest... | client/src/controllers/KeyboardController.test.js | 0 | JavaScript | 1 | none | 16 | 51 | 51 | true | Handled user keyboard shortcut preference for comments shortcut | 13,313 | wagtail/wagtail | 16,097 | Python | dhruvipatel14 | |
self.test_snippet.refresh_from_db()
# The snippet will not be live
self.assertFalse(self.test_snippet.live)
# No new revision should have been created
self.assertEqual(self.test_snippet.latest_revision_id, latest_revision.pk)
# Should not show the draft go_live_at and ... | No issues found. | self.test_snippet.refresh_from_db()
# The snippet will not be live
self.assertFalse(self.test_snippet.live)
# No new revision should have been created
self.assertEqual(self.test_snippet.latest_revision_id, latest_revision.pk)
# Should not show the draft go_live_at and ... | @@ -999,12 +999,29 @@ def test_create_with_limited_permissions(self):
def test_create_invalid(self):
response = self.post(post_data={"foo": "bar"})
- self.assertContains(response, "The advert could not be created due to errors.")
- self.assertContains(response, "error-message", count=1)
- ... | wagtail/snippets/tests/test_snippets.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | Add a button to jump to the first validation error in header messages | 13,317 | wagtail/wagtail | 16,097 | Python | lb- | |
post_data = {
"title": "I've been edited!",
"content": "Some content",
"slug": "hello-world-new",
"action-publish": "Publish",
}
response = self.client.post(
reverse("wagtailadmin_pages:edit", args=(self.... | No issues found. | post_data = {
"title": "I've been edited!",
"content": "Some content",
"slug": "hello-world-new",
"action-publish": "Publish",
}
response = self.client.post(
reverse("wagtailadmin_pages:edit", args=(self.... | @@ -32,6 +32,7 @@
EVENT_AUDIENCE_CHOICES,
Advert,
AdvertPlacement,
+ CommentableJSONPage,
CustomPermissionPage,
EventCategory,
EventPage,
@@ -4107,3 +4108,73 @@ def test_only_comments_with_valid_paths_are_shown(self):
comment_text = [comment["text"] for comment in comments_data... | wagtail/admin/tests/pages/test_edit_page.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | Tests for Allow deep contentpath for comments on fields other than StreamField | 13,326 | wagtail/wagtail | 16,097 | Python | lasse-cs | |
notification emails. Tries to form a full URL using WAGTAILADMIN_BASE_URL
if the static URL isn't already a full URL.
"""
return urljoin(base_url_setting(), versioned_static_func(path))
@register.simple_tag
def versioned_static(path):
"""
Wrapper for Django's static file finder to append a cac... | No issues found. | notification emails. Tries to form a full URL using WAGTAILADMIN_BASE_URL
if the static URL isn't already a full URL.
"""
return urljoin(base_url_setting(), versioned_static_func(path))
@register.simple_tag
def versioned_static(path):
"""
Wrapper for Django's static file finder to append a cac... | @@ -1175,6 +1175,7 @@ def formattedfield(
label_text=None,
error_message_id=None,
wrapper_id=None,
+ attrs=None,
):
"""
Renders a form field in standard Wagtail admin layout.
@@ -1192,12 +1193,15 @@ def formattedfield(
- `label_text` - Manually set this if the field’s HTML is hard-code... | wagtail/admin/templatetags/wagtailadmin_tags.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | Add support for `attrs` in `formattedfield` tag | 13,335 | wagtail/wagtail | 16,097 | Python | lb- | |
it('should call the click event when `command+j` is pressed after being registered', async () => {
expect(buttonClickMock).not.toHaveBeenCalled();
await setup(
`<button id="btn" data-controller="w-kbd" data-w-kbd-key-value="command+j">Go</button>`,
);
simulateKey({ key: 'j', which:... | No issues found. | it('should call the click event when `command+j` is pressed after being registered', async () => {
expect(buttonClickMock).not.toHaveBeenCalled();
await setup(
`<button id="btn" data-controller="w-kbd" data-w-kbd-key-value="command+j">Go</button>`,
);
simulateKey({ key: 'j', which:... | @@ -3,9 +3,16 @@ import Mousetrap from 'mousetrap';
import { KeyboardController } from './KeyboardController';
+jest.mock('../utils/forceFocus', () => ({
+ forceFocus: jest.fn(),
+}));
+
+import { forceFocus } from '../utils/forceFocus';
+
describe('KeyboardController', () => {
let app;
const buttonClickMo... | client/src/controllers/KeyboardController.test.js | 0 | JavaScript | 1 | none | 16 | 51 | 51 | true | Added shortcut to focus on search bar | 13,336 | wagtail/wagtail | 16,097 | Python | dhruvipatel14 | |
]
),
}
),
)
def test_assert_can_create_subpage_rules(self):
simple_page = SimplePage(title="Simple Page", slug="simple", content="hello")
self.root.add_child(instance=simple_page)
# This should raise an error, a... | No issues found. | ]
),
}
),
)
def test_assert_can_create_subpage_rules(self):
simple_page = SimplePage(title="Simple Page", slug="simple", content="hello")
self.root.add_child(instance=simple_page)
# This should raise an error, a... | @@ -4,12 +4,13 @@
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django.core.files.uploadedfile import SimpleUploadedFile
-from django.template import Context, Template
-from django.test import TestCase
+from django.template import Context, Origin, Template
+from django... | wagtail/tests/test_tests.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | Only apply `WAGTAIL_CHECK_TEMPLATE_NUMBER_FORMAT` for Wagtail templates | 13,344 | wagtail/wagtail | 16,097 | Python | laymonage | |
def test_publishing_does_not_cancel_workflow_when_cancel_on_publish_false(
self,
):
data = self.start_workflow()
data["object"].get_latest_revision().publish()
workflow_state = data["workflow_state"]
workflow_state.refresh_from_db()
self.assertEqual(workflow_state... | No issues found. | def test_publishing_does_not_cancel_workflow_when_cancel_on_publish_false(
self,
):
data = self.start_workflow()
data["object"].get_latest_revision().publish()
workflow_state = data["workflow_state"]
workflow_state.refresh_from_db()
self.assertEqual(workflow_state... | @@ -1,4 +1,5 @@
import datetime
+from unittest import mock
from django.conf import settings
from django.contrib.auth import get_user_model
@@ -21,7 +22,12 @@
WorkflowState,
WorkflowTask,
)
-from wagtail.test.testapp.models import FullFeaturedSnippet, ModeratedModel, SimplePage
+from wagtail.test.testapp... | wagtail/tests/test_workflow.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | Prevent error when iterating over specific tasks | 13,377 | wagtail/wagtail | 16,097 | Python | lasse-cs | |
from django.test import SimpleTestCase
from wagtail.admin.icons import get_icon_sprite_hash, get_icon_sprite_url, get_icons
from wagtail.test.utils.wagtail_tests import WagtailTestUtils
class TestIconSpriteView(WagtailTestUtils, SimpleTestCase):
def test_content_type(self):
response = self.client.get(get... | No issues found. | from django.test import SimpleTestCase
from wagtail.admin.icons import get_icon_sprite_hash, get_icon_sprite_url, get_icons
from wagtail.test.utils.wagtail_tests import WagtailTestUtils
class TestIconSpriteView(WagtailTestUtils, SimpleTestCase):
def test_content_type(self):
response = self.client.get(get... | @@ -1,9 +1,10 @@
from django.test import SimpleTestCase
-from wagtail.admin.icons import get_icon_sprite_hash, get_icon_sprite_url
+from wagtail.admin.icons import get_icon_sprite_hash, get_icon_sprite_url, get_icons
+from wagtail.test.utils.wagtail_tests import WagtailTestUtils
-class TestIconSpriteView(SimpleT... | wagtail/admin/tests/test_icon_sprite.py | 0 | Python | 1 | none | 16 | 42 | 42 | true | Fix register_icons hook to pass accumulated icons to each hook | 13,420 | wagtail/wagtail | 16,097 | Python | joeyjurjens | |
// Should not yet have the has-errors class on the controlled element
expect(element.classList).not.toContain('w-preview--has-errors');
// Simulate the request completing
await Promise.resolve();
expect(events.json).toHaveLength(2);
// Should set the has-errors class on the control... | No issues found. | // Should not yet have the has-errors class on the controlled element
expect(element.classList).not.toContain('w-preview--has-errors');
// Simulate the request completing
await Promise.resolve();
expect(events.json).toHaveLength(2);
// Should set the has-errors class on the control... | @@ -2396,6 +2396,24 @@ describe('PreviewController', () => {
expect(content).toEqual(mockExtractedContent);
});
+ it('should not require opening the panel to do content extraction', async () => {
+ application = Application.start();
+ application.register(identifier, PreviewController);
+ ... | client/src/controllers/PreviewController.test.js | 0 | JavaScript | 1 | none | 16 | 51 | 51 | true | Allow PreviewController.extractContent() to work without opening the preview panel first | 13,462 | wagtail/wagtail | 16,097 | Python | laymonage | |
expect(getReadingTime(lang, wordCount)).toBe(readingTime);
});
});
describe.each`
text | lang | lix
${'Hello world less than 10 words.'} | ${'en'} | ${0}
${'This is a simple one just o... | No issues found. | expect(getReadingTime(lang, wordCount)).toBe(readingTime);
});
});
describe.each`
text | lang | lix
${'Hello world less than 10 words.'} | ${'en'} | ${0}
${'This is a simple one just o... | @@ -1,6 +1,8 @@
import {
getWordCount,
getReadingTime,
+ getLIXScore,
+ getReadabilityScore,
contentExtractorPluginInstance,
} from './contentMetrics';
@@ -43,6 +45,37 @@ describe.each`
});
});
+describe.each`
+ text | lan... | client/src/includes/contentMetrics.test.ts | 0 | TypeScript | 1 | none | 16 | 51 | 51 | true | Implement readability score based on LIX formula. Fix #13361 | 13,473 | wagtail/wagtail | 16,097 | Python | thibaudcolas | |
if the static URL isn't already a full URL.
"""
return urljoin(base_url_setting(), versioned_static_func(path))
@register.simple_tag
def versioned_static(path):
"""
Wrapper for Django's static file finder to append a cache-busting query parameter
that updates on each Wagtail version
"""
... | No issues found. | if the static URL isn't already a full URL.
"""
return urljoin(base_url_setting(), versioned_static_func(path))
@register.simple_tag
def versioned_static(path):
"""
Wrapper for Django's static file finder to append a cache-busting query parameter
that updates on each Wagtail version
"""
... | @@ -1338,13 +1338,23 @@ def keyboard_shortcuts_dialog(context):
appropriate shortcuts for the user's platform.
Note: Shortcut keys are intentionally not translated.
"""
+ request = context.get("request")
+ keyboard_shortcuts_enabled = True
+
+ if request and getattr(request, "user", None):
+ ... | wagtail/admin/templatetags/wagtailadmin_tags.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | Showing warning/info in the keyboard_shortcuts dialog | 13,476 | wagtail/wagtail | 16,097 | Python | p-r-a-v-i-n | |
# SnippetViewSet historically allows overriding the URL prefix via the
# get_admin_base_path method or the admin_base_path attribute, so preserve that here
return self.get_admin_base_path()
@cached_property
def url_namespace(self):
# SnippetViewSet historically allows overriding... | No issues found. | # SnippetViewSet historically allows overriding the URL prefix via the
# get_admin_base_path method or the admin_base_path attribute, so preserve that here
return self.get_admin_base_path()
@cached_property
def url_namespace(self):
# SnippetViewSet historically allows overriding... | @@ -1044,39 +1044,40 @@ def url_finder_class(self):
)
def get_urlpatterns(self):
+ conv = self.pk_path_converter
urlpatterns = [
path("", self.index_view, name="list"),
path("results/", self.index_results_view, name="list_results"),
path("add/", sel... | wagtail/snippets/views/snippets.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | Use correct converter depending on pk type for ModelViewSet | 13,490 | wagtail/wagtail | 16,097 | Python | SebCorbin | |
response = self.get()
self.assertEqual(response.status_code, 200)
self.assertTemplateUsed(response, "wagtailimages/chooser/chooser.html")
# Confirm that the Baker can see the sweet buns, but not the promotional poster.
self.assertContains(response, sweet_buns.title)
self... | No issues found. | response = self.get()
self.assertEqual(response.status_code, 200)
self.assertTemplateUsed(response, "wagtailimages/chooser/chooser.html")
# Confirm that the Baker can see the sweet buns, but not the promotional poster.
self.assertContains(response, sweet_buns.title)
self... | @@ -836,6 +836,32 @@ def test_image_search_when_layout_is_grid(self):
"Expected a ul element with class 'listing horiz images' in grid layout when searching for images.",
)
+ def test_order_by_usage_count_disabled_when_searching(self):
+ # Ordering by usage count not currently availabl... | wagtail/images/tests/test_admin_views.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | Disable usage count ordering when searching on documents and images listing views | 13,560 | wagtail/wagtail | 16,097 | Python | laymonage | |
_get() {
if ! $AWS_CLI s3 cp --region "${REGION}" "s3://${BUCKET}/latest.txt" "$1"; then
printf >&2 -- "%s: failed to download latest.txt; see above messages\\n" "$0"
exit 1
fi
}
_put() {
if ! $AWS_CLI s3 cp --region "${REGION}" "$1" "s3://${BUCKET}/latest.txt"; then
printf >&2 -- ... | No issues found. |
_get() {
if ! $AWS_CLI s3 cp --region "${REGION}" "s3://${BUCKET}/latest.txt" "$1"; then
printf >&2 -- "%s: failed to download latest.txt; see above messages\\n" "$0"
exit 1
fi
}
_put() {
if ! $AWS_CLI s3 cp --region "${REGION}" "$1" "s3://${BUCKET}/latest.txt"; then
printf >&2 -- ... | @@ -47,7 +47,7 @@ _get() {
}
_put() {
- if ! $AWS_CLI s3 cp --acl public-read --region "${REGION}" "$1" "s3://${BUCKET}/latest.txt"; then
+ if ! $AWS_CLI s3 cp --region "${REGION}" "$1" "s3://${BUCKET}/latest.txt"; then
printf >&2 -- "%s: failed to upload latest.txt; see above messages\\n" "$0"
... | scripts/latest.sh | 0 | Shell | 1 | none | 16 | 51 | 51 | true | Improve release upload scripts | 13,571 | wagtail/wagtail | 16,097 | Python | RealOrangeOne | |
def get_next_url(self):
next_url = self.index_url
request_query_string = self.request.META.get("QUERY_STRING")
if request_query_string:
next_url += "?" + request_query_string
return next_url
def get_add_url(self):
# Pass the collection filter to prefill the a... | No issues found. | def get_next_url(self):
next_url = self.index_url
request_query_string = self.request.META.get("QUERY_STRING")
if request_query_string:
next_url += "?" + request_query_string
return next_url
def get_add_url(self):
# Pass the collection filter to prefill the a... | @@ -85,13 +85,21 @@ def get_base_queryset(self):
self.request.user, ["change", "delete"]
).select_related("collection")
- # Annotate with usage count from the ReferenceIndex
- documents = documents.annotate(
- usage_count=ReferenceIndex.usage_count_subquery(self.model)
-... | wagtail/documents/views/documents.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | Use a separate and more efficient query for getting usage count on images and documents when not ordering by it | 13,597 | wagtail/wagtail | 16,097 | Python | laymonage | |
),
)
],
),
)
],
),
},
self.advert,
"Stream field... | No issues found. | ),
)
],
),
)
],
),
},
self.advert,
"Stream field... | @@ -21,6 +21,7 @@
EventPageCarouselItem,
EventPageRelatedLink,
EventPageSpeaker,
+ EventPageSpeakerAward,
GenericSnippetNoFieldIndexPage,
GenericSnippetNoIndexPage,
GenericSnippetPage,
@@ -319,28 +320,26 @@ def setUpTestData(cls):
management.call_command("rebuild_references_ind... | wagtail/tests/test_reference_index.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | Issue 13614: ReferenceIndex not handling properly multiple ManyToOne fields. | 13,618 | wagtail/wagtail | 16,097 | Python | non4me21 | |
def non_json_hook_func(request, page):
self.assertIsInstance(request, HttpRequest)
self.assertEqual(page.id, self.child_page.id)
return HttpResponse("Overridden!")
def json_hook_func(request, page):
self.assertIsInstance(request, HttpRequest)
... | No issues found. | def non_json_hook_func(request, page):
self.assertIsInstance(request, HttpRequest)
self.assertEqual(page.id, self.child_page.id)
return HttpResponse("Overridden!")
def json_hook_func(request, page):
self.assertIsInstance(request, HttpRequest)
... | @@ -242,6 +242,23 @@ def test_page_edit(self):
expected_url = "/admin/pages/%d/edit/" % self.event_page.id
self.assertEqual(url_finder.get_edit_url(self.event_page), expected_url)
+ def test_loaded_revision_id_included_in_form(self):
+ # Ensure there's a revision for the page
+ self... | wagtail/admin/tests/pages/test_edit_page.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | Prevent creating a new revision via JSON request if the loaded revision is not the latest | 13,684 | wagtail/wagtail | 16,097 | Python | laymonage | |
)
self.assertEqual(response.status_code, 200)
self.assertEqual(response.json(), {"status": "purple"})
def test_before_edit_page_hook_post(self):
def hook_func(request, page):
self.assertIsInstance(request, HttpRequest)
self.assertEqual(page.id, self.chil... | No issues found. | )
self.assertEqual(response.status_code, 200)
self.assertEqual(response.json(), {"status": "purple"})
def test_before_edit_page_hook_post(self):
def hook_func(request, page):
self.assertIsInstance(request, HttpRequest)
self.assertEqual(page.id, self.chil... | @@ -242,7 +242,7 @@ def test_page_edit(self):
expected_url = "/admin/pages/%d/edit/" % self.event_page.id
self.assertEqual(url_finder.get_edit_url(self.event_page), expected_url)
- def test_loaded_revision_id_included_in_form(self):
+ def test_loaded_revision_id_and_timestamp_included_in_form(... | wagtail/admin/tests/pages/test_edit_page.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | Prevent creating a new revision via JSON request if the loaded revision timestamp is not the latest | 13,688 | wagtail/wagtail | 16,097 | Python | laymonage | |
<div id="target-container"><p>I should not be here</p></div>
`;
const template = document.querySelector('template');
template.setAttribute(
'data-w-teleport-target-value',
'#target-container',
);
template.setAttribute('data-w-teleport-reset-value', 'true');
... | No issues found. | <div id="target-container"><p>I should not be here</p></div>
`;
const template = document.querySelector('template');
template.setAttribute(
'data-w-teleport-target-value',
'#target-container',
);
template.setAttribute('data-w-teleport-reset-value', 'true');
... | @@ -365,6 +365,35 @@ describe('TeleportController', () => {
expect(contents).toEqual('');
});
+ it('should run inline scripts contained in the template content', async () => {
+ document.body.innerHTML += /* html */ `
+ <div id="target-container"></div>
+ `;
+
+ const template = d... | client/src/controllers/TeleportController.test.js | 0 | JavaScript | 1 | none | 16 | 51 | 51 | true | Add `mode` value to `w-teleport` to allow different DOM update strategies | 13,731 | wagtail/wagtail | 16,097 | Python | laymonage | |
def get_axe_custom_checks(self, request):
return super().get_axe_custom_checks(request) + [
{
"id": "check-link-text",
"options": {"pattern": "learn more$"},
}
]
with hooks.regist... | No issues found. | def get_axe_custom_checks(self, request):
return super().get_axe_custom_checks(request) + [
{
"id": "check-link-text",
"options": {"pattern": "learn more$"},
}
]
with hooks.regist... | @@ -9,6 +9,7 @@
from wagtail import hooks
from wagtail.admin.staticfiles import versioned_static
+from wagtail.admin.ui.components import Component
from wagtail.admin.userbar import AccessibilityItem, Userbar
from wagtail.coreutils import get_dummy_request
from wagtail.models import PAGE_TEMPLATE_VAR, Locale, Pa... | wagtail/admin/tests/test_userbar.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | Support custom client-side checks in accessibility checker - template components variant. Fix #12936 | 13,758 | wagtail/wagtail | 16,097 | Python | thibaudcolas | |
dependencies = [
("tests", "0060_eventpagespeakeraward_certificate"),
]
operations = [
migrations.CreateModel(
name="RevisableCluster",
fields=[
(
"id",
models.AutoField(
auto_created=Tru... | No issues found. | dependencies = [
("tests", "0060_eventpagespeakeraward_certificate"),
]
operations = [
migrations.CreateModel(
name="RevisableCluster",
fields=[
(
"id",
models.AutoField(
auto_created=Tru... | @@ -0,0 +1,68 @@
+# Generated by Django 5.2.10 on 2026-02-16 14:54
+
+import django.db.models.deletion
+import modelcluster.fields
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("tests", "0060_eventpagespeakeraward_certificate"),
+ ]
+
+ ope... | wagtail/test/testapp/migrations/0061_revisablecluster_revisableclusterchild.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | Fix duplicate inline panel items when editing snippets with autosave enabled | 13,913 | wagtail/wagtail | 16,097 | Python | laymonage | |
const newPath = path.split("/");
let schemaPart = schema;
for (let i = 1; i < newPath.length; i++) {
const inner = schemaPart[newPath[i]];
if (!inner) {
break;
}
schemaPart = inner;
}
return schemaPart;
};
/**
*
* @param {PathItem[]} path path in the schema
* @returns {string | u... | since this is cli specific this should be moved into `schema.cli.description` | const newPath = path.split("/");
let schemaPart = schema;
for (let i = 1; i < newPath.length; i++) {
const inner = schemaPart[newPath[i]];
if (!inner) {
break;
}
schemaPart = inner;
}
return schemaPart;
};
/**
*
* @param {PathItem[]} path path in the schema
* @returns {string | u... | @@ -97,10 +98,23 @@ const getArguments = (schema = webpackSchema) => {
const getDescription = path => {
for (const { schema } of path) {
if (schema.cli && schema.cli.helper) continue;
+ if (schema.cliDescription) return schema.cliDescription; | lib/cli.js | 26 | JavaScript | 0.571 | suggestion | 77 | 51 | 51 | false | feat: allow specific description for CLI options | 14,953 | webpack/webpack | 65,000 | JavaScript | sokra | snitin315 |
return schemaPart;
};
/**
*
* @param {PathItem[]} path path in the schema
* @returns {string | undefined} description
*/
const getDescription = path => {
for (const { schema } of path) {
if (schema.cli && schema.cli.helper) continue;
if (schema.cliDescription) return schema.cliDescription;
if ... | ```suggestion
if (schema.cli.negatedDescription) return schema.cli.negatedDescription;
``` |
return schemaPart;
};
/**
*
* @param {PathItem[]} path path in the schema
* @returns {string | undefined} description
*/
const getDescription = path => {
for (const { schema } of path) {
if (schema.cli) {
if (schema.cli.helper) continue;
if (schema.cli.description) return schema.cli.descript... | @@ -97,10 +98,23 @@ const getArguments = (schema = webpackSchema) => {
const getDescription = path => {
for (const { schema } of path) {
if (schema.cli && schema.cli.helper) continue;
+ if (schema.cliDescription) return schema.cliDescription;
if (schema.description) return schema.description;
}
};
... | lib/cli.js | 26 | JavaScript | 0.857 | suggestion | 95 | 51 | 51 | false | feat: allow specific description for CLI options | 14,953 | webpack/webpack | 65,000 | JavaScript | sokra | snitin315 |
/** @type {false | TemplatePath} */
let currentSourceMappingURLComment = sourceMappingURLComment;
const cssExtensionDetected =
CSS_EXTENSION_DETECT_REGEXP.test(file);
resetRegexpState(CSS_EXTENSION_DETECT_REGEXP);
if (
currentSourceMappingURLComment !== ... | https://webpack.js.org/configuration/output/#outputhashfunction | }
/** @type {false | TemplatePath} */
let currentSourceMappingURLComment = sourceMappingURLComment;
const cssExtensionDetected =
CSS_EXTENSION_DETECT_REGEXP.test(file);
resetRegexpState(CSS_EXTENSION_DETECT_REGEXP);
if (
currentSourceMappingURLC... | @@ -479,6 +479,34 @@ class SourceMapDevToolPlugin {
"\n/*$1*/"
);
}
+
+ if (options.debugIds) {
+ // We need a uuid which is 128 bits so we need 2x 64 bit hashes.
+ // The first 64 bits is a hash of the source.
+ const sourceHash = createHash("xxhash... | lib/SourceMapDevToolPlugin.js | 26 | JavaScript | 0.143 | suggestion | 63 | 51 | 51 | false | feat: Add support for injecting sourcemap debug ids | 18,947 | webpack/webpack | 65,000 | JavaScript | alexander-akait | timfish |
}
}
if (options.output.pathinfo) {
const ModuleInfoHeaderPlugin = require("./ModuleInfoHeaderPlugin");
new ModuleInfoHeaderPlugin(options.output.pathinfo !== true).apply(
compiler
);
}
if (options.output.clean) {
const CleanPlugin = require("./CleanPlugin");
new CleanPlugin(
options.... | ```suggestion
const debugIds = options.devtool.includes("debugids");
```
Should we make this `debugids` instead? I am thinking it is probably better because `-` is sort of like a delimiter with the `devtool` option. | }
}
if (options.output.pathinfo) {
const ModuleInfoHeaderPlugin = require("./ModuleInfoHeaderPlugin");
new ModuleInfoHeaderPlugin(options.output.pathinfo !== true).apply(
compiler
);
}
if (options.output.clean) {
const CleanPlugin = require("./CleanPlugin");
new CleanPlugin(
options.... | @@ -264,6 +264,7 @@ class WebpackOptionsApply extends OptionsApply {
const cheap = options.devtool.includes("cheap");
const moduleMaps = options.devtool.includes("module");
const noSources = options.devtool.includes("nosources");
+ const debugIds = options.devtool.includes("debug-ids"); | lib/WebpackOptionsApply.js | 26 | JavaScript | 1 | bug | 224 | 51 | 51 | false | feat: Add support for injecting sourcemap debug ids | 18,947 | webpack/webpack | 65,000 | JavaScript | lforst | timfish |
return JS_AND_CSS_EXPORT_TYPES;
}
const sourceTypes = new Set();
const connections = this._moduleGraph.getIncomingConnections(module);
for (const connection of connections) {
if (!connection.originModule) {
continue;
}
sourceTypes.add(connection.originModule.type.split("/")[0]);
}
if (source... | How about we detect if all source types are CSS related types, I don't know if lazy proxied module can have connection to css after sideEffectPlugin optimization | return null;
}
}
/**
* @param {NormalModule} module fresh module
* @returns {SourceTypes} available types (do not mutate)
*/
getTypes(module) {
// TODO, find a better way to prevent the original module from being removed after concatenation, maybe it is a bug
if (this.exportsOnly) {
return JS_AND... | @@ -211,8 +219,21 @@ class CssGenerator extends Generator {
* @returns {SourceTypes} available types (do not mutate)
*/
getTypes(module) {
- // TODO, find a better way to prevent the original module from being removed after concatenation, maybe it is a bug
- return this.exportsOnly ? JS_AND_CSS_EXPORT_TYPES :... | lib/css/CssGenerator.js | 26 | JavaScript | 0.571 | suggestion | 161 | 51 | 51 | false | fix(css): avoid extra module.export output for css module | 19,265 | webpack/webpack | 65,000 | JavaScript | JSerFeng | hai-x |
/** @typedef {import("../DependencyTemplate").CssData} CssData */
/** @typedef {import("../DependencyTemplate").CssDependencyTemplateContext} DependencyTemplateContext */
/** @typedef {import("../Generator").GenerateContext} GenerateContext */
/** @typedef {import("../Generator").UpdateHashContext} UpdateHashContext */... | Just idea, can we pass `moduleGraph` to `getTypes`, because in all non JS generators we need it? | /** @typedef {import("../CodeGenerationResults")} CodeGenerationResults */
/** @typedef {import("../Dependency")} Dependency */
/** @typedef {import("../DependencyTemplate").CssData} CssData */
/** @typedef {import("../DependencyTemplate").CssDependencyTemplateContext} DependencyTemplateContext */
/** @typedef {import(... | @@ -28,19 +29,22 @@ const Template = require("../Template");
/** @typedef {import("../Generator").UpdateHashContext} UpdateHashContext */
/** @typedef {import("../Module").ConcatenationBailoutReasonContext} ConcatenationBailoutReasonContext */
/** @typedef {import("../Module").SourceTypes} SourceTypes */
+/** @typed... | lib/css/CssGenerator.js | 26 | JavaScript | 0.857 | question | 96 | 51 | 51 | false | fix(css): avoid extra module.export output for css module | 19,265 | webpack/webpack | 65,000 | JavaScript | alexander-akait | hai-x |
for (const [name, v] of cssData.exports) {
exports.push(`\t${JSON.stringify(name)}: ${JSON.stringify(v)}`);
}
return new RawSource(
`${needNsObj ? `${RuntimeGlobals.makeNamespaceObject}(` : ""}${
module.moduleArgument
}.exports = {\n${exports.join(",\n")}\n}${needNsObj ? ")" : ""};`
... | I think this todo is still valid, try to change `JS_AND_CSS_EXPORT_TYPES` on `JS_AND_CSS_TYPES` (because technically it is JS and CSS, new type was added only to prevent this bug) and concatenation plugin will failed on our tests... I think it is a bug | if (needNsObj) {
generateContext.runtimeRequirements.add(
RuntimeGlobals.makeNamespaceObject
);
}
const exports = [];
for (const [name, v] of cssData.exports) {
exports.push(`\t${JSON.stringify(name)}: ${JSON.stringify(v)}`);
}
return new RawSource(
`${needNsObj ? `$... | @@ -211,8 +219,21 @@ class CssGenerator extends Generator {
* @returns {SourceTypes} available types (do not mutate)
*/
getTypes(module) {
- // TODO, find a better way to prevent the original module from being removed after concatenation, maybe it is a bug | lib/css/CssGenerator.js | 26 | JavaScript | 1 | bug | 252 | 51 | 51 | false | fix(css): avoid extra module.export output for css module | 19,265 | webpack/webpack | 65,000 | JavaScript | alexander-akait | hai-x |
}
}
const enabledLibraryTypes =
/** @type {NonNullable<WebpackOptions["output"]["enabledLibraryTypes"]>} */
(options.output.enabledLibraryTypes);
if (enabledLibraryTypes.length > 0) {
let once = true;
for (const type of enabledLibraryTypes) {
const EnableLibraryPlugin = require("./library/Ena... | Looks good, what is about apply it only for require libraries, i.e. where we use `getExportsInfo()`/`getExportInfo()`? | }
}
const enabledLibraryTypes =
/** @type {NonNullable<WebpackOptions["output"]["enabledLibraryTypes"]>} */
(options.output.enabledLibraryTypes);
if (enabledLibraryTypes.length > 0) {
let once = true;
for (const type of enabledLibraryTypes) {
const EnableLibraryPlugin = require("./library/Ena... | @@ -236,9 +237,21 @@ class WebpackOptionsApply extends OptionsApply {
(options.output.enabledLibraryTypes);
if (enabledLibraryTypes.length > 0) {
+ let once = true;
for (const type of enabledLibraryTypes) {
const EnableLibraryPlugin = require("./library/EnableLibraryPlugin");
- new EnableLibraryP... | lib/WebpackOptionsApply.js | 26 | JavaScript | 0.714 | question | 118 | 51 | 51 | false | fix: library module without export statement | 19,411 | webpack/webpack | 65,000 | JavaScript | alexander-akait | hai-x |
import * as namespace from "./module.js";
it("should work with destructuring", function() {
{
const { foo } = namespace;
expect(foo).toBe("foo");
}
{
let foo;
({ foo } = namespace);
expect(foo).toBe("foo");
}
{
let foo;
({ foo = 'foo' } = namespace);
expect(foo).toBe("foo");
}
{
const { foo... | could consider adding a test case where the default gets used, e.g.
```js
{
const { bar = 'foo' } = namespace;
expect(bar).toBe("foo");
}
``` | import * as namespace from "./module.js";
it("should work with destructuring", function() {
{
const { foo } = namespace;
expect(foo).toBe("bar");
}
{
let foo;
({ foo } = namespace);
expect(foo).toBe("bar");
}
{
let foo;
({ foo = 'foo' } = namespace);
expect(foo).toBe("bar");
}
{
const { foo... | test/configCases/parsing/destructuring-namespace-import/index.js | 1 | JavaScript | 1 | suggestion | 153 | 26 | 26 | false | fix: destructuring namespace import with default | 19,526 | webpack/webpack | 65,000 | JavaScript | TomStrepsil | alexander-akait | |
}
}
}
/**
* @param {ObjectPattern} objectPattern object pattern
* @returns {Set<DestructuringAssignmentProperty> | undefined} set of names or undefined if not all keys are identifiers
*/
_preWalkObjectPattern(objectPattern) {
/** @type {Set<DestructuringAssignmentProperty>} */
const props = new Set()... | It seems we can delete this "if", as it is already covered by the preceding if condition. | }
}
}
/**
* @param {ObjectPattern} objectPattern object pattern
* @returns {Set<DestructuringAssignmentProperty> | undefined} set of names or undefined if not all keys are identifiers
*/
_preWalkObjectPattern(objectPattern) {
/** @type {Set<DestructuringAssignmentProperty>} */
const props = new Set()... | @@ -2852,6 +2852,16 @@ class JavascriptParser extends Parser {
for (let i = 0; i < properties.length; i++) {
const property = properties[i];
if (property.type !== "Property") return;
+ if (property.shorthand) {
+ if (property.value.type === "Identifier") {
+ this.scope.inShorthand = property.value.n... | lib/javascript/JavascriptParser.js | 26 | JavaScript | 0.143 | suggestion | 89 | 51 | 51 | false | fix: destructuring namespace import with default | 19,526 | webpack/webpack | 65,000 | JavaScript | hai-x | alexander-akait |
parser.hooks.terminate.tap(PLUGIN_NAME, statement => true);
parser.hooks.statementIf.tap(PLUGIN_NAME, statement => {
if (parser.scope.isAsmJs) return;
const param = parser.evaluateExpression(statement.test);
const bool = param.asBool();
if (typeof bool === "boolean") {
if (!para... | What about `unusedStatement`? `dead` is more a harsher word :smile: | parser.hooks.terminate.tap(PLUGIN_NAME, statement => true);
parser.hooks.statementIf.tap(PLUGIN_NAME, statement => {
if (parser.scope.isAsmJs) return;
const param = parser.evaluateExpression(statement.test);
const bool = param.asBool();
if (typeof bool === "boolean") {
if (!para... | @@ -179,53 +179,21 @@ class ConstPlugin {
? statement.alternate
: statement.consequent;
if (branchToRemove) {
- // Before removing the dead branch, the hoisted declarations
- // must be collected.
- //
- // Given the following code:
- //
- // if (t... | lib/ConstPlugin.js | 26 | JavaScript | 0.571 | question | 68 | 51 | 51 | false | fix: eliminate unused statements in certain scenarios | 19,536 | webpack/webpack | 65,000 | JavaScript | alexander-akait | hai-x |
// var x, {y, z} = obj
// }
// } else {
// …
// }
//
// the generated code is:
//
// if (true) f() else {}
// if (false) {
// var f, x, y, z; (in loose mode)
// var x, y, z; (in strict mode)
// } else {
// …
// }
//
/... | Let's add a comment `// removed by dead control flow\n${replacement}` (maybe better) for debug reasons | // var x, {y, z} = obj
// }
// } else {
// …
// }
//
// the generated code is:
//
// if (true) f() else {}
// if (false) {
// var f, x, y, z; (in loose mode)
// var x, y, z; (in strict mode)
// } else {
// …
// }
//
/... | @@ -534,6 +502,56 @@ class ConstPlugin {
}
);
}
+
+ /**
+ * Eliminate a dead statement.
+ * @param {JavascriptParser} parser the parser
+ * @param {Statement} statement the statement to remove
+ * @returns {void}
+ */
+ eliminateDeadStatement(parser, statement) {
+ // Before removing the dead branch, the... | lib/ConstPlugin.js | 26 | JavaScript | 1 | bug | 103 | 35 | 35 | false | fix: eliminate unused statements in certain scenarios | 19,536 | webpack/webpack | 65,000 | JavaScript | alexander-akait | hai-x |
module
) => {
const normalizedSpecifier =
specifier.startsWith("file:")
? `./${path.relative(
path.dirname(p),
fileURLToPath(specifier)
)}`
: specifier.replace(
... | The diff may be unreadable. And here i just delete `if (esm.status !== "evaluated") {`. | importModuleDynamically: async (
specifier,
module
) => {
const normalizedSpecifier =
specifier.startsWith("file:")
? `./${path.relative(
path.dirname(p),
fileURLToPat... | @@ -360,29 +362,27 @@ const describeCases = config => {
if (esmMode === "unlinked") return esm;
return (async () => {
if (esmMode === "unlinked") return esm;
- if (esm.status !== "evaluated") { | test/WatchTestCases.template.js | 26 | JavaScript | 0.357 | suggestion | 87 | 51 | 51 | false | test: refactor watchTestCase when ESM | 19,571 | webpack/webpack | 65,000 | JavaScript | hai-x | hai-x |
if (err) {
oldAssets = undefined;
} else {
if (oldAssets) mergeAssets(currentAssets, oldAssets);
oldAssets = currentAssets;
if (keptAssets) mergeAssets(oldAssets, keptAssets);
}
callback(err);
}
);
};
if (oldAssets) {
diffCallback(null... | Let's implement them as a plugin methods (using `_` before method, i.e. `_isEqualPath` and for other too), don't want to make them as a part of public API | if (err) {
oldAssets = undefined;
} else {
if (oldAssets) mergeAssets(currentAssets, oldAssets);
oldAssets = currentAssets;
if (keptAssets) mergeAssets(oldAssets, keptAssets);
}
callback(err);
}
);
};
if (oldAssets) {
diffCallback(null... | @@ -443,3 +495,6 @@ class CleanPlugin {
}
module.exports = CleanPlugin;
+module.exports.getDirectories = getDirectories;
+module.exports.hasFile = hasFile;
+module.exports.isEqualPath = isEqualPath; | lib/CleanPlugin.js | 26 | JavaScript | 0.5 | suggestion | 154 | 27 | 27 | false | fix: CleanPlugin unlink same file twice | 19,595 | webpack/webpack | 65,000 | JavaScript | alexander-akait | xiaoxiaojx |
"Object.getPrototypeOf(obj)",
"obj"
)} : ${runtimeTemplate.returningFunction("obj.__proto__", "obj")};`,
"var leafPrototypes;",
"// create a fake namespace object",
"// mode & 1: value is a module id, require it",
"// mode & 2: merge all properties of value into the ns",
"// mode & 4: return v... | `function` have several own properties, such as name/length/prototype/caller...
Using `Object.getOwnPropertyNames(fn)` retrieves both enumerable and non-enumerable own properties. It will return `["length", "name", "arguments", "caller", "prototype"]`.
When bundle following code based changes in this PR.
```j... | "Object.getPrototypeOf(obj)",
"obj"
)} : ${runtimeTemplate.returningFunction("obj.__proto__", "obj")};`,
"var leafPrototypes;",
"// create a fake namespace object",
"// mode & 1: value is a module id, require it",
"// mode & 2: merge all properties of value into the ns",
"// mode & 4: return v... | @@ -49,7 +49,7 @@ class CreateFakeNamespaceObjectRuntimeModule extends HelperRuntimeModule {
`${RuntimeGlobals.makeNamespaceObject}(ns);`,
"var def = {};",
"leafPrototypes = leafPrototypes || [null, getProto({}), getProto([]), getProto(getProto)];",
- "for(var current = mode & 2 && value; typeof curre... | lib/runtime/CreateFakeNamespaceObjectRuntimeModule.js | 26 | JavaScript | 1 | suggestion | 778 | 44 | 44 | false | fix: CreateFakeNamespaceObject supports the export is a function | 19,609 | webpack/webpack | 65,000 | JavaScript | hai-x | xiaoxiaojx |
"error.message = 'Loading hot update chunk ' + chunkId + ' failed.\\n(' + errorMsg + ')';",
"error.name = 'ChunkLoadError';",
"reject(error);"
])}`,
`var loadScript = ${runtimeTemplate.basicFunction(
"url, onResolve, onReject",
[
`return ${i... | Why remove? If we try to bundle already bundled webpack without it will output an error/warning | "error.message = 'Loading hot update chunk ' + chunkId + ' failed.\\n(' + errorMsg + ')';",
"error.name = 'ChunkLoadError';",
"reject(error);"
])}`,
`var loadScript = ${runtimeTemplate.basicFunction(
"url, onResolve, onReject",
[
`return ${i... | @@ -407,7 +389,7 @@ class ModuleChunkLoadingRuntimeModule extends RuntimeModule {
`var loadScript = ${runtimeTemplate.basicFunction(
"url, onResolve, onReject",
[
- `return ${importFunctionName}(/* webpackIgnore: true */ url).then(onResolve).catch(onReject)` | lib/esm/ModuleChunkLoadingRuntimeModule.js | 26 | JavaScript | 0.643 | question | 95 | 41 | 38 | false | refactor: consolidate HMR code | 19,629 | webpack/webpack | 65,000 | JavaScript | alexander-akait | hai-x |
node: true,
web: true,
webworker: null,
browser: false,
electron: false,
nwjs: true,
global: true,
nodeBuiltins: true,
document: false,
importScriptsInWorker: false,
fetchWasm: false,
importScripts: false,
require: false,
globalThis: v(0, 43),
const: v(0, 15... | Confirmed
https://nwjs.io/blog/v0.44.0/#:~:text=ECMAScript%20Modules%20in%20Web%20Workers
updated to v44 by 8cc6e0c2b94837369f711679331d47583b72e905 | node: true,
web: true,
webworker: null,
browser: false,
electron: false,
nwjs: true,
global: true,
nodeBuiltins: true,
document: false,
importScriptsInWorker: false,
fetchWasm: false,
importScripts: false,
require: false,
globalThis: v(0, 43),
const: v(0, 15... | @@ -278,7 +278,7 @@ You can also more options via the 'target' option: 'browserslist' / 'browserslis
destructuring: v(0, 15),
bigIntLiteral: v(0, 32),
dynamicImport: v(0, 43),
- dynamicImportInWorker: major ? false : undefined,
+ dynamicImportInWorker: v(0, 43), | lib/config/target.js | 26 | JavaScript | 0.286 | suggestion | 154 | 51 | 51 | false | feat: enable ESM worker chunk loading for Node.js targets | 19,640 | webpack/webpack | 65,000 | JavaScript | 3ru | 3ru |
new ModuleChunkLoadingRuntimeModule(set)
);
};
compilation.hooks.runtimeRequirementInTree
.for(RuntimeGlobals.ensureChunkHandlers)
.tap(PLUGIN_NAME, handler);
compilation.hooks.runtimeRequirementInTree
.for(RuntimeGlobals.baseURI)
.tap(PLUGIN_NAME, handler);
compilation.hooks.runtim... | Could you elaborate more on why here? | };
compilation.hooks.runtimeRequirementInTree
.for(RuntimeGlobals.ensureChunkHandlers)
.tap(PLUGIN_NAME, handler);
compilation.hooks.runtimeRequirementInTree
.for(RuntimeGlobals.baseURI)
.tap(PLUGIN_NAME, handler);
compilation.hooks.runtimeRequirementInTree
.for(RuntimeGlobals.externalIn... | @@ -73,6 +75,7 @@ class ModuleChunkLoadingPlugin {
.for(RuntimeGlobals.externalInstallChunk)
.tap(PLUGIN_NAME, (chunk, set) => {
if (!isEnabledForChunk(chunk)) return;
+ if (!runtimeChunk) return; | lib/esm/ModuleChunkLoadingPlugin.js | 26 | JavaScript | 0.286 | question | 37 | 51 | 51 | false | fix(esm): ensure dependent chunks are imported before startup & fix duplicate export of 'default' | 19,661 | webpack/webpack | 65,000 | JavaScript | hai-x | xiaoxiaojx |
* @param {WebpackOptions} options webpack options
* @param {Compilation} compilation the compilation
* @param {ResolverWithOptions} resolver the resolver
* @param {InputFileSystem} fs the file system
* @param {BuildCallback} callback callback function
* @returns {void}
*/
build(options, compilation, reso... | That is wrong, raw module is just a raw and can have side effects | * @param {WebpackOptions} options webpack options
* @param {Compilation} compilation the compilation
* @param {ResolverWithOptions} resolver the resolver
* @param {InputFileSystem} fs the file system
* @param {BuildCallback} callback callback function
* @returns {void}
*/
build(options, compilation, reso... | @@ -105,6 +107,14 @@ class RawModule extends Module {
callback();
}
+ /**
+ * @param {ModuleGraph} moduleGraph the module graph
+ * @returns {ConnectionState} how this module should be connected to referencing modules when consumed for side-effects only
+ */
+ getSideEffectsConnectionState(moduleGraph) {
+ r... | lib/RawModule.js | 26 | JavaScript | 0.143 | bug | 65 | 51 | 51 | false | fix: tree-shaking unused `RawModule` | 19,671 | webpack/webpack | 65,000 | JavaScript | alexander-akait | colinaaa |
}
/**
* @returns {string | null} absolute path which should be used for condition matching (usually the resource path)
*/
nameForCondition() {
return null;
}
/**
* @param {ConcatenationBailoutReasonContext} context context
* @returns {string | undefined} reason why this module can't be concatenated, un... | Please put this login inside `RawModule`, otherwise it is potential breaking changes for plugins | }
/**
* @returns {string | null} absolute path which should be used for condition matching (usually the resource path)
*/
nameForCondition() {
return null;
}
/**
* @param {ConcatenationBailoutReasonContext} context context
* @returns {string | undefined} reason why this module can't be concatenated, un... | @@ -986,6 +986,10 @@ class Module extends DependenciesBlock {
* @returns {ConnectionState} how this module should be connected to referencing modules when consumed for side-effects only
*/
getSideEffectsConnectionState(moduleGraph) {
+ if (this.factoryMeta !== undefined) {
+ if (this.factoryMeta.sideEffectFr... | lib/Module.js | 26 | JavaScript | 0.571 | suggestion | 96 | 51 | 51 | false | fix: tree-shaking unused `RawModule` | 19,671 | webpack/webpack | 65,000 | JavaScript | alexander-akait | colinaaa |
});
if (dependencies.length > 0) {
const dep = new HarmonyAcceptDependency(
/** @type {Range} */
(expr.range),
dependencies,
false
);
dep.loc = /** @type {DependencyLocation} */ (expr.loc);
parser.state.module.addDependency(dep);
}
});
}
};
/**
* @param {JavascriptParse... | We don't need to check `deferImportEnabled` or `reportSyntaxError` here.
The `node.phase` in AST is injected by `acorn-import-phases`, so it only exists when enabled `deferImport`.
If disabled, one module parse error will occur instead. These module parse errors appear earliest. | });
}
};
/**
* @param {JavascriptParser} parser parser
* @param {ExportNamedDeclaration | ExportAllDeclaration | ImportDeclaration} node node
* @returns {{defer: boolean}} import attributes
*/
function getImportMode(parser, node) {
const result = { defer: "phase" in node && node.phase === "defer" };
if (!node... | @@ -398,23 +387,10 @@ module.exports = class HarmonyImportDependencyParserPlugin {
/**
* @param {JavascriptParser} parser parser
* @param {ExportNamedDeclaration | ExportAllDeclaration | ImportDeclaration} node node
- * @param {boolean | undefined} deferImportEnabled defer import enabled
- * @param {boolean} repor... | lib/dependencies/HarmonyImportDependencyParserPlugin.js | 26 | JavaScript | 1 | suggestion | 287 | 51 | 46 | false | refactor: extend importPhasesPlugin only when enable deferImport | 19,689 | webpack/webpack | 65,000 | JavaScript | hai-x | hai-x |
Object {
"argument": "module-wrapped-context-reg-exp",
"expected": "regular expression (example: /ab?c*/)",
"index": undefined,
"path": "module.wrappedContextRegExp",
"type": "invalid-value",
"value": 123,
},
Object {
"argument": "my-argument",
"pat... | https://github.com/jestjs/jest/blob/2a436b81249e31db22b27d1182ae15b439290efe/packages/jest-worker/src/workers/ChildProcessWorker.ts#L136 | Object {
"argument": "module-wrapped-context-reg-exp",
"expected": "regular expression (example: /ab?c*/)",
"index": undefined,
"path": "module.wrappedContextRegExp",
"type": "invalid-value",
"value": 123,
},
Object {
"argument": "my-argument",
"pat... | @@ -429,6 +429,14 @@ describe("Cli", () => {
// Most important - it clears the cache
jest.resetModules();
process.env = { ...OLD_ENV };
+ // Prevent `process.env.FORCE_COLOR` from being auto set by `jest-worker` | test/Cli.basictest.js | 26 | JavaScript | 0.286 | suggestion | 136 | 51 | 51 | false | test: correct local cli test | 19,717 | webpack/webpack | 65,000 | JavaScript | hai-x | hai-x |
expect(isColorSupported()).toBe(true);
});
it("env TERM", () => {
const isCI =
"CI" in process.env &&
("GITHUB_ACTIONS" in process.env ||
"GITLAB_CI" in process.env ||
"CIRCLECI" in process.env);
process.env.TERM = "dumb";
expect(isColorSupported()).toBe(isCI);
});
it("env CI"... | We need both `CI` and `GITHUB_ACTIONS /GITLAB_CI/CIRCLECI` | it("env NO_COLOR", () => {
process.env.NO_COLOR = "1";
expect(isColorSupported()).toBe(false);
});
it("env FORCE_COLOR", () => {
process.env.FORCE_COLOR = "1";
expect(isColorSupported()).toBe(true);
});
it("env TERM", () => {
const isCI =
"CI" in process.env &&
("GITHUB_ACTIONS" in ... | @@ -459,25 +467,22 @@ describe("Cli", () => {
expect(isColorSupported()).toBe(isCI);
});
- it("env CI", () => {
- process.env.CI = "1";
-
- expect(isColorSupported()).toBe(true);
- });
-
it("env GITHUB_ACTIONS", () => {
+ process.env.CI = "1"; | test/Cli.basictest.js | 26 | JavaScript | 0.357 | suggestion | 58 | 51 | 51 | false | test: correct local cli test | 19,717 | webpack/webpack | 65,000 | JavaScript | hai-x | hai-x |
"path": "module.wrappedContextRegExp",
"type": "invalid-value",
"value": 123,
},
Object {
"argument": "my-argument",
"path": "",
"type": "unknown-argument",
},
]
`)
);
});
describe("isColorSupported", () => {
const OLD_ENV = process.env;
beforeEach... | We should avoid interference caused by different env. | "path": "module.wrappedContextRegExp",
"type": "invalid-value",
"value": 123,
},
Object {
"argument": "my-argument",
"path": "",
"type": "unknown-argument",
},
]
`)
);
});
describe("isColorSupported", () => {
const OLD_ENV = process.env;
beforeEach... | @@ -429,6 +429,14 @@ describe("Cli", () => {
// Most important - it clears the cache
jest.resetModules();
process.env = { ...OLD_ENV };
+ // Prevent `process.env.FORCE_COLOR` from being auto set by `jest-worker`
+ if (OLD_ENV.FORCE_COLOR) {
+ delete process.env.FORCE_COLOR;
+ }
+ // Prevent `proc... | test/Cli.basictest.js | 26 | JavaScript | 0.357 | suggestion | 53 | 51 | 51 | false | test: correct local cli test | 19,717 | webpack/webpack | 65,000 | JavaScript | hai-x | hai-x |
module.exports.uncaughtErrorHandler = "__webpack_require__.oe";
/**
* an object containing all installed WebAssembly.Instance export objects keyed by module id
*/
module.exports.wasmInstances = "__webpack_require__.w";
/**
* the webpack id of the chunk
*/
module.exports.webpackId = "__webpack_id__";
/**
* the w... | Do we use these variables somewhere else? I think `__webpack_modules__` can be replaced in more place, can you check it? | module.exports.startupOnlyBefore = "__webpack_require__.x (only before)";
/**
* the System polyfill object
*/
module.exports.system = "__webpack_require__.System";
/**
* the System.register context object
*/
module.exports.systemContext = "__webpack_require__.y";
/**
* top-level this need to be the exports obje... | @@ -405,3 +405,23 @@ module.exports.uncaughtErrorHandler = "__webpack_require__.oe";
* an object containing all installed WebAssembly.Instance export objects keyed by module id
*/
module.exports.wasmInstances = "__webpack_require__.w";
+
+/**
+ * the webpack id of the chunk
+ */
+module.exports.webpackId = "__webp... | lib/RuntimeGlobals.js | 26 | JavaScript | 0.714 | question | 120 | 27 | 27 | false | perf: standardize ESM naming management | 19,730 | webpack/webpack | 65,000 | JavaScript | alexander-akait | xiaoxiaojx |
}
/** @type {ChunkRenderContext} */
const chunkRenderContext = {
...renderContext,
chunkInitFragments: [],
strictMode: allStrict
};
const chunkModules = Template.renderChunkModules(
chunkRenderContext,
inlinedModules
? allModules.filter(
(m) => !(/** @type {Set<Module>} */ (inlinedM... | Hm, maybe I was wrong, it can be misleading, because here `__webpack__modules__` is cache for loading modules, for ESM `__webpack__modules__` is place where we store new modules, maybe we should use another name for ESM runtime variables, for example - `RuntimeGlobals.ESMWebpackModules`, and do not replace here to avoi... | }
/** @type {ChunkRenderContext} */
const chunkRenderContext = {
...renderContext,
chunkInitFragments: [],
strictMode: allStrict
};
const chunkModules = Template.renderChunkModules(
chunkRenderContext,
inlinedModules
? allModules.filter(
(m) => !(/** @type {Set<Module>} */ (inlinedM... | @@ -850,7 +850,7 @@ class JavascriptModulesPlugin {
runtimeRequirements.has(RuntimeGlobals.moduleFactoriesAddOnly) ||
runtimeRequirements.has(RuntimeGlobals.require)
) {
- source.add(`${prefix}var __webpack_modules__ = (`);
+ source.add(`${prefix}var ${RuntimeGlobals.webpackModules} = (`); | lib/javascript/JavascriptModulesPlugin.js | 26 | JavaScript | 0.857 | bug | 354 | 51 | 51 | false | perf: standardize ESM naming management | 19,730 | webpack/webpack | 65,000 | JavaScript | alexander-akait | xiaoxiaojx |
/**
* the uncaught error handler for the webpack runtime
*/
module.exports.uncaughtErrorHandler = "__webpack_require__.oe";
/**
* an object containing all installed WebAssembly.Instance export objects keyed by module id
*/
module.exports.wasmInstances = "__webpack_require__.w";
/**
* the webpack id of the chunk... | Let's put comment at the right place, eslint fixer for order is not respect comments | module.exports.startupOnlyBefore = "__webpack_require__.x (only before)";
/**
* the System polyfill object
*/
module.exports.system = "__webpack_require__.System";
/**
* the System.register context object
*/
module.exports.systemContext = "__webpack_require__.y";
/**
* top-level this need to be the exports obje... | @@ -405,3 +409,19 @@ module.exports.uncaughtErrorHandler = "__webpack_require__.oe";
* an object containing all installed WebAssembly.Instance export objects keyed by module id
*/
module.exports.wasmInstances = "__webpack_require__.w";
+
+/**
+ * the webpack id of the chunk
+ */
+
+/**
+ * the webpack ids of the c... | lib/RuntimeGlobals.js | 26 | JavaScript | 0.143 | style | 84 | 27 | 27 | false | perf: standardize ESM naming management | 19,730 | webpack/webpack | 65,000 | JavaScript | alexander-akait | xiaoxiaojx |
* @param {string} outputPath output path
* @param {Map<string, number>} currentAssets filename of the current assets (must not start with .. or ., must only use / as path separator)
* @param {(err?: Error | null, set?: Diff) => void} callback returns the filenames of the assets that shouldn't be there
* @returns {v... | I think we can cache it, look at `lib/util/identifier.js`, I think we can use the same logic here | * @param {string} outputPath output path
* @param {Map<string, number>} currentAssets filename of the current assets (must not start with .. or ., must only use / as path separator)
* @param {(err?: Error | null, set?: Diff) => void} callback returns the filenames of the assets that shouldn't be there
* @returns {v... | @@ -148,11 +116,12 @@ const getDiffToFs = (fs, outputPath, currentAssets, callback) => {
for (const entry of /** @type {string[]} */ (entries)) {
const file = entry;
const filename = directory ? `${directory}/${file}` : file;
+ const normalizedFilename = path.normalize(filename); | lib/CleanPlugin.js | 26 | JavaScript | 0.571 | performance | 97 | 51 | 51 | false | fix: fix potential performance issue in CleanPlugin | 19,735 | webpack/webpack | 65,000 | JavaScript | alexander-akait | xiaoxiaojx |
if ($hasOwnProperty$(outdatedDependencies, outdatedModuleId)) {
var module = $moduleCache$[outdatedModuleId];
if (module) {
moduleOutdatedDependencies =
outdatedDependencies[outdatedModuleId];
var callbacks = [];
var errorHandlers = [];
var dependenciesForCallbacks =... | `var` is hoisted to the top of the function, so writing `var result = ...` right here without having a separate `var result` before `try` should be enough? | for (var outdatedModuleId in outdatedDependencies) {
if ($hasOwnProperty$(outdatedDependencies, outdatedModuleId)) {
var module = $moduleCache$[outdatedModuleId];
if (module) {
moduleOutdatedDependencies =
outdatedDependencies[outdatedModuleId];
var callbacks = [];
var ... | @@ -317,8 +318,9 @@ module.exports = function () {
}
}
for (var k = 0; k < callbacks.length; k++) {
+ var result;
try {
- callbacks[k].call(null, moduleOutdatedDependencies);
+ result = callbacks[k].call(null, moduleOutdatedDependencies); | lib/hmr/JavascriptHotModuleReplacement.runtime.js | 26 | JavaScript | 0.714 | question | 155 | 51 | 51 | false | feat: Support accept asyncModule | 19,741 | webpack/webpack | 65,000 | JavaScript | faergeek | xiaoxiaojx |
req: [RuntimeGlobals.initializeSharing],
type: "function",
assign: true
}
};
}
const PLUGIN_NAME = "APIPlugin";
const moduleCreateRequire = "__WEBPACK_EXTERNAL_createRequire";
class APIPlugin {
/**
* Apply the plugin
* @param {Compiler} compiler the compiler instance
* @returns {void}
*/
apply(... | Better to use `compiler.platform.node` to check is it node target or not, don't forget we have `target: ['web', 'node']` (i.e. universal target, it is not fully ready right now, but we should finish it soon) | req: [RuntimeGlobals.initializeSharing],
type: "function",
assign: true
}
};
}
const PLUGIN_NAME = "APIPlugin";
const moduleCreateRequire = "__WEBPACK_EXTERNAL_createRequire";
class APIPlugin {
/**
* Apply the plugin
* @param {Compiler} compiler the compiler instance
* @returns {void}
*/
apply(... | @@ -157,10 +143,14 @@ class APIPlugin {
const importMetaName = /** @type {string} */ (
compilation.outputOptions.importMetaName
);
- const REPLACEMENTS = getReplacements(
- this.options.module,
- importMetaName
- );
+ const moduleOutput = compilation.options.output.module;
+ const no... | lib/APIPlugin.js | 26 | JavaScript | 0.786 | suggestion | 207 | 51 | 51 | false | fix: `needCreateRequire` should be set to true only when module output and node target | 19,761 | webpack/webpack | 65,000 | JavaScript | alexander-akait | hai-x |
console.log(exports)
console.log(module)
console.log(this) | Can we avoid using `console.log`, it outputs a lot of span into CI output, ideally we should remove `console.log` and `debugger` from all tests (except where we need it) | exports.name
module.name
this.name | @@ -0,0 +1,3 @@
+console.log(exports)
+console.log(module)
+console.log(this) | test/configCases/library/0-create-library/self-reference-cjs.js | 3 | JavaScript | 1 | bug | 169 | 3 | 3 | false | test: more case about cjs bundle to esm lib | 19,787 | webpack/webpack | 65,000 | JavaScript | alexander-akait | hai-x |
import lib1 from "lib1";
import lib2 from "lib2";
import lib3 from "lib3";
import lib4 from "lib4";
import lib5 from "lib5";
it(
"should be able to import harmony exports from library (" + NAME + ")",
function () {
expect(new lib1().getNumber()).toBe(1);
expect(lib2).toMatchObject({});
expect(lib3.name).toBe(... | Is it expected, because I think we should have `adding-exports-cjs` and `foo` | import lib1 from "lib1";
import lib2 from "lib2";
import lib3 from "lib3";
import lib4 from "lib4";
import lib5 from "lib5";
it(
"should be able to import harmony exports from library (" + NAME + ")",
function () {
expect(new lib1().getNumber()).toBe(1);
expect(lib2).toMatchObject({});
expect(lib3.name).toBe(... | @@ -1,8 +1,18 @@
-import library from "library";
+import lib1 from "lib1";
+import lib2 from "lib2";
+import lib3 from "lib3";
+import lib4 from "lib4";
+import lib5 from "lib5";
+
it(
"should be able to import harmony exports from library (" + NAME + ")",
function () {
- expect(new library().getNumber()).toBe(... | test/configCases/library/1-use-library/esm-with-bundled-commonjs.js | 16 | JavaScript | 0.571 | suggestion | 77 | 19 | 20 | false | test: more case about cjs bundle to esm lib | 19,787 | webpack/webpack | 65,000 | JavaScript | alexander-akait | hai-x |
}
resolve();
});
}
});
}
}
);
} else {
bench.add(
benchName,
async () => {
if (GENERATE_PROFILE) {
await withProfiling(benchName, () =>
runWebpack(webpack, config)
);
} else {... | Can we do it for watching too? Will be great to see some our benches are unstable for watch | });
},
async afterAll() {
await new Promise((resolve, reject) => {
if (watching) {
watching.close((closeErr) => {
if (closeErr) {
reject(closeErr);
return;
}
resolve();
});
}
... | @@ -577,34 +653,15 @@ async function registerSuite(bench, test, baselines) {
bench.add(
benchName,
async () => {
- await new Promise((resolve, reject) => {
+ if (GENERATE_PROFILE) {
+ await withProfiling(benchName, () =>
+ runWebpack(webpack, config)
+ ); | test/BenchmarkTestCases.benchmark.mjs | 26 | JavaScript | 0.143 | question | 91 | 51 | 51 | false | feat(benchmark): support profiling | 19,789 | webpack/webpack | 65,000 | JavaScript | alexander-akait | avivkeller |
Template.toPath(dep.userRequest)
);
}
const block = new AsyncDependenciesBlock(
{
...this.options.groupOptions,
name: chunkName
},
dep.loc,
dep.userRequest
);
block.addDependency(dep);
this.addBlock(block);
}
} else {
callback(
... | I think we don't need it because you can't set `contextModule: false` directly | chunkName = chunkName.replace(/\[index\]/g, `${index++}`);
chunkName = chunkName.replace(
/\[request\]/g,
Template.toPath(dep.userRequest)
);
}
const block = new AsyncDependenciesBlock(
{
...this.options.groupOptions,
name: chunkName
},
dep.loc,
... | @@ -532,6 +530,11 @@ class ContextModule extends Module {
}
if (!this.context && !this.options.resource) return callback();
+ const snapshotOptions = compilation.options.snapshot.contextModule;
+ if (!snapshotOptions) {
+ return callback();
+ } | lib/ContextModule.js | 26 | JavaScript | 0.571 | suggestion | 78 | 51 | 51 | false | feat: add snapshot.contextModule to configure snapshots for context m… | 19,798 | webpack/webpack | 65,000 | JavaScript | alexander-akait | xiaoxiaojx |
}
}
if (
mode !== "lazy" &&
mode !== "lazy-once" &&
mode !== "eager" &&
mode !== "weak"
) {
parser.state.module.addWarning(
new UnsupportedFeatureWarning(
`\`webpackMode\` expected 'lazy', 'lazy-once', 'eager' or 'weak', but received: ${mode}.`,
/** @type {DependencyLo... | Do you think we really need it, yeah it can be useful in some cases, but maybe it will be too spammy
/cc @hai-x @xiaoxiaojx | }
if (
mode !== "lazy" &&
mode !== "lazy-once" &&
mode !== "eager" &&
mode !== "weak"
) {
parser.state.module.addWarning(
new UnsupportedFeatureWarning(
`\`webpackMode\` expected 'lazy', 'lazy-once', 'eager' or 'weak', but received: ${mode}.`,
/** @type {DependencyLocation... | @@ -281,19 +363,25 @@ class ImportParserPlugin {
const referencedPropertiesInDestructuring =
parser.destructuringAssignmentPropertiesFor(expr);
- if (referencedPropertiesInDestructuring) {
+ const state = getState(parser);
+ const referencedPropertiesInMember = state.get(expr);
+ if (referencedProper... | lib/dependencies/ImportParserPlugin.js | 26 | JavaScript | 0.5 | suggestion | 127 | 51 | 51 | false | feat: static analyze member expression for dynamic import | 19,818 | webpack/webpack | 65,000 | JavaScript | alexander-akait | ahabhgk |
if (HarmonyExports.isEnabled(parser.state)) return;
// Handle reexporting
const requireCall = parseRequireCall(parser, expr.right);
if (
requireCall &&
requireCall.argument.isString() &&
(members.length === 0 || members[0] !== "__esModule")
) {
enableStructuredExports();
// It's possi... | Let's rename `treatAsCommonjs` to `treatAsCommonJs` :smile: | if (HarmonyExports.isEnabled(parser.state)) return;
// Handle reexporting
const requireCall = parseRequireCall(parser, expr.right);
if (
requireCall &&
requireCall.argument.isString() &&
(members.length === 0 || members[0] !== "__esModule")
) {
enableStructuredExports();
// It's possi... | @@ -216,6 +217,10 @@ class CommonJsExportsParserPlugin {
dep.loc = /** @type {DependencyLocation} */ (expr.loc);
dep.optional = Boolean(parser.scope.inTry);
parser.state.module.addDependency(dep);
+ /** @type {BuildMeta} */ (
+ parser.state.module.buildMeta
+ ).treatAsCommonjs = true; | lib/dependencies/CommonJsExportsParserPlugin.js | 26 | JavaScript | 0.571 | suggestion | 60 | 51 | 51 | false | fix: improve CommonJs bundle to ESM library | 19,847 | webpack/webpack | 65,000 | JavaScript | alexander-akait | hai-x |
const getAssetSourceGenerator = memoize(() =>
require("./AssetSourceGenerator")
);
const type = ASSET_MODULE_TYPE;
const PLUGIN_NAME = "AssetModulesPlugin";
class AssetModulesPlugin {
/**
* Apply the plugin
* @param {Compiler} compiler the compiler instance
* @returns {void}
*/
apply(compiler) {
compiler... | We have `mergeGlobalOptions` in `NormalModuleFactory` where we merge global options with local options, so we don't need it here to make twice | require("./AssetSourceGenerator")
);
const type = ASSET_MODULE_TYPE;
const PLUGIN_NAME = "AssetModulesPlugin";
class AssetModulesPlugin {
/**
* Apply the plugin
* @param {Compiler} compiler the compiler instance
* @returns {void}
*/
apply(compiler) {
compiler.hooks.compilation.tap(
PLUGIN_NAME,
(co... | @@ -95,11 +94,6 @@ class AssetModulesPlugin {
.for(ASSET_MODULE_TYPE)
.tap(PLUGIN_NAME, (parserOptions) => {
validateParserOptions(parserOptions);
- parserOptions = cleverMerge(
- /** @type {AssetParserOptions} */
- (compiler.options.module.parser.asset),
- parserOptions
- ... | lib/asset/AssetModulesPlugin.js | 26 | JavaScript | 0.5 | suggestion | 142 | 51 | 51 | false | Refactor remove unused code | 19,857 | webpack/webpack | 65,000 | JavaScript | alexander-akait | alexander-akait |
} catch (err) {
processResult(/** @type {Error} */ (err));
return;
}
if (this.loaders.length > 0) {
/** @type {BuildInfo} */
(this.buildInfo).buildDependencies = new LazySet();
}
runLoaders(
{
resource: this.resource,
loaders: this.loaders,
context: loaderContext,
/**
* @... | Maybe we should implement `processResourceAsync` in `loader-runner` in future, to migrate on async API, having `async` and `callback` is a little bit misleading, but let's postpone it and make it when we will move `loader-runner` into core | this,
/** @type {LoaderContext<EXPECTED_ANY>} */
(loaderContext)
);
} catch (err) {
processResult(/** @type {Error} */ (err));
return;
}
if (this.loaders.length > 0) {
/** @type {BuildInfo} */
(this.buildInfo).buildDependencies = new LazySet();
}
runLoaders(
{
resource: thi... | @@ -1023,43 +1027,76 @@ class NormalModule extends Module {
* @param {LoaderContext<EXPECTED_ANY>} loaderContext the loader context
* @param {string} resourcePath the resource Path
* @param {(err: Error | null, result?: string | Buffer, sourceMap?: Result[1]) => void} callback callback
+ * @return... | lib/NormalModule.js | 26 | JavaScript | 0.786 | suggestion | 239 | 51 | 51 | false | feat: extractSourceMap supports HTTP URLs | 19,882 | webpack/webpack | 65,000 | JavaScript | alexander-akait | xiaoxiaojx |
linkPrefetch: new SyncWaterfallHook(["source", "chunk"])
};
compilationHooksMap.set(compilation, hooks);
}
return hooks;
}
/**
* @param {ReadOnlyRuntimeRequirements} runtimeRequirements runtime requirements
*/
constructor(runtimeRequirements) {
super("jsonp chunk loading", RuntimeModule.STAGE_AT... | Thanks for the PR! However this still fails
<img width="819" height="429" alt="Image" src="https://github.com/user-attachments/assets/09034ac7-f903-470a-aaf8-852089707b53" />
The correct check would have to use `typeof document` or `globalThis.document?.baseURI` | linkPrefetch: new SyncWaterfallHook(["source", "chunk"])
};
compilationHooksMap.set(compilation, hooks);
}
return hooks;
}
/**
* @param {ReadOnlyRuntimeRequirements} runtimeRequirements runtime requirements
*/
constructor(runtimeRequirements) {
super("jsonp chunk loading", RuntimeModule.STAGE_AT... | @@ -69,7 +69,7 @@ class JsonpChunkLoadingRuntimeModule extends RuntimeModule {
if (options && options.baseUri) {
return `${RuntimeGlobals.baseURI} = ${JSON.stringify(options.baseUri)};`;
}
- return `${RuntimeGlobals.baseURI} = document.baseURI || self.location.href;`;
+ return `${RuntimeGlobals.baseURI} = (... | lib/web/JsonpChunkLoadingRuntimeModule.js | 26 | JavaScript | 1 | bug | 264 | 51 | 51 | false | fix: support web workers loading for jsonp format | 19,916 | webpack/webpack | 65,000 | JavaScript | fregante | alexander-akait |
InstrumentHooks.stopBenchmark();
InstrumentHooks.setExecutedBenchmark(process.pid, uri);
return result;
};
const runTaskAsync = async (task, uri) => {
const { fnOpts, fn } = task;
// Custom setup
await bench.opts.setup?.(task, "run");
await fnOpts?.beforeAll?.call(task, "run");
// Custom... | It seems that `beforeEach` and `afterEach` are being called twice. | InstrumentHooks.setExecutedBenchmark(process.pid, uri);
return result;
};
const runTaskAsync = async (task, uri) => {
const { fnOpts, fn } = task;
// Custom setup
await bench.opts.setup?.(task, "run");
await fnOpts?.beforeAll?.call(task, "run");
// Custom warmup
// We don't run `optimize... | @@ -385,105 +371,242 @@ const scenarios = [
}
];
-const baseOutputPath = path.join(__dirname, "js", "benchmark");
+function getStackTrace(belowFn) {
+ const oldLimit = Error.stackTraceLimit;
+ Error.stackTraceLimit = Infinity;
+ const dummyObject = {};
+ const v8Handler = Error.prepareStackTrace;
+ Error.prepareSt... | test/BenchmarkTestCases.benchmark.mjs | 26 | JavaScript | 0.357 | suggestion | 66 | 51 | 51 | false | chore: update codespeed | 19,959 | webpack/webpack | 65,000 | JavaScript | hai-x | alexander-akait |
const finalizeAsyncRun = () => {
finalizeBenchRun();
};
const finalizeSyncRun = () => {
finalizeBenchRun();
};
bench.run = async () => {
setupBenchRun();
for (const task of bench.tasks) {
const uri = getTaskUri(task.bench, task.name, rootCallingFile);
await runTaskAsync(task, uri);
}... | We probably don’t need `walltime` mode here. We want to ignore system call latency and focus only on CPU instrumentation.
And the following is mentioned in `Codspeed` docs.
> If your the code you wish to optimize and measure relies heavily on system calls, you can use CodSpeed Macro Runners combined with our Wall... | const finalizeSyncRun = () => {
finalizeBenchRun();
};
bench.run = async () => {
setupBenchRun();
for (const task of bench.tasks) {
const uri = getTaskUri(task.bench, task.name, rootCallingFile);
await runTaskAsync(task, uri);
}
return finalizeAsyncRun();
};
bench.runSync = () => {
... | @@ -385,105 +371,242 @@ const scenarios = [
}
];
-const baseOutputPath = path.join(__dirname, "js", "benchmark");
+function getStackTrace(belowFn) {
+ const oldLimit = Error.stackTraceLimit;
+ Error.stackTraceLimit = Infinity;
+ const dummyObject = {};
+ const v8Handler = Error.prepareStackTrace;
+ Error.prepareSt... | test/BenchmarkTestCases.benchmark.mjs | 26 | JavaScript | 0.857 | performance | 456 | 51 | 51 | false | chore: update codespeed | 19,959 | webpack/webpack | 65,000 | JavaScript | hai-x | alexander-akait |
return require("./Dependency");
},
get DllPlugin() {
return require("./DllPlugin");
},
get DllReferencePlugin() {
return require("./DllReferencePlugin");
},
get DynamicEntryPlugin() {
return require("./DynamicEntryPlugin");
},
get DotenvPlugin() {
return require("./DotenvPlugin");
},
get EntryOption... | Let's don't expose it, `dependencies` are internal | return require("./Dependency");
},
get DllPlugin() {
return require("./DllPlugin");
},
get DllReferencePlugin() {
return require("./DllReferencePlugin");
},
get DynamicEntryPlugin() {
return require("./DynamicEntryPlugin");
},
get DotenvPlugin() {
return require("./DotenvPlugin");
},
get EntryOption... | @@ -244,6 +244,9 @@ module.exports = mergeExports(fn, {
get EnvironmentPlugin() {
return require("./EnvironmentPlugin");
},
+ get ImportMetaEnvPlugin() {
+ return require("./dependencies/ImportMetaEnvPlugin");
+ }, | lib/index.js | 26 | JavaScript | 0.357 | suggestion | 50 | 51 | 51 | false | feat: add import.meta.env support for environment variables | 19,996 | webpack/webpack | 65,000 | JavaScript | alexander-akait | xiaoxiaojx |
if (idx <= 0 || idx >= key.length - 1) {
continue;
}
const nested = key.slice(0, idx);
const final = key.slice(idx + 1);
addToMap(finalByNestedKey, nested, final);
addToMap(nestedByFinalKey, final, nested);
}
};
walkDefinitionsForKeys(definitions);
walkDefini... | Can you describe why we need this method? I think we can directly pass options to define plugin | /*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const {
JAVASCRIPT_MODULE_TYPE_AUTO,
JAVASCRIPT_MODULE_TYPE_DYNAMIC,
JAVASCRIPT_MODULE_TYPE_ESM
} = require("./ModuleTypeConstants");
const RuntimeGlobals = require("./RuntimeGlobals");
const WebpackEr... | @@ -835,6 +835,14 @@ class DefinePlugin {
}
);
}
+
+ /**
+ * @param {Record<string, CodeValue>} options Options map
+ * @returns {void}
+ */
+ updateOptions(options) { | lib/DefinePlugin.js | 26 | JavaScript | 0.143 | suggestion | 95 | 32 | 841 | false | feat: add import.meta.env support for environment variables | 19,996 | webpack/webpack | 65,000 | JavaScript | alexander-akait | xiaoxiaojx |
const OccurrenceChunkIdsPlugin = require("./ids/OccurrenceChunkIdsPlugin");
new OccurrenceChunkIdsPlugin({
prioritiseInitial: true
}).apply(compiler);
break;
}
case "total-size": {
// @ts-expect-error https://github.com/microsoft/TypeScript/issues/41697
const OccurrenceChunk... | Using `EnvironmentPlugin` is a breaking change (and can lead to unexpected behavior), we should use DefinePlugin here, because EnvironmentPlugin has
```js
const value =
process.env[key] !== undefined
? process.env[key]
: this.defaultValues[key];
```
So if you have `process.env.NODE_ENV` in your... | const OccurrenceChunkIdsPlugin = require("./ids/OccurrenceChunkIdsPlugin");
new OccurrenceChunkIdsPlugin({
prioritiseInitial: true
}).apply(compiler);
break;
}
case "total-size": {
// @ts-expect-error https://github.com/microsoft/TypeScript/issues/41697
const OccurrenceChunk... | @@ -673,10 +673,10 @@ class WebpackOptionsApply extends OptionsApply {
}
}
if (options.optimization.nodeEnv) {
- const DefinePlugin = require("./DefinePlugin");
+ const EnvironmentPlugin = require("./EnvironmentPlugin");
- new DefinePlugin({
- "process.env.NODE_ENV": JSON.stringify(options.optimiza... | lib/WebpackOptionsApply.js | 26 | JavaScript | 1 | suggestion | 429 | 51 | 51 | false | feat: add import.meta.env support for environment variables | 19,996 | webpack/webpack | 65,000 | JavaScript | alexander-akait | xiaoxiaojx |
}).apply(compiler);
break;
}
case "total-size": {
// @ts-expect-error https://github.com/microsoft/TypeScript/issues/41697
const OccurrenceChunkIdsPlugin = require("./ids/OccurrenceChunkIdsPlugin");
new OccurrenceChunkIdsPlugin({
prioritiseInitial: false
}).apply(compiler);
... | I’m not sure if we really need an ImportMetaEnvPlugin. It seems sufficient to simply add import.meta.env.xxx keys for all process.env.xxx variables.
If we introduce ImportMetaEnvPlugin, it would replace every import.meta.env reference at build time — even those that don’t exist during the build but might exist at run... | }).apply(compiler);
break;
}
case "total-size": {
// @ts-expect-error https://github.com/microsoft/TypeScript/issues/41697
const OccurrenceChunkIdsPlugin = require("./ids/OccurrenceChunkIdsPlugin");
new OccurrenceChunkIdsPlugin({
prioritiseInitial: false
}).apply(compiler);
... | @@ -675,8 +675,11 @@ class WebpackOptionsApply extends OptionsApply {
if (options.optimization.nodeEnv) {
const DefinePlugin = require("./DefinePlugin");
+ const defValue = JSON.stringify(options.optimization.nodeEnv);
+
new DefinePlugin({
- "process.env.NODE_ENV": JSON.stringify(options.optimization.... | lib/WebpackOptionsApply.js | 26 | JavaScript | 0.643 | suggestion | 325 | 51 | 51 | false | feat: add import.meta.env support for environment variables | 19,996 | webpack/webpack | 65,000 | JavaScript | xiaoxiaojx | xiaoxiaojx |
typeof this.options.dir === "string"
? this.options.dir
: typeof this.options.dir === "undefined"
? compiler.context
: this.options.dir;
/** @type {undefined | Snapshot} */
let snapshot;
/** @type {Record<string, string>} */
let envCache = {};
const cache = compiler.getCache(PLUGIN_NAME... | We can't use `thisCompilation` here, because we need to replace it in child compilation too... | ? this.options.dir
: typeof this.options.dir === "undefined"
? compiler.context
: this.options.dir;
/** @type {undefined | Snapshot} */
let snapshot;
const cache = compiler.getCache(PLUGIN_NAME);
const identifier = JSON.stringify(this.options.template);
const itemCache = cache.getItemCache... | @@ -257,16 +261,18 @@ class DotenvPlugin {
const { parsed, snapshot: newSnapshot } = dir
? await this._loadEnv(compiler, itemCache, dir)
: { parsed: {} };
- // Merge parsed env variables with `process.env`
const env = this._getEnv(prefixes, parsed);
- // update the definitions
- definePlugin.d... | lib/DotenvPlugin.js | 26 | JavaScript | 0.571 | suggestion | 94 | 51 | 51 | false | feat: add import.meta.env support for environment variables | 19,996 | webpack/webpack | 65,000 | JavaScript | alexander-akait | xiaoxiaojx |
runningParsed[key] = resolvedValue;
}
// Part of `dotenv-expand` code, but we don't need it because of we don't modify `process.env`
// for (const processKey in options.parsed) {
// if (processEnv) {
// processEnv[processKey] = options.parsed[processKey];
// }
// }
return options;
}
/**
* Format envir... | We need to use `import.meta.env` directly here, `importMetaName` should be used only in output code, not in source, same `EnvironmentPlugin` | runningParsed[key] = resolvedValue;
}
// Part of `dotenv-expand` code, but we don't need it because of we don't modify `process.env`
// for (const processKey in options.parsed) {
// if (processEnv) {
// processEnv[processKey] = options.parsed[processKey];
// }
// }
return options;
}
/**
* Format envir... | @@ -207,14 +207,16 @@ function expand(options) {
/**
* Format environment variables as DefinePlugin definitions
* @param {Env} env environment variables
+ * @param {string} importMetaName import.meta.name
* @returns {Record<string, string>} formatted definitions
*/
-const envToDefinitions = (env) => {
+const e... | lib/DotenvPlugin.js | 26 | JavaScript | 0.714 | suggestion | 140 | 51 | 51 | false | feat: add import.meta.env support for environment variables | 19,996 | webpack/webpack | 65,000 | JavaScript | alexander-akait | xiaoxiaojx |
profile?: boolean;
/**
* Enable/disable readonly mode.
*/
readonly?: boolean;
/**
* When to store data to the filesystem. (pack: Store data when compiler is idle in a single file).
*/
store?: "pack";
/**
* Filesystem caching.
*/
type: "filesystem";
/**
* Version of the cache data. Different versio... | I think we don't need it, because we have top `dotenv: false` (we don't need to follow all logic from vite) | profile?: boolean;
/**
* Enable/disable readonly mode.
*/
readonly?: boolean;
/**
* When to store data to the filesystem. (pack: Store data when compiler is idle in a single file).
*/
store?: "pack";
/**
* Filesystem caching.
*/
type: "filesystem";
/**
* Version of the cache data. Different versio... | @@ -1135,7 +1135,7 @@ export interface DotenvPluginOptions {
/**
* The directory from which .env files are loaded. Can be an absolute path, or a path relative to the project root. false will disable the .env file loading.
*/
- dir?: boolean | string;
+ dir?: string; | declarations/WebpackOptions.d.ts | 26 | TypeScript | 0.714 | suggestion | 107 | 51 | 51 | false | Refactor dovenv plugin | 20,006 | webpack/webpack | 65,000 | JavaScript | alexander-akait | alexander-akait |
/**
* Expand environment variables in parsed object
* ported from https://github.com/motdotla/dotenv-expand
* @param {{ parsed: Record<string, string>, processEnv: Record<string, string | undefined> }} options expand options
* @returns {{ parsed: Record<string, string> }} expanded options
*/
function expand(optio... | Let's run `_resolveEscapeSequences` only once |
return result;
}
/**
* Expand environment variables in parsed object
* ported from https://github.com/motdotla/dotenv-expand
* @param {{ parsed: Env, processEnv: Record<string, string | undefined> }} options expand options
* @returns {{ parsed: Env }} expanded options
*/
function expand(options) {
// for use w... | @@ -190,42 +184,23 @@ function expand(options) {
? /** @type {string} */ (processEnv[key])
: expandValue(value, processEnv, runningParsed);
- options.parsed[key] = _resolveEscapeSequences(value);
+ const resolvedValue = _resolveEscapeSequences(value); | lib/DotenvPlugin.js | 26 | JavaScript | 0.286 | security | 45 | 51 | 51 | false | Refactor dovenv plugin | 20,006 | webpack/webpack | 65,000 | JavaScript | alexander-akait | alexander-akait |
// dotenv.config() ran before this so the assumption is process.env has already been set
for (const key in options.parsed) {
let value = options.parsed[key];
// short-circuit scenario: process.env was already set prior to the file value
value =
processEnv[key] && processEnv[key] !== value
? /** @type {s... | This line to copy parsed into `process.env`, but we use `{ ...process.env }` to avoid it, so we don't need this line at all | const runningParsed = /** @type {Env} */ ({});
const processEnv = options.processEnv;
// dotenv.config() ran before this so the assumption is process.env has already been set
for (const key in options.parsed) {
let value = options.parsed[key];
// short-circuit scenario: process.env was already set prior to th... | @@ -190,42 +184,23 @@ function expand(options) {
? /** @type {string} */ (processEnv[key])
: expandValue(value, processEnv, runningParsed);
- options.parsed[key] = _resolveEscapeSequences(value);
+ const resolvedValue = _resolveEscapeSequences(value);
+ options.parsed[key] = resolvedValue;
// for us... | lib/DotenvPlugin.js | 26 | JavaScript | 0.714 | suggestion | 123 | 51 | 51 | false | Refactor dovenv plugin | 20,006 | webpack/webpack | 65,000 | JavaScript | alexander-akait | alexander-akait |
// }
return options;
}
/**
* Format environment variables as DefinePlugin definitions
* @param {Record<string, string>} env environment variables
* @returns {Record<string, string>} formatted definitions
*/
const envToDefinitions = (env) => {
const definitions = /** @type {Record<string, string>} */ ({});
fo... | We have `minLenght: 1`, in validate so it should be never happen | // if (processEnv) {
// processEnv[processKey] = options.parsed[processKey];
// }
// }
return options;
}
/**
* Format environment variables as DefinePlugin definitions
* @param {Env} env environment variables
* @returns {Record<string, string>} formatted definitions
*/
const envToDefinitions = (env) => {... | @@ -190,42 +184,23 @@ function expand(options) {
? /** @type {string} */ (processEnv[key])
: expandValue(value, processEnv, runningParsed);
- options.parsed[key] = _resolveEscapeSequences(value);
+ const resolvedValue = _resolveEscapeSequences(value);
+ options.parsed[key] = resolvedValue;
// for us... | lib/DotenvPlugin.js | 26 | JavaScript | 0.571 | suggestion | 64 | 51 | 51 | false | Refactor dovenv plugin | 20,006 | webpack/webpack | 65,000 | JavaScript | alexander-akait | alexander-akait |
...DEFAULT_OPTIONS,
...options,
prefix
};
}
/**
* @param {Compiler} compiler the compiler instance
* @returns {void}
*/
apply(compiler) {
const definePlugin = new compiler.webpack.DefinePlugin({});
const fs = /** @type {InputFileSystem} */ (compiler.inputFileSystem);
const fileSystemInfo = ne... | We have `tapPromise` to use `async`/`await` :+1: | }
/**
* @param {Compiler} compiler the compiler instance
* @returns {void}
*/
apply(compiler) {
const definePlugin = new compiler.webpack.DefinePlugin({});
const prefixes = Array.isArray(this.options.prefix)
? this.options.prefix
: [this.options.prefix || "WEBPACK_"];
/** @type {string | false} */... | @@ -257,43 +239,36 @@ class DotenvPlugin {
*/
apply(compiler) {
const definePlugin = new compiler.webpack.DefinePlugin({});
+ const fs = /** @type {InputFileSystem} */ (compiler.inputFileSystem);
+ const fileSystemInfo = new FileSystemInfo(fs, {
+ unmanagedPaths: compiler.unmanagedPaths,
+ managedPaths: c... | lib/DotenvPlugin.js | 26 | JavaScript | 0.5 | suggestion | 49 | 51 | 51 | false | Refactor dovenv plugin | 20,006 | webpack/webpack | 65,000 | JavaScript | alexander-akait | alexander-akait |
}
const startTime = Date.now();
const newSnapshot = await new Promise((resolve, reject) => {
fileSystemInfo.createSnapshot(
startTime,
fileDependencies,
null,
missingDependencies,
// `.env` files is a build dependencies
compiler.options.snapshot.buildDependencies,
(err, snapshot) =... | We can't cache it because we are looking at `process.env`, technically we can do it, but not sure it is a good solution to use all `process.env` as identifier for cache, I will test | reject(error);
return;
}
resolve(isValid);
});
});
if (isSnapshotValid) {
return { parsed: result.parsed, snapshot: result.snapshot };
}
}
const { parsed, fileDependencies, missingDependencies } =
await this._getParsed(
fs,
dir,
/** @type {string} */
(co... | @@ -323,109 +299,149 @@ class DotenvPlugin {
/**
* Load environment variables from .env files
* Similar to Vite's loadEnv implementation
- * @param {InputFileSystem} fs the input file system
- * @param {string | undefined} mode the mode
- * @param {string} context the compiler context
- * @param {(err: Erro... | lib/DotenvPlugin.js | 26 | JavaScript | 0.714 | performance | 181 | 51 | 51 | false | Refactor dovenv plugin | 20,006 | webpack/webpack | 65,000 | JavaScript | alexander-akait | alexander-akait |
"use strict";
const fs = require("fs");
const path = require("path");
require("./test1");
require("./no-source-map")
it("should extract source map - 1", () => {
const fileData = fs.readFileSync(path.resolve(__dirname, "bundle1.js.map")).toString("utf-8");
const { sources } = JSON.parse(fileData);
expect(sources).... | This should be `bundle0.js.map`. But it would be better to use `__filename + ".map"`. | "use strict";
const fs = require("fs");
const path = require("path");
require("./test1");
require("./no-source-map");
it("should extract source map - 1", () => {
const fileData = fs.readFileSync(__filename + ".map").toString("utf-8");
const { sources } = JSON.parse(fileData);
expect(sources).toContain("webpack://... | @@ -4,11 +4,12 @@ const fs = require("fs");
const path = require("path");
require("./test1");
-require("./no-source-map")
+require("./no-source-map");
it("should extract source map - 1", () => {
- const fileData = fs.readFileSync(path.resolve(__dirname, "bundle1.js.map")).toString("utf-8"); | test/configCases/source-map/extract-source-map/extract1.js | 10 | JavaScript | 0.571 | suggestion | 85 | 15 | 16 | false | test: make extract source map tests correct | 20,008 | webpack/webpack | 65,000 | JavaScript | colinaaa | colinaaa |
"use strict";
const fs = require("fs");
const path = require("path");
require("./test2");
it("should extract source map - 2", () => {
const fileData = fs.readFileSync(path.resolve(__dirname, "bundle2.js.map")).toString("utf-8");
const { sources } = JSON.parse(fileData);
expect(sources).toMatchSnapshot();
});
| ditto. This should be `bundle1.js.map`. | "use strict";
const fs = require("fs");
require("./test2");
it("should extract source map - 2", () => {
const fileData = fs.readFileSync(__filename + ".map").toString("utf-8");
const { sources } = JSON.parse(fileData);
expect(sources).toContain("webpack:///./external-source-map.txt");
expect(sources).toContain("... | @@ -1,12 +1,12 @@
"use strict";
const fs = require("fs");
-const path = require("path");
require("./test2");
it("should extract source map - 2", () => {
- const fileData = fs.readFileSync(path.resolve(__dirname, "bundle2.js.map")).toString("utf-8"); | test/configCases/source-map/extract-source-map/extract2.js | 9 | JavaScript | 0.5 | suggestion | 39 | 13 | 13 | false | test: make extract source map tests correct | 20,008 | webpack/webpack | 65,000 | JavaScript | colinaaa | colinaaa |
"if(threw) delete __webpack_module_cache__[moduleId];"
]),
"}"
])
: outputOptions.strictModuleErrorHandling
? Template.asString([
"// Execute the module function",
"try {",
Template.indent(
needModuleDefer
? [
moduleExecution,
... | I think it should be `__webpack_module_deferred_exports__[moduleId]`. Also feel free to remove the below comment. | "if(threw) delete __webpack_module_cache__[moduleId];"
]),
"}"
])
: outputOptions.strictModuleErrorHandling
? Template.asString([
"// Execute the module function",
"try {",
Template.indent(
needModuleDefer
? [
moduleExecution,
... | @@ -1585,7 +1585,7 @@ class JavascriptModulesPlugin {
moduleExecution,
...(needModuleDefer
? [
- "// delete __webpack_module_deferred_exports__[module];",
+ "delete __webpack_module_deferred_exports__[module];", | lib/javascript/JavascriptModulesPlugin.js | 26 | JavaScript | 0.714 | suggestion | 113 | 51 | 51 | false | fix: async modules in defer import | 20,020 | webpack/webpack | 65,000 | JavaScript | hai-x | ahabhgk |
*/
setDepthIfLower(module, depth) {
const mgm = this._getModuleGraphModule(module);
if (mgm.depth === null || mgm.depth > depth) {
mgm.depth = depth;
return true;
}
return false;
}
/**
* @param {Module} module the module
* @returns {boolean} true, if the module is async
*/
isAsync(module) {
... | @ahabhgk Do we need this link? | setDepthIfLower(module, depth) {
const mgm = this._getModuleGraphModule(module);
if (mgm.depth === null || mgm.depth > depth) {
mgm.depth = depth;
return true;
}
return false;
}
/**
* @param {Module} module the module
* @returns {boolean} true, if the module is async
*/
isAsync(module) {
cons... | @@ -836,6 +837,7 @@ class ModuleGraph {
*/
isDeferred(module) {
if (this.isAsync(module)) return false;
+ // if (/** @type {BuildMeta} */ (module.buildMeta).async) return false; | lib/ModuleGraph.js | 26 | JavaScript | 0.071 | question | 30 | 51 | 51 | false | fix: async modules in defer import | 20,020 | webpack/webpack | 65,000 | JavaScript | alexander-akait | ahabhgk |
/**
* Enable recursive directory lookup for partial dynamic dependencies.
*/
wrappedContextRecursive?: boolean;
/**
* Set the inner regular expression for partial dynamic dependencies.
*/
wrappedContextRegExp?: RegExp;
}
/**
* Generator options for json modules.
*/
export interface JsonGeneratorOptions {
... | Let's use `namedExport`, like we use in webpack for CSS and for other things, by default `true`, but for `{ type: "json" }` is `false` | /**
* Disable or configure parsing of WebWorker syntax like new Worker() or navigator.serviceWorker.register().
*/
worker?: string[] | boolean;
/**
* Enable warnings for partial dynamic dependencies.
*/
wrappedContextCritical?: boolean;
/**
* Enable recursive directory lookup for partial dynamic dependen... | @@ -3400,6 +3400,10 @@ export interface JsonGeneratorOptions {
* Parser options for JSON modules.
*/
export interface JsonParserOptions {
+ /**
+ * Only supports default export.
+ */
+ defaultOnly?: boolean; | declarations/WebpackOptions.d.ts | 26 | TypeScript | 1 | suggestion | 134 | 51 | 51 | false | fix: should support named export json all time and onlyDefault for import attributes | 20,031 | webpack/webpack | 65,000 | JavaScript | alexander-akait | JSerFeng |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.