hunk
dict
file
stringlengths
0
11.8M
file_path
stringlengths
2
234
label
int64
0
1
commit_url
stringlengths
74
103
dependency_score
sequencelengths
5
5
{ "id": 0, "code_window": [ "| `awsAsyncQueryCaching` | Enable caching for async queries for Redshift and Athena. Requires that the `useCachingService` feature toggle is enabled and the datasource has caching and async query support enabled |\n", "| `permissionsFilterRemoveSubquery` | Alternative permission filter implementation that does not use subqueries for fetching the dashboard folder |\n", "| `prometheusConfigOverhaulAuth` | Update the Prometheus configuration page with the new auth component |\n", "| `influxdbSqlSupport` | Enable InfluxDB SQL query language support with new querying UI |\n", "\n", "## Development feature toggles\n", "\n", "The following toggles require explicitly setting Grafana's [app mode]({{< relref \"../_index.md#app_mode\" >}}) to 'development' before you can enable this feature toggle. These features tend to be experimental.\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "| `noBasicRole` | Enables a new role that has no permissions by default |\n" ], "file_path": "docs/sources/setup-grafana/configure-grafana/feature-toggles/index.md", "type": "add", "edit_start_line_idx": 131 }
package api import ( "bytes" "context" "encoding/json" "fmt" "io" "net/http" "net/http/httptest" "path/filepath" "testing" "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" "github.com/grafana/grafana/pkg/api/response" "github.com/grafana/grafana/pkg/api/routing" "github.com/grafana/grafana/pkg/infra/db" "github.com/grafana/grafana/pkg/infra/db/dbtest" "github.com/grafana/grafana/pkg/infra/fs" "github.com/grafana/grafana/pkg/infra/remotecache" "github.com/grafana/grafana/pkg/infra/tracing" "github.com/grafana/grafana/pkg/models/usertoken" "github.com/grafana/grafana/pkg/services/accesscontrol" "github.com/grafana/grafana/pkg/services/accesscontrol/acimpl" "github.com/grafana/grafana/pkg/services/annotations/annotationstest" "github.com/grafana/grafana/pkg/services/anonymous/anontest" "github.com/grafana/grafana/pkg/services/auth/authtest" "github.com/grafana/grafana/pkg/services/auth/jwt" "github.com/grafana/grafana/pkg/services/authn" "github.com/grafana/grafana/pkg/services/authn/authntest" "github.com/grafana/grafana/pkg/services/contexthandler" "github.com/grafana/grafana/pkg/services/contexthandler/authproxy" contextmodel "github.com/grafana/grafana/pkg/services/contexthandler/model" "github.com/grafana/grafana/pkg/services/dashboards" dashver "github.com/grafana/grafana/pkg/services/dashboardversion" "github.com/grafana/grafana/pkg/services/featuremgmt" "github.com/grafana/grafana/pkg/services/guardian" "github.com/grafana/grafana/pkg/services/ldap/service" "github.com/grafana/grafana/pkg/services/licensing" "github.com/grafana/grafana/pkg/services/login" "github.com/grafana/grafana/pkg/services/login/loginservice" "github.com/grafana/grafana/pkg/services/login/logintest" "github.com/grafana/grafana/pkg/services/org" "github.com/grafana/grafana/pkg/services/org/orgtest" "github.com/grafana/grafana/pkg/services/quota/quotatest" "github.com/grafana/grafana/pkg/services/rendering" "github.com/grafana/grafana/pkg/services/search" "github.com/grafana/grafana/pkg/services/search/model" "github.com/grafana/grafana/pkg/services/searchusers" "github.com/grafana/grafana/pkg/services/team/teamtest" "github.com/grafana/grafana/pkg/services/user" "github.com/grafana/grafana/pkg/services/user/usertest" "github.com/grafana/grafana/pkg/setting" "github.com/grafana/grafana/pkg/web" "github.com/grafana/grafana/pkg/web/webtest" ) func loggedInUserScenario(t *testing.T, desc string, url string, routePattern string, fn scenarioFunc, sqlStore db.DB) { loggedInUserScenarioWithRole(t, desc, "GET", url, routePattern, org.RoleEditor, fn, sqlStore) } func loggedInUserScenarioWithRole(t *testing.T, desc string, method string, url string, routePattern string, role org.RoleType, fn scenarioFunc, sqlStore db.DB) { t.Run(fmt.Sprintf("%s %s", desc, url), func(t *testing.T) { sc := setupScenarioContext(t, url) sc.sqlStore = sqlStore sc.userService = usertest.NewUserServiceFake() sc.defaultHandler = routing.Wrap(func(c *contextmodel.ReqContext) response.Response { sc.context = c sc.context.UserID = testUserID sc.context.OrgID = testOrgID sc.context.Login = testUserLogin sc.context.OrgRole = role if sc.handlerFunc != nil { return sc.handlerFunc(sc.context) } return nil }) switch method { case "GET": sc.m.Get(routePattern, sc.defaultHandler) case "DELETE": sc.m.Delete(routePattern, sc.defaultHandler) } fn(sc) }) } func anonymousUserScenario(t *testing.T, desc string, method string, url string, routePattern string, fn scenarioFunc) { t.Run(fmt.Sprintf("%s %s", desc, url), func(t *testing.T) { sc := setupScenarioContext(t, url) sc.defaultHandler = routing.Wrap(func(c *contextmodel.ReqContext) response.Response { sc.context = c if sc.handlerFunc != nil { return sc.handlerFunc(sc.context) } return nil }) switch method { case "GET": sc.m.Get(routePattern, sc.defaultHandler) case "DELETE": sc.m.Delete(routePattern, sc.defaultHandler) } fn(sc) }) } func (sc *scenarioContext) fakeReq(method, url string) *scenarioContext { sc.resp = httptest.NewRecorder() req, err := http.NewRequest(method, url, nil) require.NoError(sc.t, err) req.Header.Add("Content-Type", "application/json") sc.req = req return sc } func (sc *scenarioContext) fakeReqWithParams(method, url string, queryParams map[string]string) *scenarioContext { sc.resp = httptest.NewRecorder() req, err := http.NewRequest(method, url, nil) // TODO: Depend on sc.t if sc.t != nil { require.NoError(sc.t, err) } else if err != nil { panic(fmt.Sprintf("Making request failed: %s", err)) } req.Header.Add("Content-Type", "application/json") q := req.URL.Query() for k, v := range queryParams { q.Add(k, v) } req.URL.RawQuery = q.Encode() sc.req = req return sc } func (sc *scenarioContext) fakeReqNoAssertions(method, url string) *scenarioContext { sc.resp = httptest.NewRecorder() req, _ := http.NewRequest(method, url, nil) req.Header.Add("Content-Type", "application/json") sc.req = req return sc } func (sc *scenarioContext) fakeReqNoAssertionsWithCookie(method, url string, cookie http.Cookie) *scenarioContext { sc.resp = httptest.NewRecorder() http.SetCookie(sc.resp, &cookie) req, _ := http.NewRequest(method, url, nil) req.Header = http.Header{"Cookie": sc.resp.Header()["Set-Cookie"]} req.Header.Add("Content-Type", "application/json") sc.req = req return sc } type scenarioContext struct { t *testing.T cfg *setting.Cfg m *web.Mux context *contextmodel.ReqContext resp *httptest.ResponseRecorder handlerFunc handlerFunc defaultHandler web.Handler req *http.Request url string userAuthTokenService *authtest.FakeUserAuthTokenService sqlStore db.DB authInfoService *logintest.AuthInfoServiceFake dashboardVersionService dashver.Service userService user.Service ctxHdlr *contexthandler.ContextHandler } func (sc *scenarioContext) exec() { sc.m.ServeHTTP(sc.resp, sc.req) } type scenarioFunc func(c *scenarioContext) type handlerFunc func(c *contextmodel.ReqContext) response.Response func getContextHandler(t *testing.T, cfg *setting.Cfg) *contexthandler.ContextHandler { t.Helper() if cfg == nil { cfg = setting.NewCfg() } sqlStore := db.InitTestDB(t) remoteCacheSvc := &remotecache.RemoteCache{} cfg.RemoteCacheOptions = &setting.RemoteCacheOptions{ Name: "database", } userAuthTokenSvc := authtest.NewFakeUserAuthTokenService() renderSvc := &fakeRenderService{} authJWTSvc := jwt.NewFakeJWTService() tracer := tracing.InitializeTracerForTest() authProxy := authproxy.ProvideAuthProxy(cfg, remoteCacheSvc, loginservice.LoginServiceMock{}, &usertest.FakeUserService{}, sqlStore, service.NewLDAPFakeService()) loginService := &logintest.LoginServiceFake{} authenticator := &logintest.AuthenticatorFake{} ctxHdlr := contexthandler.ProvideService(cfg, userAuthTokenSvc, authJWTSvc, remoteCacheSvc, renderSvc, sqlStore, tracer, authProxy, loginService, nil, authenticator, usertest.NewUserServiceFake(), orgtest.NewOrgServiceFake(), nil, featuremgmt.WithFeatures(), &authntest.FakeService{ ExpectedIdentity: &authn.Identity{OrgID: 1, ID: "user:1", SessionToken: &usertoken.UserToken{}}}, &anontest.FakeAnonymousSessionService{}) return ctxHdlr } func setupScenarioContext(t *testing.T, url string) *scenarioContext { cfg := setting.NewCfg() ctxHdlr := getContextHandler(t, cfg) sc := &scenarioContext{ url: url, t: t, cfg: cfg, ctxHdlr: ctxHdlr, } viewsPath, err := filepath.Abs("../../public/views") require.NoError(t, err) exists, err := fs.Exists(viewsPath) require.NoError(t, err) require.Truef(t, exists, "Views should be in %q", viewsPath) sc.m = web.New() sc.m.UseMiddleware(web.Renderer(viewsPath, "[[", "]]")) sc.m.Use(ctxHdlr.Middleware) return sc } type fakeRenderService struct { rendering.Service } func (s *fakeRenderService) Init() error { return nil } func userWithPermissions(orgID int64, permissions []accesscontrol.Permission) *user.SignedInUser { return &user.SignedInUser{OrgID: orgID, OrgRole: org.RoleViewer, Permissions: map[int64]map[string][]string{orgID: accesscontrol.GroupScopesByAction(permissions)}} } func setupSimpleHTTPServer(features *featuremgmt.FeatureManager) *HTTPServer { if features == nil { features = featuremgmt.WithFeatures() } cfg := setting.NewCfg() cfg.RBACEnabled = false cfg.IsFeatureToggleEnabled = features.IsEnabled return &HTTPServer{ Cfg: cfg, Features: features, License: &licensing.OSSLicensingService{}, AccessControl: acimpl.ProvideAccessControl(cfg), annotationsRepo: annotationstest.NewFakeAnnotationsRepo(), authInfoService: &logintest.AuthInfoServiceFake{ ExpectedLabels: map[int64]string{int64(1): login.GetAuthProviderLabel(login.LDAPAuthModule)}, }, } } func mockRequestBody(v interface{}) io.ReadCloser { b, _ := json.Marshal(v) return io.NopCloser(bytes.NewReader(b)) } // APITestServerOption option func for customizing HTTPServer configuration // when setting up an API test server via SetupAPITestServer. type APITestServerOption func(hs *HTTPServer) // SetupAPITestServer sets up a webtest.Server ready for testing all // routes registered via HTTPServer.registerRoutes(). // Optionally customize HTTPServer configuration by providing APITestServerOption // option(s). func SetupAPITestServer(t *testing.T, opts ...APITestServerOption) *webtest.Server { t.Helper() hs := &HTTPServer{ RouteRegister: routing.NewRouteRegister(), License: &licensing.OSSLicensingService{}, Features: featuremgmt.WithFeatures(), QuotaService: quotatest.New(false, nil), searchUsersService: &searchusers.OSSService{}, } for _, opt := range opts { opt(hs) } if hs.Cfg == nil { hs.Cfg = setting.NewCfg() } if hs.AccessControl == nil { hs.AccessControl = acimpl.ProvideAccessControl(hs.Cfg) } hs.registerRoutes() s := webtest.NewServer(t, hs.RouteRegister) return s } var ( viewerRole = org.RoleViewer editorRole = org.RoleEditor ) type setUpConf struct { aclMockResp []*dashboards.DashboardACLInfoDTO } type mockSearchService struct{ ExpectedResult model.HitList } func (mss *mockSearchService) SearchHandler(_ context.Context, q *search.Query) (model.HitList, error) { return mss.ExpectedResult, nil } func (mss *mockSearchService) SortOptions() []model.SortOption { return nil } func setUp(confs ...setUpConf) *HTTPServer { store := dbtest.NewFakeDB() hs := &HTTPServer{SQLStore: store, SearchService: &mockSearchService{}} aclMockResp := []*dashboards.DashboardACLInfoDTO{} for _, c := range confs { if c.aclMockResp != nil { aclMockResp = c.aclMockResp } } teamSvc := &teamtest.FakeService{} dashSvc := &dashboards.FakeDashboardService{} qResult := aclMockResp dashSvc.On("GetDashboardACLInfoList", mock.Anything, mock.AnythingOfType("*dashboards.GetDashboardACLInfoListQuery")).Return(qResult, nil) guardian.InitLegacyGuardian(setting.NewCfg(), store, dashSvc, teamSvc) return hs }
pkg/api/common_test.go
0
https://github.com/grafana/grafana/commit/64ed77ddce79009ce05f43801cc578c135f05b6b
[ 0.007202286273241043, 0.007202283013612032, 0.007202283013612032, 0.007202283013612032, 9.543216217267059e-10 ]
{ "id": 0, "code_window": [ "| `awsAsyncQueryCaching` | Enable caching for async queries for Redshift and Athena. Requires that the `useCachingService` feature toggle is enabled and the datasource has caching and async query support enabled |\n", "| `permissionsFilterRemoveSubquery` | Alternative permission filter implementation that does not use subqueries for fetching the dashboard folder |\n", "| `prometheusConfigOverhaulAuth` | Update the Prometheus configuration page with the new auth component |\n", "| `influxdbSqlSupport` | Enable InfluxDB SQL query language support with new querying UI |\n", "\n", "## Development feature toggles\n", "\n", "The following toggles require explicitly setting Grafana's [app mode]({{< relref \"../_index.md#app_mode\" >}}) to 'development' before you can enable this feature toggle. These features tend to be experimental.\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "| `noBasicRole` | Enables a new role that has no permissions by default |\n" ], "file_path": "docs/sources/setup-grafana/configure-grafana/feature-toggles/index.md", "type": "add", "edit_start_line_idx": 131 }
import React from 'react'; import { EditorRow, EditorFieldGroup } from '@grafana/experimental'; import { RawQuery } from '../../../prometheus/querybuilder/shared/RawQuery'; import { lokiGrammar } from '../../syntax'; export interface Props { query: string; } export function QueryPreview({ query }: Props) { return ( <EditorRow> <EditorFieldGroup> <RawQuery query={query} lang={{ grammar: lokiGrammar, name: 'lokiql' }} /> </EditorFieldGroup> </EditorRow> ); }
public/app/plugins/datasource/loki/querybuilder/components/QueryPreview.tsx
0
https://github.com/grafana/grafana/commit/64ed77ddce79009ce05f43801cc578c135f05b6b
[ 0.007202286273241043, 0.007202286273241043, 0.007202286273241043, 0.007202286273241043, 0 ]
{ "id": 1, "code_window": [ " permissionsFilterRemoveSubquery?: boolean;\n", " prometheusConfigOverhaulAuth?: boolean;\n", " configurableSchedulerTick?: boolean;\n", " influxdbSqlSupport?: boolean;\n", "}" ], "labels": [ "keep", "keep", "keep", "add", "keep" ], "after_edit": [ " noBasicRole?: boolean;\n" ], "file_path": "packages/grafana-data/src/types/featureToggles.gen.ts", "type": "add", "edit_start_line_idx": 120 }
import React from 'react'; import { SelectableValue } from '@grafana/data'; import { Icon, RadioButtonList, Tooltip, useStyles2, useTheme2 } from '@grafana/ui'; import { OrgRole } from 'app/types'; import { getStyles } from './styles'; const BasicRoleOption: Array<SelectableValue<OrgRole>> = Object.values(OrgRole).map((r) => ({ label: r === OrgRole.None ? 'No basic role' : r, value: r, })); interface Props { value?: OrgRole; onChange: (value: OrgRole) => void; disabled?: boolean; disabledMesssage?: string; tooltipMessage?: string; } export const BuiltinRoleSelector = ({ value, onChange, disabled, disabledMesssage, tooltipMessage }: Props) => { const styles = useStyles2(getStyles); const theme = useTheme2(); return ( <> <div className={styles.groupHeader}> <span style={{ marginRight: theme.spacing(1) }}>Basic roles</span> {disabled && disabledMesssage && ( <Tooltip placement="right-end" interactive={true} content={<div>{disabledMesssage}</div>}> <Icon name="question-circle" /> </Tooltip> )} {!disabled && tooltipMessage && ( <Tooltip placement="right-end" interactive={true} content={tooltipMessage}> <Icon name="info-circle" size="xs" /> </Tooltip> )} </div> <RadioButtonList name="Basic Role Selector" className={styles.basicRoleSelector} options={BasicRoleOption} value={value} onChange={onChange} disabled={disabled} /> </> ); };
public/app/core/components/RolePicker/BuiltinRoleSelector.tsx
1
https://github.com/grafana/grafana/commit/64ed77ddce79009ce05f43801cc578c135f05b6b
[ 0.00017759250476956367, 0.0001734511024551466, 0.00017058041703421623, 0.00017289037350565195, 0.00000269313159151352 ]
{ "id": 1, "code_window": [ " permissionsFilterRemoveSubquery?: boolean;\n", " prometheusConfigOverhaulAuth?: boolean;\n", " configurableSchedulerTick?: boolean;\n", " influxdbSqlSupport?: boolean;\n", "}" ], "labels": [ "keep", "keep", "keep", "add", "keep" ], "after_edit": [ " noBasicRole?: boolean;\n" ], "file_path": "packages/grafana-data/src/types/featureToggles.gen.ts", "type": "add", "edit_start_line_idx": 120 }
package team import ( "errors" "time" v1 "k8s.io/apimachinery/pkg/apis/meta/v1" "github.com/grafana/grafana/pkg/kinds/team" "github.com/grafana/grafana/pkg/services/auth/identity" "github.com/grafana/grafana/pkg/services/dashboards" "github.com/grafana/grafana/pkg/services/user" ) // Typed errors var ( ErrTeamNotFound = errors.New("team not found") ErrTeamNameTaken = errors.New("team name is taken") ErrTeamMemberNotFound = errors.New("team member not found") ErrLastTeamAdmin = errors.New("not allowed to remove last admin") ErrNotAllowedToUpdateTeam = errors.New("user not allowed to update team") ErrNotAllowedToUpdateTeamInDifferentOrg = errors.New("user not allowed to update team in another org") ErrTeamMemberAlreadyAdded = errors.New("user is already added to this team") ) // Team model type Team struct { ID int64 `json:"id" xorm:"pk autoincr 'id'"` UID string `json:"uid" xorm:"uid"` OrgID int64 `json:"orgId" xorm:"org_id"` Name string `json:"name"` Email string `json:"email"` Created time.Time `json:"created"` Updated time.Time `json:"updated"` } func (t *Team) ToResource() team.K8sResource { r := team.NewK8sResource(t.UID, &team.Spec{ Name: t.Name, }) r.Metadata.CreationTimestamp = v1.NewTime(t.Created) r.Metadata.SetUpdatedTimestamp(&t.Updated) if t.Email != "" { r.Spec.Email = &t.Email } return r } // --------------------- // COMMANDS type CreateTeamCommand struct { Name string `json:"name" binding:"Required"` Email string `json:"email"` OrgID int64 `json:"-"` } type UpdateTeamCommand struct { ID int64 Name string Email string OrgID int64 `json:"-"` } type DeleteTeamCommand struct { OrgID int64 ID int64 } type GetTeamByIDQuery struct { OrgID int64 ID int64 SignedInUser identity.Requester HiddenUsers map[string]struct{} } // FilterIgnoreUser is used in a get / search teams query when the caller does not want to filter teams by user ID / membership const FilterIgnoreUser int64 = 0 type GetTeamsByUserQuery struct { OrgID int64 UserID int64 `json:"userId"` SignedInUser identity.Requester } type SearchTeamsQuery struct { Query string Name string Limit int Page int OrgID int64 `xorm:"org_id"` SignedInUser identity.Requester HiddenUsers map[string]struct{} } type TeamDTO struct { ID int64 `json:"id" xorm:"id"` UID string `json:"uid" xorm:"uid"` OrgID int64 `json:"orgId" xorm:"org_id"` Name string `json:"name"` Email string `json:"email"` AvatarURL string `json:"avatarUrl"` MemberCount int64 `json:"memberCount"` Permission dashboards.PermissionType `json:"permission"` AccessControl map[string]bool `json:"accessControl"` } type SearchTeamQueryResult struct { TotalCount int64 `json:"totalCount"` Teams []*TeamDTO `json:"teams"` Page int `json:"page"` PerPage int `json:"perPage"` } // TeamMember model type TeamMember struct { ID int64 `xorm:"pk autoincr 'id'"` OrgID int64 `xorm:"org_id"` TeamID int64 `xorm:"team_id"` UserID int64 `xorm:"user_id"` External bool // Signals that the membership has been created by an external systems, such as LDAP Permission dashboards.PermissionType Created time.Time Updated time.Time } // --------------------- // COMMANDS type AddTeamMemberCommand struct { UserID int64 `json:"userId" binding:"Required"` OrgID int64 `json:"-"` TeamID int64 `json:"-"` External bool `json:"-"` Permission dashboards.PermissionType `json:"-"` } type UpdateTeamMemberCommand struct { UserID int64 `json:"-"` OrgID int64 `json:"-"` TeamID int64 `json:"-"` Permission dashboards.PermissionType `json:"permission"` } type RemoveTeamMemberCommand struct { OrgID int64 `json:"-"` UserID int64 TeamID int64 } // ---------------------- // QUERIES type GetTeamMembersQuery struct { OrgID int64 TeamID int64 TeamUID string UserID int64 External bool SignedInUser *user.SignedInUser } // ---------------------- // Projections and DTOs type TeamMemberDTO struct { OrgID int64 `json:"orgId" xorm:"org_id"` TeamID int64 `json:"teamId" xorm:"team_id"` TeamUID string `json:"teamUID" xorm:"uid"` UserID int64 `json:"userId" xorm:"user_id"` External bool `json:"-"` AuthModule string `json:"auth_module"` Email string `json:"email"` Name string `json:"name"` Login string `json:"login"` AvatarURL string `json:"avatarUrl" xorm:"avatar_url"` Labels []string `json:"labels"` Permission dashboards.PermissionType `json:"permission"` }
pkg/services/team/model.go
0
https://github.com/grafana/grafana/commit/64ed77ddce79009ce05f43801cc578c135f05b6b
[ 0.001005369471386075, 0.000267822906607762, 0.00016654473438393325, 0.00017262404435314238, 0.0002455829526297748 ]
{ "id": 1, "code_window": [ " permissionsFilterRemoveSubquery?: boolean;\n", " prometheusConfigOverhaulAuth?: boolean;\n", " configurableSchedulerTick?: boolean;\n", " influxdbSqlSupport?: boolean;\n", "}" ], "labels": [ "keep", "keep", "keep", "add", "keep" ], "after_edit": [ " noBasicRole?: boolean;\n" ], "file_path": "packages/grafana-data/src/types/featureToggles.gen.ts", "type": "add", "edit_start_line_idx": 120 }
<svg xmlns="http://www.w3.org/2000/svg" data-name="Layer 1" viewBox="0 0 24 24"><path d="M21,10.41H18.5a1,1,0,0,0-.71.3L16.55,12l-2.8-3.19a1,1,0,0,0-1.46,0l-1.7,1.7H9a1,1,0,0,0,0,2h2a1,1,0,0,0,.71-.29L13,10.88l2.8,3.19a1,1,0,0,0,.72.34h0a1,1,0,0,0,.71-.29l1.7-1.71H21a1,1,0,0,0,0-2Zm-7.39,5.3-1.9,1.9a1,1,0,0,1-1.42,0L5.08,12.4a3.69,3.69,0,0,1,0-5.22,3.69,3.69,0,0,1,5.21,0,1,1,0,0,0,1.42,0,3.78,3.78,0,0,1,5.21,0,3.94,3.94,0,0,1,.58.75,1,1,0,0,0,1.72-1,6,6,0,0,0-.88-1.13A5.68,5.68,0,0,0,11,5.17,5.68,5.68,0,0,0,2,9.79a5.62,5.62,0,0,0,1.67,4L8.88,19a3,3,0,0,0,4.24,0L15,17.12a1,1,0,0,0,0-1.41A1,1,0,0,0,13.61,15.71Z"/></svg>
public/img/icons/unicons/heartbeat.svg
0
https://github.com/grafana/grafana/commit/64ed77ddce79009ce05f43801cc578c135f05b6b
[ 0.0005233814008533955, 0.0005233814008533955, 0.0005233814008533955, 0.0005233814008533955, 0 ]
{ "id": 1, "code_window": [ " permissionsFilterRemoveSubquery?: boolean;\n", " prometheusConfigOverhaulAuth?: boolean;\n", " configurableSchedulerTick?: boolean;\n", " influxdbSqlSupport?: boolean;\n", "}" ], "labels": [ "keep", "keep", "keep", "add", "keep" ], "after_edit": [ " noBasicRole?: boolean;\n" ], "file_path": "packages/grafana-data/src/types/featureToggles.gen.ts", "type": "add", "edit_start_line_idx": 120 }
import { AlignedData } from 'uplot'; import { DataFrame, Field, FieldDTO, FieldType, Labels, parseLabels, QueryResultMeta } from '..'; import { join } from '../transformations/transformers/joinDataFrames'; import { renderLegendFormat } from '../utils/legend'; import { DataFrameJSON, decodeFieldValueEntities, FieldSchema, guessFieldTypeFromValue, toFilteredDataFrameDTO, } from '.'; /** * Indicate if the frame is appened or replace * * @alpha */ export enum StreamingFrameAction { Append = 'append', Replace = 'replace', } /** * @alpha * */ export interface StreamingFrameOptions { maxLength: number; // 1000 maxDelta: number; // how long to keep things action: StreamingFrameAction; // default will append /** optionally format field names based on labels */ displayNameFormat?: string; } /** * Stream packet info is attached to StreamingDataFrames and indicate how many * rows were added to the end of the frame. The number of discarded rows can be * calculated from previous state */ export interface StreamPacketInfo { number: number; action: StreamingFrameAction; length: number; schemaChanged: boolean; } const PROM_STYLE_METRIC_LABEL = '__name__'; enum PushMode { wide, labels, // long } export type SerializedStreamingDataFrame = { name?: string; fields: FieldDTO[]; refId?: string; meta: QueryResultMeta; schemaFields: FieldSchema[]; timeFieldIndex: number; pushMode: PushMode; length: number; packetInfo: StreamPacketInfo; options: StreamingFrameOptions; labels: Set<string>; }; /** * Unlike a circular buffer, this will append and periodically slice the front */ export class StreamingDataFrame implements DataFrame { name?: string; refId?: string; meta: QueryResultMeta = {}; fields: Field[] = []; length = 0; private schemaFields: FieldSchema[] = []; private timeFieldIndex = -1; private pushMode = PushMode.wide; // current labels private labels: Set<string> = new Set(); readonly packetInfo: StreamPacketInfo = { schemaChanged: true, number: 0, action: StreamingFrameAction.Replace, length: 0, }; private constructor(public options: StreamingFrameOptions) { // Get Length to show up if you use spread Object.defineProperty(this, 'length', { enumerable: true, }); // Get fields to show up if you use spread Object.defineProperty(this, 'fields', { enumerable: true, }); } serialize = ( fieldPredicate?: (f: Field) => boolean, optionsOverride?: Partial<StreamingFrameOptions>, trimValues?: { maxLength?: number; } ): SerializedStreamingDataFrame => { const options = optionsOverride ? Object.assign({}, { ...this.options, ...optionsOverride }) : this.options; const dataFrameDTO = toFilteredDataFrameDTO(this, fieldPredicate); const numberOfItemsToRemove = getNumberOfItemsToRemove( dataFrameDTO.fields.map((f) => f.values) as unknown[][], typeof trimValues?.maxLength === 'number' ? Math.min(trimValues.maxLength, options.maxLength) : options.maxLength, this.timeFieldIndex, options.maxDelta ); dataFrameDTO.fields = dataFrameDTO.fields.map((f) => ({ ...f, values: (f.values as unknown[]).slice(numberOfItemsToRemove), })); const length = dataFrameDTO.fields[0]?.values?.length ?? 0; return { ...dataFrameDTO, // TODO: Labels and schema are not filtered by field labels: this.labels, schemaFields: this.schemaFields, name: this.name, refId: this.refId, meta: this.meta, length, timeFieldIndex: this.timeFieldIndex, pushMode: this.pushMode, packetInfo: this.packetInfo, options, }; }; private initFromSerialized = (serialized: Omit<SerializedStreamingDataFrame, 'options'>) => { this.name = serialized.name; this.refId = serialized.refId; this.meta = serialized.meta; this.length = serialized.length; this.labels = serialized.labels; this.schemaFields = serialized.schemaFields; this.timeFieldIndex = serialized.timeFieldIndex; this.pushMode = serialized.pushMode; this.packetInfo.length = serialized.packetInfo.length; this.packetInfo.number = serialized.packetInfo.number; this.packetInfo.action = StreamingFrameAction.Replace; this.packetInfo.schemaChanged = true; this.fields = serialized.fields.map((f) => ({ ...f, type: f.type ?? FieldType.other, config: f.config ?? {}, values: f.values ?? [], })); assureValuesAreWithinLengthLimit( this.fields.map((f) => f.values), this.options.maxLength, this.timeFieldIndex, this.options.maxDelta ); }; static deserialize = (serialized: SerializedStreamingDataFrame) => { const frame = new StreamingDataFrame(serialized.options); frame.initFromSerialized(serialized); return frame; }; static empty = (opts?: Partial<StreamingFrameOptions>): StreamingDataFrame => new StreamingDataFrame(getStreamingFrameOptions(opts)); static fromDataFrameJSON = (frame: DataFrameJSON, opts?: Partial<StreamingFrameOptions>): StreamingDataFrame => { const streamingDataFrame = new StreamingDataFrame(getStreamingFrameOptions(opts)); streamingDataFrame.push(frame); return streamingDataFrame; }; private get alwaysReplace() { return this.options.action === StreamingFrameAction.Replace; } needsResizing = ({ maxLength, maxDelta }: StreamingFrameOptions) => { const needsMoreLength = maxLength && this.options.maxLength < maxLength; const needsBiggerDelta = maxDelta && this.options.maxDelta < maxDelta; const needsToOverrideDefaultInfinityDelta = maxDelta && this.options.maxDelta === Infinity; return Boolean(needsMoreLength || needsBiggerDelta || needsToOverrideDefaultInfinityDelta); }; resize = ({ maxLength, maxDelta }: Partial<StreamingFrameOptions>) => { if (maxDelta) { if (this.options.maxDelta === Infinity) { this.options.maxDelta = maxDelta; } else { this.options.maxDelta = Math.max(maxDelta, this.options.maxDelta); } } this.options.maxLength = Math.max(this.options.maxLength, maxLength ?? 0); }; /** * apply the new message to the existing data. This will replace the existing schema * if a new schema is included in the message, or append data matching the current schema */ push(msg: DataFrameJSON): StreamPacketInfo { const { schema, data } = msg; this.packetInfo.number++; this.packetInfo.length = 0; this.packetInfo.schemaChanged = false; if (schema) { this.pushMode = PushMode.wide; this.timeFieldIndex = schema.fields.findIndex((f) => f.type === FieldType.time); const firstField = schema.fields[0]; if ( this.timeFieldIndex === 1 && firstField.type === FieldType.string && (firstField.name === 'labels' || firstField.name === 'Labels') ) { this.pushMode = PushMode.labels; this.timeFieldIndex = 0; // after labels are removed! } const niceSchemaFields = this.pushMode === PushMode.labels ? schema.fields.slice(1) : schema.fields; this.refId = schema.refId; if (schema.meta) { this.meta = { ...schema.meta }; } const { displayNameFormat } = this.options; if (hasSameStructure(this.schemaFields, niceSchemaFields)) { const len = niceSchemaFields.length; this.fields.forEach((f, idx) => { const sf = niceSchemaFields[idx % len]; f.config = sf.config ?? {}; f.labels = sf.labels; }); if (displayNameFormat) { this.fields.forEach((f) => { const labels = { [PROM_STYLE_METRIC_LABEL]: f.name, ...f.labels }; f.config.displayNameFromDS = renderLegendFormat(displayNameFormat, labels); }); } } else { this.packetInfo.schemaChanged = true; const isWide = this.pushMode === PushMode.wide; this.fields = niceSchemaFields.map((f) => { const config = f.config ?? {}; if (displayNameFormat) { const labels = { [PROM_STYLE_METRIC_LABEL]: f.name, ...f.labels }; config.displayNameFromDS = renderLegendFormat(displayNameFormat, labels); } return { config, name: f.name, labels: f.labels, type: f.type ?? FieldType.other, // transfer old values by type & name, unless we relied on labels to match fields values: isWide ? this.fields.find((of) => of.name === f.name && f.type === of.type)?.values ?? Array(this.length).fill(undefined) : [], }; }); } this.schemaFields = niceSchemaFields; } if (data && data.values.length && data.values[0].length) { let { values, entities } = data; if (entities) { entities.forEach((ents, i) => { if (ents) { decodeFieldValueEntities(ents, values[i]); // TODO: append replacements to field } }); } if (this.pushMode === PushMode.labels) { // augment and transform data to match current schema for standard circPush() path const labeledTables = transpose(values); // make sure fields are initalized for each label for (const label of labeledTables.keys()) { if (!this.labels.has(label)) { this.packetInfo.schemaChanged = true; this.addLabel(label); } } // TODO: cache higher up let dummyTable = Array(this.schemaFields.length).fill([]); let tables: AlignedData[] = []; this.labels.forEach((label) => { tables.push(labeledTables.get(label) ?? dummyTable); }); values = join(tables); } if (values.length !== this.fields.length) { if (this.fields.length) { throw new Error( `push message mismatch. Expected: ${this.fields.length}, received: ${values.length} (labels=${ this.pushMode === PushMode.labels })` ); } this.fields = values.map((vals, idx) => { let name = `Field ${idx}`; let type = guessFieldTypeFromValue(vals[0]); const isTime = idx === 0 && type === FieldType.number && (vals as number[])[0] > 1600016688632; if (isTime) { type = FieldType.time; name = 'Time'; } return { name, type, config: {}, values: [], }; }); } let appended = values; this.packetInfo.length = values[0].length; if (this.alwaysReplace || !this.length) { this.packetInfo.action = StreamingFrameAction.Replace; } else { this.packetInfo.action = StreamingFrameAction.Append; // mutates appended appended = this.fields.map((f) => f.values); circPush(appended, values, this.options.maxLength, this.timeFieldIndex, this.options.maxDelta); } appended.forEach((v, i) => { const field = this.fields[i]; const { state } = field; field.values = v; if (state) { state.calcs = undefined; } }); // Update the frame length this.length = appended[0].length; } return { ...this.packetInfo, }; } pushNewValues = (values: unknown[][]) => { if (!values?.length) { return; } this.packetInfo.action = this.options.action; this.packetInfo.number++; this.packetInfo.length = values[0].length; this.packetInfo.schemaChanged = false; if (this.options.action === StreamingFrameAction.Append) { circPush( this.fields.map((f) => f.values), values, this.options.maxLength, this.timeFieldIndex, this.options.maxDelta ); } else { values.forEach((v, i) => { if (this.fields[i]) { this.fields[i].values = v; } }); assureValuesAreWithinLengthLimit( this.fields.map((f) => f.values), this.options.maxLength, this.timeFieldIndex, this.options.maxDelta ); } const newLength = this.fields?.[0]?.values.length; if (newLength !== undefined) { this.length = newLength; } }; resetStateCalculations = () => { this.fields.forEach((f) => { f.state = { ...(f.state ?? {}), calcs: undefined, range: undefined, }; }); }; getMatchingFieldIndexes = (fieldPredicate: (f: Field) => boolean): number[] => this.fields .map((f, index) => (fieldPredicate(f) ? index : undefined)) .filter((val) => val !== undefined) as number[]; getValuesFromLastPacket = (): unknown[][] => this.fields.map((f) => { const values = f.values; return values.slice(Math.max(values.length - this.packetInfo.length)); }); hasAtLeastOnePacket = () => Boolean(this.packetInfo.length); // adds a set of fields for a new label private addLabel(label: string) { const { displayNameFormat } = this.options; const labelCount = this.labels.size; // parse labels const parsedLabels = parseLabelsFromField(label); if (labelCount === 0) { // mutate existing fields and add labels this.fields.forEach((f, i) => { if (i > 0) { f.labels = parsedLabels; if (displayNameFormat) { const labels = { [PROM_STYLE_METRIC_LABEL]: f.name, ...parsedLabels }; f.config.displayNameFromDS = renderLegendFormat(displayNameFormat, labels); } } }); } else { for (let i = 1; i < this.schemaFields.length; i++) { let proto = this.schemaFields[i] as Field; const config = proto.config ?? {}; if (displayNameFormat) { const labels = { [PROM_STYLE_METRIC_LABEL]: proto.name, ...parsedLabels }; config.displayNameFromDS = renderLegendFormat(displayNameFormat, labels); } this.fields.push({ ...proto, config, labels: parsedLabels, values: Array(this.length).fill(undefined), }); } } this.labels.add(label); } getOptions = (): Readonly<StreamingFrameOptions> => this.options; } export function getStreamingFrameOptions(opts?: Partial<StreamingFrameOptions>): StreamingFrameOptions { return { maxLength: opts?.maxLength ?? 1000, maxDelta: opts?.maxDelta ?? Infinity, action: opts?.action ?? StreamingFrameAction.Append, displayNameFormat: opts?.displayNameFormat, }; } // converts vertical insertion records with table keys in [0] and column values in [1...N] // to join()-able tables with column arrays export function transpose(vrecs: any[][]) { let tableKeys = new Set(vrecs[0]); let tables = new Map(); tableKeys.forEach((key) => { let cols = Array(vrecs.length - 1) .fill(null) .map(() => []); tables.set(key, cols); }); for (let r = 0; r < vrecs[0].length; r++) { let table = tables.get(vrecs[0][r]); for (let c = 1; c < vrecs.length; c++) { table[c - 1].push(vrecs[c][r]); } } return tables; } // binary search for index of closest value export function closestIdx(num: number, arr: number[], lo?: number, hi?: number) { let mid; lo = lo || 0; hi = hi || arr.length - 1; let bitwise = hi <= 2147483647; while (hi - lo > 1) { mid = bitwise ? (lo + hi) >> 1 : Math.floor((lo + hi) / 2); if (arr[mid] < num) { lo = mid; } else { hi = mid; } } if (num - arr[lo] <= arr[hi] - num) { return lo; } return hi; } export function parseLabelsFromField(str: string): Labels { if (!str.length) { return {}; } if (str.charAt(0) === '{') { return parseLabels(str); } const parsedLabels: Labels = {}; str.split(',').forEach((kv) => { const [key, val] = kv.trim().split('='); parsedLabels[key] = val; }); return parsedLabels; } /** * @internal // not exported in yet */ export function getLastStreamingDataFramePacket(frame: DataFrame) { const pi = (frame as StreamingDataFrame).packetInfo; return pi?.action ? pi : undefined; } // mutable circular push function circPush(data: unknown[][], newData: unknown[][], maxLength = Infinity, deltaIdx = 0, maxDelta = Infinity) { for (let i = 0; i < data.length; i++) { for (let k = 0; k < newData[i].length; k++) { data[i].push(newData[i][k]); } } return assureValuesAreWithinLengthLimit(data, maxLength, deltaIdx, maxDelta); } function assureValuesAreWithinLengthLimit(data: unknown[][], maxLength = Infinity, deltaIdx = 0, maxDelta = Infinity) { const count = getNumberOfItemsToRemove(data, maxLength, deltaIdx, maxDelta); if (count) { for (let i = 0; i < data.length; i++) { data[i].splice(0, count); } } return count; } function getNumberOfItemsToRemove(data: unknown[][], maxLength = Infinity, deltaIdx = 0, maxDelta = Infinity) { if (!data[0]?.length) { return 0; } const nlen = data[0].length; let sliceIdx = 0; if (nlen > maxLength) { sliceIdx = nlen - maxLength; } if (maxDelta !== Infinity && deltaIdx >= 0) { const deltaLookup = data[deltaIdx] as number[]; const low = deltaLookup[sliceIdx]; const high = deltaLookup[nlen - 1]; if (high - low > maxDelta) { sliceIdx = closestIdx(high - maxDelta, deltaLookup, sliceIdx); } } return sliceIdx; } function hasSameStructure(a: FieldSchema[], b: FieldSchema[]): boolean { if (a?.length !== b.length) { return false; } for (let i = 0; i < a.length; i++) { const fA = a[i]; const fB = b[i]; if (fA.name !== fB.name || fA.type !== fB.type) { return false; } } return true; }
packages/grafana-data/src/dataframe/StreamingDataFrame.ts
0
https://github.com/grafana/grafana/commit/64ed77ddce79009ce05f43801cc578c135f05b6b
[ 0.000576607882976532, 0.00017795615713112056, 0.0001669790071900934, 0.00017143465811386704, 0.000050681730499491096 ]
{ "id": 2, "code_window": [ "\t\t\tStage: FeatureStageExperimental,\n", "\t\t\tFrontendOnly: false,\n", "\t\t\tOwner: grafanaObservabilityMetricsSquad,\n", "\t\t\tRequiresRestart: false,\n", "\t\t},\n", "\t}\n", ")" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep" ], "after_edit": [ "\t\t{\n", "\t\t\tName: \"noBasicRole\",\n", "\t\t\tDescription: \"Enables a new role that has no permissions by default\",\n", "\t\t\tStage: FeatureStageExperimental,\n", "\t\t\tFrontendOnly: true,\n", "\t\t\tOwner: grafanaAuthnzSquad,\n", "\t\t\tRequiresRestart: true,\n", "\t\t},\n" ], "file_path": "pkg/services/featuremgmt/registry.go", "type": "add", "edit_start_line_idx": 693 }
--- aliases: - /docs/grafana/latest/setup-grafana/configure-grafana/feature-toggles/ description: Learn about feature toggles, which you can enable or disable. title: Configure feature toggles weight: 150 --- <!-- DO NOT EDIT THIS PAGE, it is machine generated by running the test in --> <!-- https://github.com/grafana/grafana/blob/main/pkg/services/featuremgmt/toggles_gen_test.go#L19 --> # Configure feature toggles You use feature toggles, also known as feature flags, to enable or disable features in Grafana. You can turn on feature toggles to try out new functionality in development or test environments. This page contains a list of available feature toggles. To learn how to turn on feature toggles, refer to our [Configure Grafana documentation]({{< relref "../_index.md#feature_toggles" >}}). Feature toggles are also available to Grafana Cloud Advanced customers. If you use Grafana Cloud Advanced, you can open a support ticket and specify the feature toggles and stack for which you want them enabled. ## Feature toggles Some features are enabled by default. You can disable these feature by setting the feature flag to "false" in the configuration. | Feature toggle name | Description | Enabled by default | | ------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------ | | `disableEnvelopeEncryption` | Disable envelope encryption (emergency only) | | | `featureHighlights` | Highlight Grafana Enterprise features | | | `dataConnectionsConsole` | Enables a new top-level page called Connections. This page is an experiment that provides a better experience when you install and configure data sources and other plugins. | Yes | | `cloudWatchCrossAccountQuerying` | Enables cross-account querying in CloudWatch datasources | Yes | | `redshiftAsyncQueryDataSupport` | Enable async query data support for Redshift | Yes | | `athenaAsyncQueryDataSupport` | Enable async query data support for Athena | Yes | | `newPanelChromeUI` | Show updated look and feel of grafana-ui PanelChrome: panel header, icons, and menu | Yes | | `nestedFolderPicker` | Enables the new folder picker to work with nested folders. Requires the folderPicker feature flag | Yes | | `accessTokenExpirationCheck` | Enable OAuth access_token expiration check and token refresh using the refresh_token | | | `emptyDashboardPage` | Enable the redesigned user interface of a dashboard page that includes no panels | Yes | | `disablePrometheusExemplarSampling` | Disable Prometheus exemplar sampling | | | `logsContextDatasourceUi` | Allow datasource to provide custom UI for context view | Yes | | `lokiQuerySplitting` | Split large interval queries into subqueries with smaller time intervals | Yes | | `gcomOnlyExternalOrgRoleSync` | Prohibits a user from changing organization roles synced with Grafana Cloud auth provider | | | `prometheusMetricEncyclopedia` | Adds the metrics explorer component to the Prometheus query builder as an option in metric select | Yes | | `prometheusResourceBrowserCache` | Displays browser caching options in Prometheus data source configuration | Yes | | `prometheusDataplane` | Changes responses to from Prometheus to be compliant with the dataplane specification. In particular it sets the numeric Field.Name from 'Value' to the value of the `__name__` label when present. | Yes | | `lokiMetricDataplane` | Changes metric responses from Loki to be compliant with the dataplane specification. | Yes | | `dataplaneFrontendFallback` | Support dataplane contract field name change for transformations and field name matchers where the name is different | Yes | | `alertingNotificationsPoliciesMatchingInstances` | Enables the preview of matching instances for notification policies | Yes | | `useCachingService` | When turned on, the new query and resource caching implementation using a wire service inject will be used in place of the previous middleware implementation | | | `advancedDataSourcePicker` | Enable a new data source picker with contextual information, recently used order and advanced mode | Yes | | `transformationsRedesign` | Enables the transformations redesign | Yes | | `azureMonitorDataplane` | Adds dataplane compliant frame metadata in the Azure Monitor datasource | Yes | ## Preview feature toggles | Feature toggle name | Description | | ------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `trimDefaults` | Use cue schema to remove values that will be applied automatically | | `panelTitleSearch` | Search for dashboards using panel title | | `publicDashboards` | Enables public access to dashboards | | `migrationLocking` | Lock database during migrations | | `correlations` | Correlations page | | `newDBLibrary` | Use jmoiron/sqlx rather than xorm for a few backend services | | `validateDashboardsOnSave` | Validate dashboard JSON POSTed to api/dashboards/db | | `autoMigrateOldPanels` | Migrate old angular panels to supported versions (graph, table-old, worldmap, etc) | | `disableAngular` | Dynamic flag to disable angular at runtime. The preferred method is to set `angular_support_enabled` to `false` in the [security] settings, which allows you to change the state at runtime. | | `grpcServer` | Run the GRPC server | | `accessControlOnCall` | Access control primitives for OnCall | | `nestedFolders` | Enable folder nesting | | `alertingNoNormalState` | Stop maintaining state of alerts that are not firing | | `influxdbBackendMigration` | Query InfluxDB InfluxQL without the proxy | | `renderAuthJWT` | Uses JWT-based auth for rendering instead of relying on remote cache | | `refactorVariablesTimeRange` | Refactor time range variables flow to reduce number of API calls made when query variables are chained | | `enableElasticsearchBackendQuerying` | Enable the processing of queries and responses in the Elasticsearch data source through backend | | `faroDatasourceSelector` | Enable the data source selector within the Frontend Apps section of the Frontend Observability | | `enableDatagridEditing` | Enables the edit functionality in the datagrid panel | | `dataSourcePageHeader` | Apply new pageHeader UI in data source edit page | | `sqlDatasourceDatabaseSelection` | Enables previous SQL data source dataset dropdown behavior | | `splitScopes` | Support faster dashboard and folder search by splitting permission scopes into parts | ## Experimental feature toggles These features are early in their development lifecycle and so are not yet supported in Grafana Cloud. Experimental features might be changed or removed without prior notice. | Feature toggle name | Description | | ------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `live-service-web-worker` | This will use a webworker thread to processes events rather than the main thread | | `queryOverLive` | Use Grafana Live WebSocket to execute backend queries | | `lokiExperimentalStreaming` | Support new streaming approach for loki (prototype, needs special loki build) | | `storage` | Configurable storage for dashboards, datasources, and resources | | `datasourceQueryMultiStatus` | Introduce HTTP 207 Multi Status for api/ds/query | | `traceToMetrics` | Enable trace to metrics links | | `prometheusWideSeries` | Enable wide series responses in the Prometheus datasource | | `canvasPanelNesting` | Allow elements nesting | | `scenes` | Experimental framework to build interactive dashboards | | `disableSecretsCompatibility` | Disable duplicated secret storage in legacy tables | | `logRequestsInstrumentedAsUnknown` | Logs the path for requests that are instrumented as unknown | | `showDashboardValidationWarnings` | Show warnings when dashboards do not validate against the schema | | `mysqlAnsiQuotes` | Use double quotes to escape keyword in a MySQL query | | `alertingBacktesting` | Rule backtesting API for alerting | | `editPanelCSVDragAndDrop` | Enables drag and drop for CSV and Excel files | | `lokiQuerySplittingConfig` | Give users the option to configure split durations for Loki queries | | `individualCookiePreferences` | Support overriding cookie preferences per user | | `timeSeriesTable` | Enable time series table transformer & sparkline cell type | | `clientTokenRotation` | Replaces the current in-request token rotation so that the client initiates the rotation | | `lokiLogsDataplane` | Changes logs responses from Loki to be compliant with the dataplane specification. | | `disableSSEDataplane` | Disables dataplane specific processing in server side expressions. | | `alertStateHistoryLokiSecondary` | Enable Grafana to write alert state history to an external Loki instance in addition to Grafana annotations. | | `alertStateHistoryLokiPrimary` | Enable a remote Loki instance as the primary source for state history reads. | | `alertStateHistoryLokiOnly` | Disable Grafana alerts from emitting annotations when a remote Loki instance is available. | | `unifiedRequestLog` | Writes error logs to the request logger | | `extraThemes` | Enables extra themes | | `lokiPredefinedOperations` | Adds predefined query operations to Loki query editor | | `pluginsFrontendSandbox` | Enables the plugins frontend sandbox | | `dashboardEmbed` | Allow embedding dashboard for external use in Code editors | | `frontendSandboxMonitorOnly` | Enables monitor only in the plugin frontend sandbox (if enabled) | | `lokiFormatQuery` | Enables the ability to format Loki queries | | `cloudWatchLogsMonacoEditor` | Enables the Monaco editor for CloudWatch Logs queries | | `exploreScrollableLogsContainer` | Improves the scrolling behavior of logs in Explore | | `recordedQueriesMulti` | Enables writing multiple items from a single query within Recorded Queries | | `pluginsDynamicAngularDetectionPatterns` | Enables fetching Angular detection patterns for plugins from GCOM and fallback to hardcoded ones | | `alertingLokiRangeToInstant` | Rewrites eligible loki range queries to instant queries | | `vizAndWidgetSplit` | Split panels between vizualizations and widgets | | `prometheusIncrementalQueryInstrumentation` | Adds RudderStack events to incremental queries | | `logsExploreTableVisualisation` | A table visualisation for logs in Explore | | `awsDatasourcesTempCredentials` | Support temporary security credentials in AWS plugins for Grafana Cloud customers | | `toggleLabelsInLogsUI` | Enable toggleable filters in log details view | | `mlExpressions` | Enable support for Machine Learning in server-side expressions | | `traceQLStreaming` | Enables response streaming of TraceQL queries of the Tempo data source | | `grafanaAPIServer` | Enable Kubernetes API Server for Grafana resources | | `featureToggleAdminPage` | Enable admin page for managing feature toggles from the Grafana front-end | | `awsAsyncQueryCaching` | Enable caching for async queries for Redshift and Athena. Requires that the `useCachingService` feature toggle is enabled and the datasource has caching and async query support enabled | | `permissionsFilterRemoveSubquery` | Alternative permission filter implementation that does not use subqueries for fetching the dashboard folder | | `prometheusConfigOverhaulAuth` | Update the Prometheus configuration page with the new auth component | | `influxdbSqlSupport` | Enable InfluxDB SQL query language support with new querying UI | ## Development feature toggles The following toggles require explicitly setting Grafana's [app mode]({{< relref "../_index.md#app_mode" >}}) to 'development' before you can enable this feature toggle. These features tend to be experimental. | Feature toggle name | Description | | --------------------- | -------------------------------------------------------------- | | `entityStore` | SQL-based entity store (requires storage flag also) | | `externalServiceAuth` | Starts an OAuth2 authentication provider for external services |
docs/sources/setup-grafana/configure-grafana/feature-toggles/index.md
1
https://github.com/grafana/grafana/commit/64ed77ddce79009ce05f43801cc578c135f05b6b
[ 0.0011024740524590015, 0.00025276190717704594, 0.0001642813003854826, 0.00016655823856126517, 0.00024200369080062956 ]
{ "id": 2, "code_window": [ "\t\t\tStage: FeatureStageExperimental,\n", "\t\t\tFrontendOnly: false,\n", "\t\t\tOwner: grafanaObservabilityMetricsSquad,\n", "\t\t\tRequiresRestart: false,\n", "\t\t},\n", "\t}\n", ")" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep" ], "after_edit": [ "\t\t{\n", "\t\t\tName: \"noBasicRole\",\n", "\t\t\tDescription: \"Enables a new role that has no permissions by default\",\n", "\t\t\tStage: FeatureStageExperimental,\n", "\t\t\tFrontendOnly: true,\n", "\t\t\tOwner: grafanaAuthnzSquad,\n", "\t\t\tRequiresRestart: true,\n", "\t\t},\n" ], "file_path": "pkg/services/featuremgmt/registry.go", "type": "add", "edit_start_line_idx": 693 }
import React, { useState, useRef } from 'react'; import { useDebounce } from 'react-use'; import { FilterInput } from '@grafana/ui'; interface Props { value?: string; onSearch: (value: string) => void; } // useDebounce has a bug which causes it to fire on first render. This wrapper prevents that. // https://github.com/streamich/react-use/issues/759 const useDebounceWithoutFirstRender = (callBack: () => any, delay = 0, deps: React.DependencyList = []) => { const isFirstRender = useRef(true); const debounceDeps = [...deps, isFirstRender]; return useDebounce( () => { if (isFirstRender.current) { isFirstRender.current = false; return; } return callBack(); }, delay, debounceDeps ); }; export const SearchField = ({ value, onSearch }: Props) => { const [query, setQuery] = useState(value); useDebounceWithoutFirstRender(() => onSearch(query ?? ''), 500, [query]); return ( <FilterInput value={query} onKeyDown={(e) => { if (e.key === 'Enter' || e.keyCode === 13) { onSearch(e.currentTarget.value); } }} placeholder="Search Grafana plugins" onChange={(value) => { setQuery(value); }} width={46} /> ); };
public/app/features/plugins/admin/components/SearchField.tsx
0
https://github.com/grafana/grafana/commit/64ed77ddce79009ce05f43801cc578c135f05b6b
[ 0.00017734849825501442, 0.00017277762526646256, 0.00016671270714141428, 0.0001730396325001493, 0.0000033019900911313016 ]
{ "id": 2, "code_window": [ "\t\t\tStage: FeatureStageExperimental,\n", "\t\t\tFrontendOnly: false,\n", "\t\t\tOwner: grafanaObservabilityMetricsSquad,\n", "\t\t\tRequiresRestart: false,\n", "\t\t},\n", "\t}\n", ")" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep" ], "after_edit": [ "\t\t{\n", "\t\t\tName: \"noBasicRole\",\n", "\t\t\tDescription: \"Enables a new role that has no permissions by default\",\n", "\t\t\tStage: FeatureStageExperimental,\n", "\t\t\tFrontendOnly: true,\n", "\t\t\tOwner: grafanaAuthnzSquad,\n", "\t\t\tRequiresRestart: true,\n", "\t\t},\n" ], "file_path": "pkg/services/featuremgmt/registry.go", "type": "add", "edit_start_line_idx": 693 }
import { NavModelItem, NavModel } from '@grafana/data'; import { featureEnabled } from '@grafana/runtime'; import { ProBadge } from 'app/core/components/Upgrade/ProBadge'; import config from 'app/core/config'; import { contextSrv } from 'app/core/services/context_srv'; import { highlightTrial } from 'app/features/admin/utils'; import { AccessControlAction, Team, TeamPermissionLevel } from 'app/types'; const loadingTeam = { avatarUrl: 'public/img/user_profile.png', id: 1, name: 'Loading', email: 'loading', memberCount: 0, permission: TeamPermissionLevel.Member, accessControl: { isEditor: false }, orgId: 0, updated: '', }; export function buildNavModel(team: Team): NavModelItem { const navModel: NavModelItem = { img: team.avatarUrl, id: 'team-' + team.id, subTitle: 'Manage members and settings', url: '', text: team.name, children: [ // With RBAC this tab will always be available (but not always editable) // With Legacy it will be hidden by hideTabsFromNonTeamAdmin should the user not be allowed to see it { active: false, icon: 'sliders-v-alt', id: `team-settings-${team.id}`, text: 'Settings', url: `org/teams/edit/${team.id}/settings`, }, ], }; // While team is loading we leave the members tab // With RBAC the Members tab is available when user has ActionTeamsPermissionsRead for this team // With Legacy it will always be present if ( team === loadingTeam || contextSrv.hasPermissionInMetadata(AccessControlAction.ActionTeamsPermissionsRead, team) ) { navModel.children!.unshift({ active: false, icon: 'users-alt', id: `team-members-${team.id}`, text: 'Members', url: `org/teams/edit/${team.id}/members`, }); } const teamGroupSync: NavModelItem = { active: false, icon: 'sync', id: `team-groupsync-${team.id}`, text: 'External group sync', url: `org/teams/edit/${team.id}/groupsync`, }; const isLoadingTeam = team === loadingTeam; if (highlightTrial()) { teamGroupSync.tabSuffix = () => ProBadge({ experimentId: isLoadingTeam ? '' : 'feature-highlights-team-sync-badge', eventVariant: 'trial' }); } // With both Legacy and RBAC the tab is protected being featureEnabled // While team is loading we leave the teamsync tab // With RBAC the External Group Sync tab is available when user has ActionTeamsPermissionsRead for this team if (featureEnabled('teamsync')) { if (isLoadingTeam || contextSrv.hasPermissionInMetadata(AccessControlAction.ActionTeamsPermissionsRead, team)) { navModel.children!.push(teamGroupSync); } } else if (config.featureToggles.featureHighlights) { navModel.children!.push({ ...teamGroupSync, tabSuffix: () => ProBadge({ experimentId: isLoadingTeam ? '' : 'feature-highlights-team-sync-badge' }), }); } return navModel; } export function getTeamLoadingNav(pageName: string): NavModel { const main = buildNavModel(loadingTeam); let node: NavModelItem; // find active page for (const child of main.children!) { if (child.id!.indexOf(pageName) > 0) { child.active = true; node = child; break; } } return { main: main, node: node!, }; }
public/app/features/teams/state/navModel.ts
0
https://github.com/grafana/grafana/commit/64ed77ddce79009ce05f43801cc578c135f05b6b
[ 0.00017653460963629186, 0.00017374752496834844, 0.00016841475735418499, 0.00017400228534825146, 0.0000019997767140012 ]
{ "id": 2, "code_window": [ "\t\t\tStage: FeatureStageExperimental,\n", "\t\t\tFrontendOnly: false,\n", "\t\t\tOwner: grafanaObservabilityMetricsSquad,\n", "\t\t\tRequiresRestart: false,\n", "\t\t},\n", "\t}\n", ")" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep" ], "after_edit": [ "\t\t{\n", "\t\t\tName: \"noBasicRole\",\n", "\t\t\tDescription: \"Enables a new role that has no permissions by default\",\n", "\t\t\tStage: FeatureStageExperimental,\n", "\t\t\tFrontendOnly: true,\n", "\t\t\tOwner: grafanaAuthnzSquad,\n", "\t\t\tRequiresRestart: true,\n", "\t\t},\n" ], "file_path": "pkg/services/featuremgmt/registry.go", "type": "add", "edit_start_line_idx": 693 }
package codegen import ( "bytes" "encoding/json" "errors" "fmt" "io" "path" "path/filepath" "reflect" "sort" "strings" "text/template" "cuelang.org/go/cue/cuecontext" "github.com/grafana/codejen" "github.com/grafana/kindsys" "github.com/grafana/thema/encoding/jsonschema" "github.com/olekukonko/tablewriter" "github.com/xeipuuv/gojsonpointer" "github.com/grafana/grafana/pkg/components/simplejson" ) func DocsJenny(docsPath string) OneToOne { return docsJenny{ docsPath: docsPath, } } type docsJenny struct { docsPath string } func (j docsJenny) JennyName() string { return "DocsJenny" } func (j docsJenny) Generate(kind kindsys.Kind) (*codejen.File, error) { // TODO remove this once codejen catches nils https://github.com/grafana/codejen/issues/5 if kind == nil { return nil, nil } f, err := jsonschema.GenerateSchema(kind.Lineage().Latest()) if err != nil { return nil, fmt.Errorf("failed to generate json representation for the schema: %v", err) } b, err := cuecontext.New().BuildFile(f).MarshalJSON() if err != nil { return nil, fmt.Errorf("failed to marshal schema value to json: %v", err) } // We don't need entire json obj, only the value of components.schemas path var obj struct { Info struct { Title string } Components struct { Schemas json.RawMessage } } dec := json.NewDecoder(bytes.NewReader(b)) dec.UseNumber() err = dec.Decode(&obj) if err != nil { return nil, fmt.Errorf("failed to unmarshal schema json: %v", err) } // fixes the references between the types within a json after making components.schema.<types> the root of the json kindJsonStr := strings.Replace(string(obj.Components.Schemas), "#/components/schemas/", "#/", -1) kindProps := kind.Props().Common() data := templateData{ KindName: kindProps.Name, KindVersion: kind.Lineage().Latest().Version().String(), KindMaturity: fmt.Sprintf("[%s](../../../maturity/#%[1]s)", kindProps.Maturity), KindDescription: kindProps.Description, Markdown: "{{ .Markdown }}", } tmpl, err := makeTemplate(data, "docs.tmpl") if err != nil { return nil, err } doc, err := jsonToMarkdown([]byte(kindJsonStr), string(tmpl), obj.Info.Title) if err != nil { return nil, fmt.Errorf("failed to build markdown for kind %s: %v", kindProps.Name, err) } return codejen.NewFile(filepath.Join(j.docsPath, strings.ToLower(kindProps.Name), "schema-reference.md"), doc, j), nil } // makeTemplate pre-populates the template with the kind metadata func makeTemplate(data templateData, tmpl string) ([]byte, error) { buf := new(bytes.Buffer) if err := tmpls.Lookup(tmpl).Execute(buf, data); err != nil { return []byte{}, fmt.Errorf("failed to populate docs template with the kind metadata") } return buf.Bytes(), nil } type templateData struct { KindName string KindVersion string KindMaturity string KindDescription string Markdown string } // -------------------- JSON to Markdown conversion -------------------- // Copied from https://github.com/marcusolsson/json-schema-docs and slightly changed to fit the DocsJenny type constraints struct { Pattern string `json:"pattern"` Maximum json.Number `json:"maximum"` ExclusiveMinimum bool `json:"exclusiveMinimum"` Minimum json.Number `json:"minimum"` ExclusiveMaximum bool `json:"exclusiveMaximum"` MinLength uint `json:"minLength"` MaxLength uint `json:"maxLength"` } type schema struct { constraints ID string `json:"$id,omitempty"` Ref string `json:"$ref,omitempty"` Schema string `json:"$schema,omitempty"` Title string `json:"title,omitempty"` Description string `json:"description,omitempty"` Required []string `json:"required,omitempty"` Type PropertyTypes `json:"type,omitempty"` Properties map[string]*schema `json:"properties,omitempty"` Items *schema `json:"items,omitempty"` Definitions map[string]*schema `json:"definitions,omitempty"` Enum []Any `json:"enum"` Default any `json:"default"` AllOf []*schema `json:"allOf"` OneOf []*schema `json:"oneOf"` AdditionalProperties *schema `json:"additionalProperties"` extends []string `json:"-"` inheritedFrom string `json:"-"` } func renderMapType(props *schema) string { if props == nil { return "" } if props.Type.HasType(PropertyTypeObject) { name, anchor := propNameAndAnchor(props.Title, props.Title) return fmt.Sprintf("[%s](#%s)", name, anchor) } if props.AdditionalProperties != nil { return "map[string]" + renderMapType(props.AdditionalProperties) } if props.Items != nil { return "[]" + renderMapType(props.Items) } var types []string for _, t := range props.Type { types = append(types, string(t)) } return strings.Join(types, ", ") } func jsonToMarkdown(jsonData []byte, tpl string, kindName string) ([]byte, error) { sch, err := newSchema(jsonData, kindName) if err != nil { return []byte{}, err } t, err := template.New("markdown").Parse(tpl) if err != nil { return []byte{}, err } buf := new(bytes.Buffer) err = t.Execute(buf, sch) if err != nil { return []byte{}, err } return buf.Bytes(), nil } func newSchema(b []byte, kindName string) (*schema, error) { var data map[string]*schema if err := json.Unmarshal(b, &data); err != nil { return nil, err } // Needed for resolving in-schema references. root, err := simplejson.NewJson(b) if err != nil { return nil, err } return resolveSchema(data[kindName], root) } // resolveSchema recursively resolves schemas. func resolveSchema(schem *schema, root *simplejson.Json) (*schema, error) { for _, prop := range schem.Properties { if prop.Ref != "" { tmp, err := resolveReference(prop.Ref, root) if err != nil { return nil, err } *prop = *tmp } foo, err := resolveSchema(prop, root) if err != nil { return nil, err } *prop = *foo } if schem.Items != nil { if schem.Items.Ref != "" { tmp, err := resolveReference(schem.Items.Ref, root) if err != nil { return nil, err } *schem.Items = *tmp } foo, err := resolveSchema(schem.Items, root) if err != nil { return nil, err } *schem.Items = *foo } if len(schem.AllOf) > 0 { for idx, child := range schem.AllOf { tmp, err := resolveSubSchema(schem, child, root) if err != nil { return nil, err } schem.AllOf[idx] = tmp if len(tmp.Title) > 0 { schem.extends = append(schem.extends, tmp.Title) } } } if len(schem.OneOf) > 0 { for idx, child := range schem.OneOf { tmp, err := resolveSubSchema(schem, child, root) if err != nil { return nil, err } schem.OneOf[idx] = tmp } } if schem.AdditionalProperties != nil { if schem.AdditionalProperties.Ref != "" { tmp, err := resolveReference(schem.AdditionalProperties.Ref, root) if err != nil { return nil, err } *schem.AdditionalProperties = *tmp } foo, err := resolveSchema(schem.AdditionalProperties, root) if err != nil { return nil, err } *schem.AdditionalProperties = *foo } return schem, nil } func resolveSubSchema(parent, child *schema, root *simplejson.Json) (*schema, error) { if child.Ref != "" { tmp, err := resolveReference(child.Ref, root) if err != nil { return nil, err } *child = *tmp } if len(child.Required) > 0 { parent.Required = append(parent.Required, child.Required...) } child, err := resolveSchema(child, root) if err != nil { return nil, err } if parent.Properties == nil { parent.Properties = make(map[string]*schema) } for k, v := range child.Properties { prop := *v prop.inheritedFrom = child.Title parent.Properties[k] = &prop } return child, err } // resolveReference loads a schema from a $ref. // If ref contains a hashtag (#), the part after represents a in-schema reference. func resolveReference(ref string, root *simplejson.Json) (*schema, error) { i := strings.Index(ref, "#") if i != 0 { return nil, fmt.Errorf("not in-schema reference: %s", ref) } return resolveInSchemaReference(ref[i+1:], root) } func resolveInSchemaReference(ref string, root *simplejson.Json) (*schema, error) { // in-schema reference pointer, err := gojsonpointer.NewJsonPointer(ref) if err != nil { return nil, err } v, _, err := pointer.Get(root.MustMap()) if err != nil { return nil, err } var sch schema b, err := json.Marshal(v) if err != nil { return nil, err } if err := json.Unmarshal(b, &sch); err != nil { return nil, err } // Set the ref name as title sch.Title = path.Base(ref) return &sch, nil } type mdSection struct { title string extends string description string rows [][]string } func (md mdSection) write(w io.Writer) { if md.title != "" { fmt.Fprintf(w, "### %s\n", strings.Title(md.title)) fmt.Fprintln(w) } if md.description != "" { fmt.Fprintln(w, md.description) fmt.Fprintln(w) } if md.extends != "" { fmt.Fprintln(w, md.extends) fmt.Fprintln(w) } table := tablewriter.NewWriter(w) table.SetHeader([]string{"Property", "Type", "Required", "Default", "Description"}) table.SetBorders(tablewriter.Border{Left: true, Top: false, Right: true, Bottom: false}) table.SetCenterSeparator("|") table.SetAutoFormatHeaders(false) table.SetHeaderAlignment(tablewriter.ALIGN_LEFT) table.SetAutoWrapText(false) table.AppendBulk(md.rows) table.Render() fmt.Fprintln(w) } // Markdown returns the Markdown representation of the schema. // // The level argument can be used to offset the heading levels. This can be // useful if you want to add the schema under a subheading. func (s *schema) Markdown() string { buf := new(bytes.Buffer) for _, v := range s.sections() { v.write(buf) } return buf.String() } func (s *schema) sections() []mdSection { md := mdSection{} if s.AdditionalProperties == nil { md.title = s.Title } md.description = s.Description if len(s.extends) > 0 { md.extends = makeExtends(s.extends) } md.rows = makeRows(s) sections := []mdSection{md} for _, sch := range findDefinitions(s) { for _, ss := range sch.sections() { if !contains(sections, ss) { sections = append(sections, ss) } } } return sections } func contains(sl []mdSection, elem mdSection) bool { for _, s := range sl { if reflect.DeepEqual(s, elem) { return true } } return false } func makeExtends(from []string) string { fromLinks := make([]string, 0, len(from)) for _, f := range from { fromLinks = append(fromLinks, fmt.Sprintf("[%s](#%s)", f, strings.ToLower(f))) } return fmt.Sprintf("It extends %s.", strings.Join(fromLinks, " and ")) } func findDefinitions(s *schema) []*schema { // Gather all properties of object type so that we can generate the // properties for them recursively. var objs []*schema definition := func(k string, p *schema) { if p.Type.HasType(PropertyTypeObject) && p.AdditionalProperties == nil { // Use the identifier as the title. if len(p.Title) == 0 { p.Title = k } objs = append(objs, p) } // If the property is an array of objects, use the name of the array // property as the title. if p.Type.HasType(PropertyTypeArray) { if p.Items != nil { if p.Items.Type.HasType(PropertyTypeObject) { if len(p.Items.Title) == 0 { p.Items.Title = k } objs = append(objs, p.Items) } } } } for k, p := range s.Properties { // If a property has AdditionalProperties, then it's a map if p.AdditionalProperties != nil { definition(k, p.AdditionalProperties) } definition(k, p) } // This code could probably be unified with the one above for _, child := range s.AllOf { if child.Type.HasType(PropertyTypeObject) { objs = append(objs, child) } if child.Type.HasType(PropertyTypeArray) { if child.Items != nil { if child.Items.Type.HasType(PropertyTypeObject) { objs = append(objs, child.Items) } } } } for _, child := range s.OneOf { if child.Type.HasType(PropertyTypeObject) { objs = append(objs, child) } if child.Type.HasType(PropertyTypeArray) { if child.Items != nil { if child.Items.Type.HasType(PropertyTypeObject) { objs = append(objs, child.Items) } } } } // Sort the object schemas. sort.Slice(objs, func(i, j int) bool { return objs[i].Title < objs[j].Title }) return objs } func makeRows(s *schema) [][]string { // Buffer all property rows so that we can sort them before printing them. rows := make([][]string, 0, len(s.Properties)) var typeStr string if len(s.OneOf) > 0 { typeStr = enumStr(s) rows = append(rows, []string{"`object`", typeStr, "", ""}) return rows } for key, p := range s.Properties { alias := propTypeAlias(p) if alias != "" { typeStr = alias } else { typeStr = propTypeStr(key, p) } // Emphasize required properties. var required string if in(s.Required, key) { required = "**Yes**" } else { required = "No" } var desc string if p.inheritedFrom != "" { desc = fmt.Sprintf("*(Inherited from [%s](#%s))*", p.inheritedFrom, strings.ToLower(p.inheritedFrom)) } if p.Description != "" { desc += "\n" + p.Description } if len(p.Enum) > 0 { vals := make([]string, 0, len(p.Enum)) for _, e := range p.Enum { vals = append(vals, e.String()) } desc += "\nPossible values are: `" + strings.Join(vals, "`, `") + "`." } var defaultValue string if p.Default != nil { defaultValue = fmt.Sprintf("`%v`", p.Default) } // Render a constraint only if it's not a type alias https://cuelang.org/docs/references/spec/#predeclared-identifiers if alias == "" { desc += constraintDescr(p) } rows = append(rows, []string{fmt.Sprintf("`%s`", key), typeStr, required, defaultValue, formatForTable(desc)}) } // Sort by the required column, then by the name column. sort.Slice(rows, func(i, j int) bool { if rows[i][2] < rows[j][2] { return true } if rows[i][2] > rows[j][2] { return false } return rows[i][0] < rows[j][0] }) return rows } func propTypeAlias(prop *schema) string { if prop.Minimum == "" || prop.Maximum == "" { return "" } min := prop.Minimum max := prop.Maximum switch { case min == "0" && max == "255": return "uint8" case min == "0" && max == "65535": return "uint16" case min == "0" && max == "4294967295": return "uint32" case min == "0" && max == "18446744073709551615": return "uint64" case min == "-128" && max == "127": return "int8" case min == "-32768" && max == "32767": return "int16" case min == "-2147483648" && max == "2147483647": return "int32" case min == "-9223372036854775808" && max == "9223372036854775807": return "int64" default: return "" } } func constraintDescr(prop *schema) string { if prop.Minimum != "" && prop.Maximum != "" { var left, right string if prop.ExclusiveMinimum { left = ">" + prop.Minimum.String() } else { left = ">=" + prop.Minimum.String() } if prop.ExclusiveMaximum { right = "<" + prop.Maximum.String() } else { right = "<=" + prop.Maximum.String() } return fmt.Sprintf("\nConstraint: `%s & %s`.", left, right) } if prop.MinLength > 0 { left := fmt.Sprintf(">=%v", prop.MinLength) right := "" if prop.MaxLength > 0 { right = fmt.Sprintf(" && <=%v", prop.MaxLength) } return fmt.Sprintf("\nConstraint: `length %s`.", left+right) } if prop.Pattern != "" { return fmt.Sprintf("\nConstraint: must match `%s`.", prop.Pattern) } return "" } func enumStr(propValue *schema) string { var vals []string for _, v := range propValue.OneOf { vals = append(vals, fmt.Sprintf("[%s](#%s)", v.Title, strings.ToLower(v.Title))) } return "Possible types are: " + strings.Join(vals, ", ") + "." } func propTypeStr(propName string, propValue *schema) string { // If the property has AdditionalProperties, it is most likely a map type if propValue.AdditionalProperties != nil { mapValue := renderMapType(propValue.AdditionalProperties) return "map[string]" + mapValue } propType := make([]string, 0, len(propValue.Type)) // Generate relative links for objects and arrays of objects. for _, pt := range propValue.Type { switch pt { case PropertyTypeObject: name, anchor := propNameAndAnchor(propName, propValue.Title) propType = append(propType, fmt.Sprintf("[%s](#%s)", name, anchor)) case PropertyTypeArray: if propValue.Items != nil { for _, pi := range propValue.Items.Type { if pi == PropertyTypeObject { name, anchor := propNameAndAnchor(propName, propValue.Items.Title) propType = append(propType, fmt.Sprintf("[%s](#%s)[]", name, anchor)) } else { propType = append(propType, fmt.Sprintf("%s[]", pi)) } } } else { propType = append(propType, string(pt)) } default: propType = append(propType, string(pt)) } } if len(propType) == 0 { return "" } if len(propType) == 1 { return propType[0] } if len(propType) == 2 { return strings.Join(propType, " or ") } return fmt.Sprintf("%s, or %s", strings.Join(propType[:len(propType)-1], ", "), propType[len(propType)-1]) } func propNameAndAnchor(prop, title string) (string, string) { if len(title) > 0 { return title, strings.ToLower(title) } return string(PropertyTypeObject), strings.ToLower(prop) } // in returns true if a string slice contains a specific string. func in(strs []string, str string) bool { for _, s := range strs { if s == str { return true } } return false } // formatForTable returns string usable in a Markdown table. // It trims white spaces, replaces new lines and pipe characters. func formatForTable(in string) string { s := strings.TrimSpace(in) s = strings.ReplaceAll(s, "\n", "<br/>") s = strings.ReplaceAll(s, "|", "&#124;") return s } type PropertyTypes []PropertyType func (pts *PropertyTypes) HasType(pt PropertyType) bool { for _, t := range *pts { if t == pt { return true } } return false } func (pts *PropertyTypes) UnmarshalJSON(data []byte) error { var value interface{} if err := json.Unmarshal(data, &value); err != nil { return err } switch val := value.(type) { case string: *pts = []PropertyType{PropertyType(val)} return nil case []interface{}: var pt []PropertyType for _, t := range val { s, ok := t.(string) if !ok { return errors.New("unsupported property type") } pt = append(pt, PropertyType(s)) } *pts = pt default: return errors.New("unsupported property type") } return nil } type PropertyType string const ( PropertyTypeString PropertyType = "string" PropertyTypeNumber PropertyType = "number" PropertyTypeBoolean PropertyType = "boolean" PropertyTypeObject PropertyType = "object" PropertyTypeArray PropertyType = "array" PropertyTypeNull PropertyType = "null" ) type Any struct { value interface{} } func (u *Any) UnmarshalJSON(data []byte) error { if err := json.Unmarshal(data, &u.value); err != nil { return err } return nil } func (u *Any) String() string { return fmt.Sprintf("%v", u.value) }
pkg/codegen/jenny_docs.go
0
https://github.com/grafana/grafana/commit/64ed77ddce79009ce05f43801cc578c135f05b6b
[ 0.00021925861074123532, 0.00017266787472181022, 0.0001639392285142094, 0.0001729796640574932, 0.000006562157523148926 ]
{ "id": 3, "code_window": [ "prometheusConfigOverhaulAuth,experimental,@grafana/observability-metrics,false,false,false,false\n", "configurableSchedulerTick,experimental,@grafana/alerting-squad,false,false,true,false\n", "influxdbSqlSupport,experimental,@grafana/observability-metrics,false,false,false,false\n" ], "labels": [ "keep", "keep", "add" ], "after_edit": [ "noBasicRole,experimental,@grafana/grafana-authnz-team,false,false,true,true" ], "file_path": "pkg/services/featuremgmt/toggles_gen.csv", "type": "add", "edit_start_line_idx": 101 }
import React from 'react'; import { SelectableValue } from '@grafana/data'; import { Icon, RadioButtonList, Tooltip, useStyles2, useTheme2 } from '@grafana/ui'; import { OrgRole } from 'app/types'; import { getStyles } from './styles'; const BasicRoleOption: Array<SelectableValue<OrgRole>> = Object.values(OrgRole).map((r) => ({ label: r === OrgRole.None ? 'No basic role' : r, value: r, })); interface Props { value?: OrgRole; onChange: (value: OrgRole) => void; disabled?: boolean; disabledMesssage?: string; tooltipMessage?: string; } export const BuiltinRoleSelector = ({ value, onChange, disabled, disabledMesssage, tooltipMessage }: Props) => { const styles = useStyles2(getStyles); const theme = useTheme2(); return ( <> <div className={styles.groupHeader}> <span style={{ marginRight: theme.spacing(1) }}>Basic roles</span> {disabled && disabledMesssage && ( <Tooltip placement="right-end" interactive={true} content={<div>{disabledMesssage}</div>}> <Icon name="question-circle" /> </Tooltip> )} {!disabled && tooltipMessage && ( <Tooltip placement="right-end" interactive={true} content={tooltipMessage}> <Icon name="info-circle" size="xs" /> </Tooltip> )} </div> <RadioButtonList name="Basic Role Selector" className={styles.basicRoleSelector} options={BasicRoleOption} value={value} onChange={onChange} disabled={disabled} /> </> ); };
public/app/core/components/RolePicker/BuiltinRoleSelector.tsx
1
https://github.com/grafana/grafana/commit/64ed77ddce79009ce05f43801cc578c135f05b6b
[ 0.00017459892842452973, 0.00017313739226665348, 0.00017093942733481526, 0.00017379350902047008, 0.0000015354943343481864 ]
{ "id": 3, "code_window": [ "prometheusConfigOverhaulAuth,experimental,@grafana/observability-metrics,false,false,false,false\n", "configurableSchedulerTick,experimental,@grafana/alerting-squad,false,false,true,false\n", "influxdbSqlSupport,experimental,@grafana/observability-metrics,false,false,false,false\n" ], "labels": [ "keep", "keep", "add" ], "after_edit": [ "noBasicRole,experimental,@grafana/grafana-authnz-team,false,false,true,true" ], "file_path": "pkg/services/featuremgmt/toggles_gen.csv", "type": "add", "edit_start_line_idx": 101 }
import { LogLevel, LogRowModel, MutableDataFrame } from '@grafana/data'; export const createLogRow = (overrides?: Partial<LogRowModel>): LogRowModel => { const uid = overrides?.uid || '1'; const timeEpochMs = overrides?.timeEpochMs || 1; const entry = overrides?.entry || `log message ${uid}`; return { entryFieldIndex: 0, rowIndex: 0, dataFrame: new MutableDataFrame(), uid, logLevel: LogLevel.info, entry, hasAnsi: false, hasUnescapedContent: false, labels: {}, raw: entry, timeFromNow: '', timeEpochMs, timeEpochNs: (timeEpochMs * 1000000).toString(), timeLocal: '', timeUtc: '', searchWords: [], ...overrides, }; };
public/app/features/logs/components/__mocks__/logRow.ts
0
https://github.com/grafana/grafana/commit/64ed77ddce79009ce05f43801cc578c135f05b6b
[ 0.0001738392747938633, 0.00017183039744850248, 0.00016859406605362892, 0.00017305782239418477, 0.0000023105556010705186 ]
{ "id": 3, "code_window": [ "prometheusConfigOverhaulAuth,experimental,@grafana/observability-metrics,false,false,false,false\n", "configurableSchedulerTick,experimental,@grafana/alerting-squad,false,false,true,false\n", "influxdbSqlSupport,experimental,@grafana/observability-metrics,false,false,false,false\n" ], "labels": [ "keep", "keep", "add" ], "after_edit": [ "noBasicRole,experimental,@grafana/grafana-authnz-team,false,false,true,true" ], "file_path": "pkg/services/featuremgmt/toggles_gen.csv", "type": "add", "edit_start_line_idx": 101 }
include: - included.yaml # not yet supported vars: stack: something level: free valA: value from features.yaml flags: - name: feature1 description: feature1 expression: "false" - name: feature3 description: feature3 expression: "true" - name: feature3 description: feature3 expression: env.level == 'free' - name: displaySwedishTheme description: enable swedish background theme expression: | // restrict to users allowing swedish language req.locale.contains("sv") - name: displayFrenchFlag description: sho background theme expression: | // only admins user.id == 1 // show to users allowing french language && req.locale.contains("fr")
pkg/services/featuremgmt/testdata/features.yaml
0
https://github.com/grafana/grafana/commit/64ed77ddce79009ce05f43801cc578c135f05b6b
[ 0.00017696469149086624, 0.0001749035727698356, 0.0001728513598209247, 0.00017489910533186048, 0.0000017837451196101028 ]
{ "id": 3, "code_window": [ "prometheusConfigOverhaulAuth,experimental,@grafana/observability-metrics,false,false,false,false\n", "configurableSchedulerTick,experimental,@grafana/alerting-squad,false,false,true,false\n", "influxdbSqlSupport,experimental,@grafana/observability-metrics,false,false,false,false\n" ], "labels": [ "keep", "keep", "add" ], "after_edit": [ "noBasicRole,experimental,@grafana/grafana-authnz-team,false,false,true,true" ], "file_path": "pkg/services/featuremgmt/toggles_gen.csv", "type": "add", "edit_start_line_idx": 101 }
<svg xmlns="http://www.w3.org/2000/svg" data-name="Layer 1" viewBox="0 0 24 24"><path d="M9.21,10.54a1,1,0,0,0,1.41,0,1,1,0,0,0,0-1.41,3.08,3.08,0,0,0-4.24,0,1,1,0,1,0,1.41,1.41A1,1,0,0,1,9.21,10.54ZM12,2A10,10,0,1,0,22,12,10,10,0,0,0,12,2Zm0,18a8,8,0,1,1,8-8A8,8,0,0,1,12,20ZM15,9a1,1,0,1,0,1,1A1,1,0,0,0,15,9Zm0,4H9a1,1,0,0,0,0,2,3,3,0,0,0,6,0,1,1,0,0,0,0-2Zm-3,3a1,1,0,0,1-1-1h2A1,1,0,0,1,12,16Z"/></svg>
public/img/icons/unicons/grin-tongue-wink-alt.svg
0
https://github.com/grafana/grafana/commit/64ed77ddce79009ce05f43801cc578c135f05b6b
[ 0.00017103708523791283, 0.00017103708523791283, 0.00017103708523791283, 0.00017103708523791283, 0 ]
{ "id": 4, "code_window": [ "\t// FlagInfluxdbSqlSupport\n", "\t// Enable InfluxDB SQL query language support with new querying UI\n", "\tFlagInfluxdbSqlSupport = \"influxdbSqlSupport\"\n", ")" ], "labels": [ "keep", "keep", "add", "keep" ], "after_edit": [ "\n", "\t// FlagNoBasicRole\n", "\t// Enables a new role that has no permissions by default\n", "\tFlagNoBasicRole = \"noBasicRole\"\n" ], "file_path": "pkg/services/featuremgmt/toggles_gen.go", "type": "add", "edit_start_line_idx": 408 }
// NOTE: This file was auto generated. DO NOT EDIT DIRECTLY! // To change feature flags, edit: // pkg/services/featuremgmt/registry.go // Then run tests in: // pkg/services/featuremgmt/toggles_gen_test.go package featuremgmt const ( // FlagTrimDefaults // Use cue schema to remove values that will be applied automatically FlagTrimDefaults = "trimDefaults" // FlagDisableEnvelopeEncryption // Disable envelope encryption (emergency only) FlagDisableEnvelopeEncryption = "disableEnvelopeEncryption" // FlagLiveServiceWebWorker // This will use a webworker thread to processes events rather than the main thread FlagLiveServiceWebWorker = "live-service-web-worker" // FlagQueryOverLive // Use Grafana Live WebSocket to execute backend queries FlagQueryOverLive = "queryOverLive" // FlagPanelTitleSearch // Search for dashboards using panel title FlagPanelTitleSearch = "panelTitleSearch" // FlagPublicDashboards // Enables public access to dashboards FlagPublicDashboards = "publicDashboards" // FlagPublicDashboardsEmailSharing // Enables public dashboard sharing to be restricted to only allowed emails FlagPublicDashboardsEmailSharing = "publicDashboardsEmailSharing" // FlagLokiExperimentalStreaming // Support new streaming approach for loki (prototype, needs special loki build) FlagLokiExperimentalStreaming = "lokiExperimentalStreaming" // FlagFeatureHighlights // Highlight Grafana Enterprise features FlagFeatureHighlights = "featureHighlights" // FlagMigrationLocking // Lock database during migrations FlagMigrationLocking = "migrationLocking" // FlagStorage // Configurable storage for dashboards, datasources, and resources FlagStorage = "storage" // FlagCorrelations // Correlations page FlagCorrelations = "correlations" // FlagDatasourceQueryMultiStatus // Introduce HTTP 207 Multi Status for api/ds/query FlagDatasourceQueryMultiStatus = "datasourceQueryMultiStatus" // FlagTraceToMetrics // Enable trace to metrics links FlagTraceToMetrics = "traceToMetrics" // FlagNewDBLibrary // Use jmoiron/sqlx rather than xorm for a few backend services FlagNewDBLibrary = "newDBLibrary" // FlagValidateDashboardsOnSave // Validate dashboard JSON POSTed to api/dashboards/db FlagValidateDashboardsOnSave = "validateDashboardsOnSave" // FlagAutoMigrateOldPanels // Migrate old angular panels to supported versions (graph, table-old, worldmap, etc) FlagAutoMigrateOldPanels = "autoMigrateOldPanels" // FlagDisableAngular // Dynamic flag to disable angular at runtime. The preferred method is to set `angular_support_enabled` to `false` in the [security] settings, which allows you to change the state at runtime. FlagDisableAngular = "disableAngular" // FlagPrometheusWideSeries // Enable wide series responses in the Prometheus datasource FlagPrometheusWideSeries = "prometheusWideSeries" // FlagCanvasPanelNesting // Allow elements nesting FlagCanvasPanelNesting = "canvasPanelNesting" // FlagScenes // Experimental framework to build interactive dashboards FlagScenes = "scenes" // FlagDisableSecretsCompatibility // Disable duplicated secret storage in legacy tables FlagDisableSecretsCompatibility = "disableSecretsCompatibility" // FlagLogRequestsInstrumentedAsUnknown // Logs the path for requests that are instrumented as unknown FlagLogRequestsInstrumentedAsUnknown = "logRequestsInstrumentedAsUnknown" // FlagDataConnectionsConsole // Enables a new top-level page called Connections. This page is an experiment that provides a better experience when you install and configure data sources and other plugins. FlagDataConnectionsConsole = "dataConnectionsConsole" // FlagTopnav // Enables topnav support in external plugins. The new Grafana navigation cannot be disabled. FlagTopnav = "topnav" // FlagGrpcServer // Run the GRPC server FlagGrpcServer = "grpcServer" // FlagEntityStore // SQL-based entity store (requires storage flag also) FlagEntityStore = "entityStore" // FlagCloudWatchCrossAccountQuerying // Enables cross-account querying in CloudWatch datasources FlagCloudWatchCrossAccountQuerying = "cloudWatchCrossAccountQuerying" // FlagRedshiftAsyncQueryDataSupport // Enable async query data support for Redshift FlagRedshiftAsyncQueryDataSupport = "redshiftAsyncQueryDataSupport" // FlagAthenaAsyncQueryDataSupport // Enable async query data support for Athena FlagAthenaAsyncQueryDataSupport = "athenaAsyncQueryDataSupport" // FlagNewPanelChromeUI // Show updated look and feel of grafana-ui PanelChrome: panel header, icons, and menu FlagNewPanelChromeUI = "newPanelChromeUI" // FlagShowDashboardValidationWarnings // Show warnings when dashboards do not validate against the schema FlagShowDashboardValidationWarnings = "showDashboardValidationWarnings" // FlagMysqlAnsiQuotes // Use double quotes to escape keyword in a MySQL query FlagMysqlAnsiQuotes = "mysqlAnsiQuotes" // FlagAccessControlOnCall // Access control primitives for OnCall FlagAccessControlOnCall = "accessControlOnCall" // FlagNestedFolders // Enable folder nesting FlagNestedFolders = "nestedFolders" // FlagNestedFolderPicker // Enables the new folder picker to work with nested folders. Requires the folderPicker feature flag FlagNestedFolderPicker = "nestedFolderPicker" // FlagAccessTokenExpirationCheck // Enable OAuth access_token expiration check and token refresh using the refresh_token FlagAccessTokenExpirationCheck = "accessTokenExpirationCheck" // FlagEmptyDashboardPage // Enable the redesigned user interface of a dashboard page that includes no panels FlagEmptyDashboardPage = "emptyDashboardPage" // FlagDisablePrometheusExemplarSampling // Disable Prometheus exemplar sampling FlagDisablePrometheusExemplarSampling = "disablePrometheusExemplarSampling" // FlagAlertingBacktesting // Rule backtesting API for alerting FlagAlertingBacktesting = "alertingBacktesting" // FlagEditPanelCSVDragAndDrop // Enables drag and drop for CSV and Excel files FlagEditPanelCSVDragAndDrop = "editPanelCSVDragAndDrop" // FlagAlertingNoNormalState // Stop maintaining state of alerts that are not firing FlagAlertingNoNormalState = "alertingNoNormalState" // FlagLogsContextDatasourceUi // Allow datasource to provide custom UI for context view FlagLogsContextDatasourceUi = "logsContextDatasourceUi" // FlagLokiQuerySplitting // Split large interval queries into subqueries with smaller time intervals FlagLokiQuerySplitting = "lokiQuerySplitting" // FlagLokiQuerySplittingConfig // Give users the option to configure split durations for Loki queries FlagLokiQuerySplittingConfig = "lokiQuerySplittingConfig" // FlagIndividualCookiePreferences // Support overriding cookie preferences per user FlagIndividualCookiePreferences = "individualCookiePreferences" // FlagGcomOnlyExternalOrgRoleSync // Prohibits a user from changing organization roles synced with Grafana Cloud auth provider FlagGcomOnlyExternalOrgRoleSync = "gcomOnlyExternalOrgRoleSync" // FlagPrometheusMetricEncyclopedia // Adds the metrics explorer component to the Prometheus query builder as an option in metric select FlagPrometheusMetricEncyclopedia = "prometheusMetricEncyclopedia" // FlagTimeSeriesTable // Enable time series table transformer &amp; sparkline cell type FlagTimeSeriesTable = "timeSeriesTable" // FlagPrometheusResourceBrowserCache // Displays browser caching options in Prometheus data source configuration FlagPrometheusResourceBrowserCache = "prometheusResourceBrowserCache" // FlagInfluxdbBackendMigration // Query InfluxDB InfluxQL without the proxy FlagInfluxdbBackendMigration = "influxdbBackendMigration" // FlagClientTokenRotation // Replaces the current in-request token rotation so that the client initiates the rotation FlagClientTokenRotation = "clientTokenRotation" // FlagPrometheusDataplane // Changes responses to from Prometheus to be compliant with the dataplane specification. In particular it sets the numeric Field.Name from &#39;Value&#39; to the value of the `__name__` label when present. FlagPrometheusDataplane = "prometheusDataplane" // FlagLokiMetricDataplane // Changes metric responses from Loki to be compliant with the dataplane specification. FlagLokiMetricDataplane = "lokiMetricDataplane" // FlagLokiLogsDataplane // Changes logs responses from Loki to be compliant with the dataplane specification. FlagLokiLogsDataplane = "lokiLogsDataplane" // FlagDataplaneFrontendFallback // Support dataplane contract field name change for transformations and field name matchers where the name is different FlagDataplaneFrontendFallback = "dataplaneFrontendFallback" // FlagDisableSSEDataplane // Disables dataplane specific processing in server side expressions. FlagDisableSSEDataplane = "disableSSEDataplane" // FlagAlertStateHistoryLokiSecondary // Enable Grafana to write alert state history to an external Loki instance in addition to Grafana annotations. FlagAlertStateHistoryLokiSecondary = "alertStateHistoryLokiSecondary" // FlagAlertingNotificationsPoliciesMatchingInstances // Enables the preview of matching instances for notification policies FlagAlertingNotificationsPoliciesMatchingInstances = "alertingNotificationsPoliciesMatchingInstances" // FlagAlertStateHistoryLokiPrimary // Enable a remote Loki instance as the primary source for state history reads. FlagAlertStateHistoryLokiPrimary = "alertStateHistoryLokiPrimary" // FlagAlertStateHistoryLokiOnly // Disable Grafana alerts from emitting annotations when a remote Loki instance is available. FlagAlertStateHistoryLokiOnly = "alertStateHistoryLokiOnly" // FlagUnifiedRequestLog // Writes error logs to the request logger FlagUnifiedRequestLog = "unifiedRequestLog" // FlagRenderAuthJWT // Uses JWT-based auth for rendering instead of relying on remote cache FlagRenderAuthJWT = "renderAuthJWT" // FlagExternalServiceAuth // Starts an OAuth2 authentication provider for external services FlagExternalServiceAuth = "externalServiceAuth" // FlagRefactorVariablesTimeRange // Refactor time range variables flow to reduce number of API calls made when query variables are chained FlagRefactorVariablesTimeRange = "refactorVariablesTimeRange" // FlagUseCachingService // When turned on, the new query and resource caching implementation using a wire service inject will be used in place of the previous middleware implementation FlagUseCachingService = "useCachingService" // FlagEnableElasticsearchBackendQuerying // Enable the processing of queries and responses in the Elasticsearch data source through backend FlagEnableElasticsearchBackendQuerying = "enableElasticsearchBackendQuerying" // FlagAdvancedDataSourcePicker // Enable a new data source picker with contextual information, recently used order and advanced mode FlagAdvancedDataSourcePicker = "advancedDataSourcePicker" // FlagFaroDatasourceSelector // Enable the data source selector within the Frontend Apps section of the Frontend Observability FlagFaroDatasourceSelector = "faroDatasourceSelector" // FlagEnableDatagridEditing // Enables the edit functionality in the datagrid panel FlagEnableDatagridEditing = "enableDatagridEditing" // FlagDataSourcePageHeader // Apply new pageHeader UI in data source edit page FlagDataSourcePageHeader = "dataSourcePageHeader" // FlagExtraThemes // Enables extra themes FlagExtraThemes = "extraThemes" // FlagLokiPredefinedOperations // Adds predefined query operations to Loki query editor FlagLokiPredefinedOperations = "lokiPredefinedOperations" // FlagPluginsFrontendSandbox // Enables the plugins frontend sandbox FlagPluginsFrontendSandbox = "pluginsFrontendSandbox" // FlagDashboardEmbed // Allow embedding dashboard for external use in Code editors FlagDashboardEmbed = "dashboardEmbed" // FlagFrontendSandboxMonitorOnly // Enables monitor only in the plugin frontend sandbox (if enabled) FlagFrontendSandboxMonitorOnly = "frontendSandboxMonitorOnly" // FlagSqlDatasourceDatabaseSelection // Enables previous SQL data source dataset dropdown behavior FlagSqlDatasourceDatabaseSelection = "sqlDatasourceDatabaseSelection" // FlagLokiFormatQuery // Enables the ability to format Loki queries FlagLokiFormatQuery = "lokiFormatQuery" // FlagCloudWatchLogsMonacoEditor // Enables the Monaco editor for CloudWatch Logs queries FlagCloudWatchLogsMonacoEditor = "cloudWatchLogsMonacoEditor" // FlagExploreScrollableLogsContainer // Improves the scrolling behavior of logs in Explore FlagExploreScrollableLogsContainer = "exploreScrollableLogsContainer" // FlagRecordedQueriesMulti // Enables writing multiple items from a single query within Recorded Queries FlagRecordedQueriesMulti = "recordedQueriesMulti" // FlagPluginsDynamicAngularDetectionPatterns // Enables fetching Angular detection patterns for plugins from GCOM and fallback to hardcoded ones FlagPluginsDynamicAngularDetectionPatterns = "pluginsDynamicAngularDetectionPatterns" // FlagAlertingLokiRangeToInstant // Rewrites eligible loki range queries to instant queries FlagAlertingLokiRangeToInstant = "alertingLokiRangeToInstant" // FlagVizAndWidgetSplit // Split panels between vizualizations and widgets FlagVizAndWidgetSplit = "vizAndWidgetSplit" // FlagPrometheusIncrementalQueryInstrumentation // Adds RudderStack events to incremental queries FlagPrometheusIncrementalQueryInstrumentation = "prometheusIncrementalQueryInstrumentation" // FlagLogsExploreTableVisualisation // A table visualisation for logs in Explore FlagLogsExploreTableVisualisation = "logsExploreTableVisualisation" // FlagAwsDatasourcesTempCredentials // Support temporary security credentials in AWS plugins for Grafana Cloud customers FlagAwsDatasourcesTempCredentials = "awsDatasourcesTempCredentials" // FlagTransformationsRedesign // Enables the transformations redesign FlagTransformationsRedesign = "transformationsRedesign" // FlagToggleLabelsInLogsUI // Enable toggleable filters in log details view FlagToggleLabelsInLogsUI = "toggleLabelsInLogsUI" // FlagMlExpressions // Enable support for Machine Learning in server-side expressions FlagMlExpressions = "mlExpressions" // FlagTraceQLStreaming // Enables response streaming of TraceQL queries of the Tempo data source FlagTraceQLStreaming = "traceQLStreaming" // FlagGrafanaAPIServer // Enable Kubernetes API Server for Grafana resources FlagGrafanaAPIServer = "grafanaAPIServer" // FlagFeatureToggleAdminPage // Enable admin page for managing feature toggles from the Grafana front-end FlagFeatureToggleAdminPage = "featureToggleAdminPage" // FlagAwsAsyncQueryCaching // Enable caching for async queries for Redshift and Athena. Requires that the `useCachingService` feature toggle is enabled and the datasource has caching and async query support enabled FlagAwsAsyncQueryCaching = "awsAsyncQueryCaching" // FlagSplitScopes // Support faster dashboard and folder search by splitting permission scopes into parts FlagSplitScopes = "splitScopes" // FlagAzureMonitorDataplane // Adds dataplane compliant frame metadata in the Azure Monitor datasource FlagAzureMonitorDataplane = "azureMonitorDataplane" // FlagPermissionsFilterRemoveSubquery // Alternative permission filter implementation that does not use subqueries for fetching the dashboard folder FlagPermissionsFilterRemoveSubquery = "permissionsFilterRemoveSubquery" // FlagPrometheusConfigOverhaulAuth // Update the Prometheus configuration page with the new auth component FlagPrometheusConfigOverhaulAuth = "prometheusConfigOverhaulAuth" // FlagConfigurableSchedulerTick // Enable changing the scheduler base interval via configuration option unified_alerting.scheduler_tick_interval FlagConfigurableSchedulerTick = "configurableSchedulerTick" // FlagInfluxdbSqlSupport // Enable InfluxDB SQL query language support with new querying UI FlagInfluxdbSqlSupport = "influxdbSqlSupport" )
pkg/services/featuremgmt/toggles_gen.go
1
https://github.com/grafana/grafana/commit/64ed77ddce79009ce05f43801cc578c135f05b6b
[ 0.9713488221168518, 0.024013886228203773, 0.00016754023090470582, 0.00024743779795244336, 0.14978696405887604 ]
{ "id": 4, "code_window": [ "\t// FlagInfluxdbSqlSupport\n", "\t// Enable InfluxDB SQL query language support with new querying UI\n", "\tFlagInfluxdbSqlSupport = \"influxdbSqlSupport\"\n", ")" ], "labels": [ "keep", "keep", "add", "keep" ], "after_edit": [ "\n", "\t// FlagNoBasicRole\n", "\t// Enables a new role that has no permissions by default\n", "\tFlagNoBasicRole = \"noBasicRole\"\n" ], "file_path": "pkg/services/featuremgmt/toggles_gen.go", "type": "add", "edit_start_line_idx": 408 }
// 🌟 This was machine generated. Do not edit. 🌟 // // Frame[0] { // "typeVersion": [ // 0, // 0 // ], // "custom": { // "stats": { // "ingester": { // "compressedBytes": 0, // "decompressedBytes": 0, // "decompressedLines": 0, // "headChunkBytes": 0, // "headChunkLines": 0, // "totalBatches": 0, // "totalChunksMatched": 0, // "totalDuplicates": 0, // "totalLinesSent": 0, // "totalReached": 0 // }, // "store": { // "chunksDownloadTime": 0.000390958, // "compressedBytes": 31432, // "decompressedBytes": 7772, // "decompressedLines": 55, // "headChunkBytes": 0, // "headChunkLines": 0, // "totalChunksDownloaded": 2, // "totalChunksRef": 2, // "totalDuplicates": 0 // }, // "summary": { // "bytesProcessedPerSecond": 3507022, // "execTime": 0.002216125, // "linesProcessedPerSecond": 24818, // "totalBytesProcessed": 7772, // "totalLinesProcessed": 55 // } // } // } // } // Name: // Dimensions: 4 Fields by 6 Rows // +---------------------------------------+-----------------------------------------+------------------+---------------------+ // | Name: __labels | Name: Time | Name: Line | Name: TS | // | Labels: | Labels: | Labels: | Labels: | // | Type: []json.RawMessage | Type: []time.Time | Type: []string | Type: []string | // +---------------------------------------+-----------------------------------------+------------------+---------------------+ // | {"level":"error","location":"moon🌙"} | 2022-02-16 16:50:44.81075712 +0000 UTC | log line error 1 | 1645030244810757120 | // | {"level":"info","location":"moon🌙"} | 2022-02-16 16:50:47.02773504 +0000 UTC | log line info 1 | 1645030247027735040 | // | {"level":"info","location":"moon🌙"} | 2022-02-16 16:50:46.277587968 +0000 UTC | log line info 2 | 1645030246277587968 | // | {"level":"info","location":"moon🌙"} | 2022-02-16 16:50:46.277587968 +0000 UTC | log line info 2 | 1645030246277587968 | // | {"level":"info","location":"moon🌙"} | 2022-02-16 16:50:45.539423744 +0000 UTC | log line info 3 | 1645030245539423744 | // | {"level":"info","location":"moon🌙"} | 2022-02-16 16:50:44.091700992 +0000 UTC | log line info 4 | 1645030244091700992 | // +---------------------------------------+-----------------------------------------+------------------+---------------------+ // // // 🌟 This was machine generated. Do not edit. 🌟 { "status": 200, "frames": [ { "schema": { "meta": { "typeVersion": [ 0, 0 ], "custom": { "stats": { "ingester": { "compressedBytes": 0, "decompressedBytes": 0, "decompressedLines": 0, "headChunkBytes": 0, "headChunkLines": 0, "totalBatches": 0, "totalChunksMatched": 0, "totalDuplicates": 0, "totalLinesSent": 0, "totalReached": 0 }, "store": { "chunksDownloadTime": 0.000390958, "compressedBytes": 31432, "decompressedBytes": 7772, "decompressedLines": 55, "headChunkBytes": 0, "headChunkLines": 0, "totalChunksDownloaded": 2, "totalChunksRef": 2, "totalDuplicates": 0 }, "summary": { "bytesProcessedPerSecond": 3507022, "execTime": 0.002216125, "linesProcessedPerSecond": 24818, "totalBytesProcessed": 7772, "totalLinesProcessed": 55 } } } }, "fields": [ { "name": "__labels", "type": "other", "typeInfo": { "frame": "json.RawMessage" } }, { "name": "Time", "type": "time", "typeInfo": { "frame": "time.Time" } }, { "name": "Line", "type": "string", "typeInfo": { "frame": "string" } }, { "name": "TS", "type": "string", "typeInfo": { "frame": "string" } } ] }, "data": { "values": [ [ { "level": "error", "location": "moon🌙" }, { "level": "info", "location": "moon🌙" }, { "level": "info", "location": "moon🌙" }, { "level": "info", "location": "moon🌙" }, { "level": "info", "location": "moon🌙" }, { "level": "info", "location": "moon🌙" } ], [ 1645030244810, 1645030247027, 1645030246277, 1645030246277, 1645030245539, 1645030244091 ], [ "log line error 1", "log line info 1", "log line info 2", "log line info 2", "log line info 3", "log line info 4" ], [ "1645030244810757120", "1645030247027735040", "1645030246277587968", "1645030246277587968", "1645030245539423744", "1645030244091700992" ] ], "nanos": [ null, [ 757120, 735040, 587968, 587968, 423744, 700992 ], null, null ] } } ] }
pkg/util/converter/testdata/loki-streams-a-wide-frame.jsonc
0
https://github.com/grafana/grafana/commit/64ed77ddce79009ce05f43801cc578c135f05b6b
[ 0.00017475349886808544, 0.00016876831068657339, 0.00016606948338449, 0.0001684618036961183, 0.0000022631963929597987 ]
{ "id": 4, "code_window": [ "\t// FlagInfluxdbSqlSupport\n", "\t// Enable InfluxDB SQL query language support with new querying UI\n", "\tFlagInfluxdbSqlSupport = \"influxdbSqlSupport\"\n", ")" ], "labels": [ "keep", "keep", "add", "keep" ], "after_edit": [ "\n", "\t// FlagNoBasicRole\n", "\t// Enables a new role that has no permissions by default\n", "\tFlagNoBasicRole = \"noBasicRole\"\n" ], "file_path": "pkg/services/featuremgmt/toggles_gen.go", "type": "add", "edit_start_line_idx": 408 }
global: scrape_interval: 15s evaluation_interval: 15s scrape_configs: - job_name: grafana static_configs: - targets: - host.docker.internal:3000
devenv/docker/blocks/self-instrumentation/prometheus.yaml
0
https://github.com/grafana/grafana/commit/64ed77ddce79009ce05f43801cc578c135f05b6b
[ 0.00016923573275562376, 0.00016923573275562376, 0.00016923573275562376, 0.00016923573275562376, 0 ]
{ "id": 4, "code_window": [ "\t// FlagInfluxdbSqlSupport\n", "\t// Enable InfluxDB SQL query language support with new querying UI\n", "\tFlagInfluxdbSqlSupport = \"influxdbSqlSupport\"\n", ")" ], "labels": [ "keep", "keep", "add", "keep" ], "after_edit": [ "\n", "\t// FlagNoBasicRole\n", "\t// Enables a new role that has no permissions by default\n", "\tFlagNoBasicRole = \"noBasicRole\"\n" ], "file_path": "pkg/services/featuremgmt/toggles_gen.go", "type": "add", "edit_start_line_idx": 408 }
import React from 'react'; import { DataSourceInstanceSettings } from '@grafana/data'; import { DataSourceRef } from '@grafana/schema'; import { useDatasources } from '../../hooks'; import { DataSourceCard } from './DataSourceCard'; import { isDataSourceMatch } from './utils'; const CUSTOM_DESCRIPTIONS_BY_UID: Record<string, string> = { grafana: 'Discover visualizations using mock data', '-- Mixed --': 'Use multiple data sources', '-- Dashboard --': 'Reuse query results from other visualizations', }; interface BuiltInDataSourceListProps { className?: string; current: DataSourceRef | string | null | undefined; onChange: (ds: DataSourceInstanceSettings) => void; // DS filters filter?: (ds: DataSourceInstanceSettings) => boolean; tracing?: boolean; mixed?: boolean; dashboard?: boolean; metrics?: boolean; type?: string | string[]; annotations?: boolean; variables?: boolean; alerting?: boolean; pluginId?: string; logs?: boolean; } export function BuiltInDataSourceList({ className, current, onChange, tracing, dashboard, mixed, metrics, type, annotations, variables, alerting, pluginId, logs, filter, }: BuiltInDataSourceListProps) { const grafanaDataSources = useDatasources({ tracing, dashboard, mixed, metrics, type, annotations, variables, alerting, pluginId, logs, }); const filteredResults = grafanaDataSources.filter((ds) => (filter ? filter?.(ds) : true) && !!ds.meta.builtIn); return ( <div className={className} data-testid="built-in-data-sources-list"> {filteredResults.map((ds) => { return ( <DataSourceCard key={ds.uid} ds={ds} description={CUSTOM_DESCRIPTIONS_BY_UID[ds.uid]} selected={isDataSourceMatch(ds, current)} onClick={() => onChange(ds)} /> ); })} </div> ); }
public/app/features/datasources/components/picker/BuiltInDataSourceList.tsx
0
https://github.com/grafana/grafana/commit/64ed77ddce79009ce05f43801cc578c135f05b6b
[ 0.0004346980422269553, 0.00020277871226426214, 0.0001678177941357717, 0.00017516021034680307, 0.00008209067891584709 ]
{ "id": 5, "code_window": [ "import React from 'react';\n", "\n", "import { SelectableValue } from '@grafana/data';\n", "import { Icon, RadioButtonList, Tooltip, useStyles2, useTheme2 } from '@grafana/ui';\n" ], "labels": [ "keep", "keep", "add", "keep" ], "after_edit": [ "import { config } from '@grafana/runtime';\n" ], "file_path": "public/app/core/components/RolePicker/BuiltinRoleSelector.tsx", "type": "add", "edit_start_line_idx": 3 }
import React from 'react'; import { SelectableValue } from '@grafana/data'; import { Icon, RadioButtonList, Tooltip, useStyles2, useTheme2 } from '@grafana/ui'; import { OrgRole } from 'app/types'; import { getStyles } from './styles'; const BasicRoleOption: Array<SelectableValue<OrgRole>> = Object.values(OrgRole).map((r) => ({ label: r === OrgRole.None ? 'No basic role' : r, value: r, })); interface Props { value?: OrgRole; onChange: (value: OrgRole) => void; disabled?: boolean; disabledMesssage?: string; tooltipMessage?: string; } export const BuiltinRoleSelector = ({ value, onChange, disabled, disabledMesssage, tooltipMessage }: Props) => { const styles = useStyles2(getStyles); const theme = useTheme2(); return ( <> <div className={styles.groupHeader}> <span style={{ marginRight: theme.spacing(1) }}>Basic roles</span> {disabled && disabledMesssage && ( <Tooltip placement="right-end" interactive={true} content={<div>{disabledMesssage}</div>}> <Icon name="question-circle" /> </Tooltip> )} {!disabled && tooltipMessage && ( <Tooltip placement="right-end" interactive={true} content={tooltipMessage}> <Icon name="info-circle" size="xs" /> </Tooltip> )} </div> <RadioButtonList name="Basic Role Selector" className={styles.basicRoleSelector} options={BasicRoleOption} value={value} onChange={onChange} disabled={disabled} /> </> ); };
public/app/core/components/RolePicker/BuiltinRoleSelector.tsx
1
https://github.com/grafana/grafana/commit/64ed77ddce79009ce05f43801cc578c135f05b6b
[ 0.8444475531578064, 0.14102216064929962, 0.00016935922030825168, 0.00031455172575078905, 0.3145814836025238 ]
{ "id": 5, "code_window": [ "import React from 'react';\n", "\n", "import { SelectableValue } from '@grafana/data';\n", "import { Icon, RadioButtonList, Tooltip, useStyles2, useTheme2 } from '@grafana/ui';\n" ], "labels": [ "keep", "keep", "add", "keep" ], "after_edit": [ "import { config } from '@grafana/runtime';\n" ], "file_path": "public/app/core/components/RolePicker/BuiltinRoleSelector.tsx", "type": "add", "edit_start_line_idx": 3 }
package service import ( "context" "testing" "github.com/grafana/grafana-plugin-sdk-go/backend" "github.com/stretchr/testify/require" "github.com/grafana/grafana/pkg/components/simplejson" "github.com/grafana/grafana/pkg/infra/db" "github.com/grafana/grafana/pkg/infra/localcache" "github.com/grafana/grafana/pkg/infra/log" "github.com/grafana/grafana/pkg/plugins" pluginFakes "github.com/grafana/grafana/pkg/plugins/manager/fakes" acmock "github.com/grafana/grafana/pkg/services/accesscontrol/mock" "github.com/grafana/grafana/pkg/services/datasources" datasourceservice "github.com/grafana/grafana/pkg/services/datasources/service" "github.com/grafana/grafana/pkg/services/featuremgmt" "github.com/grafana/grafana/pkg/services/pluginsintegration/plugincontext" pluginSettings "github.com/grafana/grafana/pkg/services/pluginsintegration/pluginsettings/service" "github.com/grafana/grafana/pkg/services/quota/quotatest" "github.com/grafana/grafana/pkg/services/secrets/fakes" secretskvs "github.com/grafana/grafana/pkg/services/secrets/kvstore" secretsmng "github.com/grafana/grafana/pkg/services/secrets/manager" "github.com/grafana/grafana/pkg/services/user" "github.com/grafana/grafana/pkg/tsdb/legacydata" ) func TestHandleRequest(t *testing.T) { t.Run("Should invoke plugin manager QueryData when handling request for query", func(t *testing.T) { client := &fakePluginsClient{} var actualReq *backend.QueryDataRequest client.QueryDataHandlerFunc = func(ctx context.Context, req *backend.QueryDataRequest) (*backend.QueryDataResponse, error) { actualReq = req return backend.NewQueryDataResponse(), nil } sqlStore := db.InitTestDB(t) secretsService := secretsmng.SetupTestService(t, fakes.NewFakeSecretsStore()) secretsStore := secretskvs.NewSQLSecretsKVStore(sqlStore, secretsService, log.New("test.logger")) datasourcePermissions := acmock.NewMockedPermissionsService() quotaService := quotatest.New(false, nil) dsService, err := datasourceservice.ProvideService(nil, secretsService, secretsStore, sqlStore.Cfg, featuremgmt.WithFeatures(), acmock.New(), datasourcePermissions, quotaService) require.NoError(t, err) pCtxProvider := plugincontext.ProvideService(localcache.ProvideService(), &pluginFakes.FakePluginStore{ PluginList: []plugins.PluginDTO{{JSONData: plugins.JSONData{ID: "test"}}}, }, dsService, pluginSettings.ProvideService(sqlStore, secretsService)) s := ProvideService(client, nil, dsService, pCtxProvider) ds := &datasources.DataSource{ID: 12, Type: "test", JsonData: simplejson.New()} req := legacydata.DataQuery{ TimeRange: &legacydata.DataTimeRange{}, Queries: []legacydata.DataSubQuery{ {RefID: "A", Model: simplejson.New()}, {RefID: "B", Model: simplejson.New()}, }, User: &user.SignedInUser{}, } res, err := s.HandleRequest(context.Background(), ds, req) require.NoError(t, err) require.NotNil(t, actualReq) require.NotNil(t, res) }) } type fakePluginsClient struct { plugins.Client backend.QueryDataHandlerFunc } func (m *fakePluginsClient) QueryData(ctx context.Context, req *backend.QueryDataRequest) (*backend.QueryDataResponse, error) { if m.QueryDataHandlerFunc != nil { return m.QueryDataHandlerFunc.QueryData(ctx, req) } return nil, nil }
pkg/tsdb/legacydata/service/service_test.go
0
https://github.com/grafana/grafana/commit/64ed77ddce79009ce05f43801cc578c135f05b6b
[ 0.00028575840406119823, 0.00019083707593381405, 0.00016564597899559885, 0.0001712018856778741, 0.000040182920201914385 ]
{ "id": 5, "code_window": [ "import React from 'react';\n", "\n", "import { SelectableValue } from '@grafana/data';\n", "import { Icon, RadioButtonList, Tooltip, useStyles2, useTheme2 } from '@grafana/ui';\n" ], "labels": [ "keep", "keep", "add", "keep" ], "after_edit": [ "import { config } from '@grafana/runtime';\n" ], "file_path": "public/app/core/components/RolePicker/BuiltinRoleSelector.tsx", "type": "add", "edit_start_line_idx": 3 }
import React from 'react'; import { Alert } from '@grafana/ui'; export const missingRightsMessage = 'You are not allowed to modify this data source. Please contact your server admin to update this data source.'; export function DataSourceMissingRightsMessage() { return ( <Alert severity="info" title="Missing rights"> {missingRightsMessage} </Alert> ); }
public/app/features/datasources/components/DataSourceMissingRightsMessage.tsx
0
https://github.com/grafana/grafana/commit/64ed77ddce79009ce05f43801cc578c135f05b6b
[ 0.00018286965496372432, 0.0001744350593071431, 0.00016600046365056187, 0.0001744350593071431, 0.000008434595656581223 ]
{ "id": 5, "code_window": [ "import React from 'react';\n", "\n", "import { SelectableValue } from '@grafana/data';\n", "import { Icon, RadioButtonList, Tooltip, useStyles2, useTheme2 } from '@grafana/ui';\n" ], "labels": [ "keep", "keep", "add", "keep" ], "after_edit": [ "import { config } from '@grafana/runtime';\n" ], "file_path": "public/app/core/components/RolePicker/BuiltinRoleSelector.tsx", "type": "add", "edit_start_line_idx": 3 }
import { css } from '@emotion/css'; import React from 'react'; import { GrafanaTheme2 } from '@grafana/data'; import { IconButton, ReactUtils, useStyles2 } from '@grafana/ui'; export interface Props { onRowToggle: () => void; isContentVisible?: boolean; title?: string; headerElement?: React.ReactNode | ((props: { className?: string }) => React.ReactNode); } export function SettingsBarHeader({ headerElement, isContentVisible = false, onRowToggle, title, ...rest }: Props) { const styles = useStyles2(getStyles); const headerElementRendered = headerElement && ReactUtils.renderOrCallToRender(headerElement, { className: styles.summaryWrapper }); return ( <div className={styles.wrapper}> <div className={styles.header}> <IconButton name={isContentVisible ? 'angle-down' : 'angle-right'} tooltip={isContentVisible ? 'Collapse settings' : 'Expand settings'} className={styles.collapseIcon} onClick={onRowToggle} aria-expanded={isContentVisible} {...rest} /> {title && ( // disabling the a11y rules here as the IconButton above handles keyboard interactions // this is just to provide a better experience for mouse users // eslint-disable-next-line jsx-a11y/click-events-have-key-events, jsx-a11y/no-static-element-interactions <div className={styles.titleWrapper} onClick={onRowToggle}> <span className={styles.title}>{title}</span> </div> )} {headerElementRendered} </div> </div> ); } SettingsBarHeader.displayName = 'SettingsBarHeader'; function getStyles(theme: GrafanaTheme2) { return { wrapper: css({ label: 'header', padding: theme.spacing(0.5, 0.5), borderRadius: theme.shape.radius.default, background: theme.colors.background.secondary, minHeight: theme.spacing(4), '&:focus': { outline: 'none', }, }), header: css({ label: 'column', display: 'flex', alignItems: 'center', whiteSpace: 'nowrap', }), collapseIcon: css({ marginLeft: theme.spacing(0.5), color: theme.colors.text.disabled, }), titleWrapper: css({ display: 'flex', alignItems: 'center', cursor: 'pointer', overflow: 'hidden', marginRight: `${theme.spacing(0.5)}`, [theme.breakpoints.down('sm')]: { flex: '1 1', }, }), title: css({ fontWeight: theme.typography.fontWeightBold, marginLeft: theme.spacing(0.5), overflow: 'hidden', textOverflow: 'ellipsis', }), summaryWrapper: css({ display: 'flex', flexWrap: 'wrap', [theme.breakpoints.down('sm')]: { flex: '2 2', }, }), }; }
public/app/features/dashboard/components/ShareModal/SharePublicDashboard/ConfigPublicDashboard/SettingsBarHeader.tsx
0
https://github.com/grafana/grafana/commit/64ed77ddce79009ce05f43801cc578c135f05b6b
[ 0.0008217177237384021, 0.00025729427579790354, 0.00016833559493534267, 0.00017987366300076246, 0.00019135569164063781 ]
{ "id": 6, "code_window": [ "import { Icon, RadioButtonList, Tooltip, useStyles2, useTheme2 } from '@grafana/ui';\n", "import { OrgRole } from 'app/types';\n", "\n", "import { getStyles } from './styles';\n", "\n" ], "labels": [ "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { contextSrv } from 'app/core/core';\n" ], "file_path": "public/app/core/components/RolePicker/BuiltinRoleSelector.tsx", "type": "add", "edit_start_line_idx": 4 }
// NOTE: This file was auto generated. DO NOT EDIT DIRECTLY! // To change feature flags, edit: // pkg/services/featuremgmt/registry.go // Then run tests in: // pkg/services/featuremgmt/toggles_gen_test.go package featuremgmt const ( // FlagTrimDefaults // Use cue schema to remove values that will be applied automatically FlagTrimDefaults = "trimDefaults" // FlagDisableEnvelopeEncryption // Disable envelope encryption (emergency only) FlagDisableEnvelopeEncryption = "disableEnvelopeEncryption" // FlagLiveServiceWebWorker // This will use a webworker thread to processes events rather than the main thread FlagLiveServiceWebWorker = "live-service-web-worker" // FlagQueryOverLive // Use Grafana Live WebSocket to execute backend queries FlagQueryOverLive = "queryOverLive" // FlagPanelTitleSearch // Search for dashboards using panel title FlagPanelTitleSearch = "panelTitleSearch" // FlagPublicDashboards // Enables public access to dashboards FlagPublicDashboards = "publicDashboards" // FlagPublicDashboardsEmailSharing // Enables public dashboard sharing to be restricted to only allowed emails FlagPublicDashboardsEmailSharing = "publicDashboardsEmailSharing" // FlagLokiExperimentalStreaming // Support new streaming approach for loki (prototype, needs special loki build) FlagLokiExperimentalStreaming = "lokiExperimentalStreaming" // FlagFeatureHighlights // Highlight Grafana Enterprise features FlagFeatureHighlights = "featureHighlights" // FlagMigrationLocking // Lock database during migrations FlagMigrationLocking = "migrationLocking" // FlagStorage // Configurable storage for dashboards, datasources, and resources FlagStorage = "storage" // FlagCorrelations // Correlations page FlagCorrelations = "correlations" // FlagDatasourceQueryMultiStatus // Introduce HTTP 207 Multi Status for api/ds/query FlagDatasourceQueryMultiStatus = "datasourceQueryMultiStatus" // FlagTraceToMetrics // Enable trace to metrics links FlagTraceToMetrics = "traceToMetrics" // FlagNewDBLibrary // Use jmoiron/sqlx rather than xorm for a few backend services FlagNewDBLibrary = "newDBLibrary" // FlagValidateDashboardsOnSave // Validate dashboard JSON POSTed to api/dashboards/db FlagValidateDashboardsOnSave = "validateDashboardsOnSave" // FlagAutoMigrateOldPanels // Migrate old angular panels to supported versions (graph, table-old, worldmap, etc) FlagAutoMigrateOldPanels = "autoMigrateOldPanels" // FlagDisableAngular // Dynamic flag to disable angular at runtime. The preferred method is to set `angular_support_enabled` to `false` in the [security] settings, which allows you to change the state at runtime. FlagDisableAngular = "disableAngular" // FlagPrometheusWideSeries // Enable wide series responses in the Prometheus datasource FlagPrometheusWideSeries = "prometheusWideSeries" // FlagCanvasPanelNesting // Allow elements nesting FlagCanvasPanelNesting = "canvasPanelNesting" // FlagScenes // Experimental framework to build interactive dashboards FlagScenes = "scenes" // FlagDisableSecretsCompatibility // Disable duplicated secret storage in legacy tables FlagDisableSecretsCompatibility = "disableSecretsCompatibility" // FlagLogRequestsInstrumentedAsUnknown // Logs the path for requests that are instrumented as unknown FlagLogRequestsInstrumentedAsUnknown = "logRequestsInstrumentedAsUnknown" // FlagDataConnectionsConsole // Enables a new top-level page called Connections. This page is an experiment that provides a better experience when you install and configure data sources and other plugins. FlagDataConnectionsConsole = "dataConnectionsConsole" // FlagTopnav // Enables topnav support in external plugins. The new Grafana navigation cannot be disabled. FlagTopnav = "topnav" // FlagGrpcServer // Run the GRPC server FlagGrpcServer = "grpcServer" // FlagEntityStore // SQL-based entity store (requires storage flag also) FlagEntityStore = "entityStore" // FlagCloudWatchCrossAccountQuerying // Enables cross-account querying in CloudWatch datasources FlagCloudWatchCrossAccountQuerying = "cloudWatchCrossAccountQuerying" // FlagRedshiftAsyncQueryDataSupport // Enable async query data support for Redshift FlagRedshiftAsyncQueryDataSupport = "redshiftAsyncQueryDataSupport" // FlagAthenaAsyncQueryDataSupport // Enable async query data support for Athena FlagAthenaAsyncQueryDataSupport = "athenaAsyncQueryDataSupport" // FlagNewPanelChromeUI // Show updated look and feel of grafana-ui PanelChrome: panel header, icons, and menu FlagNewPanelChromeUI = "newPanelChromeUI" // FlagShowDashboardValidationWarnings // Show warnings when dashboards do not validate against the schema FlagShowDashboardValidationWarnings = "showDashboardValidationWarnings" // FlagMysqlAnsiQuotes // Use double quotes to escape keyword in a MySQL query FlagMysqlAnsiQuotes = "mysqlAnsiQuotes" // FlagAccessControlOnCall // Access control primitives for OnCall FlagAccessControlOnCall = "accessControlOnCall" // FlagNestedFolders // Enable folder nesting FlagNestedFolders = "nestedFolders" // FlagNestedFolderPicker // Enables the new folder picker to work with nested folders. Requires the folderPicker feature flag FlagNestedFolderPicker = "nestedFolderPicker" // FlagAccessTokenExpirationCheck // Enable OAuth access_token expiration check and token refresh using the refresh_token FlagAccessTokenExpirationCheck = "accessTokenExpirationCheck" // FlagEmptyDashboardPage // Enable the redesigned user interface of a dashboard page that includes no panels FlagEmptyDashboardPage = "emptyDashboardPage" // FlagDisablePrometheusExemplarSampling // Disable Prometheus exemplar sampling FlagDisablePrometheusExemplarSampling = "disablePrometheusExemplarSampling" // FlagAlertingBacktesting // Rule backtesting API for alerting FlagAlertingBacktesting = "alertingBacktesting" // FlagEditPanelCSVDragAndDrop // Enables drag and drop for CSV and Excel files FlagEditPanelCSVDragAndDrop = "editPanelCSVDragAndDrop" // FlagAlertingNoNormalState // Stop maintaining state of alerts that are not firing FlagAlertingNoNormalState = "alertingNoNormalState" // FlagLogsContextDatasourceUi // Allow datasource to provide custom UI for context view FlagLogsContextDatasourceUi = "logsContextDatasourceUi" // FlagLokiQuerySplitting // Split large interval queries into subqueries with smaller time intervals FlagLokiQuerySplitting = "lokiQuerySplitting" // FlagLokiQuerySplittingConfig // Give users the option to configure split durations for Loki queries FlagLokiQuerySplittingConfig = "lokiQuerySplittingConfig" // FlagIndividualCookiePreferences // Support overriding cookie preferences per user FlagIndividualCookiePreferences = "individualCookiePreferences" // FlagGcomOnlyExternalOrgRoleSync // Prohibits a user from changing organization roles synced with Grafana Cloud auth provider FlagGcomOnlyExternalOrgRoleSync = "gcomOnlyExternalOrgRoleSync" // FlagPrometheusMetricEncyclopedia // Adds the metrics explorer component to the Prometheus query builder as an option in metric select FlagPrometheusMetricEncyclopedia = "prometheusMetricEncyclopedia" // FlagTimeSeriesTable // Enable time series table transformer &amp; sparkline cell type FlagTimeSeriesTable = "timeSeriesTable" // FlagPrometheusResourceBrowserCache // Displays browser caching options in Prometheus data source configuration FlagPrometheusResourceBrowserCache = "prometheusResourceBrowserCache" // FlagInfluxdbBackendMigration // Query InfluxDB InfluxQL without the proxy FlagInfluxdbBackendMigration = "influxdbBackendMigration" // FlagClientTokenRotation // Replaces the current in-request token rotation so that the client initiates the rotation FlagClientTokenRotation = "clientTokenRotation" // FlagPrometheusDataplane // Changes responses to from Prometheus to be compliant with the dataplane specification. In particular it sets the numeric Field.Name from &#39;Value&#39; to the value of the `__name__` label when present. FlagPrometheusDataplane = "prometheusDataplane" // FlagLokiMetricDataplane // Changes metric responses from Loki to be compliant with the dataplane specification. FlagLokiMetricDataplane = "lokiMetricDataplane" // FlagLokiLogsDataplane // Changes logs responses from Loki to be compliant with the dataplane specification. FlagLokiLogsDataplane = "lokiLogsDataplane" // FlagDataplaneFrontendFallback // Support dataplane contract field name change for transformations and field name matchers where the name is different FlagDataplaneFrontendFallback = "dataplaneFrontendFallback" // FlagDisableSSEDataplane // Disables dataplane specific processing in server side expressions. FlagDisableSSEDataplane = "disableSSEDataplane" // FlagAlertStateHistoryLokiSecondary // Enable Grafana to write alert state history to an external Loki instance in addition to Grafana annotations. FlagAlertStateHistoryLokiSecondary = "alertStateHistoryLokiSecondary" // FlagAlertingNotificationsPoliciesMatchingInstances // Enables the preview of matching instances for notification policies FlagAlertingNotificationsPoliciesMatchingInstances = "alertingNotificationsPoliciesMatchingInstances" // FlagAlertStateHistoryLokiPrimary // Enable a remote Loki instance as the primary source for state history reads. FlagAlertStateHistoryLokiPrimary = "alertStateHistoryLokiPrimary" // FlagAlertStateHistoryLokiOnly // Disable Grafana alerts from emitting annotations when a remote Loki instance is available. FlagAlertStateHistoryLokiOnly = "alertStateHistoryLokiOnly" // FlagUnifiedRequestLog // Writes error logs to the request logger FlagUnifiedRequestLog = "unifiedRequestLog" // FlagRenderAuthJWT // Uses JWT-based auth for rendering instead of relying on remote cache FlagRenderAuthJWT = "renderAuthJWT" // FlagExternalServiceAuth // Starts an OAuth2 authentication provider for external services FlagExternalServiceAuth = "externalServiceAuth" // FlagRefactorVariablesTimeRange // Refactor time range variables flow to reduce number of API calls made when query variables are chained FlagRefactorVariablesTimeRange = "refactorVariablesTimeRange" // FlagUseCachingService // When turned on, the new query and resource caching implementation using a wire service inject will be used in place of the previous middleware implementation FlagUseCachingService = "useCachingService" // FlagEnableElasticsearchBackendQuerying // Enable the processing of queries and responses in the Elasticsearch data source through backend FlagEnableElasticsearchBackendQuerying = "enableElasticsearchBackendQuerying" // FlagAdvancedDataSourcePicker // Enable a new data source picker with contextual information, recently used order and advanced mode FlagAdvancedDataSourcePicker = "advancedDataSourcePicker" // FlagFaroDatasourceSelector // Enable the data source selector within the Frontend Apps section of the Frontend Observability FlagFaroDatasourceSelector = "faroDatasourceSelector" // FlagEnableDatagridEditing // Enables the edit functionality in the datagrid panel FlagEnableDatagridEditing = "enableDatagridEditing" // FlagDataSourcePageHeader // Apply new pageHeader UI in data source edit page FlagDataSourcePageHeader = "dataSourcePageHeader" // FlagExtraThemes // Enables extra themes FlagExtraThemes = "extraThemes" // FlagLokiPredefinedOperations // Adds predefined query operations to Loki query editor FlagLokiPredefinedOperations = "lokiPredefinedOperations" // FlagPluginsFrontendSandbox // Enables the plugins frontend sandbox FlagPluginsFrontendSandbox = "pluginsFrontendSandbox" // FlagDashboardEmbed // Allow embedding dashboard for external use in Code editors FlagDashboardEmbed = "dashboardEmbed" // FlagFrontendSandboxMonitorOnly // Enables monitor only in the plugin frontend sandbox (if enabled) FlagFrontendSandboxMonitorOnly = "frontendSandboxMonitorOnly" // FlagSqlDatasourceDatabaseSelection // Enables previous SQL data source dataset dropdown behavior FlagSqlDatasourceDatabaseSelection = "sqlDatasourceDatabaseSelection" // FlagLokiFormatQuery // Enables the ability to format Loki queries FlagLokiFormatQuery = "lokiFormatQuery" // FlagCloudWatchLogsMonacoEditor // Enables the Monaco editor for CloudWatch Logs queries FlagCloudWatchLogsMonacoEditor = "cloudWatchLogsMonacoEditor" // FlagExploreScrollableLogsContainer // Improves the scrolling behavior of logs in Explore FlagExploreScrollableLogsContainer = "exploreScrollableLogsContainer" // FlagRecordedQueriesMulti // Enables writing multiple items from a single query within Recorded Queries FlagRecordedQueriesMulti = "recordedQueriesMulti" // FlagPluginsDynamicAngularDetectionPatterns // Enables fetching Angular detection patterns for plugins from GCOM and fallback to hardcoded ones FlagPluginsDynamicAngularDetectionPatterns = "pluginsDynamicAngularDetectionPatterns" // FlagAlertingLokiRangeToInstant // Rewrites eligible loki range queries to instant queries FlagAlertingLokiRangeToInstant = "alertingLokiRangeToInstant" // FlagVizAndWidgetSplit // Split panels between vizualizations and widgets FlagVizAndWidgetSplit = "vizAndWidgetSplit" // FlagPrometheusIncrementalQueryInstrumentation // Adds RudderStack events to incremental queries FlagPrometheusIncrementalQueryInstrumentation = "prometheusIncrementalQueryInstrumentation" // FlagLogsExploreTableVisualisation // A table visualisation for logs in Explore FlagLogsExploreTableVisualisation = "logsExploreTableVisualisation" // FlagAwsDatasourcesTempCredentials // Support temporary security credentials in AWS plugins for Grafana Cloud customers FlagAwsDatasourcesTempCredentials = "awsDatasourcesTempCredentials" // FlagTransformationsRedesign // Enables the transformations redesign FlagTransformationsRedesign = "transformationsRedesign" // FlagToggleLabelsInLogsUI // Enable toggleable filters in log details view FlagToggleLabelsInLogsUI = "toggleLabelsInLogsUI" // FlagMlExpressions // Enable support for Machine Learning in server-side expressions FlagMlExpressions = "mlExpressions" // FlagTraceQLStreaming // Enables response streaming of TraceQL queries of the Tempo data source FlagTraceQLStreaming = "traceQLStreaming" // FlagGrafanaAPIServer // Enable Kubernetes API Server for Grafana resources FlagGrafanaAPIServer = "grafanaAPIServer" // FlagFeatureToggleAdminPage // Enable admin page for managing feature toggles from the Grafana front-end FlagFeatureToggleAdminPage = "featureToggleAdminPage" // FlagAwsAsyncQueryCaching // Enable caching for async queries for Redshift and Athena. Requires that the `useCachingService` feature toggle is enabled and the datasource has caching and async query support enabled FlagAwsAsyncQueryCaching = "awsAsyncQueryCaching" // FlagSplitScopes // Support faster dashboard and folder search by splitting permission scopes into parts FlagSplitScopes = "splitScopes" // FlagAzureMonitorDataplane // Adds dataplane compliant frame metadata in the Azure Monitor datasource FlagAzureMonitorDataplane = "azureMonitorDataplane" // FlagPermissionsFilterRemoveSubquery // Alternative permission filter implementation that does not use subqueries for fetching the dashboard folder FlagPermissionsFilterRemoveSubquery = "permissionsFilterRemoveSubquery" // FlagPrometheusConfigOverhaulAuth // Update the Prometheus configuration page with the new auth component FlagPrometheusConfigOverhaulAuth = "prometheusConfigOverhaulAuth" // FlagConfigurableSchedulerTick // Enable changing the scheduler base interval via configuration option unified_alerting.scheduler_tick_interval FlagConfigurableSchedulerTick = "configurableSchedulerTick" // FlagInfluxdbSqlSupport // Enable InfluxDB SQL query language support with new querying UI FlagInfluxdbSqlSupport = "influxdbSqlSupport" )
pkg/services/featuremgmt/toggles_gen.go
1
https://github.com/grafana/grafana/commit/64ed77ddce79009ce05f43801cc578c135f05b6b
[ 0.0001728623901726678, 0.00016750264330767095, 0.00016348013014066964, 0.00016734433302190155, 0.0000025038577859959332 ]
{ "id": 6, "code_window": [ "import { Icon, RadioButtonList, Tooltip, useStyles2, useTheme2 } from '@grafana/ui';\n", "import { OrgRole } from 'app/types';\n", "\n", "import { getStyles } from './styles';\n", "\n" ], "labels": [ "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { contextSrv } from 'app/core/core';\n" ], "file_path": "public/app/core/components/RolePicker/BuiltinRoleSelector.tsx", "type": "add", "edit_start_line_idx": 4 }
package notifiers import ( "testing" "github.com/stretchr/testify/require" "github.com/grafana/grafana/pkg/components/simplejson" "github.com/grafana/grafana/pkg/services/alerting/models" encryptionservice "github.com/grafana/grafana/pkg/services/encryption/service" ) func TestLineNotifier(t *testing.T) { encryptionService := encryptionservice.SetupTestService(t) t.Run("empty settings should return error", func(t *testing.T) { json := `{ }` settingsJSON, _ := simplejson.NewJson([]byte(json)) model := &models.AlertNotification{ Name: "line_testing", Type: "line", Settings: settingsJSON, } _, err := NewLINENotifier(model, encryptionService.GetDecryptedValue, nil) require.Error(t, err) }) t.Run("settings should trigger incident", func(t *testing.T) { json := ` { "token": "abcdefgh0123456789" }` settingsJSON, _ := simplejson.NewJson([]byte(json)) model := &models.AlertNotification{ Name: "line_testing", Type: "line", Settings: settingsJSON, } not, err := NewLINENotifier(model, encryptionService.GetDecryptedValue, nil) lineNotifier := not.(*LineNotifier) require.Nil(t, err) require.Equal(t, "line_testing", lineNotifier.Name) require.Equal(t, "line", lineNotifier.Type) require.Equal(t, "abcdefgh0123456789", lineNotifier.Token) }) }
pkg/services/alerting/notifiers/line_test.go
0
https://github.com/grafana/grafana/commit/64ed77ddce79009ce05f43801cc578c135f05b6b
[ 0.00017541124543640763, 0.00017162831500172615, 0.0001634940126677975, 0.00017347960965707898, 0.000004212816747894976 ]
{ "id": 6, "code_window": [ "import { Icon, RadioButtonList, Tooltip, useStyles2, useTheme2 } from '@grafana/ui';\n", "import { OrgRole } from 'app/types';\n", "\n", "import { getStyles } from './styles';\n", "\n" ], "labels": [ "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { contextSrv } from 'app/core/core';\n" ], "file_path": "public/app/core/components/RolePicker/BuiltinRoleSelector.tsx", "type": "add", "edit_start_line_idx": 4 }
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M12.57,17.29a1,1,0,0,0-1.41,0,1.06,1.06,0,0,0-.22.33,1.07,1.07,0,0,0,0,.76,1.19,1.19,0,0,0,.22.33,1,1,0,0,0,.32.21,1,1,0,0,0,.39.08,1,1,0,0,0,.92-1.38A.91.91,0,0,0,12.57,17.29ZM20,8.94a1.31,1.31,0,0,0-.06-.27l0-.09a1.07,1.07,0,0,0-.19-.28h0l-6-6h0a1.07,1.07,0,0,0-.28-.19l-.09,0A.88.88,0,0,0,13.05,2H7A3,3,0,0,0,4,5V19a3,3,0,0,0,3,3H17a3,3,0,0,0,3-3V9S20,9,20,8.94ZM14,5.41,16.59,8H15a1,1,0,0,1-1-1ZM18,19a1,1,0,0,1-1,1H7a1,1,0,0,1-1-1V5A1,1,0,0,1,7,4h5V7a3,3,0,0,0,3,3h3Zm-6.13-9a3,3,0,0,0-2.6,1.5,1,1,0,1,0,1.73,1,1,1,0,0,1,.87-.5,1,1,0,0,1,0,2,1,1,0,1,0,0,2,3,3,0,0,0,0-6Z"/></svg>
public/img/icons/unicons/file-question.svg
0
https://github.com/grafana/grafana/commit/64ed77ddce79009ce05f43801cc578c135f05b6b
[ 0.00016573302855249494, 0.00016573302855249494, 0.00016573302855249494, 0.00016573302855249494, 0 ]
{ "id": 6, "code_window": [ "import { Icon, RadioButtonList, Tooltip, useStyles2, useTheme2 } from '@grafana/ui';\n", "import { OrgRole } from 'app/types';\n", "\n", "import { getStyles } from './styles';\n", "\n" ], "labels": [ "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { contextSrv } from 'app/core/core';\n" ], "file_path": "public/app/core/components/RolePicker/BuiltinRoleSelector.tsx", "type": "add", "edit_start_line_idx": 4 }
package historian import ( "context" "fmt" "github.com/grafana/grafana/pkg/infra/log" "github.com/grafana/grafana/pkg/services/annotations" "github.com/grafana/grafana/pkg/services/dashboards" "github.com/grafana/grafana/pkg/services/ngalert/metrics" ) type AnnotationService interface { Find(ctx context.Context, query *annotations.ItemQuery) ([]*annotations.ItemDTO, error) SaveMany(ctx context.Context, items []annotations.Item) error } type AnnotationServiceStore struct { svc AnnotationService dashboards *dashboardResolver metrics *metrics.Historian } func NewAnnotationStore(svc AnnotationService, dashboards dashboards.DashboardService, metrics *metrics.Historian) *AnnotationServiceStore { return &AnnotationServiceStore{ svc: svc, dashboards: newDashboardResolver(dashboards, defaultDashboardCacheExpiry), metrics: metrics, } } func (s *AnnotationServiceStore) Save(ctx context.Context, panel *PanelKey, annotations []annotations.Item, orgID int64, logger log.Logger) error { if panel != nil { dashID, err := s.dashboards.getID(ctx, panel.orgID, panel.dashUID) if err != nil { logger.Error("Error getting dashboard for alert annotation", "dashboardUID", panel.dashUID, "error", err) dashID = 0 } for i := range annotations { annotations[i].DashboardID = dashID annotations[i].PanelID = panel.panelID } } org := fmt.Sprint(orgID) s.metrics.WritesTotal.WithLabelValues(org, "annotations").Inc() s.metrics.TransitionsTotal.WithLabelValues(org).Add(float64(len(annotations))) if err := s.svc.SaveMany(ctx, annotations); err != nil { logger.Error("Error saving alert annotation batch", "error", err) s.metrics.WritesFailed.WithLabelValues(org, "annotations").Inc() s.metrics.TransitionsFailed.WithLabelValues(org).Add(float64(len(annotations))) return fmt.Errorf("error saving alert annotation batch: %w", err) } logger.Debug("Done saving alert annotation batch") return nil } func (s *AnnotationServiceStore) Find(ctx context.Context, query *annotations.ItemQuery) ([]*annotations.ItemDTO, error) { return s.svc.Find(ctx, query) }
pkg/services/ngalert/state/historian/annotation_store.go
0
https://github.com/grafana/grafana/commit/64ed77ddce79009ce05f43801cc578c135f05b6b
[ 0.00017735846631694585, 0.00017097718955483288, 0.0001655640226090327, 0.00017030689923558384, 0.000003852200279652607 ]
{ "id": 7, "code_window": [ "import { OrgRole } from 'app/types';\n", "\n", "import { getStyles } from './styles';\n", "\n", "const BasicRoleOption: Array<SelectableValue<OrgRole>> = Object.values(OrgRole).map((r) => ({\n", " label: r === OrgRole.None ? 'No basic role' : r,\n", " value: r,\n", "}));\n", "\n", "interface Props {\n", " value?: OrgRole;\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ "const noBasicRoleFlag = contextSrv.licensedAccessControlEnabled();\n", "\n", "const noBasicRole = config.featureToggles.noBasicRole && noBasicRoleFlag;\n", "\n", "const BasicRoleOption: Array<SelectableValue<OrgRole>> = Object.values(OrgRole)\n", " .filter((r) => noBasicRole || r !== OrgRole.None)\n", " .map((r) => ({\n", " label: r === OrgRole.None ? 'No basic role' : r,\n", " value: r,\n", " }));\n" ], "file_path": "public/app/core/components/RolePicker/BuiltinRoleSelector.tsx", "type": "replace", "edit_start_line_idx": 8 }
// NOTE: This file was auto generated. DO NOT EDIT DIRECTLY! // To change feature flags, edit: // pkg/services/featuremgmt/registry.go // Then run tests in: // pkg/services/featuremgmt/toggles_gen_test.go package featuremgmt const ( // FlagTrimDefaults // Use cue schema to remove values that will be applied automatically FlagTrimDefaults = "trimDefaults" // FlagDisableEnvelopeEncryption // Disable envelope encryption (emergency only) FlagDisableEnvelopeEncryption = "disableEnvelopeEncryption" // FlagLiveServiceWebWorker // This will use a webworker thread to processes events rather than the main thread FlagLiveServiceWebWorker = "live-service-web-worker" // FlagQueryOverLive // Use Grafana Live WebSocket to execute backend queries FlagQueryOverLive = "queryOverLive" // FlagPanelTitleSearch // Search for dashboards using panel title FlagPanelTitleSearch = "panelTitleSearch" // FlagPublicDashboards // Enables public access to dashboards FlagPublicDashboards = "publicDashboards" // FlagPublicDashboardsEmailSharing // Enables public dashboard sharing to be restricted to only allowed emails FlagPublicDashboardsEmailSharing = "publicDashboardsEmailSharing" // FlagLokiExperimentalStreaming // Support new streaming approach for loki (prototype, needs special loki build) FlagLokiExperimentalStreaming = "lokiExperimentalStreaming" // FlagFeatureHighlights // Highlight Grafana Enterprise features FlagFeatureHighlights = "featureHighlights" // FlagMigrationLocking // Lock database during migrations FlagMigrationLocking = "migrationLocking" // FlagStorage // Configurable storage for dashboards, datasources, and resources FlagStorage = "storage" // FlagCorrelations // Correlations page FlagCorrelations = "correlations" // FlagDatasourceQueryMultiStatus // Introduce HTTP 207 Multi Status for api/ds/query FlagDatasourceQueryMultiStatus = "datasourceQueryMultiStatus" // FlagTraceToMetrics // Enable trace to metrics links FlagTraceToMetrics = "traceToMetrics" // FlagNewDBLibrary // Use jmoiron/sqlx rather than xorm for a few backend services FlagNewDBLibrary = "newDBLibrary" // FlagValidateDashboardsOnSave // Validate dashboard JSON POSTed to api/dashboards/db FlagValidateDashboardsOnSave = "validateDashboardsOnSave" // FlagAutoMigrateOldPanels // Migrate old angular panels to supported versions (graph, table-old, worldmap, etc) FlagAutoMigrateOldPanels = "autoMigrateOldPanels" // FlagDisableAngular // Dynamic flag to disable angular at runtime. The preferred method is to set `angular_support_enabled` to `false` in the [security] settings, which allows you to change the state at runtime. FlagDisableAngular = "disableAngular" // FlagPrometheusWideSeries // Enable wide series responses in the Prometheus datasource FlagPrometheusWideSeries = "prometheusWideSeries" // FlagCanvasPanelNesting // Allow elements nesting FlagCanvasPanelNesting = "canvasPanelNesting" // FlagScenes // Experimental framework to build interactive dashboards FlagScenes = "scenes" // FlagDisableSecretsCompatibility // Disable duplicated secret storage in legacy tables FlagDisableSecretsCompatibility = "disableSecretsCompatibility" // FlagLogRequestsInstrumentedAsUnknown // Logs the path for requests that are instrumented as unknown FlagLogRequestsInstrumentedAsUnknown = "logRequestsInstrumentedAsUnknown" // FlagDataConnectionsConsole // Enables a new top-level page called Connections. This page is an experiment that provides a better experience when you install and configure data sources and other plugins. FlagDataConnectionsConsole = "dataConnectionsConsole" // FlagTopnav // Enables topnav support in external plugins. The new Grafana navigation cannot be disabled. FlagTopnav = "topnav" // FlagGrpcServer // Run the GRPC server FlagGrpcServer = "grpcServer" // FlagEntityStore // SQL-based entity store (requires storage flag also) FlagEntityStore = "entityStore" // FlagCloudWatchCrossAccountQuerying // Enables cross-account querying in CloudWatch datasources FlagCloudWatchCrossAccountQuerying = "cloudWatchCrossAccountQuerying" // FlagRedshiftAsyncQueryDataSupport // Enable async query data support for Redshift FlagRedshiftAsyncQueryDataSupport = "redshiftAsyncQueryDataSupport" // FlagAthenaAsyncQueryDataSupport // Enable async query data support for Athena FlagAthenaAsyncQueryDataSupport = "athenaAsyncQueryDataSupport" // FlagNewPanelChromeUI // Show updated look and feel of grafana-ui PanelChrome: panel header, icons, and menu FlagNewPanelChromeUI = "newPanelChromeUI" // FlagShowDashboardValidationWarnings // Show warnings when dashboards do not validate against the schema FlagShowDashboardValidationWarnings = "showDashboardValidationWarnings" // FlagMysqlAnsiQuotes // Use double quotes to escape keyword in a MySQL query FlagMysqlAnsiQuotes = "mysqlAnsiQuotes" // FlagAccessControlOnCall // Access control primitives for OnCall FlagAccessControlOnCall = "accessControlOnCall" // FlagNestedFolders // Enable folder nesting FlagNestedFolders = "nestedFolders" // FlagNestedFolderPicker // Enables the new folder picker to work with nested folders. Requires the folderPicker feature flag FlagNestedFolderPicker = "nestedFolderPicker" // FlagAccessTokenExpirationCheck // Enable OAuth access_token expiration check and token refresh using the refresh_token FlagAccessTokenExpirationCheck = "accessTokenExpirationCheck" // FlagEmptyDashboardPage // Enable the redesigned user interface of a dashboard page that includes no panels FlagEmptyDashboardPage = "emptyDashboardPage" // FlagDisablePrometheusExemplarSampling // Disable Prometheus exemplar sampling FlagDisablePrometheusExemplarSampling = "disablePrometheusExemplarSampling" // FlagAlertingBacktesting // Rule backtesting API for alerting FlagAlertingBacktesting = "alertingBacktesting" // FlagEditPanelCSVDragAndDrop // Enables drag and drop for CSV and Excel files FlagEditPanelCSVDragAndDrop = "editPanelCSVDragAndDrop" // FlagAlertingNoNormalState // Stop maintaining state of alerts that are not firing FlagAlertingNoNormalState = "alertingNoNormalState" // FlagLogsContextDatasourceUi // Allow datasource to provide custom UI for context view FlagLogsContextDatasourceUi = "logsContextDatasourceUi" // FlagLokiQuerySplitting // Split large interval queries into subqueries with smaller time intervals FlagLokiQuerySplitting = "lokiQuerySplitting" // FlagLokiQuerySplittingConfig // Give users the option to configure split durations for Loki queries FlagLokiQuerySplittingConfig = "lokiQuerySplittingConfig" // FlagIndividualCookiePreferences // Support overriding cookie preferences per user FlagIndividualCookiePreferences = "individualCookiePreferences" // FlagGcomOnlyExternalOrgRoleSync // Prohibits a user from changing organization roles synced with Grafana Cloud auth provider FlagGcomOnlyExternalOrgRoleSync = "gcomOnlyExternalOrgRoleSync" // FlagPrometheusMetricEncyclopedia // Adds the metrics explorer component to the Prometheus query builder as an option in metric select FlagPrometheusMetricEncyclopedia = "prometheusMetricEncyclopedia" // FlagTimeSeriesTable // Enable time series table transformer &amp; sparkline cell type FlagTimeSeriesTable = "timeSeriesTable" // FlagPrometheusResourceBrowserCache // Displays browser caching options in Prometheus data source configuration FlagPrometheusResourceBrowserCache = "prometheusResourceBrowserCache" // FlagInfluxdbBackendMigration // Query InfluxDB InfluxQL without the proxy FlagInfluxdbBackendMigration = "influxdbBackendMigration" // FlagClientTokenRotation // Replaces the current in-request token rotation so that the client initiates the rotation FlagClientTokenRotation = "clientTokenRotation" // FlagPrometheusDataplane // Changes responses to from Prometheus to be compliant with the dataplane specification. In particular it sets the numeric Field.Name from &#39;Value&#39; to the value of the `__name__` label when present. FlagPrometheusDataplane = "prometheusDataplane" // FlagLokiMetricDataplane // Changes metric responses from Loki to be compliant with the dataplane specification. FlagLokiMetricDataplane = "lokiMetricDataplane" // FlagLokiLogsDataplane // Changes logs responses from Loki to be compliant with the dataplane specification. FlagLokiLogsDataplane = "lokiLogsDataplane" // FlagDataplaneFrontendFallback // Support dataplane contract field name change for transformations and field name matchers where the name is different FlagDataplaneFrontendFallback = "dataplaneFrontendFallback" // FlagDisableSSEDataplane // Disables dataplane specific processing in server side expressions. FlagDisableSSEDataplane = "disableSSEDataplane" // FlagAlertStateHistoryLokiSecondary // Enable Grafana to write alert state history to an external Loki instance in addition to Grafana annotations. FlagAlertStateHistoryLokiSecondary = "alertStateHistoryLokiSecondary" // FlagAlertingNotificationsPoliciesMatchingInstances // Enables the preview of matching instances for notification policies FlagAlertingNotificationsPoliciesMatchingInstances = "alertingNotificationsPoliciesMatchingInstances" // FlagAlertStateHistoryLokiPrimary // Enable a remote Loki instance as the primary source for state history reads. FlagAlertStateHistoryLokiPrimary = "alertStateHistoryLokiPrimary" // FlagAlertStateHistoryLokiOnly // Disable Grafana alerts from emitting annotations when a remote Loki instance is available. FlagAlertStateHistoryLokiOnly = "alertStateHistoryLokiOnly" // FlagUnifiedRequestLog // Writes error logs to the request logger FlagUnifiedRequestLog = "unifiedRequestLog" // FlagRenderAuthJWT // Uses JWT-based auth for rendering instead of relying on remote cache FlagRenderAuthJWT = "renderAuthJWT" // FlagExternalServiceAuth // Starts an OAuth2 authentication provider for external services FlagExternalServiceAuth = "externalServiceAuth" // FlagRefactorVariablesTimeRange // Refactor time range variables flow to reduce number of API calls made when query variables are chained FlagRefactorVariablesTimeRange = "refactorVariablesTimeRange" // FlagUseCachingService // When turned on, the new query and resource caching implementation using a wire service inject will be used in place of the previous middleware implementation FlagUseCachingService = "useCachingService" // FlagEnableElasticsearchBackendQuerying // Enable the processing of queries and responses in the Elasticsearch data source through backend FlagEnableElasticsearchBackendQuerying = "enableElasticsearchBackendQuerying" // FlagAdvancedDataSourcePicker // Enable a new data source picker with contextual information, recently used order and advanced mode FlagAdvancedDataSourcePicker = "advancedDataSourcePicker" // FlagFaroDatasourceSelector // Enable the data source selector within the Frontend Apps section of the Frontend Observability FlagFaroDatasourceSelector = "faroDatasourceSelector" // FlagEnableDatagridEditing // Enables the edit functionality in the datagrid panel FlagEnableDatagridEditing = "enableDatagridEditing" // FlagDataSourcePageHeader // Apply new pageHeader UI in data source edit page FlagDataSourcePageHeader = "dataSourcePageHeader" // FlagExtraThemes // Enables extra themes FlagExtraThemes = "extraThemes" // FlagLokiPredefinedOperations // Adds predefined query operations to Loki query editor FlagLokiPredefinedOperations = "lokiPredefinedOperations" // FlagPluginsFrontendSandbox // Enables the plugins frontend sandbox FlagPluginsFrontendSandbox = "pluginsFrontendSandbox" // FlagDashboardEmbed // Allow embedding dashboard for external use in Code editors FlagDashboardEmbed = "dashboardEmbed" // FlagFrontendSandboxMonitorOnly // Enables monitor only in the plugin frontend sandbox (if enabled) FlagFrontendSandboxMonitorOnly = "frontendSandboxMonitorOnly" // FlagSqlDatasourceDatabaseSelection // Enables previous SQL data source dataset dropdown behavior FlagSqlDatasourceDatabaseSelection = "sqlDatasourceDatabaseSelection" // FlagLokiFormatQuery // Enables the ability to format Loki queries FlagLokiFormatQuery = "lokiFormatQuery" // FlagCloudWatchLogsMonacoEditor // Enables the Monaco editor for CloudWatch Logs queries FlagCloudWatchLogsMonacoEditor = "cloudWatchLogsMonacoEditor" // FlagExploreScrollableLogsContainer // Improves the scrolling behavior of logs in Explore FlagExploreScrollableLogsContainer = "exploreScrollableLogsContainer" // FlagRecordedQueriesMulti // Enables writing multiple items from a single query within Recorded Queries FlagRecordedQueriesMulti = "recordedQueriesMulti" // FlagPluginsDynamicAngularDetectionPatterns // Enables fetching Angular detection patterns for plugins from GCOM and fallback to hardcoded ones FlagPluginsDynamicAngularDetectionPatterns = "pluginsDynamicAngularDetectionPatterns" // FlagAlertingLokiRangeToInstant // Rewrites eligible loki range queries to instant queries FlagAlertingLokiRangeToInstant = "alertingLokiRangeToInstant" // FlagVizAndWidgetSplit // Split panels between vizualizations and widgets FlagVizAndWidgetSplit = "vizAndWidgetSplit" // FlagPrometheusIncrementalQueryInstrumentation // Adds RudderStack events to incremental queries FlagPrometheusIncrementalQueryInstrumentation = "prometheusIncrementalQueryInstrumentation" // FlagLogsExploreTableVisualisation // A table visualisation for logs in Explore FlagLogsExploreTableVisualisation = "logsExploreTableVisualisation" // FlagAwsDatasourcesTempCredentials // Support temporary security credentials in AWS plugins for Grafana Cloud customers FlagAwsDatasourcesTempCredentials = "awsDatasourcesTempCredentials" // FlagTransformationsRedesign // Enables the transformations redesign FlagTransformationsRedesign = "transformationsRedesign" // FlagToggleLabelsInLogsUI // Enable toggleable filters in log details view FlagToggleLabelsInLogsUI = "toggleLabelsInLogsUI" // FlagMlExpressions // Enable support for Machine Learning in server-side expressions FlagMlExpressions = "mlExpressions" // FlagTraceQLStreaming // Enables response streaming of TraceQL queries of the Tempo data source FlagTraceQLStreaming = "traceQLStreaming" // FlagGrafanaAPIServer // Enable Kubernetes API Server for Grafana resources FlagGrafanaAPIServer = "grafanaAPIServer" // FlagFeatureToggleAdminPage // Enable admin page for managing feature toggles from the Grafana front-end FlagFeatureToggleAdminPage = "featureToggleAdminPage" // FlagAwsAsyncQueryCaching // Enable caching for async queries for Redshift and Athena. Requires that the `useCachingService` feature toggle is enabled and the datasource has caching and async query support enabled FlagAwsAsyncQueryCaching = "awsAsyncQueryCaching" // FlagSplitScopes // Support faster dashboard and folder search by splitting permission scopes into parts FlagSplitScopes = "splitScopes" // FlagAzureMonitorDataplane // Adds dataplane compliant frame metadata in the Azure Monitor datasource FlagAzureMonitorDataplane = "azureMonitorDataplane" // FlagPermissionsFilterRemoveSubquery // Alternative permission filter implementation that does not use subqueries for fetching the dashboard folder FlagPermissionsFilterRemoveSubquery = "permissionsFilterRemoveSubquery" // FlagPrometheusConfigOverhaulAuth // Update the Prometheus configuration page with the new auth component FlagPrometheusConfigOverhaulAuth = "prometheusConfigOverhaulAuth" // FlagConfigurableSchedulerTick // Enable changing the scheduler base interval via configuration option unified_alerting.scheduler_tick_interval FlagConfigurableSchedulerTick = "configurableSchedulerTick" // FlagInfluxdbSqlSupport // Enable InfluxDB SQL query language support with new querying UI FlagInfluxdbSqlSupport = "influxdbSqlSupport" )
pkg/services/featuremgmt/toggles_gen.go
1
https://github.com/grafana/grafana/commit/64ed77ddce79009ce05f43801cc578c135f05b6b
[ 0.00017980171833187342, 0.00017555053636897355, 0.00016899965703487396, 0.0001760138984536752, 0.0000025761935376067413 ]
{ "id": 7, "code_window": [ "import { OrgRole } from 'app/types';\n", "\n", "import { getStyles } from './styles';\n", "\n", "const BasicRoleOption: Array<SelectableValue<OrgRole>> = Object.values(OrgRole).map((r) => ({\n", " label: r === OrgRole.None ? 'No basic role' : r,\n", " value: r,\n", "}));\n", "\n", "interface Props {\n", " value?: OrgRole;\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ "const noBasicRoleFlag = contextSrv.licensedAccessControlEnabled();\n", "\n", "const noBasicRole = config.featureToggles.noBasicRole && noBasicRoleFlag;\n", "\n", "const BasicRoleOption: Array<SelectableValue<OrgRole>> = Object.values(OrgRole)\n", " .filter((r) => noBasicRole || r !== OrgRole.None)\n", " .map((r) => ({\n", " label: r === OrgRole.None ? 'No basic role' : r,\n", " value: r,\n", " }));\n" ], "file_path": "public/app/core/components/RolePicker/BuiltinRoleSelector.tsx", "type": "replace", "edit_start_line_idx": 8 }
<svg xmlns="http://www.w3.org/2000/svg" enable-background="new 0 0 24 24" viewBox="0 0 24 24"><path d="M16.9,13.4l-4.2-4.2l0,0c-0.4-0.4-1-0.4-1.4,0l-4.2,4.2c-0.4,0.4-0.4,1,0,1.4s1,0.4,1.4,0l3.5-3.5l3.5,3.5c0.2,0.2,0.4,0.3,0.7,0.3l0,0c0.3,0,0.5-0.1,0.7-0.3C17.3,14.4,17.3,13.8,16.9,13.4z"/></svg>
public/img/icons/solid/angle-up.svg
0
https://github.com/grafana/grafana/commit/64ed77ddce79009ce05f43801cc578c135f05b6b
[ 0.0001764792250469327, 0.0001764792250469327, 0.0001764792250469327, 0.0001764792250469327, 0 ]
{ "id": 7, "code_window": [ "import { OrgRole } from 'app/types';\n", "\n", "import { getStyles } from './styles';\n", "\n", "const BasicRoleOption: Array<SelectableValue<OrgRole>> = Object.values(OrgRole).map((r) => ({\n", " label: r === OrgRole.None ? 'No basic role' : r,\n", " value: r,\n", "}));\n", "\n", "interface Props {\n", " value?: OrgRole;\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ "const noBasicRoleFlag = contextSrv.licensedAccessControlEnabled();\n", "\n", "const noBasicRole = config.featureToggles.noBasicRole && noBasicRoleFlag;\n", "\n", "const BasicRoleOption: Array<SelectableValue<OrgRole>> = Object.values(OrgRole)\n", " .filter((r) => noBasicRole || r !== OrgRole.None)\n", " .map((r) => ({\n", " label: r === OrgRole.None ? 'No basic role' : r,\n", " value: r,\n", " }));\n" ], "file_path": "public/app/core/components/RolePicker/BuiltinRoleSelector.tsx", "type": "replace", "edit_start_line_idx": 8 }
import React, { useMemo } from 'react'; import { SelectableValue } from '@grafana/data'; import { EditorField } from '@grafana/experimental'; import { Select } from '@grafana/ui'; import { getAggregationOptionsByMetric } from '../functions'; import { MetricKind, ValueTypes } from '../types/query'; import { MetricDescriptor } from '../types/types'; export interface Props { refId: string; onChange: (metricDescriptor: string) => void; metricDescriptor?: MetricDescriptor; crossSeriesReducer: string; groupBys: string[]; templateVariableOptions: Array<SelectableValue<string>>; } export const Aggregation = (props: Props) => { const aggOptions = useAggregationOptionsByMetric(props); const selected = useSelectedFromOptions(aggOptions, props); return ( <EditorField label="Group by function" data-testid="cloud-monitoring-aggregation"> <Select width="auto" onChange={({ value }) => props.onChange(value!)} value={selected} options={[ { label: 'Template Variables', options: props.templateVariableOptions, }, { label: 'Aggregations', expanded: true, options: aggOptions, }, ]} placeholder="Select Reducer" inputId={`${props.refId}-group-by-function`} menuPlacement="top" /> </EditorField> ); }; const useAggregationOptionsByMetric = ({ metricDescriptor }: Props): Array<SelectableValue<string>> => { const valueType = metricDescriptor?.valueType; const metricKind = metricDescriptor?.metricKind; return useMemo(() => { if (!valueType || !metricKind) { return []; } return getAggregationOptionsByMetric(valueType as ValueTypes, metricKind as MetricKind).map((a) => ({ ...a, label: a.text, })); }, [valueType, metricKind]); }; const useSelectedFromOptions = (aggOptions: Array<SelectableValue<string>>, props: Props) => { return useMemo(() => { const allOptions = [...aggOptions, ...props.templateVariableOptions]; return allOptions.find((s) => s.value === props.crossSeriesReducer); }, [aggOptions, props.crossSeriesReducer, props.templateVariableOptions]); };
public/app/plugins/datasource/cloud-monitoring/components/Aggregation.tsx
0
https://github.com/grafana/grafana/commit/64ed77ddce79009ce05f43801cc578c135f05b6b
[ 0.9985584616661072, 0.43766647577285767, 0.00016975257312878966, 0.2830672264099121, 0.4556705057621002 ]
{ "id": 7, "code_window": [ "import { OrgRole } from 'app/types';\n", "\n", "import { getStyles } from './styles';\n", "\n", "const BasicRoleOption: Array<SelectableValue<OrgRole>> = Object.values(OrgRole).map((r) => ({\n", " label: r === OrgRole.None ? 'No basic role' : r,\n", " value: r,\n", "}));\n", "\n", "interface Props {\n", " value?: OrgRole;\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ "const noBasicRoleFlag = contextSrv.licensedAccessControlEnabled();\n", "\n", "const noBasicRole = config.featureToggles.noBasicRole && noBasicRoleFlag;\n", "\n", "const BasicRoleOption: Array<SelectableValue<OrgRole>> = Object.values(OrgRole)\n", " .filter((r) => noBasicRole || r !== OrgRole.None)\n", " .map((r) => ({\n", " label: r === OrgRole.None ? 'No basic role' : r,\n", " value: r,\n", " }));\n" ], "file_path": "public/app/core/components/RolePicker/BuiltinRoleSelector.tsx", "type": "replace", "edit_start_line_idx": 8 }
package remotecache import ( "context" "testing" "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/grafana/grafana/pkg/infra/db" "github.com/grafana/grafana/pkg/infra/usagestats" "github.com/grafana/grafana/pkg/services/secrets" "github.com/grafana/grafana/pkg/services/secrets/fakes" "github.com/grafana/grafana/pkg/setting" ) func createTestClient(t *testing.T, opts *setting.RemoteCacheOptions, sqlstore db.DB) CacheStorage { t.Helper() cfg := &setting.Cfg{ RemoteCacheOptions: opts, } dc, err := ProvideService(cfg, sqlstore, &usagestats.UsageStatsMock{}, fakes.NewFakeSecretsService()) require.Nil(t, err, "Failed to init client for test") return dc } func TestCachedBasedOnConfig(t *testing.T) { cfg := setting.NewCfg() err := cfg.Load(setting.CommandLineArgs{ HomePath: "../../../", }) require.Nil(t, err, "Failed to load config") client := createTestClient(t, cfg.RemoteCacheOptions, db.InitTestDB(t)) runTestsForClient(t, client) runCountTestsForClient(t, cfg.RemoteCacheOptions, db.InitTestDB(t)) } func TestInvalidCacheTypeReturnsError(t *testing.T) { _, err := createClient(&setting.RemoteCacheOptions{Name: "invalid"}, nil, nil) assert.Equal(t, err, ErrInvalidCacheType) } func runTestsForClient(t *testing.T, client CacheStorage) { canPutGetAndDeleteCachedObjects(t, client) canNotFetchExpiredItems(t, client) } func runCountTestsForClient(t *testing.T, opts *setting.RemoteCacheOptions, sqlstore db.DB) { client := createTestClient(t, opts, sqlstore) expectError := false if opts.Name == memcachedCacheType { expectError = true } t.Run("can count items", func(t *testing.T) { cacheableValue := []byte("hej hej") err := client.Set(context.Background(), "pref-key1", cacheableValue, 0) require.NoError(t, err) err = client.Set(context.Background(), "pref-key2", cacheableValue, 0) require.NoError(t, err) err = client.Set(context.Background(), "key3-not-pref", cacheableValue, 0) require.NoError(t, err) n, errC := client.Count(context.Background(), "pref-") if expectError { require.ErrorIs(t, ErrNotImplemented, errC) assert.Equal(t, int64(0), n) return } require.NoError(t, errC) assert.Equal(t, int64(2), n) }) } func canPutGetAndDeleteCachedObjects(t *testing.T, client CacheStorage) { dataToCache := []byte("some bytes") err := client.Set(context.Background(), "key1", dataToCache, 0) assert.Equal(t, err, nil, "expected nil. got: ", err) data, err := client.Get(context.Background(), "key1") assert.Equal(t, err, nil) assert.Equal(t, string(data), "some bytes") err = client.Delete(context.Background(), "key1") assert.Equal(t, err, nil) _, err = client.Get(context.Background(), "key1") // redis client returns redis.Nil error when key does not exist. assert.Error(t, err) } func canNotFetchExpiredItems(t *testing.T, client CacheStorage) { dataToCache := []byte("some bytes") err := client.Set(context.Background(), "key1", dataToCache, time.Second) assert.Equal(t, err, nil) // not sure how this can be avoided when testing redis/memcached :/ <-time.After(time.Second + time.Millisecond) // should not be able to read that value since its expired _, err = client.Get(context.Background(), "key1") // redis client returns redis.Nil error when key does not exist. assert.Error(t, err) } func TestCollectUsageStats(t *testing.T) { wantMap := map[string]interface{}{ "stats.remote_cache.redis.count": 1, "stats.remote_cache.encrypt_enabled.count": 1, } cfg := setting.NewCfg() cfg.RemoteCacheOptions = &setting.RemoteCacheOptions{Name: redisCacheType, Encryption: true} remoteCache := &RemoteCache{ Cfg: cfg, } stats, err := remoteCache.getUsageStats(context.Background()) require.NoError(t, err) assert.EqualValues(t, wantMap, stats) } func TestCachePrefix(t *testing.T) { cache := NewFakeCacheStorage() prefixCache := &prefixCacheStorage{cache: cache, prefix: "test/"} // Set a value (with a prefix) err := prefixCache.Set(context.Background(), "foo", []byte("bar"), time.Hour) require.NoError(t, err) // Get a value (with a prefix) v, err := prefixCache.Get(context.Background(), "foo") require.NoError(t, err) require.Equal(t, "bar", string(v)) // Get a value directly from the underlying cache, ensure the prefix is in the key v, err = cache.Get(context.Background(), "test/foo") require.NoError(t, err) require.Equal(t, "bar", string(v)) // Get a value directly from the underlying cache without a prefix, should not be there _, err = cache.Get(context.Background(), "foo") require.Error(t, err) } func TestEncryptedCache(t *testing.T) { cache := NewFakeCacheStorage() encryptedCache := &encryptedCacheStorage{cache: cache, secretsService: &fakeSecretsService{}} // Set a value in the encrypted cache err := encryptedCache.Set(context.Background(), "foo", []byte("bar"), time.Hour) require.NoError(t, err) // make sure the stored value is not equal to input v, err := cache.Get(context.Background(), "foo") require.NoError(t, err) require.NotEqual(t, "bar", string(v)) // make sure the returned value is the same as orignial v, err = encryptedCache.Get(context.Background(), "foo") require.NoError(t, err) require.Equal(t, "bar", string(v)) } type fakeSecretsService struct{} func (f fakeSecretsService) Encrypt(_ context.Context, payload []byte, _ secrets.EncryptionOptions) ([]byte, error) { return f.reverse(payload), nil } func (f fakeSecretsService) Decrypt(_ context.Context, payload []byte) ([]byte, error) { return f.reverse(payload), nil } func (f fakeSecretsService) reverse(input []byte) []byte { r := []rune(string(input)) for i, j := 0, len(r)-1; i < len(r)/2; i, j = i+1, j-1 { r[i], r[j] = r[j], r[i] } return []byte(string(r)) }
pkg/infra/remotecache/remotecache_test.go
0
https://github.com/grafana/grafana/commit/64ed77ddce79009ce05f43801cc578c135f05b6b
[ 0.00017931258480530232, 0.00017557773389853537, 0.000165182413184084, 0.00017696505528874695, 0.000004011991222796496 ]
{ "id": 8, "code_window": [ "import { css, cx } from '@emotion/css';\n", "import React, { useEffect, useRef, useState } from 'react';\n", "\n", "import { Button, CustomScrollbar, HorizontalGroup, useStyles2, useTheme2 } from '@grafana/ui';\n", "import { getSelectStyles } from '@grafana/ui/src/components/Select/getSelectStyles';\n", "import { contextSrv } from 'app/core/core';\n", "import { OrgRole, Role } from 'app/types';\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { config } from '@grafana/runtime';\n" ], "file_path": "public/app/core/components/RolePicker/RolePickerMenu.tsx", "type": "add", "edit_start_line_idx": 3 }
import React from 'react'; import { SelectableValue } from '@grafana/data'; import { Icon, RadioButtonList, Tooltip, useStyles2, useTheme2 } from '@grafana/ui'; import { OrgRole } from 'app/types'; import { getStyles } from './styles'; const BasicRoleOption: Array<SelectableValue<OrgRole>> = Object.values(OrgRole).map((r) => ({ label: r === OrgRole.None ? 'No basic role' : r, value: r, })); interface Props { value?: OrgRole; onChange: (value: OrgRole) => void; disabled?: boolean; disabledMesssage?: string; tooltipMessage?: string; } export const BuiltinRoleSelector = ({ value, onChange, disabled, disabledMesssage, tooltipMessage }: Props) => { const styles = useStyles2(getStyles); const theme = useTheme2(); return ( <> <div className={styles.groupHeader}> <span style={{ marginRight: theme.spacing(1) }}>Basic roles</span> {disabled && disabledMesssage && ( <Tooltip placement="right-end" interactive={true} content={<div>{disabledMesssage}</div>}> <Icon name="question-circle" /> </Tooltip> )} {!disabled && tooltipMessage && ( <Tooltip placement="right-end" interactive={true} content={tooltipMessage}> <Icon name="info-circle" size="xs" /> </Tooltip> )} </div> <RadioButtonList name="Basic Role Selector" className={styles.basicRoleSelector} options={BasicRoleOption} value={value} onChange={onChange} disabled={disabled} /> </> ); };
public/app/core/components/RolePicker/BuiltinRoleSelector.tsx
1
https://github.com/grafana/grafana/commit/64ed77ddce79009ce05f43801cc578c135f05b6b
[ 0.0005305722588673234, 0.00027624412905424833, 0.00016681922716088593, 0.00020098598906770349, 0.00013669635518454015 ]
{ "id": 8, "code_window": [ "import { css, cx } from '@emotion/css';\n", "import React, { useEffect, useRef, useState } from 'react';\n", "\n", "import { Button, CustomScrollbar, HorizontalGroup, useStyles2, useTheme2 } from '@grafana/ui';\n", "import { getSelectStyles } from '@grafana/ui/src/components/Select/getSelectStyles';\n", "import { contextSrv } from 'app/core/core';\n", "import { OrgRole, Role } from 'app/types';\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { config } from '@grafana/runtime';\n" ], "file_path": "public/app/core/components/RolePicker/RolePickerMenu.tsx", "type": "add", "edit_start_line_idx": 3 }
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 82.59 82.5"><defs><style>.cls-1{fill:#3865ab;}.cls-2{fill:#84aff1;}.cls-3{fill:url(#linear-gradient);}</style><linearGradient id="linear-gradient" y1="21.17" x2="82.59" y2="21.17" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#f2cc0c"/><stop offset="1" stop-color="#ff9830"/></linearGradient></defs><g id="Layer_2" data-name="Layer 2"><g id="Layer_1-2" data-name="Layer 1"><rect class="cls-1" x="73.22" y="19.61" width="8" height="62.89" rx="1"/><rect class="cls-1" x="1.78" y="53.61" width="8" height="28.89" rx="1"/><path class="cls-2" d="M8.78,82.5h-6a1,1,0,0,1-1-1V71.61h8V81.5A1,1,0,0,1,8.78,82.5Z"/><path class="cls-2" d="M80.22,82.5h-6a1,1,0,0,1-1-1V46.61h8V81.5A1,1,0,0,1,80.22,82.5Z"/><rect class="cls-1" x="58.93" y="49.61" width="8" height="32.89" rx="1"/><path class="cls-2" d="M65.93,82.5h-6a1,1,0,0,1-1-1V64.61h8V81.5A1,1,0,0,1,65.93,82.5Z"/><rect class="cls-1" x="44.64" y="38.61" width="8" height="43.89" rx="1"/><path class="cls-2" d="M51.64,82.5h-6a1,1,0,0,1-1-1V75.61h8V81.5A1,1,0,0,1,51.64,82.5Z"/><rect class="cls-1" x="30.36" y="27.61" width="8" height="54.89" rx="1"/><path class="cls-2" d="M37.36,82.5h-6a1,1,0,0,1-1-1V42.61h8V81.5A1,1,0,0,1,37.36,82.5Z"/><rect class="cls-1" x="16.07" y="37.61" width="8" height="44.89" rx="1"/><path class="cls-2" d="M23.07,82.5h-6a1,1,0,0,1-1-1V55.61h8V81.5A1,1,0,0,1,23.07,82.5Z"/><path class="cls-3" d="M2,42.33a2,2,0,0,1-1.44-.61,2,2,0,0,1,0-2.83l26-25a2,2,0,0,1,2.2-.39L54.56,25,79.18.58A2,2,0,0,1,82,3.42L56.41,28.75a2,2,0,0,1-2.22.41L28.42,17.71l-25,24.06A2,2,0,0,1,2,42.33Z"/></g></g></svg>
public/app/plugins/panel/timeseries/img/icn-graph-panel.svg
0
https://github.com/grafana/grafana/commit/64ed77ddce79009ce05f43801cc578c135f05b6b
[ 0.00016592767497058958, 0.00016592767497058958, 0.00016592767497058958, 0.00016592767497058958, 0 ]
{ "id": 8, "code_window": [ "import { css, cx } from '@emotion/css';\n", "import React, { useEffect, useRef, useState } from 'react';\n", "\n", "import { Button, CustomScrollbar, HorizontalGroup, useStyles2, useTheme2 } from '@grafana/ui';\n", "import { getSelectStyles } from '@grafana/ui/src/components/Select/getSelectStyles';\n", "import { contextSrv } from 'app/core/core';\n", "import { OrgRole, Role } from 'app/types';\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { config } from '@grafana/runtime';\n" ], "file_path": "public/app/core/components/RolePicker/RolePickerMenu.tsx", "type": "add", "edit_start_line_idx": 3 }
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M20.67,5.85a2.63,2.63,0,0,0-2.67,0L14,8.15h0a2.67,2.67,0,0,0-4-2.31L3.33,9.69a2.67,2.67,0,0,0,0,4.62L10,18.16a2.66,2.66,0,0,0,2.67,0A2.65,2.65,0,0,0,14,15.85h0l4,2.31a2.69,2.69,0,0,0,1.33.36,2.61,2.61,0,0,0,1.34-.37A2.63,2.63,0,0,0,22,15.85V8.15A2.63,2.63,0,0,0,20.67,5.85ZM12,15.85a.66.66,0,0,1-.33.58.69.69,0,0,1-.67,0L4.33,12.58a.67.67,0,0,1,0-1.16L11,7.57a.67.67,0,0,1,.67,0,.66.66,0,0,1,.33.58Zm8,0a.67.67,0,0,1-1,.57l-5-2.88V10.46l5-2.88a.67.67,0,0,1,1,.57Z"/></svg>
public/img/icons/unicons/backward.svg
0
https://github.com/grafana/grafana/commit/64ed77ddce79009ce05f43801cc578c135f05b6b
[ 0.00016490498092025518, 0.00016490498092025518, 0.00016490498092025518, 0.00016490498092025518, 0 ]
{ "id": 8, "code_window": [ "import { css, cx } from '@emotion/css';\n", "import React, { useEffect, useRef, useState } from 'react';\n", "\n", "import { Button, CustomScrollbar, HorizontalGroup, useStyles2, useTheme2 } from '@grafana/ui';\n", "import { getSelectStyles } from '@grafana/ui/src/components/Select/getSelectStyles';\n", "import { contextSrv } from 'app/core/core';\n", "import { OrgRole, Role } from 'app/types';\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { config } from '@grafana/runtime';\n" ], "file_path": "public/app/core/components/RolePicker/RolePickerMenu.tsx", "type": "add", "edit_start_line_idx": 3 }
import { PanelPluginMeta, escapeStringForRegex } from '@grafana/data'; import { filterPluginList } from './util'; describe('panel state utils', () => { it('should include timeseries in a graph query', async () => { const pluginsList = [ { id: 'graph', name: 'Graph (old)' }, { id: 'timeseries', name: 'Graph (old)' }, { id: 'timeline', name: 'Timeline' }, ] as PanelPluginMeta[]; const found = filterPluginList(pluginsList, escapeStringForRegex('gra'), { id: 'xyz' } as PanelPluginMeta); expect(found.map((v) => v.id)).toEqual(['graph', 'timeseries']); }); it('should handle escaped regex characters in the search query (e.g. -)', async () => { const pluginsList = [ { id: 'graph', name: 'Graph (old)' }, { id: 'timeseries', name: 'Graph (old)' }, { id: 'timeline', name: 'Timeline' }, { id: 'panelwithdashes', name: 'Panel-With-Dashes' }, ] as PanelPluginMeta[]; const found = filterPluginList(pluginsList, escapeStringForRegex('panel-'), { id: 'xyz' } as PanelPluginMeta); expect(found.map((v) => v.id)).toEqual(['panelwithdashes']); }); });
public/app/features/panel/state/utils.test.ts
0
https://github.com/grafana/grafana/commit/64ed77ddce79009ce05f43801cc578c135f05b6b
[ 0.00017562095308676362, 0.00017070549074560404, 0.0001671179197728634, 0.00016937762848101556, 0.0000035960929380962625 ]
{ "id": 9, "code_window": [ " current: 'Current org',\n", "};\n", "\n", "const noBasicRoleFlag = contextSrv.licensedAccessControlEnabled();\n", "const tooltipMessage = noBasicRoleFlag\n", " ? 'You can now select the \"No basic role\" option and add permissions to your custom needs.'\n", " : undefined;\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "const noBasicRoleFlag = contextSrv.licensedAccessControlEnabled() && config.featureToggles.noBasicRole;\n" ], "file_path": "public/app/core/components/RolePicker/RolePickerMenu.tsx", "type": "replace", "edit_start_line_idx": 37 }
import React from 'react'; import { SelectableValue } from '@grafana/data'; import { Icon, RadioButtonList, Tooltip, useStyles2, useTheme2 } from '@grafana/ui'; import { OrgRole } from 'app/types'; import { getStyles } from './styles'; const BasicRoleOption: Array<SelectableValue<OrgRole>> = Object.values(OrgRole).map((r) => ({ label: r === OrgRole.None ? 'No basic role' : r, value: r, })); interface Props { value?: OrgRole; onChange: (value: OrgRole) => void; disabled?: boolean; disabledMesssage?: string; tooltipMessage?: string; } export const BuiltinRoleSelector = ({ value, onChange, disabled, disabledMesssage, tooltipMessage }: Props) => { const styles = useStyles2(getStyles); const theme = useTheme2(); return ( <> <div className={styles.groupHeader}> <span style={{ marginRight: theme.spacing(1) }}>Basic roles</span> {disabled && disabledMesssage && ( <Tooltip placement="right-end" interactive={true} content={<div>{disabledMesssage}</div>}> <Icon name="question-circle" /> </Tooltip> )} {!disabled && tooltipMessage && ( <Tooltip placement="right-end" interactive={true} content={tooltipMessage}> <Icon name="info-circle" size="xs" /> </Tooltip> )} </div> <RadioButtonList name="Basic Role Selector" className={styles.basicRoleSelector} options={BasicRoleOption} value={value} onChange={onChange} disabled={disabled} /> </> ); };
public/app/core/components/RolePicker/BuiltinRoleSelector.tsx
1
https://github.com/grafana/grafana/commit/64ed77ddce79009ce05f43801cc578c135f05b6b
[ 0.9878913164138794, 0.25084230303764343, 0.00017501162074040622, 0.0042443834245204926, 0.37782999873161316 ]
{ "id": 9, "code_window": [ " current: 'Current org',\n", "};\n", "\n", "const noBasicRoleFlag = contextSrv.licensedAccessControlEnabled();\n", "const tooltipMessage = noBasicRoleFlag\n", " ? 'You can now select the \"No basic role\" option and add permissions to your custom needs.'\n", " : undefined;\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "const noBasicRoleFlag = contextSrv.licensedAccessControlEnabled() && config.featureToggles.noBasicRole;\n" ], "file_path": "public/app/core/components/RolePicker/RolePickerMenu.tsx", "type": "replace", "edit_start_line_idx": 37 }
<svg xmlns="http://www.w3.org/2000/svg" data-name="Layer 1" viewBox="0 0 24 24"><path d="M14,15.5H11v-1A1,1,0,0,1,12.88,14a1,1,0,0,0,1.37.34A1,1,0,0,0,14.59,13a3.08,3.08,0,0,0-.46-.59A3,3,0,0,0,12,11.5a3,3,0,0,0-3,3v1.18a3,3,0,0,0,1,5.82h4a3,3,0,0,0,0-6Zm0,4H10a1,1,0,0,1,0-2h4a1,1,0,0,1,0,2ZM18.42,6.72A7,7,0,0,0,5.06,8.61a4,4,0,0,0-.38,7.66,1.13,1.13,0,0,0,.32.05,1,1,0,0,0,.32-2A2,2,0,0,1,4,12.5a2,2,0,0,1,2-2,1,1,0,0,0,1-1,5,5,0,0,1,9.73-1.61,1,1,0,0,0,.78.67,3,3,0,0,1,1,5.53,1,1,0,1,0,1,1.74A5,5,0,0,0,22,11.5,5,5,0,0,0,18.42,6.72Z"/></svg>
public/img/icons/unicons/cloud-unlock.svg
0
https://github.com/grafana/grafana/commit/64ed77ddce79009ce05f43801cc578c135f05b6b
[ 0.0001646765012992546, 0.0001646765012992546, 0.0001646765012992546, 0.0001646765012992546, 0 ]
{ "id": 9, "code_window": [ " current: 'Current org',\n", "};\n", "\n", "const noBasicRoleFlag = contextSrv.licensedAccessControlEnabled();\n", "const tooltipMessage = noBasicRoleFlag\n", " ? 'You can now select the \"No basic role\" option and add permissions to your custom needs.'\n", " : undefined;\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "const noBasicRoleFlag = contextSrv.licensedAccessControlEnabled() && config.featureToggles.noBasicRole;\n" ], "file_path": "public/app/core/components/RolePicker/RolePickerMenu.tsx", "type": "replace", "edit_start_line_idx": 37 }
import { PanelPluginMeta, escapeStringForRegex } from '@grafana/data'; import { filterPluginList } from './util'; describe('panel state utils', () => { it('should include timeseries in a graph query', async () => { const pluginsList = [ { id: 'graph', name: 'Graph (old)' }, { id: 'timeseries', name: 'Graph (old)' }, { id: 'timeline', name: 'Timeline' }, ] as PanelPluginMeta[]; const found = filterPluginList(pluginsList, escapeStringForRegex('gra'), { id: 'xyz' } as PanelPluginMeta); expect(found.map((v) => v.id)).toEqual(['graph', 'timeseries']); }); it('should handle escaped regex characters in the search query (e.g. -)', async () => { const pluginsList = [ { id: 'graph', name: 'Graph (old)' }, { id: 'timeseries', name: 'Graph (old)' }, { id: 'timeline', name: 'Timeline' }, { id: 'panelwithdashes', name: 'Panel-With-Dashes' }, ] as PanelPluginMeta[]; const found = filterPluginList(pluginsList, escapeStringForRegex('panel-'), { id: 'xyz' } as PanelPluginMeta); expect(found.map((v) => v.id)).toEqual(['panelwithdashes']); }); });
public/app/features/panel/state/utils.test.ts
0
https://github.com/grafana/grafana/commit/64ed77ddce79009ce05f43801cc578c135f05b6b
[ 0.00017321365885436535, 0.00017197354463860393, 0.00017031289462465793, 0.00017239409498870373, 0.0000012209974329380202 ]
{ "id": 9, "code_window": [ " current: 'Current org',\n", "};\n", "\n", "const noBasicRoleFlag = contextSrv.licensedAccessControlEnabled();\n", "const tooltipMessage = noBasicRoleFlag\n", " ? 'You can now select the \"No basic role\" option and add permissions to your custom needs.'\n", " : undefined;\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "const noBasicRoleFlag = contextSrv.licensedAccessControlEnabled() && config.featureToggles.noBasicRole;\n" ], "file_path": "public/app/core/components/RolePicker/RolePickerMenu.tsx", "type": "replace", "edit_start_line_idx": 37 }
import { render, waitFor } from '@testing-library/react'; import React from 'react'; import InfluxDatasource from '../../../../../datasource'; import { getMockDS, getMockDSInstanceSettings } from '../../../../../specs/mocks'; import { InfluxQuery } from '../../../../../types'; import { VisualInfluxQLEditor } from './VisualInfluxQLEditor'; // we mock the @grafana/ui components we use to make sure they just show their "value". // we mostly need this for `Input`, because that one is not visible with `.textContent`, // but i have decided to do all we use to be consistent here. jest.mock('@grafana/ui', () => { const Input = ({ value, placeholder }: { value: string; placeholder?: string }) => ( <span>[{value || placeholder}]</span> ); const WithContextMenu = ({ children }: { children: (x: unknown) => JSX.Element }) => ( <span>[{children({ openMenu: undefined })}]</span> ); const Select = ({ value }: { value: string }) => <span>[{value}]</span>; const orig = jest.requireActual('@grafana/ui'); return { ...orig, Input, WithContextMenu, Select, }; }); jest.mock('./Seg', () => { const Seg = ({ value }: { value: string }) => <span>[{value}]</span>; return { Seg, }; }); async function assertEditor(query: InfluxQuery, textContent: string) { const onChange = jest.fn(); const onRunQuery = jest.fn(); const datasource: InfluxDatasource = getMockDS(getMockDSInstanceSettings()); datasource.metricFindQuery = () => Promise.resolve([]); const { container } = render( <VisualInfluxQLEditor query={query} datasource={datasource} onChange={onChange} onRunQuery={onRunQuery} /> ); await waitFor(() => { expect(container.textContent).toBe(textContent); }); } describe('InfluxDB InfluxQL Visual Editor', () => { it('should handle minimal query', async () => { const query: InfluxQuery = { refId: 'A', policy: 'default', }; await assertEditor( query, 'FROM[default][select measurement]WHERE[+]' + 'SELECT[field]([value])[mean]()[+]' + 'GROUP BY[time]([$__interval])[fill]([null])[+]' + 'TIMEZONE[(optional)]ORDER BY TIME[ASC]' + 'LIMIT[(optional)]SLIMIT[(optional)]' + 'FORMAT AS[time_series]ALIAS[Naming pattern]' ); }); it('should have the alias-field hidden when format-as-table', async () => { const query: InfluxQuery = { refId: 'A', alias: 'test-alias', resultFormat: 'table', policy: 'default', }; await assertEditor( query, 'FROM[default][select measurement]WHERE[+]' + 'SELECT[field]([value])[mean]()[+]' + 'GROUP BY[time]([$__interval])[fill]([null])[+]' + 'TIMEZONE[(optional)]ORDER BY TIME[ASC]' + 'LIMIT[(optional)]SLIMIT[(optional)]' + 'FORMAT AS[table]' ); }); it('should handle complex query', async () => { const query: InfluxQuery = { refId: 'A', policy: 'default', resultFormat: 'logs', orderByTime: 'DESC', tags: [ { key: 'cpu', operator: '=', value: 'cpu1', }, { condition: 'AND', key: 'cpu', operator: '<', value: 'cpu3', }, ], groupBy: [ { type: 'time', params: ['$__interval'], }, { type: 'tag', params: ['cpu'], }, { type: 'tag', params: ['host'], }, { type: 'fill', params: ['null'], }, ], select: [ [ { type: 'field', params: ['usage_idle'], }, { type: 'mean', params: [], }, ], [ { type: 'field', params: ['usage_guest'], }, { type: 'median', params: [], }, { type: 'holt_winters_with_fit', params: [10, 2], }, ], ], measurement: 'cpu', limit: '4', slimit: '5', tz: 'UTC', alias: 'all i as', }; await assertEditor( query, 'FROM[default][cpu]WHERE[cpu][=][cpu1][AND][cpu][<][cpu3][+]' + 'SELECT[field]([usage_idle])[mean]()[+]' + '[field]([usage_guest])[median]()[holt_winters_with_fit]([10],[2])[+]' + 'GROUP BY[time]([$__interval])[tag]([cpu])[tag]([host])[fill]([null])[+]' + 'TIMEZONE[UTC]ORDER BY TIME[DESC]' + 'LIMIT[4]SLIMIT[5]' + 'FORMAT AS[logs]ALIAS[all i as]' ); }); });
public/app/plugins/datasource/influxdb/components/editor/query/influxql/visual/VisualInfluxQLEditor.test.tsx
0
https://github.com/grafana/grafana/commit/64ed77ddce79009ce05f43801cc578c135f05b6b
[ 0.0001773040130501613, 0.00017196839326061308, 0.0001643480354687199, 0.00017232654499821365, 0.0000033998835533566307 ]
{ "id": 10, "code_window": [ "import React from 'react';\n", "\n", "import { locationUtil, SelectableValue } from '@grafana/data';\n", "import { Stack } from '@grafana/experimental';\n", "import { locationService } from '@grafana/runtime';\n", "import {\n", " Button,\n", " LinkButton,\n", " Input,\n", " Switch,\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { config, locationService } from '@grafana/runtime';\n" ], "file_path": "public/app/features/org/UserInviteForm.tsx", "type": "replace", "edit_start_line_idx": 4 }
Name,Stage,Owner,requiresDevMode,RequiresLicense,RequiresRestart,FrontendOnly trimDefaults,preview,@grafana/grafana-as-code,false,false,false,false disableEnvelopeEncryption,GA,@grafana/grafana-as-code,false,false,false,false live-service-web-worker,experimental,@grafana/grafana-app-platform-squad,false,false,false,true queryOverLive,experimental,@grafana/grafana-app-platform-squad,false,false,false,true panelTitleSearch,preview,@grafana/grafana-app-platform-squad,false,false,false,false publicDashboards,preview,@grafana/dashboards-squad,false,false,false,false publicDashboardsEmailSharing,preview,@grafana/dashboards-squad,false,true,false,false lokiExperimentalStreaming,experimental,@grafana/observability-logs,false,false,false,false featureHighlights,GA,@grafana/grafana-as-code,false,false,false,false migrationLocking,preview,@grafana/backend-platform,false,false,false,false storage,experimental,@grafana/grafana-app-platform-squad,false,false,false,false correlations,preview,@grafana/explore-squad,false,false,false,false datasourceQueryMultiStatus,experimental,@grafana/plugins-platform-backend,false,false,false,false traceToMetrics,experimental,@grafana/observability-traces-and-profiling,false,false,false,true newDBLibrary,preview,@grafana/backend-platform,false,false,false,false validateDashboardsOnSave,preview,@grafana/grafana-as-code,false,false,true,false autoMigrateOldPanels,preview,@grafana/dataviz-squad,false,false,false,true disableAngular,preview,@grafana/dataviz-squad,false,false,false,true prometheusWideSeries,experimental,@grafana/observability-metrics,false,false,false,false canvasPanelNesting,experimental,@grafana/dataviz-squad,false,false,false,true scenes,experimental,@grafana/dashboards-squad,false,false,false,true disableSecretsCompatibility,experimental,@grafana/hosted-grafana-team,false,false,true,false logRequestsInstrumentedAsUnknown,experimental,@grafana/hosted-grafana-team,false,false,false,false dataConnectionsConsole,GA,@grafana/plugins-platform-backend,false,false,false,false topnav,deprecated,@grafana/grafana-frontend-platform,false,false,false,false grpcServer,preview,@grafana/grafana-app-platform-squad,false,false,false,false entityStore,experimental,@grafana/grafana-app-platform-squad,true,false,false,false cloudWatchCrossAccountQuerying,GA,@grafana/aws-datasources,false,false,false,false redshiftAsyncQueryDataSupport,GA,@grafana/aws-datasources,false,false,false,false athenaAsyncQueryDataSupport,GA,@grafana/aws-datasources,false,false,false,true newPanelChromeUI,GA,@grafana/dashboards-squad,false,false,false,true showDashboardValidationWarnings,experimental,@grafana/dashboards-squad,false,false,false,false mysqlAnsiQuotes,experimental,@grafana/backend-platform,false,false,false,false accessControlOnCall,preview,@grafana/grafana-authnz-team,false,false,false,false nestedFolders,preview,@grafana/backend-platform,false,false,false,false nestedFolderPicker,GA,@grafana/grafana-frontend-platform,false,false,false,true accessTokenExpirationCheck,GA,@grafana/grafana-authnz-team,false,false,false,false emptyDashboardPage,GA,@grafana/dashboards-squad,false,false,false,true disablePrometheusExemplarSampling,GA,@grafana/observability-metrics,false,false,false,false alertingBacktesting,experimental,@grafana/alerting-squad,false,false,false,false editPanelCSVDragAndDrop,experimental,@grafana/grafana-bi-squad,false,false,false,true alertingNoNormalState,preview,@grafana/alerting-squad,false,false,false,false logsContextDatasourceUi,GA,@grafana/observability-logs,false,false,false,true lokiQuerySplitting,GA,@grafana/observability-logs,false,false,false,true lokiQuerySplittingConfig,experimental,@grafana/observability-logs,false,false,false,true individualCookiePreferences,experimental,@grafana/backend-platform,false,false,false,false gcomOnlyExternalOrgRoleSync,GA,@grafana/grafana-authnz-team,false,false,false,false prometheusMetricEncyclopedia,GA,@grafana/observability-metrics,false,false,false,true timeSeriesTable,experimental,@grafana/app-o11y,false,false,false,true prometheusResourceBrowserCache,GA,@grafana/observability-metrics,false,false,false,true influxdbBackendMigration,preview,@grafana/observability-metrics,false,false,false,true clientTokenRotation,experimental,@grafana/grafana-authnz-team,false,false,false,false prometheusDataplane,GA,@grafana/observability-metrics,false,false,false,false lokiMetricDataplane,GA,@grafana/observability-logs,false,false,false,false lokiLogsDataplane,experimental,@grafana/observability-logs,false,false,false,false dataplaneFrontendFallback,GA,@grafana/observability-metrics,false,false,false,true disableSSEDataplane,experimental,@grafana/observability-metrics,false,false,false,false alertStateHistoryLokiSecondary,experimental,@grafana/alerting-squad,false,false,false,false alertingNotificationsPoliciesMatchingInstances,GA,@grafana/alerting-squad,false,false,false,true alertStateHistoryLokiPrimary,experimental,@grafana/alerting-squad,false,false,false,false alertStateHistoryLokiOnly,experimental,@grafana/alerting-squad,false,false,false,false unifiedRequestLog,experimental,@grafana/backend-platform,false,false,false,false renderAuthJWT,preview,@grafana/grafana-as-code,false,false,false,false externalServiceAuth,experimental,@grafana/grafana-authnz-team,true,false,false,false refactorVariablesTimeRange,preview,@grafana/dashboards-squad,false,false,false,false useCachingService,GA,@grafana/grafana-operator-experience-squad,false,false,true,false enableElasticsearchBackendQuerying,preview,@grafana/observability-logs,false,false,false,false advancedDataSourcePicker,GA,@grafana/dashboards-squad,false,false,false,true faroDatasourceSelector,preview,@grafana/app-o11y,false,false,false,true enableDatagridEditing,preview,@grafana/grafana-bi-squad,false,false,false,true dataSourcePageHeader,preview,@grafana/enterprise-datasources,false,false,false,true extraThemes,experimental,@grafana/grafana-frontend-platform,false,false,false,true lokiPredefinedOperations,experimental,@grafana/observability-logs,false,false,false,true pluginsFrontendSandbox,experimental,@grafana/plugins-platform-backend,false,false,false,true dashboardEmbed,experimental,@grafana/grafana-as-code,false,false,false,true frontendSandboxMonitorOnly,experimental,@grafana/plugins-platform-backend,false,false,false,true sqlDatasourceDatabaseSelection,preview,@grafana/grafana-bi-squad,false,false,false,true lokiFormatQuery,experimental,@grafana/observability-logs,false,false,false,true cloudWatchLogsMonacoEditor,experimental,@grafana/aws-datasources,false,false,false,true exploreScrollableLogsContainer,experimental,@grafana/observability-logs,false,false,false,true recordedQueriesMulti,experimental,@grafana/observability-metrics,false,false,false,false pluginsDynamicAngularDetectionPatterns,experimental,@grafana/plugins-platform-backend,false,false,false,false alertingLokiRangeToInstant,experimental,@grafana/alerting-squad,false,false,false,false vizAndWidgetSplit,experimental,@grafana/dashboards-squad,false,false,false,true prometheusIncrementalQueryInstrumentation,experimental,@grafana/observability-metrics,false,false,false,true logsExploreTableVisualisation,experimental,@grafana/observability-logs,false,false,false,true awsDatasourcesTempCredentials,experimental,@grafana/aws-datasources,false,false,false,false transformationsRedesign,GA,@grafana/observability-metrics,false,false,false,true toggleLabelsInLogsUI,experimental,@grafana/observability-logs,false,false,false,true mlExpressions,experimental,@grafana/alerting-squad,false,false,false,false traceQLStreaming,experimental,@grafana/observability-traces-and-profiling,false,false,false,true grafanaAPIServer,experimental,@grafana/grafana-app-platform-squad,false,false,false,false featureToggleAdminPage,experimental,@grafana/grafana-operator-experience-squad,false,false,true,false awsAsyncQueryCaching,experimental,@grafana/aws-datasources,false,false,false,false splitScopes,preview,@grafana/grafana-authnz-team,false,false,true,false azureMonitorDataplane,GA,@grafana/partner-datasources,false,false,false,false permissionsFilterRemoveSubquery,experimental,@grafana/backend-platform,false,false,false,false prometheusConfigOverhaulAuth,experimental,@grafana/observability-metrics,false,false,false,false configurableSchedulerTick,experimental,@grafana/alerting-squad,false,false,true,false influxdbSqlSupport,experimental,@grafana/observability-metrics,false,false,false,false
pkg/services/featuremgmt/toggles_gen.csv
1
https://github.com/grafana/grafana/commit/64ed77ddce79009ce05f43801cc578c135f05b6b
[ 0.0001885301317088306, 0.0001704996539046988, 0.00016455423610750586, 0.00016905188385862857, 0.000006259491328819422 ]
{ "id": 10, "code_window": [ "import React from 'react';\n", "\n", "import { locationUtil, SelectableValue } from '@grafana/data';\n", "import { Stack } from '@grafana/experimental';\n", "import { locationService } from '@grafana/runtime';\n", "import {\n", " Button,\n", " LinkButton,\n", " Input,\n", " Switch,\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { config, locationService } from '@grafana/runtime';\n" ], "file_path": "public/app/features/org/UserInviteForm.tsx", "type": "replace", "edit_start_line_idx": 4 }
package web import ( "encoding/json" "errors" "fmt" "io" "mime" "net/http" "reflect" ) // Bind deserializes JSON payload from the request func Bind(req *http.Request, v interface{}) error { if req.Body != nil { m, _, err := mime.ParseMediaType(req.Header.Get("Content-type")) if err != nil { return err } if m != "application/json" { return errors.New("bad content type") } defer func() { _ = req.Body.Close() }() err = json.NewDecoder(req.Body).Decode(v) if err != nil && !errors.Is(err, io.EOF) { return err } } return validate(v) } type Validator interface { Validate() error } func validate(obj interface{}) error { // First check if obj is nil, because we cannot validate those. if obj == nil { return nil } // Second, check if obj has a nil interface value. // This is to prevent panics when obj is an instance of uninitialised struct pointer / interface. t := reflect.TypeOf(obj) v := reflect.ValueOf(obj) if v.Kind() == reflect.Ptr && v.IsNil() { return nil } // If type has a Validate() method - use that if validator, ok := obj.(Validator); ok { return validator.Validate() } // Otherwise, use reflection to match `binding:"Required"` struct field tags. // Resolve all pointers and interfaces, until we get a concrete type. for v.Kind() == reflect.Interface || v.Kind() == reflect.Ptr { t = t.Elem() v = v.Elem() } switch v.Kind() { // For arrays and slices - iterate over each element and validate it recursively case reflect.Slice, reflect.Array: for i := 0; i < v.Len(); i++ { e := v.Index(i).Interface() if err := validate(e); err != nil { return err } } // For structs - iterate over each field, check for the "Required" constraint (Macaron legacy), then validate it recursively case reflect.Struct: for i := 0; i < v.NumField(); i++ { field := t.Field(i) value := v.Field(i) rule := field.Tag.Get("binding") if !value.CanInterface() { continue } if rule == "Required" { zero := reflect.Zero(field.Type).Interface() if value.Kind() == reflect.Slice { if value.Len() == 0 { return fmt.Errorf("required slice %s must not be empty", field.Name) } } else if reflect.DeepEqual(zero, value.Interface()) { return fmt.Errorf("required value %s must not be empty", field.Name) } } if err := validate(value.Interface()); err != nil { return err } } default: // ignore } return nil }
pkg/web/binding.go
0
https://github.com/grafana/grafana/commit/64ed77ddce79009ce05f43801cc578c135f05b6b
[ 0.0001776287390384823, 0.0001732430828269571, 0.0001680421264609322, 0.00017381642828695476, 0.000002960654455819167 ]
{ "id": 10, "code_window": [ "import React from 'react';\n", "\n", "import { locationUtil, SelectableValue } from '@grafana/data';\n", "import { Stack } from '@grafana/experimental';\n", "import { locationService } from '@grafana/runtime';\n", "import {\n", " Button,\n", " LinkButton,\n", " Input,\n", " Switch,\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { config, locationService } from '@grafana/runtime';\n" ], "file_path": "public/app/features/org/UserInviteForm.tsx", "type": "replace", "edit_start_line_idx": 4 }
export { default } from './ResourceField';
public/app/plugins/datasource/azuremonitor/components/ResourceField/index.tsx
0
https://github.com/grafana/grafana/commit/64ed77ddce79009ce05f43801cc578c135f05b6b
[ 0.00016428066010121256, 0.00016428066010121256, 0.00016428066010121256, 0.00016428066010121256, 0 ]
{ "id": 10, "code_window": [ "import React from 'react';\n", "\n", "import { locationUtil, SelectableValue } from '@grafana/data';\n", "import { Stack } from '@grafana/experimental';\n", "import { locationService } from '@grafana/runtime';\n", "import {\n", " Button,\n", " LinkButton,\n", " Input,\n", " Switch,\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { config, locationService } from '@grafana/runtime';\n" ], "file_path": "public/app/features/org/UserInviteForm.tsx", "type": "replace", "edit_start_line_idx": 4 }
package extensions import ( _ "cloud.google.com/go/kms/apiv1" _ "cloud.google.com/go/kms/apiv1/kmspb" _ "github.com/Azure/azure-sdk-for-go/sdk/azidentity" _ "github.com/Azure/azure-sdk-for-go/sdk/keyvault/azkeys" _ "github.com/Azure/azure-sdk-for-go/services/keyvault/v7.1/keyvault" _ "github.com/Azure/go-autorest/autorest" _ "github.com/Azure/go-autorest/autorest/adal" _ "github.com/beevik/etree" _ "github.com/blugelabs/bluge" _ "github.com/blugelabs/bluge_segment_api" _ "github.com/crewjam/saml" _ "github.com/go-jose/go-jose/v3" _ "github.com/gobwas/glob" _ "github.com/googleapis/gax-go/v2" _ "github.com/grafana/dskit/backoff" _ "github.com/grafana/dskit/flagext" _ "github.com/grpc-ecosystem/go-grpc-middleware" _ "github.com/jung-kurt/gofpdf" _ "github.com/linkedin/goavro/v2" _ "github.com/m3db/prometheus_remote_client_golang/promremote" _ "github.com/robfig/cron/v3" _ "github.com/russellhaering/goxmldsig" _ "github.com/stretchr/testify/require" _ "github.com/vectordotdev/go-datemath" _ "golang.org/x/time/rate" ) var IsEnterprise bool = false
pkg/extensions/main.go
0
https://github.com/grafana/grafana/commit/64ed77ddce79009ce05f43801cc578c135f05b6b
[ 0.0001753151009324938, 0.00017083866987377405, 0.00016539770876988769, 0.00017132092034444213, 0.000003632642119555385 ]
{ "id": 11, "code_window": [ "\n", "import { addInvitee } from '../invites/state/actions';\n", "\n", "const noBasicRoleFlag = contextSrv.licensedAccessControlEnabled();\n", "\n", "const tooltipMessage = noBasicRoleFlag\n", " ? 'You can now select the \"No basic role\" option and add permissions to your custom needs.'\n", " : undefined;\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "const noBasicRoleFlag = contextSrv.licensedAccessControlEnabled() && config.featureToggles.noBasicRole;\n" ], "file_path": "public/app/features/org/UserInviteForm.tsx", "type": "replace", "edit_start_line_idx": 25 }
import React from 'react'; import { SelectableValue } from '@grafana/data'; import { Icon, RadioButtonList, Tooltip, useStyles2, useTheme2 } from '@grafana/ui'; import { OrgRole } from 'app/types'; import { getStyles } from './styles'; const BasicRoleOption: Array<SelectableValue<OrgRole>> = Object.values(OrgRole).map((r) => ({ label: r === OrgRole.None ? 'No basic role' : r, value: r, })); interface Props { value?: OrgRole; onChange: (value: OrgRole) => void; disabled?: boolean; disabledMesssage?: string; tooltipMessage?: string; } export const BuiltinRoleSelector = ({ value, onChange, disabled, disabledMesssage, tooltipMessage }: Props) => { const styles = useStyles2(getStyles); const theme = useTheme2(); return ( <> <div className={styles.groupHeader}> <span style={{ marginRight: theme.spacing(1) }}>Basic roles</span> {disabled && disabledMesssage && ( <Tooltip placement="right-end" interactive={true} content={<div>{disabledMesssage}</div>}> <Icon name="question-circle" /> </Tooltip> )} {!disabled && tooltipMessage && ( <Tooltip placement="right-end" interactive={true} content={tooltipMessage}> <Icon name="info-circle" size="xs" /> </Tooltip> )} </div> <RadioButtonList name="Basic Role Selector" className={styles.basicRoleSelector} options={BasicRoleOption} value={value} onChange={onChange} disabled={disabled} /> </> ); };
public/app/core/components/RolePicker/BuiltinRoleSelector.tsx
1
https://github.com/grafana/grafana/commit/64ed77ddce79009ce05f43801cc578c135f05b6b
[ 0.9881165027618408, 0.329783171415329, 0.0001807871158234775, 0.0050565702840685844, 0.4626635015010834 ]
{ "id": 11, "code_window": [ "\n", "import { addInvitee } from '../invites/state/actions';\n", "\n", "const noBasicRoleFlag = contextSrv.licensedAccessControlEnabled();\n", "\n", "const tooltipMessage = noBasicRoleFlag\n", " ? 'You can now select the \"No basic role\" option and add permissions to your custom needs.'\n", " : undefined;\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "const noBasicRoleFlag = contextSrv.licensedAccessControlEnabled() && config.featureToggles.noBasicRole;\n" ], "file_path": "public/app/features/org/UserInviteForm.tsx", "type": "replace", "edit_start_line_idx": 25 }
<svg xmlns="http://www.w3.org/2000/svg" data-name="Layer 1" viewBox="0 0 24 24"><path d="M22.60107,2.062a1.00088,1.00088,0,0,0-.71289-.71289A11.25224,11.25224,0,0,0,10.46924,4.97217L9.35431,6.296l-2.6048-.62848A2.77733,2.77733,0,0,0,3.36279,7.0249L1.1626,10.9248A.99989.99989,0,0,0,1.82422,12.394l3.07275.65869a13.41952,13.41952,0,0,0-.55517,2.43409,1.00031,1.00031,0,0,0,.28466.83642l3.1001,3.1001a.99941.99941,0,0,0,.707.293c.02881,0,.05762-.00147.08692-.00391a12.16892,12.16892,0,0,0,2.49157-.49l.64368,3.00318a1.0003,1.0003,0,0,0,1.46924.66162l3.90527-2.20264a3.03526,3.03526,0,0,0,1.375-3.30371l-.6687-2.759,1.23706-1.13751A11.20387,11.20387,0,0,0,22.60107,2.062ZM3.57227,10.72314,5.12842,7.96338a.82552.82552,0,0,1,1.06982-.37549l1.71741.4162-.65.77179A13.09523,13.09523,0,0,0,5.67633,11.174Zm12.47021,8.22217L13.32666,20.477l-.4295-2.00464a11.33992,11.33992,0,0,0,2.41339-1.61987l.74353-.68366.40344,1.66462A1.041,1.041,0,0,1,16.04248,18.94531ZM17.65674,11.98l-3.68457,3.38623a9.77348,9.77348,0,0,1-5.17041,2.3042l-2.4043-2.4043a10.932,10.932,0,0,1,2.40088-5.206l1.67834-1.99268a.9635.9635,0,0,0,.07813-.09277L11.98975,6.271a9.27757,9.27757,0,0,1,8.80957-3.12012A9.21808,9.21808,0,0,1,17.65674,11.98Zm-.923-6.16376a1.5,1.5,0,1,0,1.5,1.5A1.49992,1.49992,0,0,0,16.7337,5.81622Z"/></svg>
public/img/icons/unicons/rocket.svg
0
https://github.com/grafana/grafana/commit/64ed77ddce79009ce05f43801cc578c135f05b6b
[ 0.00024286023108288646, 0.00024286023108288646, 0.00024286023108288646, 0.00024286023108288646, 0 ]
{ "id": 11, "code_window": [ "\n", "import { addInvitee } from '../invites/state/actions';\n", "\n", "const noBasicRoleFlag = contextSrv.licensedAccessControlEnabled();\n", "\n", "const tooltipMessage = noBasicRoleFlag\n", " ? 'You can now select the \"No basic role\" option and add permissions to your custom needs.'\n", " : undefined;\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "const noBasicRoleFlag = contextSrv.licensedAccessControlEnabled() && config.featureToggles.noBasicRole;\n" ], "file_path": "public/app/features/org/UserInviteForm.tsx", "type": "replace", "edit_start_line_idx": 25 }
import { editor } from 'monaco-editor'; import { Monaco, monacoTypes } from '@grafana/ui'; import { CompletionProvider } from './autocomplete'; import IEditorModel = editor.IEditorModel; describe('CompletionProvider', () => { it('suggests labels', async () => { const { provider, model } = await setup('{}', 1, defaultLabels); const result = await provider.provideCompletionItems(model, {} as monacoTypes.Position); expect((result! as monacoTypes.languages.CompletionList).suggestions).toEqual([ expect.objectContaining({ label: 'foo', insertText: 'foo' }), ]); }); it('suggests label names with quotes', async () => { const { provider, model } = await setup('{foo=}', 6, defaultLabels); const result = await provider.provideCompletionItems(model, {} as monacoTypes.Position); expect((result! as monacoTypes.languages.CompletionList).suggestions).toEqual([ expect.objectContaining({ label: 'bar', insertText: '"bar"' }), ]); }); it('suggests label names without quotes', async () => { const { provider, model } = await setup('{foo="}', 7, defaultLabels); const result = await provider.provideCompletionItems(model, {} as monacoTypes.Position); expect((result! as monacoTypes.languages.CompletionList).suggestions).toEqual([ expect.objectContaining({ label: 'bar', insertText: 'bar' }), ]); }); it('suggests nothing without labels', async () => { const { provider, model } = await setup('{foo="}', 7, {}); const result = await provider.provideCompletionItems(model, {} as monacoTypes.Position); expect((result! as monacoTypes.languages.CompletionList).suggestions).toEqual([]); }); it('suggests labels on empty input', async () => { const { provider, model } = await setup('', 0, defaultLabels); const result = await provider.provideCompletionItems(model, {} as monacoTypes.Position); expect((result! as monacoTypes.languages.CompletionList).suggestions).toEqual([ expect.objectContaining({ label: 'foo', insertText: '{foo="' }), ]); }); }); const defaultLabels = { foo: ['bar'] }; const fakeMonaco = { Range: { fromPositions() { return null; }, }, languages: { CompletionItemKind: { Enum: 1, EnumMember: 2, }, }, } as unknown as Monaco; function makeFakeEditor(model: IEditorModel) { return { getModel(): IEditorModel | null { return model; }, } as unknown as monacoTypes.editor.IStandaloneCodeEditor; } async function setup(value: string, offset: number, labels: { [label: string]: string[] }) { const model = makeModel(value, offset); const editor = makeFakeEditor(model); const provider = new CompletionProvider( { getLabelNames() { return Promise.resolve(Object.keys(labels)); }, getLabelValues(label: string) { return Promise.resolve(labels[label]); }, }, fakeMonaco, editor ); await provider.init(); return { provider, model }; } function makeModel(value: string, offset: number): monacoTypes.editor.ITextModel { return { id: 'test_monaco', getWordAtPosition() { return null; }, getOffsetAt() { return offset; }, getValue() { return value; }, } as unknown as monacoTypes.editor.ITextModel; }
public/app/plugins/datasource/parca/QueryEditor/autocomplete.test.ts
0
https://github.com/grafana/grafana/commit/64ed77ddce79009ce05f43801cc578c135f05b6b
[ 0.000186011049663648, 0.00017793434381019324, 0.000164744837093167, 0.0001793775736587122, 0.00000496950497108628 ]
{ "id": 11, "code_window": [ "\n", "import { addInvitee } from '../invites/state/actions';\n", "\n", "const noBasicRoleFlag = contextSrv.licensedAccessControlEnabled();\n", "\n", "const tooltipMessage = noBasicRoleFlag\n", " ? 'You can now select the \"No basic role\" option and add permissions to your custom needs.'\n", " : undefined;\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "const noBasicRoleFlag = contextSrv.licensedAccessControlEnabled() && config.featureToggles.noBasicRole;\n" ], "file_path": "public/app/features/org/UserInviteForm.tsx", "type": "replace", "edit_start_line_idx": 25 }
<svg xmlns="http://www.w3.org/2000/svg" enable-background="new 0 0 24 24" viewBox="0 0 24 24"><path d="M21.2,17.3l-2-2c-0.4-0.4-1-0.4-1.4,0c-0.4,0.4-0.4,1,0,1.4l0.3,0.3h-2.6c-0.6,0-1,0.4-1,1s0.4,1,1,1h2.6l-0.3,0.3c-0.2,0.2-0.3,0.4-0.3,0.7c0,0.6,0.4,1,1,1c0.3,0,0.5-0.1,0.7-0.3l2-2l0,0c0,0,0,0,0,0c0.1-0.1,0.2-0.2,0.2-0.3c0-0.1,0.1-0.2,0.1-0.4c0,0,0,0,0,0c0,0,0,0,0,0c0-0.1,0-0.3-0.1-0.4C21.4,17.5,21.3,17.4,21.2,17.3z M8.5,17H5.9l0.3-0.3c0.4-0.4,0.4-1,0-1.4c-0.4-0.4-1-0.4-1.4,0l-2,2c0,0,0,0,0,0l0,0c0,0,0,0,0,0c-0.1,0.1-0.2,0.2-0.2,0.3c0,0.1-0.1,0.2-0.1,0.4c0,0,0,0,0,0c0,0,0,0,0,0c0,0.1,0,0.3,0.1,0.4c0.1,0.1,0.1,0.2,0.2,0.3l2,2C5,20.9,5.2,21,5.5,21c0.3,0,0.5-0.1,0.7-0.3c0.4-0.4,0.4-1,0-1.4L5.9,19h2.6c0.6,0,1-0.4,1-1S9.1,17,8.5,17z M18,9.2c1.4,0,2.6-1.2,2.6-2.6S19.4,4,18,4c-1.4,0-2.6,1.2-2.6,2.6C15.4,8,16.6,9.2,18,9.2z M22.7,12.9c-2.1-2.6-5.9-3-8.5-0.9c-0.3,0.3-0.7,0.6-0.9,0.9c-0.4,0.6-0.4,1.4,0.2,1.8c0.2,0.2,0.5,0.3,0.8,0.3h1.9c0.1-0.3,0.3-0.5,0.5-0.8c1-1,2.6-1,3.5,0L21,15h0.6c0.7,0,1.3-0.6,1.3-1.3C23,13.4,22.9,13.1,22.7,12.9z M2.2,11.9c-0.3,0.3-0.7,0.6-0.9,0.9c-0.4,0.6-0.4,1.4,0.2,1.8C1.7,14.9,2,15,2.3,15H3l0.8-0.8c1-1,2.6-1,3.5,0c0.2,0.2,0.4,0.5,0.5,0.8h1.9c0.7,0,1.3-0.6,1.3-1.3c0-0.3-0.1-0.6-0.3-0.8C8.6,10.3,4.8,9.9,2.2,11.9z M6,9.2c1.4,0,2.6-1.2,2.6-2.6S7.4,4,6,4C4.6,4,3.4,5.2,3.4,6.6C3.4,8,4.6,9.2,6,9.2z"/></svg>
public/img/icons/solid/social-distancing.svg
0
https://github.com/grafana/grafana/commit/64ed77ddce79009ce05f43801cc578c135f05b6b
[ 0.00019369774963706732, 0.00019369774963706732, 0.00019369774963706732, 0.00019369774963706732, 0 ]
{ "id": 0, "code_window": [ "export type ClassNamesFn = (\n", " ...args: Array<string | string[] | Record<string, boolean | undefined | null>>\n", ") => string;\n", "\n" ], "labels": [ "replace", "replace", "replace", "keep" ], "after_edit": [ "import * as cn from \"./index\";\n" ], "file_path": "types/classnames/bind.d.ts", "type": "replace", "edit_start_line_idx": 0 }
export type ClassNamesFn = ( ...args: Array<string | string[] | Record<string, boolean | undefined | null>> ) => string; export function bind(styles: Record<string, string>): ClassNamesFn;
types/classnames/bind.d.ts
1
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/23b64b59906de27f6a690f2f6904a682f385d7a1
[ 0.9981905817985535, 0.9981905817985535, 0.9981905817985535, 0.9981905817985535, 0 ]
{ "id": 0, "code_window": [ "export type ClassNamesFn = (\n", " ...args: Array<string | string[] | Record<string, boolean | undefined | null>>\n", ") => string;\n", "\n" ], "labels": [ "replace", "replace", "replace", "keep" ], "after_edit": [ "import * as cn from \"./index\";\n" ], "file_path": "types/classnames/bind.d.ts", "type": "replace", "edit_start_line_idx": 0 }
/// <reference types="yui" /> YUI.add('mode-ctr-test', function (Y) { var C = CryptoJS; Y.Test.Runner.add(new Y.Test.Case({ name: 'CTR', setUp: function () { this.data = {}; this.data.message = C.lib.WordArray.create([ 0x00010203, 0x04050607, 0x08090a0b, 0x0c0d0e0f, 0x10111213, 0x14151617, 0x18191a1b, 0x1c1d1e1f ]); this.data.key = C.lib.WordArray.create([0x20212223, 0x24252627, 0x28292a2b, 0x2c2d2e2f]); this.data.iv = C.lib.WordArray.create([0x30313233, 0x34353637, 0x38393a3b, 0x3c3d3e3f]); }, testEncryptor: function () { // Compute expected var expected = this.data.message.clone(); var aes = C.algo.AES.createEncryptor(this.data.key); // Counter initialized with IV var counter = this.data.iv.words.slice(0); // First block XORed with encrypted counter var keystream = counter.slice(0); aes.encryptBlock(keystream, 0); for (var i = 0; i < 4; i++) { expected.words[i] ^= keystream[i]; } // Subsequent blocks XORed with encrypted incremented counter counter[3]++; var keystream = counter.slice(0); aes.encryptBlock(keystream, 0); for (var i = 4; i < 8; i++) { expected.words[i] ^= keystream[i % 4]; } // Compute actual var actual = C.AES.encrypt(this.data.message, this.data.key, { iv: this.data.iv, mode: C.mode.CTR, padding: C.pad.NoPadding }).ciphertext; // Test Y.Assert.areEqual(expected.toString(), actual.toString()); }, testDecryptor: function () { var encrypted = C.AES.encrypt(this.data.message, this.data.key, { iv: this.data.iv, mode: C.mode.CTR, padding: C.pad.NoPadding }); var decrypted = C.AES.decrypt(encrypted, this.data.key, { iv: this.data.iv, mode: C.mode.CTR, padding: C.pad.NoPadding }); Y.Assert.areEqual(this.data.message.toString(), decrypted.toString()); } })); }, '$Rev$');
types/cryptojs/test/mode-ctr-tests.ts
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/23b64b59906de27f6a690f2f6904a682f385d7a1
[ 0.00017334385483991355, 0.00017116684466600418, 0.00016877084271982312, 0.00017121306154876947, 0.0000017075168443625444 ]
{ "id": 0, "code_window": [ "export type ClassNamesFn = (\n", " ...args: Array<string | string[] | Record<string, boolean | undefined | null>>\n", ") => string;\n", "\n" ], "labels": [ "replace", "replace", "replace", "keep" ], "after_edit": [ "import * as cn from \"./index\";\n" ], "file_path": "types/classnames/bind.d.ts", "type": "replace", "edit_start_line_idx": 0 }
import recursiveReaddir = require("recursive-readdir"); recursiveReaddir("some/path", (err, files) => {}); recursiveReaddir("some/path", ["foo.cs", "*.html"], (err, files) => {});
types/recursive-readdir/recursive-readdir-tests.ts
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/23b64b59906de27f6a690f2f6904a682f385d7a1
[ 0.0001749690854921937, 0.0001749690854921937, 0.0001749690854921937, 0.0001749690854921937, 0 ]
{ "id": 0, "code_window": [ "export type ClassNamesFn = (\n", " ...args: Array<string | string[] | Record<string, boolean | undefined | null>>\n", ") => string;\n", "\n" ], "labels": [ "replace", "replace", "replace", "keep" ], "after_edit": [ "import * as cn from \"./index\";\n" ], "file_path": "types/classnames/bind.d.ts", "type": "replace", "edit_start_line_idx": 0 }
{ "compilerOptions": { "module": "commonjs", "lib": [ "es6", "dom" ], "noImplicitAny": false, "noImplicitThis": true, "strictNullChecks": false, "baseUrl": "../", "typeRoots": [ "../" ], "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true }, "files": [ "index.d.ts" ] }
types/jquery.noty/tsconfig.json
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/23b64b59906de27f6a690f2f6904a682f385d7a1
[ 0.00017967149324249476, 0.0001735678524710238, 0.00016988713468890637, 0.00017114492948167026, 0.0000043463651309139095 ]
{ "id": 1, "code_window": [ "\n", "export function bind(styles: Record<string, string>): ClassNamesFn;\n" ], "labels": [ "keep", "replace" ], "after_edit": [ "export function bind(styles: Record<string, string>): typeof cn;" ], "file_path": "types/classnames/bind.d.ts", "type": "replace", "edit_start_line_idx": 4 }
export type ClassNamesFn = ( ...args: Array<string | string[] | Record<string, boolean | undefined | null>> ) => string; export function bind(styles: Record<string, string>): ClassNamesFn;
types/classnames/bind.d.ts
1
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/23b64b59906de27f6a690f2f6904a682f385d7a1
[ 0.9976835250854492, 0.9976835250854492, 0.9976835250854492, 0.9976835250854492, 0 ]
{ "id": 1, "code_window": [ "\n", "export function bind(styles: Record<string, string>): ClassNamesFn;\n" ], "labels": [ "keep", "replace" ], "after_edit": [ "export function bind(styles: Record<string, string>): typeof cn;" ], "file_path": "types/classnames/bind.d.ts", "type": "replace", "edit_start_line_idx": 4 }
// Type definitions for jQuery.transit.js 0.9.9 // Project: http://ricostacruz.com/jquery.transit/ // Definitions by: MrBigDog2U <https://github.com/MrBigDog2U> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 /// <reference types="jquery"/> // Transit ////////////////////////////////////////////////// interface JQueryTransitOptions { opacity?: number; duration?: number; delay?: number; easing?: string; complete?: () => void; scale?: any; } //////////////////////////////////////////////////////////////////////////////////////////////////// interface JQuery { transition(options: JQueryTransitOptions): JQuery; transition(options: JQueryTransitOptions, duration: number): JQuery; transition(options: JQueryTransitOptions, easing: string): JQuery; transition(options: JQueryTransitOptions, duration: number, easing: string): JQuery; transition(options: JQueryTransitOptions, complete: () => void): JQuery; transition(options: JQueryTransitOptions, duration: number, easing: string, complete: () => void): JQuery; /** * Set one or more CSS properties for the set of matched elements. * * @param propertyName A CSS property name. * @param value A value to set for the property. */ css(propertyName: string, value: number[]): JQuery; }
types/jquery.transit/index.d.ts
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/23b64b59906de27f6a690f2f6904a682f385d7a1
[ 0.0003607469843700528, 0.00024199628387577832, 0.0001714946556603536, 0.0002178717404603958, 0.00007566521526314318 ]
{ "id": 1, "code_window": [ "\n", "export function bind(styles: Record<string, string>): ClassNamesFn;\n" ], "labels": [ "keep", "replace" ], "after_edit": [ "export function bind(styles: Record<string, string>): typeof cn;" ], "file_path": "types/classnames/bind.d.ts", "type": "replace", "edit_start_line_idx": 4 }
{ "compilerOptions": { "module": "commonjs", "lib": [ "es6", "dom" ], "noImplicitAny": true, "noImplicitThis": false, "strictNullChecks": false, "baseUrl": "../", "typeRoots": [ "../" ], "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true, "jsx": "react" }, "files": [ "index.d.ts", "react-datepicker-tests.tsx" ] }
types/react-datepicker/tsconfig.json
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/23b64b59906de27f6a690f2f6904a682f385d7a1
[ 0.00017086771549656987, 0.00016948446864262223, 0.00016866078658495098, 0.00016892490384634584, 9.840285883910838e-7 ]
{ "id": 1, "code_window": [ "\n", "export function bind(styles: Record<string, string>): ClassNamesFn;\n" ], "labels": [ "keep", "replace" ], "after_edit": [ "export function bind(styles: Record<string, string>): typeof cn;" ], "file_path": "types/classnames/bind.d.ts", "type": "replace", "edit_start_line_idx": 4 }
import * as React from 'react'; import { IconBaseProps } from 'react-icon-base'; export default class IoSocialGithub extends React.Component<IconBaseProps> { }
types/react-icons/io/social-github.d.ts
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/23b64b59906de27f6a690f2f6904a682f385d7a1
[ 0.0001688203919911757, 0.0001688203919911757, 0.0001688203919911757, 0.0001688203919911757, 0 ]
{ "id": 2, "code_window": [ "\n", "const cx = cn.bind(styles);\n", "const className = cx('foo', ['bar'], { baz: true }); // => \"abc def xyz\"\n" ], "labels": [ "keep", "keep", "add" ], "after_edit": [ "\n", "// falsey values are just ignored\n", "cx(null, 'bar', undefined, 0, 1, { baz: null }, ''); // => 'bar 1'" ], "file_path": "types/classnames/classnames-tests.ts", "type": "add", "edit_start_line_idx": 37 }
export type ClassNamesFn = ( ...args: Array<string | string[] | Record<string, boolean | undefined | null>> ) => string; export function bind(styles: Record<string, string>): ClassNamesFn;
types/classnames/bind.d.ts
1
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/23b64b59906de27f6a690f2f6904a682f385d7a1
[ 0.0014003610704094172, 0.0014003610704094172, 0.0014003610704094172, 0.0014003610704094172, 0 ]
{ "id": 2, "code_window": [ "\n", "const cx = cn.bind(styles);\n", "const className = cx('foo', ['bar'], { baz: true }); // => \"abc def xyz\"\n" ], "labels": [ "keep", "keep", "add" ], "after_edit": [ "\n", "// falsey values are just ignored\n", "cx(null, 'bar', undefined, 0, 1, { baz: null }, ''); // => 'bar 1'" ], "file_path": "types/classnames/classnames-tests.ts", "type": "add", "edit_start_line_idx": 37 }
{ "extends": "dtslint/dt.json" }
types/swagger-hapi/tslint.json
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/23b64b59906de27f6a690f2f6904a682f385d7a1
[ 0.00017684661725070328, 0.00017684661725070328, 0.00017684661725070328, 0.00017684661725070328, 0 ]
{ "id": 2, "code_window": [ "\n", "const cx = cn.bind(styles);\n", "const className = cx('foo', ['bar'], { baz: true }); // => \"abc def xyz\"\n" ], "labels": [ "keep", "keep", "add" ], "after_edit": [ "\n", "// falsey values are just ignored\n", "cx(null, 'bar', undefined, 0, 1, { baz: null }, ''); // => 'bar 1'" ], "file_path": "types/classnames/classnames-tests.ts", "type": "add", "edit_start_line_idx": 37 }
import * as piSPI from 'pi-spi'; var spi:piSPI.SPI = piSPI.initialize("test"); var b:Buffer = new Buffer("Hello, World!"); var cb = function(error:Error, data:Buffer):void { }; spi.bitOrder(piSPI.order.LSB_FIRST); spi.bitOrder(piSPI.order.MSB_FIRST); console.log(spi.bitOrder()); spi.dataMode(piSPI.mode.CPHA); spi.dataMode(piSPI.mode.CPOL); console.log(spi.dataMode()); spi.clockSpeed(4e6); console.log(spi.clockSpeed()); spi.write(b, cb); spi.read(13, cb); spi.transfer(b, cb); spi.transfer(b, 13, cb); spi.close();
types/pi-spi/pi-spi-tests.ts
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/23b64b59906de27f6a690f2f6904a682f385d7a1
[ 0.00017713317356538028, 0.00017357258184347302, 0.00016723538283258677, 0.000176349189132452, 0.000004492492280405713 ]
{ "id": 2, "code_window": [ "\n", "const cx = cn.bind(styles);\n", "const className = cx('foo', ['bar'], { baz: true }); // => \"abc def xyz\"\n" ], "labels": [ "keep", "keep", "add" ], "after_edit": [ "\n", "// falsey values are just ignored\n", "cx(null, 'bar', undefined, 0, 1, { baz: null }, ''); // => 'bar 1'" ], "file_path": "types/classnames/classnames-tests.ts", "type": "add", "edit_start_line_idx": 37 }
{ "compilerOptions": { "target": "es6", "module": "commonjs", "lib": [ "es6" ], "noImplicitAny": true, "noImplicitThis": true, "strictNullChecks": true, "baseUrl": "../", "typeRoots": [ "../" ], "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true }, "files": [ "index.d.ts", "node-ral-tests.ts" ] }
types/node-ral/tsconfig.json
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/23b64b59906de27f6a690f2f6904a682f385d7a1
[ 0.00017781446513254195, 0.00017457769718021154, 0.00017188479250762612, 0.00017403381934855133, 0.00000245113619712356 ]
{ "id": 0, "code_window": [ " \"lockfileVersion\": 2,\n", " \"requires\": true,\n", " \"packages\": {\n", " \"\": {\n", " \"dependencies\": {\n", " \"@playwright/test\": \"1.35.0-alpha-1685046878000\"\n", " }\n", " },\n", " \"node_modules/@playwright/test\": {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " \"@playwright/test\": \"1.35.0-alpha-1685109821000\"\n" ], "file_path": "tests/playwright-test/stable-test-runner/package-lock.json", "type": "replace", "edit_start_line_idx": 7 }
{ "name": "stable-test-runner", "lockfileVersion": 2, "requires": true, "packages": { "": { "dependencies": { "@playwright/test": "1.35.0-alpha-1685046878000" } }, "node_modules/@playwright/test": { "version": "1.35.0-alpha-1685046878000", "resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.35.0-alpha-1685046878000.tgz", "integrity": "sha512-OgZV/Ncwxjodqjl7FrOOaVUiPhxc6h3gYGw9ElKT9Eac+67wjZafDgdH8eGOSXIwwyHOqP+M4PM6T8sq3vyvyA==", "dependencies": { "@types/node": "*", "playwright-core": "1.35.0-alpha-1685046878000" }, "bin": { "playwright": "cli.js" }, "engines": { "node": ">=14" }, "optionalDependencies": { "fsevents": "2.3.2" } }, "node_modules/@types/node": { "version": "18.0.0", "resolved": "https://registry.npmjs.org/@types/node/-/node-18.0.0.tgz", "integrity": "sha512-cHlGmko4gWLVI27cGJntjs/Sj8th9aYwplmZFwmmgYQQvL5NUsgVJG7OddLvNfLqYS31KFN0s3qlaD9qCaxACA==" }, "node_modules/fsevents": { "version": "2.3.2", "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz", "integrity": "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==", "hasInstallScript": true, "optional": true, "os": [ "darwin" ], "engines": { "node": "^8.16.0 || ^10.6.0 || >=11.0.0" } }, "node_modules/playwright-core": { "version": "1.35.0-alpha-1685046878000", "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.35.0-alpha-1685046878000.tgz", "integrity": "sha512-2MdjKmIKazxVH4uZ8TSGjEJ6lpjfg4xgnCdoL46gKfKBd42mgPutfAplCGEtb0CRb9Oke8sYzo9HnA9EUuXQSg==", "bin": { "playwright-core": "cli.js" }, "engines": { "node": ">=14" } } }, "dependencies": { "@playwright/test": { "version": "1.35.0-alpha-1685046878000", "resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.35.0-alpha-1685046878000.tgz", "integrity": "sha512-OgZV/Ncwxjodqjl7FrOOaVUiPhxc6h3gYGw9ElKT9Eac+67wjZafDgdH8eGOSXIwwyHOqP+M4PM6T8sq3vyvyA==", "requires": { "@types/node": "*", "fsevents": "2.3.2", "playwright-core": "1.35.0-alpha-1685046878000" } }, "@types/node": { "version": "18.0.0", "resolved": "https://registry.npmjs.org/@types/node/-/node-18.0.0.tgz", "integrity": "sha512-cHlGmko4gWLVI27cGJntjs/Sj8th9aYwplmZFwmmgYQQvL5NUsgVJG7OddLvNfLqYS31KFN0s3qlaD9qCaxACA==" }, "fsevents": { "version": "2.3.2", "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz", "integrity": "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==", "optional": true }, "playwright-core": { "version": "1.35.0-alpha-1685046878000", "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.35.0-alpha-1685046878000.tgz", "integrity": "sha512-2MdjKmIKazxVH4uZ8TSGjEJ6lpjfg4xgnCdoL46gKfKBd42mgPutfAplCGEtb0CRb9Oke8sYzo9HnA9EUuXQSg==" } } }
tests/playwright-test/stable-test-runner/package-lock.json
1
https://github.com/microsoft/playwright/commit/624e88e504c4855b809c4e0ee3b1b8991f7e85fc
[ 0.9882144927978516, 0.11383476853370667, 0.00016801328456494957, 0.0020477224607020617, 0.30924537777900696 ]
{ "id": 0, "code_window": [ " \"lockfileVersion\": 2,\n", " \"requires\": true,\n", " \"packages\": {\n", " \"\": {\n", " \"dependencies\": {\n", " \"@playwright/test\": \"1.35.0-alpha-1685046878000\"\n", " }\n", " },\n", " \"node_modules/@playwright/test\": {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " \"@playwright/test\": \"1.35.0-alpha-1685109821000\"\n" ], "file_path": "tests/playwright-test/stable-test-runner/package-lock.json", "type": "replace", "edit_start_line_idx": 7 }
/* Copyright (c) Microsoft Corporation. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import type { TestCase, TestFile } from './types'; import * as React from 'react'; import './colors.css'; import './common.css'; import { Filter } from './filter'; import { HeaderView } from './headerView'; import { Route } from './links'; import type { LoadedReport } from './loadedReport'; import './reportView.css'; import type { Metainfo } from './metadataView'; import { MetadataView } from './metadataView'; import { TestCaseView } from './testCaseView'; import { TestFilesView } from './testFilesView'; import './theme.css'; declare global { interface Window { playwrightReportBase64?: string; } } // These are extracted to preserve the function identity between renders to avoid re-triggering effects. const testFilesRoutePredicate = (params: URLSearchParams) => !params.has('testId'); const testCaseRoutePredicate = (params: URLSearchParams) => params.has('testId'); export const ReportView: React.FC<{ report: LoadedReport | undefined, }> = ({ report }) => { const searchParams = new URLSearchParams(window.location.hash.slice(1)); const [expandedFiles, setExpandedFiles] = React.useState<Map<string, boolean>>(new Map()); const [filterText, setFilterText] = React.useState(searchParams.get('q') || ''); const filter = React.useMemo(() => Filter.parse(filterText), [filterText]); return <div className='htmlreport vbox px-4 pb-4'> <main> {report?.json() && <HeaderView stats={report.json().stats} filterText={filterText} setFilterText={setFilterText}></HeaderView>} {report?.json().metadata && <MetadataView {...report?.json().metadata as Metainfo} />} <Route predicate={testFilesRoutePredicate}> <TestFilesView report={report?.json()} filter={filter} expandedFiles={expandedFiles} setExpandedFiles={setExpandedFiles} projectNames={report?.json().projectNames || []} stats={report?.json().stats || { duration: 0 }} /> </Route> <Route predicate={testCaseRoutePredicate}> {!!report && <TestCaseViewLoader report={report}></TestCaseViewLoader>} </Route> </main> </div>; }; const TestCaseViewLoader: React.FC<{ report: LoadedReport, }> = ({ report }) => { const searchParams = new URLSearchParams(window.location.hash.slice(1)); const [test, setTest] = React.useState<TestCase | undefined>(); const testId = searchParams.get('testId'); const anchor = (searchParams.get('anchor') || '') as 'video' | 'diff' | ''; const run = +(searchParams.get('run') || '0'); React.useEffect(() => { (async () => { if (!testId || testId === test?.testId) return; const fileId = testId.split('-')[0]; if (!fileId) return; const file = await report.entry(`${fileId}.json`) as TestFile; for (const t of file.tests) { if (t.testId === testId) { setTest(t); break; } } })(); }, [test, report, testId]); return <TestCaseView projectNames={report.json().projectNames} test={test} anchor={anchor} run={run}></TestCaseView>; };
packages/html-reporter/src/reportView.tsx
0
https://github.com/microsoft/playwright/commit/624e88e504c4855b809c4e0ee3b1b8991f7e85fc
[ 0.00031460917671211064, 0.00018662508227862418, 0.00016765609325375408, 0.0001734221586957574, 0.00004271731449989602 ]
{ "id": 0, "code_window": [ " \"lockfileVersion\": 2,\n", " \"requires\": true,\n", " \"packages\": {\n", " \"\": {\n", " \"dependencies\": {\n", " \"@playwright/test\": \"1.35.0-alpha-1685046878000\"\n", " }\n", " },\n", " \"node_modules/@playwright/test\": {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " \"@playwright/test\": \"1.35.0-alpha-1685109821000\"\n" ], "file_path": "tests/playwright-test/stable-test-runner/package-lock.json", "type": "replace", "edit_start_line_idx": 7 }
<!doctype html> <html> <head> <title>Name test case 755</title> <meta content="text/html; charset=utf-8" http-equiv="Content-Type"/> <link rel="stylesheet" href="/wai-aria/scripts/manual.css"> <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> <script src="/wai-aria/scripts/ATTAcomm.js"></script> <script> setup({explicit_timeout: true, explicit_done: true }); var theTest = new ATTAcomm( { "steps" : [ { "element" : "test", "test" : { "ATK" : [ [ "property", "name", "is", "fancy fruit" ] ], "AXAPI" : [ [ "property", "AXDescription", "is", "fancy fruit" ] ], "IAccessible2" : [ [ "property", "accName", "is", "fancy fruit" ] ], "UIA" : [ [ "property", "Name", "is", "fancy fruit" ] ] }, "title" : "step 1", "type" : "test" } ], "title" : "Name test case 755" } ) ; </script> </head> <body> <p>This test examines the ARIA properties for Name test case 755.</p> <style> label:before { content:"fancy "; } </style> <label for="test">fruit</label> <input type="radio" id="test"/> <div id="manualMode"></div> <div id="log"></div> <div id="ATTAmessages"></div> </body> </html>
tests/assets/wpt/accname/name_test_case_755-manual.html
0
https://github.com/microsoft/playwright/commit/624e88e504c4855b809c4e0ee3b1b8991f7e85fc
[ 0.00017416113405488431, 0.00017114747606683522, 0.00016921007772907615, 0.00017085860599763691, 0.000001397611413267441 ]
{ "id": 0, "code_window": [ " \"lockfileVersion\": 2,\n", " \"requires\": true,\n", " \"packages\": {\n", " \"\": {\n", " \"dependencies\": {\n", " \"@playwright/test\": \"1.35.0-alpha-1685046878000\"\n", " }\n", " },\n", " \"node_modules/@playwright/test\": {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " \"@playwright/test\": \"1.35.0-alpha-1685109821000\"\n" ], "file_path": "tests/playwright-test/stable-test-runner/package-lock.json", "type": "replace", "edit_start_line_idx": 7 }
/** * Copyright (c) Microsoft Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import fs from 'fs'; import { progress as ProgressBar } from '../../utilsBundle'; import { httpRequest } from '../../utils/network'; import { ManualPromise } from '../../utils/manualPromise'; type OnProgressCallback = (downloadedBytes: number, totalBytes: number) => void; type DownloadFileLogger = (message: string) => void; type DownloadFileOptions = { progressCallback: OnProgressCallback, log: DownloadFileLogger, userAgent: string, connectionTimeout: number, }; function downloadFile(url: string, destinationPath: string, options: DownloadFileOptions): Promise<void> { const { progressCallback, log = () => { }, } = options; log(`running download:`); log(`-- from url: ${url}`); log(`-- to location: ${destinationPath}`); let downloadedBytes = 0; let totalBytes = 0; const promise = new ManualPromise<void>(); httpRequest({ url, headers: { 'User-Agent': options.userAgent, }, timeout: options.connectionTimeout, }, response => { log(`-- response status code: ${response.statusCode}`); if (response.statusCode !== 200) { let content = ''; const handleError = () => { const error = new Error(`Download failed: server returned code ${response.statusCode} body '${content}'. URL: ${url}`); // consume response data to free up memory response.resume(); promise.reject(error); }; response .on('data', chunk => content += chunk) .on('end', handleError) .on('error', handleError); return; } const file = fs.createWriteStream(destinationPath); file.on('finish', () => promise.resolve()); file.on('error', error => promise.reject(error)); response.pipe(file); totalBytes = parseInt(response.headers['content-length'] || '0', 10); log(`-- total bytes: ${totalBytes}`); response.on('data', onData); }, (error: any) => promise.reject(error)); return promise; function onData(chunk: string) { downloadedBytes += chunk.length; progressCallback!(downloadedBytes, totalBytes); } } function getDownloadProgress(): OnProgressCallback { if (process.stdout.isTTY) return getAnimatedDownloadProgress(); return getBasicDownloadProgress(); } function getAnimatedDownloadProgress(): OnProgressCallback { let progressBar: ProgressBar; let lastDownloadedBytes = 0; return (downloadedBytes: number, totalBytes: number) => { if (!progressBar) { progressBar = new ProgressBar( `${toMegabytes( totalBytes )} [:bar] :percent :etas`, { complete: '=', incomplete: ' ', width: 20, total: totalBytes, } ); } const delta = downloadedBytes - lastDownloadedBytes; lastDownloadedBytes = downloadedBytes; progressBar.tick(delta); }; } function getBasicDownloadProgress(): OnProgressCallback { // eslint-disable-next-line no-console const totalRows = 10; const stepWidth = 8; let lastRow = -1; return (downloadedBytes: number, totalBytes: number) => { const percentage = downloadedBytes / totalBytes; const row = Math.floor(totalRows * percentage); if (row > lastRow) { lastRow = row; const percentageString = String(percentage * 100 | 0).padStart(3); // eslint-disable-next-line no-console console.log(`|${'■'.repeat(row * stepWidth)}${' '.repeat((totalRows - row) * stepWidth)}| ${percentageString}% of ${toMegabytes(totalBytes)}`); } }; } function toMegabytes(bytes: number) { const mb = bytes / 1024 / 1024; return `${Math.round(mb * 10) / 10} Mb`; } async function main() { const [url, destination, userAgent, downloadConnectionTimeout] = process.argv.slice(2); await downloadFile(url, destination, { progressCallback: getDownloadProgress(), userAgent, log: message => process.send?.({ method: 'log', params: { message } }), connectionTimeout: +downloadConnectionTimeout, }); } main().catch(error => { // eslint-disable-next-line no-console console.error(error); process.exit(1); });
packages/playwright-core/src/server/registry/oopDownloadMain.ts
0
https://github.com/microsoft/playwright/commit/624e88e504c4855b809c4e0ee3b1b8991f7e85fc
[ 0.00017496707732789218, 0.0001700874272501096, 0.00016580542433075607, 0.0001700921857263893, 0.0000024837070213834522 ]
{ "id": 1, "code_window": [ " }\n", " },\n", " \"node_modules/@playwright/test\": {\n", " \"version\": \"1.35.0-alpha-1685046878000\",\n", " \"resolved\": \"https://registry.npmjs.org/@playwright/test/-/test-1.35.0-alpha-1685046878000.tgz\",\n", " \"integrity\": \"sha512-OgZV/Ncwxjodqjl7FrOOaVUiPhxc6h3gYGw9ElKT9Eac+67wjZafDgdH8eGOSXIwwyHOqP+M4PM6T8sq3vyvyA==\",\n", " \"dependencies\": {\n", " \"@types/node\": \"*\",\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep" ], "after_edit": [ " \"version\": \"1.35.0-alpha-1685109821000\",\n", " \"resolved\": \"https://registry.npmjs.org/@playwright/test/-/test-1.35.0-alpha-1685109821000.tgz\",\n", " \"integrity\": \"sha512-FX1g4UHazT58jr4FbPKyr+Iw87umRz4jxlViZiS1x4FB87XW6VYRaViaXOPnI+sD/p8c4SMde+vSetHwkBLwpQ==\",\n" ], "file_path": "tests/playwright-test/stable-test-runner/package-lock.json", "type": "replace", "edit_start_line_idx": 11 }
{ "name": "stable-test-runner", "lockfileVersion": 2, "requires": true, "packages": { "": { "dependencies": { "@playwright/test": "1.35.0-alpha-1685046878000" } }, "node_modules/@playwright/test": { "version": "1.35.0-alpha-1685046878000", "resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.35.0-alpha-1685046878000.tgz", "integrity": "sha512-OgZV/Ncwxjodqjl7FrOOaVUiPhxc6h3gYGw9ElKT9Eac+67wjZafDgdH8eGOSXIwwyHOqP+M4PM6T8sq3vyvyA==", "dependencies": { "@types/node": "*", "playwright-core": "1.35.0-alpha-1685046878000" }, "bin": { "playwright": "cli.js" }, "engines": { "node": ">=14" }, "optionalDependencies": { "fsevents": "2.3.2" } }, "node_modules/@types/node": { "version": "18.0.0", "resolved": "https://registry.npmjs.org/@types/node/-/node-18.0.0.tgz", "integrity": "sha512-cHlGmko4gWLVI27cGJntjs/Sj8th9aYwplmZFwmmgYQQvL5NUsgVJG7OddLvNfLqYS31KFN0s3qlaD9qCaxACA==" }, "node_modules/fsevents": { "version": "2.3.2", "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz", "integrity": "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==", "hasInstallScript": true, "optional": true, "os": [ "darwin" ], "engines": { "node": "^8.16.0 || ^10.6.0 || >=11.0.0" } }, "node_modules/playwright-core": { "version": "1.35.0-alpha-1685046878000", "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.35.0-alpha-1685046878000.tgz", "integrity": "sha512-2MdjKmIKazxVH4uZ8TSGjEJ6lpjfg4xgnCdoL46gKfKBd42mgPutfAplCGEtb0CRb9Oke8sYzo9HnA9EUuXQSg==", "bin": { "playwright-core": "cli.js" }, "engines": { "node": ">=14" } } }, "dependencies": { "@playwright/test": { "version": "1.35.0-alpha-1685046878000", "resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.35.0-alpha-1685046878000.tgz", "integrity": "sha512-OgZV/Ncwxjodqjl7FrOOaVUiPhxc6h3gYGw9ElKT9Eac+67wjZafDgdH8eGOSXIwwyHOqP+M4PM6T8sq3vyvyA==", "requires": { "@types/node": "*", "fsevents": "2.3.2", "playwright-core": "1.35.0-alpha-1685046878000" } }, "@types/node": { "version": "18.0.0", "resolved": "https://registry.npmjs.org/@types/node/-/node-18.0.0.tgz", "integrity": "sha512-cHlGmko4gWLVI27cGJntjs/Sj8th9aYwplmZFwmmgYQQvL5NUsgVJG7OddLvNfLqYS31KFN0s3qlaD9qCaxACA==" }, "fsevents": { "version": "2.3.2", "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz", "integrity": "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==", "optional": true }, "playwright-core": { "version": "1.35.0-alpha-1685046878000", "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.35.0-alpha-1685046878000.tgz", "integrity": "sha512-2MdjKmIKazxVH4uZ8TSGjEJ6lpjfg4xgnCdoL46gKfKBd42mgPutfAplCGEtb0CRb9Oke8sYzo9HnA9EUuXQSg==" } } }
tests/playwright-test/stable-test-runner/package-lock.json
1
https://github.com/microsoft/playwright/commit/624e88e504c4855b809c4e0ee3b1b8991f7e85fc
[ 0.990400493144989, 0.22211821377277374, 0.00016984145622700453, 0.010178623721003532, 0.39894217252731323 ]
{ "id": 1, "code_window": [ " }\n", " },\n", " \"node_modules/@playwright/test\": {\n", " \"version\": \"1.35.0-alpha-1685046878000\",\n", " \"resolved\": \"https://registry.npmjs.org/@playwright/test/-/test-1.35.0-alpha-1685046878000.tgz\",\n", " \"integrity\": \"sha512-OgZV/Ncwxjodqjl7FrOOaVUiPhxc6h3gYGw9ElKT9Eac+67wjZafDgdH8eGOSXIwwyHOqP+M4PM6T8sq3vyvyA==\",\n", " \"dependencies\": {\n", " \"@types/node\": \"*\",\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep" ], "after_edit": [ " \"version\": \"1.35.0-alpha-1685109821000\",\n", " \"resolved\": \"https://registry.npmjs.org/@playwright/test/-/test-1.35.0-alpha-1685109821000.tgz\",\n", " \"integrity\": \"sha512-FX1g4UHazT58jr4FbPKyr+Iw87umRz4jxlViZiS1x4FB87XW6VYRaViaXOPnI+sD/p8c4SMde+vSetHwkBLwpQ==\",\n" ], "file_path": "tests/playwright-test/stable-test-runner/package-lock.json", "type": "replace", "edit_start_line_idx": 11 }
/** * * ISC License * * Copyright (c) 2019, Mapbox * Permission to use, copy, modify, and/or distribute this software for any purpose * with or without fee is hereby granted, provided that the above copyright notice * and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND * FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF * THIS SOFTWARE. */ 'use strict'; module.exports = pixelmatch; const defaultOptions = { threshold: 0.1, // matching threshold (0 to 1); smaller is more sensitive includeAA: false, // whether to skip anti-aliasing detection alpha: 0.1, // opacity of original image in diff output aaColor: [255, 255, 0], // color of anti-aliased pixels in diff output diffColor: [255, 0, 0], // color of different pixels in diff output diffColorAlt: null, // whether to detect dark on light differences between img1 and img2 and set an alternative color to differentiate between the two diffMask: false // draw the diff over a transparent background (a mask) }; function pixelmatch(img1, img2, output, width, height, options) { if (!isPixelData(img1) || !isPixelData(img2) || (output && !isPixelData(output))) throw new Error('Image data: Uint8Array, Uint8ClampedArray or Buffer expected.'); if (img1.length !== img2.length || (output && output.length !== img1.length)) throw new Error('Image sizes do not match.'); if (img1.length !== width * height * 4) throw new Error('Image data size does not match width/height.'); options = Object.assign({}, defaultOptions, options); // check if images are identical const len = width * height; const a32 = new Uint32Array(img1.buffer, img1.byteOffset, len); const b32 = new Uint32Array(img2.buffer, img2.byteOffset, len); let identical = true; for (let i = 0; i < len; i++) { if (a32[i] !== b32[i]) { identical = false; break; } } if (identical) { // fast path if identical if (output && !options.diffMask) { for (let i = 0; i < len; i++) drawGrayPixel(img1, 4 * i, options.alpha, output); } return 0; } // maximum acceptable square distance between two colors; // 35215 is the maximum possible value for the YIQ difference metric const maxDelta = 35215 * options.threshold * options.threshold; let diff = 0; // compare each pixel of one image against the other one for (let y = 0; y < height; y++) { for (let x = 0; x < width; x++) { const pos = (y * width + x) * 4; // squared YUV distance between colors at this pixel position, negative if the img2 pixel is darker const delta = colorDelta(img1, img2, pos, pos); // the color difference is above the threshold if (Math.abs(delta) > maxDelta) { // check it's a real rendering difference or just anti-aliasing if (!options.includeAA && (antialiased(img1, x, y, width, height, img2) || antialiased(img2, x, y, width, height, img1))) { // one of the pixels is anti-aliasing; draw as yellow and do not count as difference // note that we do not include such pixels in a mask if (output && !options.diffMask) drawPixel(output, pos, ...options.aaColor); } else { // found substantial difference not caused by anti-aliasing; draw it as such if (output) { drawPixel(output, pos, ...(delta < 0 && options.diffColorAlt || options.diffColor)); } diff++; } } else if (output) { // pixels are similar; draw background as grayscale image blended with white if (!options.diffMask) drawGrayPixel(img1, pos, options.alpha, output); } } } // return the number of different pixels return diff; } function isPixelData(arr) { // work around instanceof Uint8Array not working properly in some Jest environments return ArrayBuffer.isView(arr) && arr.constructor.BYTES_PER_ELEMENT === 1; } // check if a pixel is likely a part of anti-aliasing; // based on "Anti-aliased Pixel and Intensity Slope Detector" paper by V. Vysniauskas, 2009 function antialiased(img, x1, y1, width, height, img2) { const x0 = Math.max(x1 - 1, 0); const y0 = Math.max(y1 - 1, 0); const x2 = Math.min(x1 + 1, width - 1); const y2 = Math.min(y1 + 1, height - 1); const pos = (y1 * width + x1) * 4; let zeroes = x1 === x0 || x1 === x2 || y1 === y0 || y1 === y2 ? 1 : 0; let min = 0; let max = 0; let minX, minY, maxX, maxY; // go through 8 adjacent pixels for (let x = x0; x <= x2; x++) { for (let y = y0; y <= y2; y++) { if (x === x1 && y === y1) continue; // brightness delta between the center pixel and adjacent one const delta = colorDelta(img, img, pos, (y * width + x) * 4, true); // count the number of equal, darker and brighter adjacent pixels if (delta === 0) { zeroes++; // if found more than 2 equal siblings, it's definitely not anti-aliasing if (zeroes > 2) return false; // remember the darkest pixel } else if (delta < min) { min = delta; minX = x; minY = y; // remember the brightest pixel } else if (delta > max) { max = delta; maxX = x; maxY = y; } } } // if there are no both darker and brighter pixels among siblings, it's not anti-aliasing if (min === 0 || max === 0) return false; // if either the darkest or the brightest pixel has 3+ equal siblings in both images // (definitely not anti-aliased), this pixel is anti-aliased return (hasManySiblings(img, minX, minY, width, height) && hasManySiblings(img2, minX, minY, width, height)) || (hasManySiblings(img, maxX, maxY, width, height) && hasManySiblings(img2, maxX, maxY, width, height)); } // check if a pixel has 3+ adjacent pixels of the same color. function hasManySiblings(img, x1, y1, width, height) { const x0 = Math.max(x1 - 1, 0); const y0 = Math.max(y1 - 1, 0); const x2 = Math.min(x1 + 1, width - 1); const y2 = Math.min(y1 + 1, height - 1); const pos = (y1 * width + x1) * 4; let zeroes = x1 === x0 || x1 === x2 || y1 === y0 || y1 === y2 ? 1 : 0; // go through 8 adjacent pixels for (let x = x0; x <= x2; x++) { for (let y = y0; y <= y2; y++) { if (x === x1 && y === y1) continue; const pos2 = (y * width + x) * 4; if (img[pos] === img[pos2] && img[pos + 1] === img[pos2 + 1] && img[pos + 2] === img[pos2 + 2] && img[pos + 3] === img[pos2 + 3]) zeroes++; if (zeroes > 2) return true; } } return false; } // calculate color difference according to the paper "Measuring perceived color difference // using YIQ NTSC transmission color space in mobile applications" by Y. Kotsarenko and F. Ramos function colorDelta(img1, img2, k, m, yOnly) { let r1 = img1[k + 0]; let g1 = img1[k + 1]; let b1 = img1[k + 2]; let a1 = img1[k + 3]; let r2 = img2[m + 0]; let g2 = img2[m + 1]; let b2 = img2[m + 2]; let a2 = img2[m + 3]; if (a1 === a2 && r1 === r2 && g1 === g2 && b1 === b2) return 0; if (a1 < 255) { a1 /= 255; r1 = blend(r1, a1); g1 = blend(g1, a1); b1 = blend(b1, a1); } if (a2 < 255) { a2 /= 255; r2 = blend(r2, a2); g2 = blend(g2, a2); b2 = blend(b2, a2); } const y1 = rgb2y(r1, g1, b1); const y2 = rgb2y(r2, g2, b2); const y = y1 - y2; if (yOnly) return y; // brightness difference only const i = rgb2i(r1, g1, b1) - rgb2i(r2, g2, b2); const q = rgb2q(r1, g1, b1) - rgb2q(r2, g2, b2); const delta = 0.5053 * y * y + 0.299 * i * i + 0.1957 * q * q; // encode whether the pixel lightens or darkens in the sign return y1 > y2 ? -delta : delta; } function rgb2y(r, g, b) { return r * 0.29889531 + g * 0.58662247 + b * 0.11448223; } function rgb2i(r, g, b) { return r * 0.59597799 - g * 0.27417610 - b * 0.32180189; } function rgb2q(r, g, b) { return r * 0.21147017 - g * 0.52261711 + b * 0.31114694; } // blend semi-transparent color with white function blend(c, a) { return 255 + (c - 255) * a; } function drawPixel(output, pos, r, g, b) { output[pos + 0] = r; output[pos + 1] = g; output[pos + 2] = b; output[pos + 3] = 255; } function drawGrayPixel(img, i, alpha, output) { const r = img[i + 0]; const g = img[i + 1]; const b = img[i + 2]; const val = blend(rgb2y(r, g, b), alpha * img[i + 3] / 255); drawPixel(output, i, val, val, val); }
packages/playwright-core/src/third_party/pixelmatch.js
0
https://github.com/microsoft/playwright/commit/624e88e504c4855b809c4e0ee3b1b8991f7e85fc
[ 0.00017383016529493034, 0.0001693885715212673, 0.00016166198474820703, 0.0001698284177109599, 0.000002591632437543012 ]
{ "id": 1, "code_window": [ " }\n", " },\n", " \"node_modules/@playwright/test\": {\n", " \"version\": \"1.35.0-alpha-1685046878000\",\n", " \"resolved\": \"https://registry.npmjs.org/@playwright/test/-/test-1.35.0-alpha-1685046878000.tgz\",\n", " \"integrity\": \"sha512-OgZV/Ncwxjodqjl7FrOOaVUiPhxc6h3gYGw9ElKT9Eac+67wjZafDgdH8eGOSXIwwyHOqP+M4PM6T8sq3vyvyA==\",\n", " \"dependencies\": {\n", " \"@types/node\": \"*\",\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep" ], "after_edit": [ " \"version\": \"1.35.0-alpha-1685109821000\",\n", " \"resolved\": \"https://registry.npmjs.org/@playwright/test/-/test-1.35.0-alpha-1685109821000.tgz\",\n", " \"integrity\": \"sha512-FX1g4UHazT58jr4FbPKyr+Iw87umRz4jxlViZiS1x4FB87XW6VYRaViaXOPnI+sD/p8c4SMde+vSetHwkBLwpQ==\",\n" ], "file_path": "tests/playwright-test/stable-test-runner/package-lock.json", "type": "replace", "edit_start_line_idx": 11 }
<!doctype html> <html> <head> <title>Name test case 565</title> <meta content="text/html; charset=utf-8" http-equiv="Content-Type"/> <link rel="stylesheet" href="/wai-aria/scripts/manual.css"> <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> <script src="/wai-aria/scripts/ATTAcomm.js"></script> <script> setup({explicit_timeout: true, explicit_done: true }); var theTest = new ATTAcomm( { "steps" : [ { "element" : "test", "test" : { "ATK" : [ [ "property", "name", "is", "l peanuts popcorn apple jacks" ] ], "AXAPI" : [ [ "property", "AXDescription", "is", "l peanuts popcorn apple jacks" ] ], "IAccessible2" : [ [ "property", "accName", "is", "l peanuts popcorn apple jacks" ] ], "UIA" : [ [ "property", "Name", "is", "l peanuts popcorn apple jacks" ] ] }, "title" : "step 1", "type" : "test" } ], "title" : "Name test case 565" } ) ; </script> </head> <body> <p>This test examines the ARIA properties for Name test case 565.</p> <input type="text" value="peanuts" id="ID1"> <input type="text" value="popcorn" id="ID2"> <input type="text" value="apple jacks" id="ID3"> <img id="test" aria-label="l" aria-labelledby="test ID1 ID2 ID3" alt= "a" title="t" src="foo.jpg"/> <div id="manualMode"></div> <div id="log"></div> <div id="ATTAmessages"></div> </body> </html>
tests/assets/wpt/accname/name_test_case_565-manual.html
0
https://github.com/microsoft/playwright/commit/624e88e504c4855b809c4e0ee3b1b8991f7e85fc
[ 0.00017459809896536171, 0.0001692351361270994, 0.00016664211580064148, 0.00016878207679837942, 0.0000021793819087179145 ]
{ "id": 1, "code_window": [ " }\n", " },\n", " \"node_modules/@playwright/test\": {\n", " \"version\": \"1.35.0-alpha-1685046878000\",\n", " \"resolved\": \"https://registry.npmjs.org/@playwright/test/-/test-1.35.0-alpha-1685046878000.tgz\",\n", " \"integrity\": \"sha512-OgZV/Ncwxjodqjl7FrOOaVUiPhxc6h3gYGw9ElKT9Eac+67wjZafDgdH8eGOSXIwwyHOqP+M4PM6T8sq3vyvyA==\",\n", " \"dependencies\": {\n", " \"@types/node\": \"*\",\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep" ], "after_edit": [ " \"version\": \"1.35.0-alpha-1685109821000\",\n", " \"resolved\": \"https://registry.npmjs.org/@playwright/test/-/test-1.35.0-alpha-1685109821000.tgz\",\n", " \"integrity\": \"sha512-FX1g4UHazT58jr4FbPKyr+Iw87umRz4jxlViZiS1x4FB87XW6VYRaViaXOPnI+sD/p8c4SMde+vSetHwkBLwpQ==\",\n" ], "file_path": "tests/playwright-test/stable-test-runner/package-lock.json", "type": "replace", "edit_start_line_idx": 11 }
/** * Copyright (c) Microsoft Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { config as loadEnv } from 'dotenv'; loadEnv({ path: path.join(__dirname, '..', '..', '.env') }); import { defineConfig, type ReporterDescription } from './stable-test-runner'; import * as path from 'path'; const outputDir = path.join(__dirname, '..', '..', 'test-results'); const reporters = () => { const result: ReporterDescription[] = process.env.CI ? [ ['dot'], ['json', { outputFile: path.join(outputDir, 'report.json') }], ] : [ ['list'] ]; if (process.env.PWTEST_BLOB_REPORT === '1') result.push(['blob', { outputDir: path.join(outputDir, 'blob-report') }]); return result; }; export default defineConfig({ timeout: 30000, forbidOnly: !!process.env.CI, workers: process.env.CI ? 2 : undefined, snapshotPathTemplate: '__screenshots__/{testFilePath}/{arg}{ext}', projects: [ { name: 'playwright-test', testDir: __dirname, testIgnore: ['assets/**', 'stable-test-runner/**'], }, { name: 'image_tools', testDir: path.join(__dirname, '../image_tools'), testIgnore: [path.join(__dirname, '../fixtures/**')], }, ], reporter: reporters(), });
tests/playwright-test/playwright.config.ts
0
https://github.com/microsoft/playwright/commit/624e88e504c4855b809c4e0ee3b1b8991f7e85fc
[ 0.00017336236487608403, 0.00017134810332208872, 0.00016595187480561435, 0.00017297003068961203, 0.0000027433657123765443 ]
{ "id": 2, "code_window": [ " \"dependencies\": {\n", " \"@types/node\": \"*\",\n", " \"playwright-core\": \"1.35.0-alpha-1685046878000\"\n", " },\n", " \"bin\": {\n", " \"playwright\": \"cli.js\"\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " \"playwright-core\": \"1.35.0-alpha-1685109821000\"\n" ], "file_path": "tests/playwright-test/stable-test-runner/package-lock.json", "type": "replace", "edit_start_line_idx": 16 }
{ "name": "stable-test-runner", "lockfileVersion": 2, "requires": true, "packages": { "": { "dependencies": { "@playwright/test": "1.35.0-alpha-1685046878000" } }, "node_modules/@playwright/test": { "version": "1.35.0-alpha-1685046878000", "resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.35.0-alpha-1685046878000.tgz", "integrity": "sha512-OgZV/Ncwxjodqjl7FrOOaVUiPhxc6h3gYGw9ElKT9Eac+67wjZafDgdH8eGOSXIwwyHOqP+M4PM6T8sq3vyvyA==", "dependencies": { "@types/node": "*", "playwright-core": "1.35.0-alpha-1685046878000" }, "bin": { "playwright": "cli.js" }, "engines": { "node": ">=14" }, "optionalDependencies": { "fsevents": "2.3.2" } }, "node_modules/@types/node": { "version": "18.0.0", "resolved": "https://registry.npmjs.org/@types/node/-/node-18.0.0.tgz", "integrity": "sha512-cHlGmko4gWLVI27cGJntjs/Sj8th9aYwplmZFwmmgYQQvL5NUsgVJG7OddLvNfLqYS31KFN0s3qlaD9qCaxACA==" }, "node_modules/fsevents": { "version": "2.3.2", "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz", "integrity": "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==", "hasInstallScript": true, "optional": true, "os": [ "darwin" ], "engines": { "node": "^8.16.0 || ^10.6.0 || >=11.0.0" } }, "node_modules/playwright-core": { "version": "1.35.0-alpha-1685046878000", "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.35.0-alpha-1685046878000.tgz", "integrity": "sha512-2MdjKmIKazxVH4uZ8TSGjEJ6lpjfg4xgnCdoL46gKfKBd42mgPutfAplCGEtb0CRb9Oke8sYzo9HnA9EUuXQSg==", "bin": { "playwright-core": "cli.js" }, "engines": { "node": ">=14" } } }, "dependencies": { "@playwright/test": { "version": "1.35.0-alpha-1685046878000", "resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.35.0-alpha-1685046878000.tgz", "integrity": "sha512-OgZV/Ncwxjodqjl7FrOOaVUiPhxc6h3gYGw9ElKT9Eac+67wjZafDgdH8eGOSXIwwyHOqP+M4PM6T8sq3vyvyA==", "requires": { "@types/node": "*", "fsevents": "2.3.2", "playwright-core": "1.35.0-alpha-1685046878000" } }, "@types/node": { "version": "18.0.0", "resolved": "https://registry.npmjs.org/@types/node/-/node-18.0.0.tgz", "integrity": "sha512-cHlGmko4gWLVI27cGJntjs/Sj8th9aYwplmZFwmmgYQQvL5NUsgVJG7OddLvNfLqYS31KFN0s3qlaD9qCaxACA==" }, "fsevents": { "version": "2.3.2", "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz", "integrity": "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==", "optional": true }, "playwright-core": { "version": "1.35.0-alpha-1685046878000", "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.35.0-alpha-1685046878000.tgz", "integrity": "sha512-2MdjKmIKazxVH4uZ8TSGjEJ6lpjfg4xgnCdoL46gKfKBd42mgPutfAplCGEtb0CRb9Oke8sYzo9HnA9EUuXQSg==" } } }
tests/playwright-test/stable-test-runner/package-lock.json
1
https://github.com/microsoft/playwright/commit/624e88e504c4855b809c4e0ee3b1b8991f7e85fc
[ 0.9954853653907776, 0.11299969255924225, 0.00016506953397765756, 0.0014116954989731312, 0.3120175898075104 ]
{ "id": 2, "code_window": [ " \"dependencies\": {\n", " \"@types/node\": \"*\",\n", " \"playwright-core\": \"1.35.0-alpha-1685046878000\"\n", " },\n", " \"bin\": {\n", " \"playwright\": \"cli.js\"\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " \"playwright-core\": \"1.35.0-alpha-1685109821000\"\n" ], "file_path": "tests/playwright-test/stable-test-runner/package-lock.json", "type": "replace", "edit_start_line_idx": 16 }
/* Copyright (c) Microsoft Corporation. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ .call-tab { flex: auto; line-height: 24px; white-space: pre; overflow: auto; user-select: text; } .call-error { border-bottom: 1px solid var(--vscode-panel-border); padding: 3px 0 3px 12px; } .call-error .codicon { color: var(--vscode-errorForeground); position: relative; top: 2px; margin-right: 2px; } .call-section { padding-left: 6px; font-weight: bold; text-transform: uppercase; font-size: 10px; color: var(--vscode-sideBarTitle-foreground); line-height: 24px; } .call-section:not(:first-child) { border-top: 1px solid var(--vscode-panel-border); } .call-line { padding: 4px 0 4px 6px; display: flex; align-items: center; text-overflow: ellipsis; overflow: hidden; line-height: 18px; white-space: nowrap; } .copy-icon { display: none; margin-right: 4px; } .call-line:hover .copy-icon { display: block; cursor: pointer; } .call-value { margin-left: 2px; text-overflow: ellipsis; overflow: hidden; flex: 1; } .call-value::before { content: '\00a0'; } .call-value.datetime, .call-value.string, .call-value.locator { color: var(--orange); } .call-value.number, .call-value.bigint, .call-value.boolean, .call-value.symbol, .call-value.undefined, .call-value.function, .call-value.object { color: var(--blue); } .call-tab .error-message { padding: 5px; }
packages/trace-viewer/src/ui/callTab.css
0
https://github.com/microsoft/playwright/commit/624e88e504c4855b809c4e0ee3b1b8991f7e85fc
[ 0.00017477099027018994, 0.00017218287393916398, 0.0001675788953434676, 0.0001723073801258579, 0.0000022351532606990077 ]
{ "id": 2, "code_window": [ " \"dependencies\": {\n", " \"@types/node\": \"*\",\n", " \"playwright-core\": \"1.35.0-alpha-1685046878000\"\n", " },\n", " \"bin\": {\n", " \"playwright\": \"cli.js\"\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " \"playwright-core\": \"1.35.0-alpha-1685109821000\"\n" ], "file_path": "tests/playwright-test/stable-test-runner/package-lock.json", "type": "replace", "edit_start_line_idx": 16 }
/** * Copyright (c) Microsoft Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { test, expect } from './playwright-test-fixtures'; test('should merge options', async ({ runInlineTest }) => { const result = await runInlineTest({ 'a.test.ts': ` import { test as base, expect } from '@playwright/test'; const test = base.extend({ foo: 'foo', bar: 'bar', }); test.use({ foo: 'foo2' }); test.use({ bar: 'bar2' }); test('test', ({ foo, bar }) => { expect(foo).toBe('foo2'); expect(bar).toBe('bar2'); }); ` }); expect(result.exitCode).toBe(0); expect(result.passed).toBe(1); }); test('should run tests with different test options in the same worker', async ({ runInlineTest }) => { const result = await runInlineTest({ 'helper.ts': ` import { test as base } from '@playwright/test'; export * from '@playwright/test'; export const test = base.extend({ foo: 'foo', }); `, 'a.test.ts': ` import { test, expect } from './helper'; test('test', ({ foo }, testInfo) => { expect(foo).toBe('foo'); expect(testInfo.workerIndex).toBe(0); }); test.describe('suite1', () => { test.use({ foo: 'bar' }); test('test1', ({ foo }, testInfo) => { expect(foo).toBe('bar'); expect(testInfo.workerIndex).toBe(0); }); test.describe('suite2', () => { test.use({ foo: 'baz' }); test('test2', ({ foo }, testInfo) => { expect(foo).toBe('baz'); expect(testInfo.workerIndex).toBe(0); }); }); }); ` }, { workers: 1 }); expect(result.exitCode).toBe(0); expect(result.passed).toBe(3); }); test('should throw when setting worker options in describe', async ({ runInlineTest }) => { const result = await runInlineTest({ 'a.test.ts': ` import { test as base, expect } from '@playwright/test'; const test = base.extend({ foo: [undefined, { scope: 'worker' }], }); test.describe('suite', () => { test.use({ foo: 'bar' }); test('test', ({ foo }, testInfo) => { }); }); ` }, { workers: 1 }); expect(result.exitCode).toBe(1); expect(result.output).toContain([ `Cannot use({ foo }) in a describe group, because it forces a new worker.`, `Make it top-level in the test file or put in the configuration file.`, ].join('\n')); expect(result.output).toContain(`{ foo: 'bar' }`); }); test('should run tests with different worker options', async ({ runInlineTest }) => { const result = await runInlineTest({ 'helper.ts': ` import { test as base } from '@playwright/test'; export * from '@playwright/test'; export const test = base.extend({ foo: [undefined, { scope: 'worker' }], }); `, 'a.test.ts': ` import { test, expect } from './helper'; test('test', ({ foo }, testInfo) => { expect(foo).toBe(undefined); expect(testInfo.workerIndex).toBe(0); }); `, 'b.test.ts': ` import { test, expect } from './helper'; test.use({ foo: 'bar' }); test('test1', ({ foo }, testInfo) => { expect(foo).toBe('bar'); expect(testInfo.workerIndex).toBe(1); }); test('test2', ({ foo }, testInfo) => { expect(foo).toBe('bar'); expect(testInfo.workerIndex).toBe(1); }); `, 'c.test.ts': ` import { test, expect } from './helper'; test.use({ foo: 'baz' }); test('test2', ({ foo }, testInfo) => { expect(foo).toBe('baz'); expect(testInfo.workerIndex).toBe(2); }); ` }, { workers: 1 }); expect(result.exitCode).toBe(0); expect(result.passed).toBe(4); }); test('should use options from the config', async ({ runInlineTest }) => { const result = await runInlineTest({ 'helper.ts': ` import { test as base } from '@playwright/test'; export * from '@playwright/test'; export const test = base.extend({ foo: [ 'foo', { option: true } ], }); `, 'playwright.config.ts': ` module.exports = { use: { foo: 'bar' } }; `, 'a.test.ts': ` import { test, expect } from './helper'; test('test1', ({ foo }) => { expect(foo).toBe('bar'); }); test.describe('suite1', () => { test.use({ foo: 'baz' }); test('test2', ({ foo }) => { expect(foo).toBe('baz'); }); }); ` }); expect(result.exitCode).toBe(0); expect(result.passed).toBe(2); }); test('test.use() should throw if called from beforeAll ', async ({ runInlineTest }) => { const result = await runInlineTest({ 'a.test.ts': ` import { test, expect } from '@playwright/test'; test.beforeAll(() => { test.use({}); }); test('should work', async () => { }); `, }); expect(result.exitCode).toBe(1); expect(result.output).toContain('Playwright Test did not expect test.use() to be called here'); });
tests/playwright-test/test-use.spec.ts
0
https://github.com/microsoft/playwright/commit/624e88e504c4855b809c4e0ee3b1b8991f7e85fc
[ 0.00017697886505629867, 0.0001714196550892666, 0.00016503869846928865, 0.00017358087643515319, 0.000004025960151921026 ]
{ "id": 2, "code_window": [ " \"dependencies\": {\n", " \"@types/node\": \"*\",\n", " \"playwright-core\": \"1.35.0-alpha-1685046878000\"\n", " },\n", " \"bin\": {\n", " \"playwright\": \"cli.js\"\n" ], "labels": [ "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " \"playwright-core\": \"1.35.0-alpha-1685109821000\"\n" ], "file_path": "tests/playwright-test/stable-test-runner/package-lock.json", "type": "replace", "edit_start_line_idx": 16 }
/* Copyright (c) Microsoft Corporation. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ .error-message { font-family: var(--vscode-editor-font-family); font-weight: var(--vscode-editor-font-weight); font-size: var(--vscode-editor-font-size); background-color: var(--vscode-inputValidation-errorBackground); white-space: pre; overflow: auto; }
packages/web/src/components/errorMessage.css
0
https://github.com/microsoft/playwright/commit/624e88e504c4855b809c4e0ee3b1b8991f7e85fc
[ 0.00017604141612537205, 0.000172023952472955, 0.0001653295912547037, 0.00017470086459070444, 0.000004765163339470746 ]
{ "id": 3, "code_window": [ " \"engines\": {\n", " \"node\": \"^8.16.0 || ^10.6.0 || >=11.0.0\"\n", " }\n", " },\n", " \"node_modules/playwright-core\": {\n", " \"version\": \"1.35.0-alpha-1685046878000\",\n", " \"resolved\": \"https://registry.npmjs.org/playwright-core/-/playwright-core-1.35.0-alpha-1685046878000.tgz\",\n", " \"integrity\": \"sha512-2MdjKmIKazxVH4uZ8TSGjEJ6lpjfg4xgnCdoL46gKfKBd42mgPutfAplCGEtb0CRb9Oke8sYzo9HnA9EUuXQSg==\",\n", " \"bin\": {\n", " \"playwright-core\": \"cli.js\"\n", " },\n", " \"engines\": {\n", " \"node\": \">=14\"\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " \"version\": \"1.35.0-alpha-1685109821000\",\n", " \"resolved\": \"https://registry.npmjs.org/playwright-core/-/playwright-core-1.35.0-alpha-1685109821000.tgz\",\n", " \"integrity\": \"sha512-IuaxLekxpKacjz3g7weJAfUQoj0Uz/viWBADJTFXuyP3wMviqRqUgaat/i2H4vfOvvQeYmGpi9MXs8d3olE6cQ==\",\n" ], "file_path": "tests/playwright-test/stable-test-runner/package-lock.json", "type": "replace", "edit_start_line_idx": 47 }
{ "name": "stable-test-runner", "lockfileVersion": 2, "requires": true, "packages": { "": { "dependencies": { "@playwright/test": "1.35.0-alpha-1685046878000" } }, "node_modules/@playwright/test": { "version": "1.35.0-alpha-1685046878000", "resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.35.0-alpha-1685046878000.tgz", "integrity": "sha512-OgZV/Ncwxjodqjl7FrOOaVUiPhxc6h3gYGw9ElKT9Eac+67wjZafDgdH8eGOSXIwwyHOqP+M4PM6T8sq3vyvyA==", "dependencies": { "@types/node": "*", "playwright-core": "1.35.0-alpha-1685046878000" }, "bin": { "playwright": "cli.js" }, "engines": { "node": ">=14" }, "optionalDependencies": { "fsevents": "2.3.2" } }, "node_modules/@types/node": { "version": "18.0.0", "resolved": "https://registry.npmjs.org/@types/node/-/node-18.0.0.tgz", "integrity": "sha512-cHlGmko4gWLVI27cGJntjs/Sj8th9aYwplmZFwmmgYQQvL5NUsgVJG7OddLvNfLqYS31KFN0s3qlaD9qCaxACA==" }, "node_modules/fsevents": { "version": "2.3.2", "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz", "integrity": "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==", "hasInstallScript": true, "optional": true, "os": [ "darwin" ], "engines": { "node": "^8.16.0 || ^10.6.0 || >=11.0.0" } }, "node_modules/playwright-core": { "version": "1.35.0-alpha-1685046878000", "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.35.0-alpha-1685046878000.tgz", "integrity": "sha512-2MdjKmIKazxVH4uZ8TSGjEJ6lpjfg4xgnCdoL46gKfKBd42mgPutfAplCGEtb0CRb9Oke8sYzo9HnA9EUuXQSg==", "bin": { "playwright-core": "cli.js" }, "engines": { "node": ">=14" } } }, "dependencies": { "@playwright/test": { "version": "1.35.0-alpha-1685046878000", "resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.35.0-alpha-1685046878000.tgz", "integrity": "sha512-OgZV/Ncwxjodqjl7FrOOaVUiPhxc6h3gYGw9ElKT9Eac+67wjZafDgdH8eGOSXIwwyHOqP+M4PM6T8sq3vyvyA==", "requires": { "@types/node": "*", "fsevents": "2.3.2", "playwright-core": "1.35.0-alpha-1685046878000" } }, "@types/node": { "version": "18.0.0", "resolved": "https://registry.npmjs.org/@types/node/-/node-18.0.0.tgz", "integrity": "sha512-cHlGmko4gWLVI27cGJntjs/Sj8th9aYwplmZFwmmgYQQvL5NUsgVJG7OddLvNfLqYS31KFN0s3qlaD9qCaxACA==" }, "fsevents": { "version": "2.3.2", "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz", "integrity": "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==", "optional": true }, "playwright-core": { "version": "1.35.0-alpha-1685046878000", "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.35.0-alpha-1685046878000.tgz", "integrity": "sha512-2MdjKmIKazxVH4uZ8TSGjEJ6lpjfg4xgnCdoL46gKfKBd42mgPutfAplCGEtb0CRb9Oke8sYzo9HnA9EUuXQSg==" } } }
tests/playwright-test/stable-test-runner/package-lock.json
1
https://github.com/microsoft/playwright/commit/624e88e504c4855b809c4e0ee3b1b8991f7e85fc
[ 0.9961767196655273, 0.21054846048355103, 0.00037821329897269607, 0.004779275506734848, 0.3875497579574585 ]
{ "id": 3, "code_window": [ " \"engines\": {\n", " \"node\": \"^8.16.0 || ^10.6.0 || >=11.0.0\"\n", " }\n", " },\n", " \"node_modules/playwright-core\": {\n", " \"version\": \"1.35.0-alpha-1685046878000\",\n", " \"resolved\": \"https://registry.npmjs.org/playwright-core/-/playwright-core-1.35.0-alpha-1685046878000.tgz\",\n", " \"integrity\": \"sha512-2MdjKmIKazxVH4uZ8TSGjEJ6lpjfg4xgnCdoL46gKfKBd42mgPutfAplCGEtb0CRb9Oke8sYzo9HnA9EUuXQSg==\",\n", " \"bin\": {\n", " \"playwright-core\": \"cli.js\"\n", " },\n", " \"engines\": {\n", " \"node\": \">=14\"\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " \"version\": \"1.35.0-alpha-1685109821000\",\n", " \"resolved\": \"https://registry.npmjs.org/playwright-core/-/playwright-core-1.35.0-alpha-1685109821000.tgz\",\n", " \"integrity\": \"sha512-IuaxLekxpKacjz3g7weJAfUQoj0Uz/viWBADJTFXuyP3wMviqRqUgaat/i2H4vfOvvQeYmGpi9MXs8d3olE6cQ==\",\n" ], "file_path": "tests/playwright-test/stable-test-runner/package-lock.json", "type": "replace", "edit_start_line_idx": 47 }
FROM ubuntu:jammy ARG DEBIAN_FRONTEND=noninteractive ARG TZ=America/Los_Angeles ARG DOCKER_IMAGE_NAME_TEMPLATE="mcr.microsoft.com/playwright:v%version%-jammy" # === INSTALL Node.js === RUN apt-get update && \ # Install Node 18 apt-get install -y curl wget gpg && \ curl -sL https://deb.nodesource.com/setup_18.x | bash - && \ apt-get install -y nodejs && \ # Feature-parity with node.js base images. apt-get install -y --no-install-recommends git openssh-client && \ npm install -g yarn && \ # clean apt cache rm -rf /var/lib/apt/lists/* && \ # Create the pwuser adduser pwuser # === BAKE BROWSERS INTO IMAGE === ENV PLAYWRIGHT_BROWSERS_PATH=/ms-playwright # 1. Add tip-of-tree Playwright package to install its browsers. # The package should be built beforehand from tip-of-tree Playwright. COPY ./playwright-core.tar.gz /tmp/playwright-core.tar.gz # 2. Bake in browsers & deps. # Browsers will be downloaded in `/ms-playwright`. # Note: make sure to set 777 to the registry so that any user can access # registry. RUN mkdir /ms-playwright && \ mkdir /ms-playwright-agent && \ cd /ms-playwright-agent && npm init -y && \ npm i /tmp/playwright-core.tar.gz && \ npm exec --no -- playwright-core mark-docker-image "${DOCKER_IMAGE_NAME_TEMPLATE}" && \ npm exec --no -- playwright-core install --with-deps && rm -rf /var/lib/apt/lists/* && \ rm /tmp/playwright-core.tar.gz && \ rm -rf /ms-playwright-agent && \ chmod -R 777 /ms-playwright
utils/docker/Dockerfile.jammy
0
https://github.com/microsoft/playwright/commit/624e88e504c4855b809c4e0ee3b1b8991f7e85fc
[ 0.00020140723790973425, 0.00017920798563864082, 0.0001629368489375338, 0.00017993824440054595, 0.0000141850496220286 ]
{ "id": 3, "code_window": [ " \"engines\": {\n", " \"node\": \"^8.16.0 || ^10.6.0 || >=11.0.0\"\n", " }\n", " },\n", " \"node_modules/playwright-core\": {\n", " \"version\": \"1.35.0-alpha-1685046878000\",\n", " \"resolved\": \"https://registry.npmjs.org/playwright-core/-/playwright-core-1.35.0-alpha-1685046878000.tgz\",\n", " \"integrity\": \"sha512-2MdjKmIKazxVH4uZ8TSGjEJ6lpjfg4xgnCdoL46gKfKBd42mgPutfAplCGEtb0CRb9Oke8sYzo9HnA9EUuXQSg==\",\n", " \"bin\": {\n", " \"playwright-core\": \"cli.js\"\n", " },\n", " \"engines\": {\n", " \"node\": \">=14\"\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " \"version\": \"1.35.0-alpha-1685109821000\",\n", " \"resolved\": \"https://registry.npmjs.org/playwright-core/-/playwright-core-1.35.0-alpha-1685109821000.tgz\",\n", " \"integrity\": \"sha512-IuaxLekxpKacjz3g7weJAfUQoj0Uz/viWBADJTFXuyP3wMviqRqUgaat/i2H4vfOvvQeYmGpi9MXs8d3olE6cQ==\",\n" ], "file_path": "tests/playwright-test/stable-test-runner/package-lock.json", "type": "replace", "edit_start_line_idx": 47 }
{"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"} {"foo": "bar"}
tests/assets/simplezip.json
0
https://github.com/microsoft/playwright/commit/624e88e504c4855b809c4e0ee3b1b8991f7e85fc
[ 0.00016434240387752652, 0.00016432932170573622, 0.00016388420772273093, 0.00016434240387752652, 7.633484955249514e-8 ]
{ "id": 3, "code_window": [ " \"engines\": {\n", " \"node\": \"^8.16.0 || ^10.6.0 || >=11.0.0\"\n", " }\n", " },\n", " \"node_modules/playwright-core\": {\n", " \"version\": \"1.35.0-alpha-1685046878000\",\n", " \"resolved\": \"https://registry.npmjs.org/playwright-core/-/playwright-core-1.35.0-alpha-1685046878000.tgz\",\n", " \"integrity\": \"sha512-2MdjKmIKazxVH4uZ8TSGjEJ6lpjfg4xgnCdoL46gKfKBd42mgPutfAplCGEtb0CRb9Oke8sYzo9HnA9EUuXQSg==\",\n", " \"bin\": {\n", " \"playwright-core\": \"cli.js\"\n", " },\n", " \"engines\": {\n", " \"node\": \">=14\"\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " \"version\": \"1.35.0-alpha-1685109821000\",\n", " \"resolved\": \"https://registry.npmjs.org/playwright-core/-/playwright-core-1.35.0-alpha-1685109821000.tgz\",\n", " \"integrity\": \"sha512-IuaxLekxpKacjz3g7weJAfUQoj0Uz/viWBADJTFXuyP3wMviqRqUgaat/i2H4vfOvvQeYmGpi9MXs8d3olE6cQ==\",\n" ], "file_path": "tests/playwright-test/stable-test-runner/package-lock.json", "type": "replace", "edit_start_line_idx": 47 }
#!/bin/bash set -e if [[ ($1 == '--help') || ($1 == '-h') ]]; then echo "usage: $(basename $0) {--stable,--beta,--canary}" echo echo "Build the Trace Viewer and push it to the GitHub repository." echo echo "NOTE: the following env variables are required:" echo " GH_SERVICE_ACCOUNT_TOKEN GitHub token with access to the microsoft/trace.playwright.dev repository" echo " GITHUB_SHA GitHub commit SHA - injected via GitHub Actions" echo echo "This script is designed to get executed via GitHub Actions" exit 0 fi if [[ -z "${GH_SERVICE_ACCOUNT_TOKEN}" ]]; then echo "NOTE: GH_SERVICE_ACCOUNT_TOKEN environment variable is required" exit 1 fi RELEASE_CHANNEL="$1" # 1. Install dependencies and build the Trace Viewer npm ci npm run build # 2. Configure Git and clone the Trace Viewer repository git config --global user.name github-actions git config --global user.email 41898282+github-actions[bot]@users.noreply.github.com git clone "https://${GH_SERVICE_ACCOUNT_TOKEN}@github.com/microsoft/trace.playwright.dev.git" trace.playwright.dev # 3. Copy the built Trace Viewer to the repository if [[ "${RELEASE_CHANNEL}" == "--stable" ]]; then rm -rf trace.playwright.dev/docs/ mkdir trace.playwright.dev/docs/ cp -r packages/playwright-core/lib/webpack/traceViewer/* trace.playwright.dev/docs/ # Restore CNAME, beta/ & next/ branches. cd trace.playwright.dev/ git checkout docs/beta git checkout docs/next git checkout docs/CNAME cd - echo "Updated stable version" elif [[ "${RELEASE_CHANNEL}" == "--canary" ]]; then rm -rf trace.playwright.dev/docs/next/ cp -r packages/playwright-core/lib/webpack/traceViewer/ trace.playwright.dev/docs/next/ echo "Updated canary version" elif [[ "${RELEASE_CHANNEL}" == "--beta" ]]; then rm -rf trace.playwright.dev/docs/beta/ cp -r packages/playwright-core/lib/webpack/traceViewer/ trace.playwright.dev/docs/beta/ echo "Updated beta version" else echo "ERROR: unknown environment - ${RELEASE_CHANNEL}" exit 1 fi # 4. Commit and push the changes cd trace.playwright.dev/ git add . if [[ "$(git status --porcelain)" == "" ]]; then echo "there are no changes"; exit 0; fi git commit -m "Update Trace Viewer Upstream commit: https://github.com/microsoft/playwright/commit/$GITHUB_SHA" git push origin echo "Pushed changes successfully!"
utils/build/deploy-trace-viewer.sh
0
https://github.com/microsoft/playwright/commit/624e88e504c4855b809c4e0ee3b1b8991f7e85fc
[ 0.00027983266045339406, 0.000184330900083296, 0.0001638071844354272, 0.0001668603508733213, 0.00003688269134727307 ]
{ "id": 4, "code_window": [ " }\n", " }\n", " },\n", " \"dependencies\": {\n", " \"@playwright/test\": {\n", " \"version\": \"1.35.0-alpha-1685046878000\",\n", " \"resolved\": \"https://registry.npmjs.org/@playwright/test/-/test-1.35.0-alpha-1685046878000.tgz\",\n", " \"integrity\": \"sha512-OgZV/Ncwxjodqjl7FrOOaVUiPhxc6h3gYGw9ElKT9Eac+67wjZafDgdH8eGOSXIwwyHOqP+M4PM6T8sq3vyvyA==\",\n", " \"requires\": {\n", " \"@types/node\": \"*\",\n", " \"fsevents\": \"2.3.2\",\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ " \"version\": \"1.35.0-alpha-1685109821000\",\n", " \"resolved\": \"https://registry.npmjs.org/@playwright/test/-/test-1.35.0-alpha-1685109821000.tgz\",\n", " \"integrity\": \"sha512-FX1g4UHazT58jr4FbPKyr+Iw87umRz4jxlViZiS1x4FB87XW6VYRaViaXOPnI+sD/p8c4SMde+vSetHwkBLwpQ==\",\n" ], "file_path": "tests/playwright-test/stable-test-runner/package-lock.json", "type": "replace", "edit_start_line_idx": 60 }
{ "name": "stable-test-runner", "lockfileVersion": 2, "requires": true, "packages": { "": { "dependencies": { "@playwright/test": "1.35.0-alpha-1685046878000" } }, "node_modules/@playwright/test": { "version": "1.35.0-alpha-1685046878000", "resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.35.0-alpha-1685046878000.tgz", "integrity": "sha512-OgZV/Ncwxjodqjl7FrOOaVUiPhxc6h3gYGw9ElKT9Eac+67wjZafDgdH8eGOSXIwwyHOqP+M4PM6T8sq3vyvyA==", "dependencies": { "@types/node": "*", "playwright-core": "1.35.0-alpha-1685046878000" }, "bin": { "playwright": "cli.js" }, "engines": { "node": ">=14" }, "optionalDependencies": { "fsevents": "2.3.2" } }, "node_modules/@types/node": { "version": "18.0.0", "resolved": "https://registry.npmjs.org/@types/node/-/node-18.0.0.tgz", "integrity": "sha512-cHlGmko4gWLVI27cGJntjs/Sj8th9aYwplmZFwmmgYQQvL5NUsgVJG7OddLvNfLqYS31KFN0s3qlaD9qCaxACA==" }, "node_modules/fsevents": { "version": "2.3.2", "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz", "integrity": "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==", "hasInstallScript": true, "optional": true, "os": [ "darwin" ], "engines": { "node": "^8.16.0 || ^10.6.0 || >=11.0.0" } }, "node_modules/playwright-core": { "version": "1.35.0-alpha-1685046878000", "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.35.0-alpha-1685046878000.tgz", "integrity": "sha512-2MdjKmIKazxVH4uZ8TSGjEJ6lpjfg4xgnCdoL46gKfKBd42mgPutfAplCGEtb0CRb9Oke8sYzo9HnA9EUuXQSg==", "bin": { "playwright-core": "cli.js" }, "engines": { "node": ">=14" } } }, "dependencies": { "@playwright/test": { "version": "1.35.0-alpha-1685046878000", "resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.35.0-alpha-1685046878000.tgz", "integrity": "sha512-OgZV/Ncwxjodqjl7FrOOaVUiPhxc6h3gYGw9ElKT9Eac+67wjZafDgdH8eGOSXIwwyHOqP+M4PM6T8sq3vyvyA==", "requires": { "@types/node": "*", "fsevents": "2.3.2", "playwright-core": "1.35.0-alpha-1685046878000" } }, "@types/node": { "version": "18.0.0", "resolved": "https://registry.npmjs.org/@types/node/-/node-18.0.0.tgz", "integrity": "sha512-cHlGmko4gWLVI27cGJntjs/Sj8th9aYwplmZFwmmgYQQvL5NUsgVJG7OddLvNfLqYS31KFN0s3qlaD9qCaxACA==" }, "fsevents": { "version": "2.3.2", "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz", "integrity": "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==", "optional": true }, "playwright-core": { "version": "1.35.0-alpha-1685046878000", "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.35.0-alpha-1685046878000.tgz", "integrity": "sha512-2MdjKmIKazxVH4uZ8TSGjEJ6lpjfg4xgnCdoL46gKfKBd42mgPutfAplCGEtb0CRb9Oke8sYzo9HnA9EUuXQSg==" } } }
tests/playwright-test/stable-test-runner/package-lock.json
1
https://github.com/microsoft/playwright/commit/624e88e504c4855b809c4e0ee3b1b8991f7e85fc
[ 0.9837270975112915, 0.2265613079071045, 0.0001702200243016705, 0.005802033934742212, 0.40377864241600037 ]
{ "id": 4, "code_window": [ " }\n", " }\n", " },\n", " \"dependencies\": {\n", " \"@playwright/test\": {\n", " \"version\": \"1.35.0-alpha-1685046878000\",\n", " \"resolved\": \"https://registry.npmjs.org/@playwright/test/-/test-1.35.0-alpha-1685046878000.tgz\",\n", " \"integrity\": \"sha512-OgZV/Ncwxjodqjl7FrOOaVUiPhxc6h3gYGw9ElKT9Eac+67wjZafDgdH8eGOSXIwwyHOqP+M4PM6T8sq3vyvyA==\",\n", " \"requires\": {\n", " \"@types/node\": \"*\",\n", " \"fsevents\": \"2.3.2\",\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ " \"version\": \"1.35.0-alpha-1685109821000\",\n", " \"resolved\": \"https://registry.npmjs.org/@playwright/test/-/test-1.35.0-alpha-1685109821000.tgz\",\n", " \"integrity\": \"sha512-FX1g4UHazT58jr4FbPKyr+Iw87umRz4jxlViZiS1x4FB87XW6VYRaViaXOPnI+sD/p8c4SMde+vSetHwkBLwpQ==\",\n" ], "file_path": "tests/playwright-test/stable-test-runner/package-lock.json", "type": "replace", "edit_start_line_idx": 60 }
<style> body { margin: 0; padding: 0; } div { display: inline-flex; width: 50px; height: 50px; border-right: 1px solid black; border-bottom: 1px solid black; } </style> <body></body> <script> const colors = ['#222', '#444', '#666', '#888', '#aaa']; for (let i = 0; i < 200; ++i) { const div = document.createElement('div'); div.style.setProperty('background-color', colors[i % 5]); document.body.appendChild(div); } </script>
tests/assets/overflow.html
0
https://github.com/microsoft/playwright/commit/624e88e504c4855b809c4e0ee3b1b8991f7e85fc
[ 0.00017076007497962564, 0.00016730291827116162, 0.0001629940525162965, 0.00016815464186947793, 0.0000032271600503008813 ]
{ "id": 4, "code_window": [ " }\n", " }\n", " },\n", " \"dependencies\": {\n", " \"@playwright/test\": {\n", " \"version\": \"1.35.0-alpha-1685046878000\",\n", " \"resolved\": \"https://registry.npmjs.org/@playwright/test/-/test-1.35.0-alpha-1685046878000.tgz\",\n", " \"integrity\": \"sha512-OgZV/Ncwxjodqjl7FrOOaVUiPhxc6h3gYGw9ElKT9Eac+67wjZafDgdH8eGOSXIwwyHOqP+M4PM6T8sq3vyvyA==\",\n", " \"requires\": {\n", " \"@types/node\": \"*\",\n", " \"fsevents\": \"2.3.2\",\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ " \"version\": \"1.35.0-alpha-1685109821000\",\n", " \"resolved\": \"https://registry.npmjs.org/@playwright/test/-/test-1.35.0-alpha-1685109821000.tgz\",\n", " \"integrity\": \"sha512-FX1g4UHazT58jr4FbPKyr+Iw87umRz4jxlViZiS1x4FB87XW6VYRaViaXOPnI+sD/p8c4SMde+vSetHwkBLwpQ==\",\n" ], "file_path": "tests/playwright-test/stable-test-runner/package-lock.json", "type": "replace", "edit_start_line_idx": 60 }
/** * Copyright (c) Microsoft Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { test, expect } from './npmTest'; test('codegen should work', async ({ exec }) => { await exec('npm i --foreground-scripts playwright'); await test.step('codegen without arguments', async () => { const result = await exec('npx playwright codegen', { env: { PWTEST_CLI_IS_UNDER_TEST: '1', PWTEST_CLI_AUTO_EXIT_WHEN: '@playwright/test', } }); expect(result).toContain(`{ page }`); }); await test.step('codegen --target=javascript', async () => { const result = await exec('npx playwright codegen --target=javascript', { env: { PWTEST_CLI_IS_UNDER_TEST: '1', PWTEST_CLI_AUTO_EXIT_WHEN: 'context.close', } }); expect(result).toContain(`playwright`); }); await test.step('codegen --target=python', async () => { const result = await exec('npx playwright codegen --target=python', { env: { PWTEST_CLI_IS_UNDER_TEST: '1', PWTEST_CLI_AUTO_EXIT_WHEN: 'chromium.launch', }, }); expect(result).toContain(`browser.close`); }); });
tests/installation/playwright-cli-codegen.spec.ts
0
https://github.com/microsoft/playwright/commit/624e88e504c4855b809c4e0ee3b1b8991f7e85fc
[ 0.0001736341801006347, 0.00016891442646738142, 0.00016486598178744316, 0.00016799938748590648, 0.0000030857604542688932 ]
{ "id": 4, "code_window": [ " }\n", " }\n", " },\n", " \"dependencies\": {\n", " \"@playwright/test\": {\n", " \"version\": \"1.35.0-alpha-1685046878000\",\n", " \"resolved\": \"https://registry.npmjs.org/@playwright/test/-/test-1.35.0-alpha-1685046878000.tgz\",\n", " \"integrity\": \"sha512-OgZV/Ncwxjodqjl7FrOOaVUiPhxc6h3gYGw9ElKT9Eac+67wjZafDgdH8eGOSXIwwyHOqP+M4PM6T8sq3vyvyA==\",\n", " \"requires\": {\n", " \"@types/node\": \"*\",\n", " \"fsevents\": \"2.3.2\",\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ " \"version\": \"1.35.0-alpha-1685109821000\",\n", " \"resolved\": \"https://registry.npmjs.org/@playwright/test/-/test-1.35.0-alpha-1685109821000.tgz\",\n", " \"integrity\": \"sha512-FX1g4UHazT58jr4FbPKyr+Iw87umRz4jxlViZiS1x4FB87XW6VYRaViaXOPnI+sD/p8c4SMde+vSetHwkBLwpQ==\",\n" ], "file_path": "tests/playwright-test/stable-test-runner/package-lock.json", "type": "replace", "edit_start_line_idx": 60 }
<!doctype html> <html> <head> <title>Name test case 746</title> <meta content="text/html; charset=utf-8" http-equiv="Content-Type"/> <link rel="stylesheet" href="/wai-aria/scripts/manual.css"> <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> <script src="/wai-aria/scripts/ATTAcomm.js"></script> <script> setup({explicit_timeout: true, explicit_done: true }); var theTest = new ATTAcomm( { "steps" : [ { "element" : "test", "test" : { "ATK" : [ [ "property", "name", "is", "crazy 4" ] ], "AXAPI" : [ [ "property", "AXDescription", "is", "crazy 4" ] ], "IAccessible2" : [ [ "property", "accName", "is", "crazy 4" ] ], "UIA" : [ [ "property", "Name", "is", "crazy 4" ] ] }, "title" : "step 1", "type" : "test" } ], "title" : "Name test case 746" } ) ; </script> </head> <body> <p>This test examines the ARIA properties for Name test case 746.</p> <label for="test"> crazy <div role="spinbutton" aria-valuemin="1" aria-valuemax="7" aria-valuenow="4"> </div> </label> <input type="file" id="test"/> <div id="manualMode"></div> <div id="log"></div> <div id="ATTAmessages"></div> </body> </html>
tests/assets/wpt/accname/name_test_case_746-manual.html
0
https://github.com/microsoft/playwright/commit/624e88e504c4855b809c4e0ee3b1b8991f7e85fc
[ 0.00017323480278719217, 0.00016992082237266004, 0.00016777843120507896, 0.00016934203449636698, 0.00000177776598775381 ]
{ "id": 5, "code_window": [ " \"requires\": {\n", " \"@types/node\": \"*\",\n", " \"fsevents\": \"2.3.2\",\n", " \"playwright-core\": \"1.35.0-alpha-1685046878000\"\n", " }\n", " },\n", " \"@types/node\": {\n", " \"version\": \"18.0.0\",\n", " \"resolved\": \"https://registry.npmjs.org/@types/node/-/node-18.0.0.tgz\",\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " \"playwright-core\": \"1.35.0-alpha-1685109821000\"\n" ], "file_path": "tests/playwright-test/stable-test-runner/package-lock.json", "type": "replace", "edit_start_line_idx": 66 }
{ "private": true, "dependencies": { "@playwright/test": "1.35.0-alpha-1685046878000" } }
tests/playwright-test/stable-test-runner/package.json
1
https://github.com/microsoft/playwright/commit/624e88e504c4855b809c4e0ee3b1b8991f7e85fc
[ 0.00438626017421484, 0.00438626017421484, 0.00438626017421484, 0.00438626017421484, 0 ]
{ "id": 5, "code_window": [ " \"requires\": {\n", " \"@types/node\": \"*\",\n", " \"fsevents\": \"2.3.2\",\n", " \"playwright-core\": \"1.35.0-alpha-1685046878000\"\n", " }\n", " },\n", " \"@types/node\": {\n", " \"version\": \"18.0.0\",\n", " \"resolved\": \"https://registry.npmjs.org/@types/node/-/node-18.0.0.tgz\",\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " \"playwright-core\": \"1.35.0-alpha-1685109821000\"\n" ], "file_path": "tests/playwright-test/stable-test-runner/package-lock.json", "type": "replace", "edit_start_line_idx": 66 }
<main>Login</main>
tests/components/ct-svelte-vite/src/pages/LoginPage.svelte
0
https://github.com/microsoft/playwright/commit/624e88e504c4855b809c4e0ee3b1b8991f7e85fc
[ 0.00016711727948859334, 0.00016711727948859334, 0.00016711727948859334, 0.00016711727948859334, 0 ]
{ "id": 5, "code_window": [ " \"requires\": {\n", " \"@types/node\": \"*\",\n", " \"fsevents\": \"2.3.2\",\n", " \"playwright-core\": \"1.35.0-alpha-1685046878000\"\n", " }\n", " },\n", " \"@types/node\": {\n", " \"version\": \"18.0.0\",\n", " \"resolved\": \"https://registry.npmjs.org/@types/node/-/node-18.0.0.tgz\",\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " \"playwright-core\": \"1.35.0-alpha-1685109821000\"\n" ], "file_path": "tests/playwright-test/stable-test-runner/package-lock.json", "type": "replace", "edit_start_line_idx": 66 }
import { createApp } from 'vue'; import App from './App.vue'; import './assets/index.css'; import { router } from './router'; createApp(App).use(router).mount('#app');
tests/components/ct-vue-vite/src/main.js
0
https://github.com/microsoft/playwright/commit/624e88e504c4855b809c4e0ee3b1b8991f7e85fc
[ 0.00017082536942325532, 0.00017082536942325532, 0.00017082536942325532, 0.00017082536942325532, 0 ]
{ "id": 5, "code_window": [ " \"requires\": {\n", " \"@types/node\": \"*\",\n", " \"fsevents\": \"2.3.2\",\n", " \"playwright-core\": \"1.35.0-alpha-1685046878000\"\n", " }\n", " },\n", " \"@types/node\": {\n", " \"version\": \"18.0.0\",\n", " \"resolved\": \"https://registry.npmjs.org/@types/node/-/node-18.0.0.tgz\",\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " \"playwright-core\": \"1.35.0-alpha-1685109821000\"\n" ], "file_path": "tests/playwright-test/stable-test-runner/package-lock.json", "type": "replace", "edit_start_line_idx": 66 }
{ "log": { "version": "1.2", "creator": { "name": "Playwright", "version": "1.23.0-next" }, "browser": { "name": "chromium", "version": "103.0.5060.33" }, "pages": [ { "startedDateTime": "2022-06-10T04:27:32.125Z", "id": "page@b17b177f1c2e66459db3dcbe44636ffd", "title": "Hey", "pageTimings": { "onContentLoad": 70, "onLoad": 70 } } ], "entries": [ { "_frameref": "frame@c7467fc0f1f86f09fc3b0d727a3862ea", "_monotonicTime": 270572145.898, "startedDateTime": "2022-06-10T04:27:32.146Z", "time": 8.286, "request": { "method": "GET", "url": "http://no.playwright/", "httpVersion": "HTTP/1.1", "cookies": [], "headers": [ { "name": "Accept", "value": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9" }, { "name": "Upgrade-Insecure-Requests", "value": "1" }, { "name": "User-Agent", "value": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.5060.33 Safari/537.36" } ], "queryString": [], "headersSize": 326, "bodySize": 0 }, "response": { "status": 200, "statusText": "OK", "httpVersion": "HTTP/1.1", "cookies": [], "headers": [ { "name": "content-length", "value": "111" }, { "name": "content-type", "value": "text/html" } ], "content": { "size": 111, "mimeType": "text/html", "compression": 0, "text": "<title>Hey</title><link rel='stylesheet' href='./style.css'><script src='./script.js'></script><div>hello</div>" }, "headersSize": 65, "bodySize": 170, "redirectURL": "", "_transferSize": 170 }, "cache": { "beforeRequest": null, "afterRequest": null }, "timings": { "dns": -1, "connect": -1, "ssl": -1, "send": 0, "wait": 8.286, "receive": -1 }, "pageref": "page@b17b177f1c2e66459db3dcbe44636ffd", "_securityDetails": {} }, { "_frameref": "frame@c7467fc0f1f86f09fc3b0d727a3862ea", "_monotonicTime": 270572174.683, "startedDateTime": "2022-06-10T04:27:32.172Z", "time": 7.132, "request": { "method": "POST", "url": "http://no.playwright/style.css", "httpVersion": "HTTP/1.1", "cookies": [], "headers": [ { "name": "Accept", "value": "text/css,*/*;q=0.1" }, { "name": "Referer", "value": "http://no.playwright/" }, { "name": "User-Agent", "value": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.5060.33 Safari/537.36" } ], "queryString": [], "headersSize": 220, "bodySize": 0 }, "response": { "status": 200, "statusText": "OK", "httpVersion": "HTTP/1.1", "cookies": [], "headers": [ { "name": "content-length", "value": "24" }, { "name": "content-type", "value": "text/css" } ], "content": { "size": 24, "mimeType": "text/css", "compression": 0, "text": "body { background:cyan }" }, "headersSize": 63, "bodySize": 81, "redirectURL": "", "_transferSize": 81 }, "cache": { "beforeRequest": null, "afterRequest": null }, "timings": { "dns": -1, "connect": -1, "ssl": -1, "send": 0, "wait": 8.132, "receive": -1 }, "pageref": "page@b17b177f1c2e66459db3dcbe44636ffd", "_securityDetails": {} }, { "_frameref": "frame@c7467fc0f1f86f09fc3b0d727a3862ea", "_monotonicTime": 270572174.683, "startedDateTime": "2022-06-10T04:27:32.174Z", "time": 8.132, "request": { "method": "GET", "url": "http://no.playwright/style.css", "httpVersion": "HTTP/1.1", "cookies": [], "headers": [ { "name": "Accept", "value": "text/css,*/*;q=0.1" }, { "name": "Referer", "value": "http://no.playwright/" }, { "name": "User-Agent", "value": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.5060.33 Safari/537.36" } ], "queryString": [], "headersSize": 220, "bodySize": 0 }, "response": { "status": 200, "statusText": "OK", "httpVersion": "HTTP/1.1", "cookies": [], "headers": [ { "name": "content-length", "value": "24" }, { "name": "content-type", "value": "text/css" } ], "content": { "size": 24, "mimeType": "text/css", "compression": 0, "text": "body { background: red }" }, "headersSize": 63, "bodySize": 81, "redirectURL": "", "_transferSize": 81 }, "cache": { "beforeRequest": null, "afterRequest": null }, "timings": { "dns": -1, "connect": -1, "ssl": -1, "send": 0, "wait": 8.132, "receive": -1 }, "pageref": "page@b17b177f1c2e66459db3dcbe44636ffd", "_securityDetails": {} }, { "_frameref": "frame@c7467fc0f1f86f09fc3b0d727a3862ea", "_monotonicTime": 270572175.042, "startedDateTime": "2022-06-10T04:27:32.175Z", "time": 15.997, "request": { "method": "GET", "url": "http://no.playwright/script.js", "httpVersion": "HTTP/1.1", "cookies": [], "headers": [ { "name": "Accept", "value": "*/*" }, { "name": "Referer", "value": "http://no.playwright/" }, { "name": "User-Agent", "value": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.5060.33 Safari/537.36" } ], "queryString": [], "headersSize": 205, "bodySize": 0 }, "response": { "status": 301, "statusText": "Moved Permanently", "httpVersion": "HTTP/1.1", "cookies": [], "headers": [ { "name": "location", "value": "http://no.playwright/script2.js" } ], "content": { "size": -1, "mimeType": "x-unknown", "compression": 0 }, "headersSize": 77, "bodySize": 0, "redirectURL": "http://no.playwright/script2.js", "_transferSize": 77 }, "cache": { "beforeRequest": null, "afterRequest": null }, "timings": { "dns": -1, "connect": -1, "ssl": -1, "send": 0, "wait": 7.673, "receive": 8.324 }, "pageref": "page@b17b177f1c2e66459db3dcbe44636ffd", "_securityDetails": {} }, { "_frameref": "frame@c7467fc0f1f86f09fc3b0d727a3862ea", "_monotonicTime": 270572181.822, "startedDateTime": "2022-06-10T04:27:32.182Z", "time": 6.735, "request": { "method": "GET", "url": "http://no.playwright/script2.js", "httpVersion": "HTTP/1.1", "cookies": [], "headers": [ { "name": "Accept", "value": "*/*" }, { "name": "Referer", "value": "http://no.playwright/" }, { "name": "User-Agent", "value": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.5060.33 Safari/537.36" } ], "queryString": [], "headersSize": 206, "bodySize": 0 }, "response": { "status": 200, "statusText": "OK", "httpVersion": "HTTP/1.1", "cookies": [], "headers": [ { "name": "content-length", "value": "18" }, { "name": "content-type", "value": "text/javascript" } ], "content": { "size": 18, "mimeType": "text/javascript", "compression": 0, "text": "window.value='foo'" }, "headersSize": 70, "bodySize": 82, "redirectURL": "", "_transferSize": 82 }, "cache": { "beforeRequest": null, "afterRequest": null }, "timings": { "dns": -1, "connect": -1, "ssl": -1, "send": 0, "wait": 6.735, "receive": -1 }, "pageref": "page@b17b177f1c2e66459db3dcbe44636ffd", "_securityDetails": {} } ] } }
tests/assets/har-fulfill.har
0
https://github.com/microsoft/playwright/commit/624e88e504c4855b809c4e0ee3b1b8991f7e85fc
[ 0.0002335623576072976, 0.00017141138960141689, 0.00016344879986718297, 0.0001667804317548871, 0.000013423617019725498 ]
{ "id": 6, "code_window": [ " \"optional\": true\n", " },\n", " \"playwright-core\": {\n", " \"version\": \"1.35.0-alpha-1685046878000\",\n", " \"resolved\": \"https://registry.npmjs.org/playwright-core/-/playwright-core-1.35.0-alpha-1685046878000.tgz\",\n", " \"integrity\": \"sha512-2MdjKmIKazxVH4uZ8TSGjEJ6lpjfg4xgnCdoL46gKfKBd42mgPutfAplCGEtb0CRb9Oke8sYzo9HnA9EUuXQSg==\"\n", " }\n", " }\n", "}" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ " \"version\": \"1.35.0-alpha-1685109821000\",\n", " \"resolved\": \"https://registry.npmjs.org/playwright-core/-/playwright-core-1.35.0-alpha-1685109821000.tgz\",\n", " \"integrity\": \"sha512-IuaxLekxpKacjz3g7weJAfUQoj0Uz/viWBADJTFXuyP3wMviqRqUgaat/i2H4vfOvvQeYmGpi9MXs8d3olE6cQ==\"\n" ], "file_path": "tests/playwright-test/stable-test-runner/package-lock.json", "type": "replace", "edit_start_line_idx": 81 }
{ "name": "stable-test-runner", "lockfileVersion": 2, "requires": true, "packages": { "": { "dependencies": { "@playwright/test": "1.35.0-alpha-1685046878000" } }, "node_modules/@playwright/test": { "version": "1.35.0-alpha-1685046878000", "resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.35.0-alpha-1685046878000.tgz", "integrity": "sha512-OgZV/Ncwxjodqjl7FrOOaVUiPhxc6h3gYGw9ElKT9Eac+67wjZafDgdH8eGOSXIwwyHOqP+M4PM6T8sq3vyvyA==", "dependencies": { "@types/node": "*", "playwright-core": "1.35.0-alpha-1685046878000" }, "bin": { "playwright": "cli.js" }, "engines": { "node": ">=14" }, "optionalDependencies": { "fsevents": "2.3.2" } }, "node_modules/@types/node": { "version": "18.0.0", "resolved": "https://registry.npmjs.org/@types/node/-/node-18.0.0.tgz", "integrity": "sha512-cHlGmko4gWLVI27cGJntjs/Sj8th9aYwplmZFwmmgYQQvL5NUsgVJG7OddLvNfLqYS31KFN0s3qlaD9qCaxACA==" }, "node_modules/fsevents": { "version": "2.3.2", "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz", "integrity": "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==", "hasInstallScript": true, "optional": true, "os": [ "darwin" ], "engines": { "node": "^8.16.0 || ^10.6.0 || >=11.0.0" } }, "node_modules/playwright-core": { "version": "1.35.0-alpha-1685046878000", "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.35.0-alpha-1685046878000.tgz", "integrity": "sha512-2MdjKmIKazxVH4uZ8TSGjEJ6lpjfg4xgnCdoL46gKfKBd42mgPutfAplCGEtb0CRb9Oke8sYzo9HnA9EUuXQSg==", "bin": { "playwright-core": "cli.js" }, "engines": { "node": ">=14" } } }, "dependencies": { "@playwright/test": { "version": "1.35.0-alpha-1685046878000", "resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.35.0-alpha-1685046878000.tgz", "integrity": "sha512-OgZV/Ncwxjodqjl7FrOOaVUiPhxc6h3gYGw9ElKT9Eac+67wjZafDgdH8eGOSXIwwyHOqP+M4PM6T8sq3vyvyA==", "requires": { "@types/node": "*", "fsevents": "2.3.2", "playwright-core": "1.35.0-alpha-1685046878000" } }, "@types/node": { "version": "18.0.0", "resolved": "https://registry.npmjs.org/@types/node/-/node-18.0.0.tgz", "integrity": "sha512-cHlGmko4gWLVI27cGJntjs/Sj8th9aYwplmZFwmmgYQQvL5NUsgVJG7OddLvNfLqYS31KFN0s3qlaD9qCaxACA==" }, "fsevents": { "version": "2.3.2", "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz", "integrity": "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==", "optional": true }, "playwright-core": { "version": "1.35.0-alpha-1685046878000", "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.35.0-alpha-1685046878000.tgz", "integrity": "sha512-2MdjKmIKazxVH4uZ8TSGjEJ6lpjfg4xgnCdoL46gKfKBd42mgPutfAplCGEtb0CRb9Oke8sYzo9HnA9EUuXQSg==" } } }
tests/playwright-test/stable-test-runner/package-lock.json
1
https://github.com/microsoft/playwright/commit/624e88e504c4855b809c4e0ee3b1b8991f7e85fc
[ 0.9787126779556274, 0.23191149532794952, 0.00016615503409411758, 0.0064456528052687645, 0.400240421295166 ]
{ "id": 6, "code_window": [ " \"optional\": true\n", " },\n", " \"playwright-core\": {\n", " \"version\": \"1.35.0-alpha-1685046878000\",\n", " \"resolved\": \"https://registry.npmjs.org/playwright-core/-/playwright-core-1.35.0-alpha-1685046878000.tgz\",\n", " \"integrity\": \"sha512-2MdjKmIKazxVH4uZ8TSGjEJ6lpjfg4xgnCdoL46gKfKBd42mgPutfAplCGEtb0CRb9Oke8sYzo9HnA9EUuXQSg==\"\n", " }\n", " }\n", "}" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ " \"version\": \"1.35.0-alpha-1685109821000\",\n", " \"resolved\": \"https://registry.npmjs.org/playwright-core/-/playwright-core-1.35.0-alpha-1685109821000.tgz\",\n", " \"integrity\": \"sha512-IuaxLekxpKacjz3g7weJAfUQoj0Uz/viWBADJTFXuyP3wMviqRqUgaat/i2H4vfOvvQeYmGpi9MXs8d3olE6cQ==\"\n" ], "file_path": "tests/playwright-test/stable-test-runner/package-lock.json", "type": "replace", "edit_start_line_idx": 81 }
/** * Copyright (c) Microsoft Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { escapeWithQuotes, toSnakeCase, toTitleCase } from './stringUtils'; import { type NestedSelectorBody, parseAttributeSelector, parseSelector, stringifySelector } from './selectorParser'; import type { ParsedSelector } from './selectorParser'; export type Language = 'javascript' | 'python' | 'java' | 'csharp' | 'jsonl'; export type LocatorType = 'default' | 'role' | 'text' | 'label' | 'placeholder' | 'alt' | 'title' | 'test-id' | 'nth' | 'first' | 'last' | 'has-text' | 'has-not-text' | 'has' | 'hasNot' | 'frame' | 'and' | 'or'; export type LocatorBase = 'page' | 'locator' | 'frame-locator'; type LocatorOptions = { attrs?: { name: string, value: string | boolean | number }[], exact?: boolean, name?: string | RegExp, hasText?: string | RegExp, hasNotText?: string | RegExp, }; export interface LocatorFactory { generateLocator(base: LocatorBase, kind: LocatorType, body: string | RegExp, options?: LocatorOptions): string; chainLocators(locators: string[]): string; } export function asLocator(lang: Language, selector: string, isFrameLocator: boolean = false, playSafe: boolean = false): string { return asLocators(lang, selector, isFrameLocator, playSafe)[0]; } export function asLocators(lang: Language, selector: string, isFrameLocator: boolean = false, playSafe: boolean = false, maxOutputSize = 20): string[] { if (playSafe) { try { return innerAsLocators(generators[lang], parseSelector(selector), isFrameLocator, maxOutputSize); } catch (e) { // Tolerate invalid input. return [selector]; } } else { return innerAsLocators(generators[lang], parseSelector(selector), isFrameLocator, maxOutputSize); } } function innerAsLocators(factory: LocatorFactory, parsed: ParsedSelector, isFrameLocator: boolean = false, maxOutputSize = 20): string[] { const parts = [...parsed.parts]; // frameLocator('iframe').first is actually "iframe >> nth=0 >> internal:control=enter-frame" // To make it easier to parse, we turn it into "iframe >> internal:control=enter-frame >> nth=0" for (let index = 0; index < parts.length - 1; index++) { if (parts[index].name === 'nth' && parts[index + 1].name === 'internal:control' && (parts[index + 1].body as string) === 'enter-frame') { // Swap nth and enter-frame. const [nth] = parts.splice(index, 1); parts.splice(index + 1, 0, nth); } } const tokens: string[][] = []; let nextBase: LocatorBase = isFrameLocator ? 'frame-locator' : 'page'; for (let index = 0; index < parts.length; index++) { const part = parts[index]; const base = nextBase; nextBase = 'locator'; if (part.name === 'nth') { if (part.body === '0') tokens.push([factory.generateLocator(base, 'first', ''), factory.generateLocator(base, 'nth', '0')]); else if (part.body === '-1') tokens.push([factory.generateLocator(base, 'last', ''), factory.generateLocator(base, 'nth', '-1')]); else tokens.push([factory.generateLocator(base, 'nth', part.body as string)]); continue; } if (part.name === 'internal:text') { const { exact, text } = detectExact(part.body as string); tokens.push([factory.generateLocator(base, 'text', text, { exact })]); continue; } if (part.name === 'internal:has-text') { const { exact, text } = detectExact(part.body as string); // There is no locator equivalent for strict has-text, leave it as is. if (!exact) { tokens.push([factory.generateLocator(base, 'has-text', text, { exact })]); continue; } } if (part.name === 'internal:has-not-text') { const { exact, text } = detectExact(part.body as string); // There is no locator equivalent for strict has-not-text, leave it as is. if (!exact) { tokens.push([factory.generateLocator(base, 'has-not-text', text, { exact })]); continue; } } if (part.name === 'internal:has') { const inners = innerAsLocators(factory, (part.body as NestedSelectorBody).parsed, false, maxOutputSize); tokens.push(inners.map(inner => factory.generateLocator(base, 'has', inner))); continue; } if (part.name === 'internal:has-not') { const inners = innerAsLocators(factory, (part.body as NestedSelectorBody).parsed, false, maxOutputSize); tokens.push(inners.map(inner => factory.generateLocator(base, 'hasNot', inner))); continue; } if (part.name === 'internal:and') { const inners = innerAsLocators(factory, (part.body as NestedSelectorBody).parsed, false, maxOutputSize); tokens.push(inners.map(inner => factory.generateLocator(base, 'and', inner))); continue; } if (part.name === 'internal:or') { const inners = innerAsLocators(factory, (part.body as NestedSelectorBody).parsed, false, maxOutputSize); tokens.push(inners.map(inner => factory.generateLocator(base, 'or', inner))); continue; } if (part.name === 'internal:label') { const { exact, text } = detectExact(part.body as string); tokens.push([factory.generateLocator(base, 'label', text, { exact })]); continue; } if (part.name === 'internal:role') { const attrSelector = parseAttributeSelector(part.body as string, true); const options: LocatorOptions = { attrs: [] }; for (const attr of attrSelector.attributes) { if (attr.name === 'name') { options.exact = attr.caseSensitive; options.name = attr.value; } else { if (attr.name === 'level' && typeof attr.value === 'string') attr.value = +attr.value; options.attrs!.push({ name: attr.name === 'include-hidden' ? 'includeHidden' : attr.name, value: attr.value }); } } tokens.push([factory.generateLocator(base, 'role', attrSelector.name, options)]); continue; } if (part.name === 'internal:testid') { const attrSelector = parseAttributeSelector(part.body as string, true); const { value } = attrSelector.attributes[0]; tokens.push([factory.generateLocator(base, 'test-id', value)]); continue; } if (part.name === 'internal:attr') { const attrSelector = parseAttributeSelector(part.body as string, true); const { name, value, caseSensitive } = attrSelector.attributes[0]; const text = value as string | RegExp; const exact = !!caseSensitive; if (name === 'placeholder') { tokens.push([factory.generateLocator(base, 'placeholder', text, { exact })]); continue; } if (name === 'alt') { tokens.push([factory.generateLocator(base, 'alt', text, { exact })]); continue; } if (name === 'title') { tokens.push([factory.generateLocator(base, 'title', text, { exact })]); continue; } } let locatorType: LocatorType = 'default'; const nextPart = parts[index + 1]; if (nextPart && nextPart.name === 'internal:control' && (nextPart.body as string) === 'enter-frame') { locatorType = 'frame'; nextBase = 'frame-locator'; index++; } const selectorPart = stringifySelector({ parts: [part] }); const locatorPart = factory.generateLocator(base, locatorType, selectorPart); if (locatorType === 'default' && nextPart && ['internal:has-text', 'internal:has-not-text'].includes(nextPart.name)) { const { exact, text } = detectExact(nextPart.body as string); // There is no locator equivalent for strict has-text and has-not-text, leave it as is. if (!exact) { const nextLocatorPart = factory.generateLocator('locator', nextPart.name === 'internal:has-text' ? 'has-text' : 'has-not-text', text, { exact }); const options: LocatorOptions = {}; if (nextPart.name === 'internal:has-text') options.hasText = text; else options.hasNotText = text; const combinedPart = factory.generateLocator(base, 'default', selectorPart, options); // Two options: // - locator('div').filter({ hasText: 'foo' }) // - locator('div', { hasText: 'foo' }) tokens.push([factory.chainLocators([locatorPart, nextLocatorPart]), combinedPart]); index++; continue; } } tokens.push([locatorPart]); } return combineTokens(factory, tokens, maxOutputSize); } function combineTokens(factory: LocatorFactory, tokens: string[][], maxOutputSize: number): string[] { const currentTokens = tokens.map(() => ''); const result: string[] = []; const visit = (index: number) => { if (index === tokens.length) { result.push(factory.chainLocators(currentTokens)); return currentTokens.length < maxOutputSize; } for (const taken of tokens[index]) { currentTokens[index] = taken; if (!visit(index + 1)) return false; } return true; }; visit(0); return result; } function detectExact(text: string): { exact?: boolean, text: string | RegExp } { let exact = false; const match = text.match(/^\/(.*)\/([igm]*)$/); if (match) return { text: new RegExp(match[1], match[2]) }; if (text.endsWith('"')) { text = JSON.parse(text); exact = true; } else if (text.endsWith('"s')) { text = JSON.parse(text.substring(0, text.length - 1)); exact = true; } else if (text.endsWith('"i')) { text = JSON.parse(text.substring(0, text.length - 1)); exact = false; } return { exact, text }; } export class JavaScriptLocatorFactory implements LocatorFactory { generateLocator(base: LocatorBase, kind: LocatorType, body: string | RegExp, options: LocatorOptions = {}): string { switch (kind) { case 'default': if (options.hasText !== undefined) return `locator(${this.quote(body as string)}, { hasText: ${this.toHasText(options.hasText)} })`; if (options.hasNotText !== undefined) return `locator(${this.quote(body as string)}, { hasNotText: ${this.toHasText(options.hasNotText)} })`; return `locator(${this.quote(body as string)})`; case 'frame': return `frameLocator(${this.quote(body as string)})`; case 'nth': return `nth(${body})`; case 'first': return `first()`; case 'last': return `last()`; case 'role': const attrs: string[] = []; if (isRegExp(options.name)) { attrs.push(`name: ${options.name}`); } else if (typeof options.name === 'string') { attrs.push(`name: ${this.quote(options.name)}`); if (options.exact) attrs.push(`exact: true`); } for (const { name, value } of options.attrs!) attrs.push(`${name}: ${typeof value === 'string' ? this.quote(value) : value}`); const attrString = attrs.length ? `, { ${attrs.join(', ')} }` : ''; return `getByRole(${this.quote(body as string)}${attrString})`; case 'has-text': return `filter({ hasText: ${this.toHasText(body)} })`; case 'has-not-text': return `filter({ hasNotText: ${this.toHasText(body)} })`; case 'has': return `filter({ has: ${body} })`; case 'hasNot': return `filter({ hasNot: ${body} })`; case 'and': return `and(${body})`; case 'or': return `or(${body})`; case 'test-id': return `getByTestId(${this.quote(body as string)})`; case 'text': return this.toCallWithExact('getByText', body, !!options.exact); case 'alt': return this.toCallWithExact('getByAltText', body, !!options.exact); case 'placeholder': return this.toCallWithExact('getByPlaceholder', body, !!options.exact); case 'label': return this.toCallWithExact('getByLabel', body, !!options.exact); case 'title': return this.toCallWithExact('getByTitle', body, !!options.exact); default: throw new Error('Unknown selector kind ' + kind); } } chainLocators(locators: string[]): string { return locators.join('.'); } private toCallWithExact(method: string, body: string | RegExp, exact?: boolean) { if (isRegExp(body)) return `${method}(${body})`; return exact ? `${method}(${this.quote(body)}, { exact: true })` : `${method}(${this.quote(body)})`; } private toHasText(body: string | RegExp) { if (isRegExp(body)) return String(body); return this.quote(body); } private quote(text: string) { return escapeWithQuotes(text, '\''); } } export class PythonLocatorFactory implements LocatorFactory { generateLocator(base: LocatorBase, kind: LocatorType, body: string | RegExp, options: LocatorOptions = {}): string { switch (kind) { case 'default': if (options.hasText !== undefined) return `locator(${this.quote(body as string)}, has_text=${this.toHasText(options.hasText)})`; if (options.hasNotText !== undefined) return `locator(${this.quote(body as string)}, has_not_text=${this.toHasText(options.hasNotText)})`; return `locator(${this.quote(body as string)})`; case 'frame': return `frame_locator(${this.quote(body as string)})`; case 'nth': return `nth(${body})`; case 'first': return `first`; case 'last': return `last`; case 'role': const attrs: string[] = []; if (isRegExp(options.name)) { attrs.push(`name=${this.regexToString(options.name)}`); } else if (typeof options.name === 'string') { attrs.push(`name=${this.quote(options.name)}`); if (options.exact) attrs.push(`exact=True`); } for (const { name, value } of options.attrs!) { let valueString = typeof value === 'string' ? this.quote(value) : value; if (typeof value === 'boolean') valueString = value ? 'True' : 'False'; attrs.push(`${toSnakeCase(name)}=${valueString}`); } const attrString = attrs.length ? `, ${attrs.join(', ')}` : ''; return `get_by_role(${this.quote(body as string)}${attrString})`; case 'has-text': return `filter(has_text=${this.toHasText(body)})`; case 'has-not-text': return `filter(has_not_text=${this.toHasText(body)})`; case 'has': return `filter(has=${body})`; case 'hasNot': return `filter(has_not=${body})`; case 'and': return `and_(${body})`; case 'or': return `or_(${body})`; case 'test-id': return `get_by_test_id(${this.quote(body as string)})`; case 'text': return this.toCallWithExact('get_by_text', body, !!options.exact); case 'alt': return this.toCallWithExact('get_by_alt_text', body, !!options.exact); case 'placeholder': return this.toCallWithExact('get_by_placeholder', body, !!options.exact); case 'label': return this.toCallWithExact('get_by_label', body, !!options.exact); case 'title': return this.toCallWithExact('get_by_title', body, !!options.exact); default: throw new Error('Unknown selector kind ' + kind); } } chainLocators(locators: string[]): string { return locators.join('.'); } private regexToString(body: RegExp) { const suffix = body.flags.includes('i') ? ', re.IGNORECASE' : ''; return `re.compile(r"${body.source.replace(/\\\//, '/').replace(/"/g, '\\"')}"${suffix})`; } private toCallWithExact(method: string, body: string | RegExp, exact: boolean) { if (isRegExp(body)) return `${method}(${this.regexToString(body)})`; if (exact) return `${method}(${this.quote(body)}, exact=True)`; return `${method}(${this.quote(body)})`; } private toHasText(body: string | RegExp) { if (isRegExp(body)) return this.regexToString(body); return `${this.quote(body)}`; } private quote(text: string) { return escapeWithQuotes(text, '\"'); } } export class JavaLocatorFactory implements LocatorFactory { generateLocator(base: LocatorBase, kind: LocatorType, body: string | RegExp, options: LocatorOptions = {}): string { let clazz: string; switch (base) { case 'page': clazz = 'Page'; break; case 'frame-locator': clazz = 'FrameLocator'; break; case 'locator': clazz = 'Locator'; break; } switch (kind) { case 'default': if (options.hasText !== undefined) return `locator(${this.quote(body as string)}, new ${clazz}.LocatorOptions().setHasText(${this.toHasText(options.hasText)}))`; if (options.hasNotText !== undefined) return `locator(${this.quote(body as string)}, new ${clazz}.LocatorOptions().setHasNotText(${this.toHasText(options.hasNotText)}))`; return `locator(${this.quote(body as string)})`; case 'frame': return `frameLocator(${this.quote(body as string)})`; case 'nth': return `nth(${body})`; case 'first': return `first()`; case 'last': return `last()`; case 'role': const attrs: string[] = []; if (isRegExp(options.name)) { attrs.push(`.setName(${this.regexToString(options.name)})`); } else if (typeof options.name === 'string') { attrs.push(`.setName(${this.quote(options.name)})`); if (options.exact) attrs.push(`.setExact(true)`); } for (const { name, value } of options.attrs!) attrs.push(`.set${toTitleCase(name)}(${typeof value === 'string' ? this.quote(value) : value})`); const attrString = attrs.length ? `, new ${clazz}.GetByRoleOptions()${attrs.join('')}` : ''; return `getByRole(AriaRole.${toSnakeCase(body as string).toUpperCase()}${attrString})`; case 'has-text': return `filter(new ${clazz}.FilterOptions().setHasText(${this.toHasText(body)}))`; case 'has-not-text': return `filter(new ${clazz}.FilterOptions().setHasNotText(${this.toHasText(body)}))`; case 'has': return `filter(new ${clazz}.FilterOptions().setHas(${body}))`; case 'hasNot': return `filter(new ${clazz}.FilterOptions().setHasNot(${body}))`; case 'and': return `and(${body})`; case 'or': return `or(${body})`; case 'test-id': return `getByTestId(${this.quote(body as string)})`; case 'text': return this.toCallWithExact(clazz, 'getByText', body, !!options.exact); case 'alt': return this.toCallWithExact(clazz, 'getByAltText', body, !!options.exact); case 'placeholder': return this.toCallWithExact(clazz, 'getByPlaceholder', body, !!options.exact); case 'label': return this.toCallWithExact(clazz, 'getByLabel', body, !!options.exact); case 'title': return this.toCallWithExact(clazz, 'getByTitle', body, !!options.exact); default: throw new Error('Unknown selector kind ' + kind); } } chainLocators(locators: string[]): string { return locators.join('.'); } private regexToString(body: RegExp) { const suffix = body.flags.includes('i') ? ', Pattern.CASE_INSENSITIVE' : ''; return `Pattern.compile(${this.quote(body.source)}${suffix})`; } private toCallWithExact(clazz: string, method: string, body: string | RegExp, exact: boolean) { if (isRegExp(body)) return `${method}(${this.regexToString(body)})`; if (exact) return `${method}(${this.quote(body)}, new ${clazz}.${toTitleCase(method)}Options().setExact(true))`; return `${method}(${this.quote(body)})`; } private toHasText(body: string | RegExp) { if (isRegExp(body)) return this.regexToString(body); return this.quote(body); } private quote(text: string) { return escapeWithQuotes(text, '\"'); } } export class CSharpLocatorFactory implements LocatorFactory { generateLocator(base: LocatorBase, kind: LocatorType, body: string | RegExp, options: LocatorOptions = {}): string { switch (kind) { case 'default': if (options.hasText !== undefined) return `Locator(${this.quote(body as string)}, new() { ${this.toHasText(options.hasText)} })`; if (options.hasNotText !== undefined) return `Locator(${this.quote(body as string)}, new() { ${this.toHasNotText(options.hasNotText)} })`; return `Locator(${this.quote(body as string)})`; case 'frame': return `FrameLocator(${this.quote(body as string)})`; case 'nth': return `Nth(${body})`; case 'first': return `First`; case 'last': return `Last`; case 'role': const attrs: string[] = []; if (isRegExp(options.name)) { attrs.push(`NameRegex = ${this.regexToString(options.name)}`); } else if (typeof options.name === 'string') { attrs.push(`Name = ${this.quote(options.name)}`); if (options.exact) attrs.push(`Exact = true`); } for (const { name, value } of options.attrs!) attrs.push(`${toTitleCase(name)} = ${typeof value === 'string' ? this.quote(value) : value}`); const attrString = attrs.length ? `, new() { ${attrs.join(', ')} }` : ''; return `GetByRole(AriaRole.${toTitleCase(body as string)}${attrString})`; case 'has-text': return `Filter(new() { ${this.toHasText(body)} })`; case 'has-not-text': return `Filter(new() { ${this.toHasNotText(body)} })`; case 'has': return `Filter(new() { Has = ${body} })`; case 'hasNot': return `Filter(new() { HasNot = ${body} })`; case 'and': return `And(${body})`; case 'or': return `Or(${body})`; case 'test-id': return `GetByTestId(${this.quote(body as string)})`; case 'text': return this.toCallWithExact('GetByText', body, !!options.exact); case 'alt': return this.toCallWithExact('GetByAltText', body, !!options.exact); case 'placeholder': return this.toCallWithExact('GetByPlaceholder', body, !!options.exact); case 'label': return this.toCallWithExact('GetByLabel', body, !!options.exact); case 'title': return this.toCallWithExact('GetByTitle', body, !!options.exact); default: throw new Error('Unknown selector kind ' + kind); } } chainLocators(locators: string[]): string { return locators.join('.'); } private regexToString(body: RegExp): string { const suffix = body.flags.includes('i') ? ', RegexOptions.IgnoreCase' : ''; return `new Regex(${this.quote(body.source)}${suffix})`; } private toCallWithExact(method: string, body: string | RegExp, exact: boolean) { if (isRegExp(body)) return `${method}(${this.regexToString(body)})`; if (exact) return `${method}(${this.quote(body)}, new() { Exact = true })`; return `${method}(${this.quote(body)})`; } private toHasText(body: string | RegExp) { if (isRegExp(body)) return `HasTextRegex = ${this.regexToString(body)}`; return `HasText = ${this.quote(body)}`; } private toHasNotText(body: string | RegExp) { if (isRegExp(body)) return `HasNotTextRegex = ${this.regexToString(body)}`; return `HasNotText = ${this.quote(body)}`; } private quote(text: string) { return escapeWithQuotes(text, '\"'); } } export class JsonlLocatorFactory implements LocatorFactory { generateLocator(base: LocatorBase, kind: LocatorType, body: string | RegExp, options: LocatorOptions = {}): string { return JSON.stringify({ kind, body, options, }); } chainLocators(locators: string[]): string { const objects = locators.map(l => JSON.parse(l)); for (let i = 0; i < objects.length - 1; ++i) objects[i].next = objects[i + 1]; return JSON.stringify(objects[0]); } } const generators: Record<Language, LocatorFactory> = { javascript: new JavaScriptLocatorFactory(), python: new PythonLocatorFactory(), java: new JavaLocatorFactory(), csharp: new CSharpLocatorFactory(), jsonl: new JsonlLocatorFactory(), }; function isRegExp(obj: any): obj is RegExp { return obj instanceof RegExp; }
packages/playwright-core/src/utils/isomorphic/locatorGenerators.ts
0
https://github.com/microsoft/playwright/commit/624e88e504c4855b809c4e0ee3b1b8991f7e85fc
[ 0.00017703119374345988, 0.00017116221715696156, 0.00016380201850552112, 0.00017203604511450976, 0.000003090508016612148 ]
{ "id": 6, "code_window": [ " \"optional\": true\n", " },\n", " \"playwright-core\": {\n", " \"version\": \"1.35.0-alpha-1685046878000\",\n", " \"resolved\": \"https://registry.npmjs.org/playwright-core/-/playwright-core-1.35.0-alpha-1685046878000.tgz\",\n", " \"integrity\": \"sha512-2MdjKmIKazxVH4uZ8TSGjEJ6lpjfg4xgnCdoL46gKfKBd42mgPutfAplCGEtb0CRb9Oke8sYzo9HnA9EUuXQSg==\"\n", " }\n", " }\n", "}" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ " \"version\": \"1.35.0-alpha-1685109821000\",\n", " \"resolved\": \"https://registry.npmjs.org/playwright-core/-/playwright-core-1.35.0-alpha-1685109821000.tgz\",\n", " \"integrity\": \"sha512-IuaxLekxpKacjz3g7weJAfUQoj0Uz/viWBADJTFXuyP3wMviqRqUgaat/i2H4vfOvvQeYmGpi9MXs8d3olE6cQ==\"\n" ], "file_path": "tests/playwright-test/stable-test-runner/package-lock.json", "type": "replace", "edit_start_line_idx": 81 }
/** * Copyright (c) Microsoft Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import '@web/common.css'; import { applyTheme } from '@web/theme'; import '@web/third_party/vscode/codicon.css'; import * as React from 'react'; import * as ReactDOM from 'react-dom'; import { Main } from './main'; (async () => { applyTheme(); ReactDOM.render(<Main/>, document.querySelector('#root')); })();
packages/recorder/src/index.tsx
0
https://github.com/microsoft/playwright/commit/624e88e504c4855b809c4e0ee3b1b8991f7e85fc
[ 0.00017467686848249286, 0.0001726758637232706, 0.00017153653607238084, 0.00017181415751110762, 0.0000014194629329722375 ]
{ "id": 6, "code_window": [ " \"optional\": true\n", " },\n", " \"playwright-core\": {\n", " \"version\": \"1.35.0-alpha-1685046878000\",\n", " \"resolved\": \"https://registry.npmjs.org/playwright-core/-/playwright-core-1.35.0-alpha-1685046878000.tgz\",\n", " \"integrity\": \"sha512-2MdjKmIKazxVH4uZ8TSGjEJ6lpjfg4xgnCdoL46gKfKBd42mgPutfAplCGEtb0CRb9Oke8sYzo9HnA9EUuXQSg==\"\n", " }\n", " }\n", "}" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ " \"version\": \"1.35.0-alpha-1685109821000\",\n", " \"resolved\": \"https://registry.npmjs.org/playwright-core/-/playwright-core-1.35.0-alpha-1685109821000.tgz\",\n", " \"integrity\": \"sha512-IuaxLekxpKacjz3g7weJAfUQoj0Uz/viWBADJTFXuyP3wMviqRqUgaat/i2H4vfOvvQeYmGpi9MXs8d3olE6cQ==\"\n" ], "file_path": "tests/playwright-test/stable-test-runner/package-lock.json", "type": "replace", "edit_start_line_idx": 81 }
# class: Fixtures * since: v1.10 * langs: js Playwright Test is based on the concept of the [test fixtures](../test-fixtures.md). Test fixtures are used to establish environment for each test, giving the test everything it needs and nothing else. Playwright Test looks at each test declaration, analyses the set of fixtures the test needs and prepares those fixtures specifically for the test. Values prepared by the fixtures are merged into a single object that is available to the `test`, hooks, annotations and other fixtures as a first parameter. ```js import { test, expect } from '@playwright/test'; test('basic test', async ({ page }) => { // ... }); ``` Given the test above, Playwright Test will set up the `page` fixture before running the test, and tear it down after the test has finished. `page` fixture provides a [Page] object that is available to the test. Playwright Test comes with builtin fixtures listed below, and you can add your own fixtures as well. Playwright Test also [provides options][TestOptions] to configure [`property: Fixtures.browser`], [`property: Fixtures.context`] and [`property: Fixtures.page`]. ## property: Fixtures.browser * since: v1.10 - type: <[Browser]> [Browser] instance is shared between all tests in the [same worker](../test-parallel.md) - this makes testing efficient. However, each test runs in an isolated [BrowserContext] and gets a fresh environment. Learn how to [configure browser](../test-configuration.md) and see [available options][TestOptions]. **Usage** ```js test.beforeAll(async ({ browser }) => { const page = await browser.newPage(); // ... }); ``` ## property: Fixtures.browserName * since: v1.10 - type: <[BrowserName]<"chromium"|"firefox"|"webkit">> Name of the browser that runs tests. Defaults to `'chromium'`. Useful to [annotate tests](../test-annotations.md) based on the browser. **Usage** ```js test('skip this test in Firefox', async ({ page, browserName }) => { test.skip(browserName === 'firefox', 'Still working on it'); // ... }); ``` ## property: Fixtures.context * since: v1.10 - type: <[BrowserContext]> Isolated [BrowserContext] instance, created for each test. Since contexts are isolated between each other, every test gets a fresh environment, even when multiple tests run in a single [Browser] for maximum efficiency. Learn how to [configure context](../test-configuration.md) and see [available options][TestOptions]. Default [`property: Fixtures.page`] belongs to this context. **Usage** ```js test('example test', async ({ page, context }) => { await context.route('*external.com/*', route => route.abort()); // ... }); ``` ## property: Fixtures.page * since: v1.10 - type: <[Page]> Isolated [Page] instance, created for each test. Pages are isolated between tests due to [`property: Fixtures.context`] isolation. This is the most common fixture used in a test. **Usage** ```js import { test, expect } from '@playwright/test'; test('basic test', async ({ page }) => { await page.goto('/signin'); await page.getByLabel('User Name').fill('user'); await page.getByLabel('Password').fill('password'); await page.getByText('Sign in').click(); // ... }); ``` ## property: Fixtures.request * since: v1.10 - type: <[APIRequestContext]> Isolated [APIRequestContext] instance for each test. **Usage** ```js import { test, expect } from '@playwright/test'; test('basic test', async ({ request }) => { await request.post('/signin', { data: { username: 'user', password: 'password' } }); // ... }); ```
docs/src/test-api/class-fixtures.md
0
https://github.com/microsoft/playwright/commit/624e88e504c4855b809c4e0ee3b1b8991f7e85fc
[ 0.0001709516509436071, 0.00016675691585987806, 0.00016117531049530953, 0.00016778883582446724, 0.0000034605650398589205 ]
{ "id": 7, "code_window": [ "{\n", " \"private\": true,\n", " \"dependencies\": {\n", " \"@playwright/test\": \"1.35.0-alpha-1685046878000\"\n", " }\n", "}" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [ " \"@playwright/test\": \"1.35.0-alpha-1685109821000\"\n" ], "file_path": "tests/playwright-test/stable-test-runner/package.json", "type": "replace", "edit_start_line_idx": 3 }
{ "name": "stable-test-runner", "lockfileVersion": 2, "requires": true, "packages": { "": { "dependencies": { "@playwright/test": "1.35.0-alpha-1685046878000" } }, "node_modules/@playwright/test": { "version": "1.35.0-alpha-1685046878000", "resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.35.0-alpha-1685046878000.tgz", "integrity": "sha512-OgZV/Ncwxjodqjl7FrOOaVUiPhxc6h3gYGw9ElKT9Eac+67wjZafDgdH8eGOSXIwwyHOqP+M4PM6T8sq3vyvyA==", "dependencies": { "@types/node": "*", "playwright-core": "1.35.0-alpha-1685046878000" }, "bin": { "playwright": "cli.js" }, "engines": { "node": ">=14" }, "optionalDependencies": { "fsevents": "2.3.2" } }, "node_modules/@types/node": { "version": "18.0.0", "resolved": "https://registry.npmjs.org/@types/node/-/node-18.0.0.tgz", "integrity": "sha512-cHlGmko4gWLVI27cGJntjs/Sj8th9aYwplmZFwmmgYQQvL5NUsgVJG7OddLvNfLqYS31KFN0s3qlaD9qCaxACA==" }, "node_modules/fsevents": { "version": "2.3.2", "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz", "integrity": "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==", "hasInstallScript": true, "optional": true, "os": [ "darwin" ], "engines": { "node": "^8.16.0 || ^10.6.0 || >=11.0.0" } }, "node_modules/playwright-core": { "version": "1.35.0-alpha-1685046878000", "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.35.0-alpha-1685046878000.tgz", "integrity": "sha512-2MdjKmIKazxVH4uZ8TSGjEJ6lpjfg4xgnCdoL46gKfKBd42mgPutfAplCGEtb0CRb9Oke8sYzo9HnA9EUuXQSg==", "bin": { "playwright-core": "cli.js" }, "engines": { "node": ">=14" } } }, "dependencies": { "@playwright/test": { "version": "1.35.0-alpha-1685046878000", "resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.35.0-alpha-1685046878000.tgz", "integrity": "sha512-OgZV/Ncwxjodqjl7FrOOaVUiPhxc6h3gYGw9ElKT9Eac+67wjZafDgdH8eGOSXIwwyHOqP+M4PM6T8sq3vyvyA==", "requires": { "@types/node": "*", "fsevents": "2.3.2", "playwright-core": "1.35.0-alpha-1685046878000" } }, "@types/node": { "version": "18.0.0", "resolved": "https://registry.npmjs.org/@types/node/-/node-18.0.0.tgz", "integrity": "sha512-cHlGmko4gWLVI27cGJntjs/Sj8th9aYwplmZFwmmgYQQvL5NUsgVJG7OddLvNfLqYS31KFN0s3qlaD9qCaxACA==" }, "fsevents": { "version": "2.3.2", "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz", "integrity": "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==", "optional": true }, "playwright-core": { "version": "1.35.0-alpha-1685046878000", "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.35.0-alpha-1685046878000.tgz", "integrity": "sha512-2MdjKmIKazxVH4uZ8TSGjEJ6lpjfg4xgnCdoL46gKfKBd42mgPutfAplCGEtb0CRb9Oke8sYzo9HnA9EUuXQSg==" } } }
tests/playwright-test/stable-test-runner/package-lock.json
1
https://github.com/microsoft/playwright/commit/624e88e504c4855b809c4e0ee3b1b8991f7e85fc
[ 0.022731995210051537, 0.007242981810122728, 0.00016793017857708037, 0.008815745823085308, 0.007408390287309885 ]
{ "id": 7, "code_window": [ "{\n", " \"private\": true,\n", " \"dependencies\": {\n", " \"@playwright/test\": \"1.35.0-alpha-1685046878000\"\n", " }\n", "}" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [ " \"@playwright/test\": \"1.35.0-alpha-1685109821000\"\n" ], "file_path": "tests/playwright-test/stable-test-runner/package.json", "type": "replace", "edit_start_line_idx": 3 }
<script> import { update, remountCount } from '../store' import { createEventDispatcher } from "svelte"; export let count; const dispatch = createEventDispatcher(); update(); </script> <button on:click={() => dispatch('submit', 'hello')}> <span data-testid="props">{count}</span> <span data-testid="remount-count">{remountCount}</span> <slot name="main" /> <slot /> </button>
tests/components/ct-svelte/src/components/Counter.svelte
0
https://github.com/microsoft/playwright/commit/624e88e504c4855b809c4e0ee3b1b8991f7e85fc
[ 0.00017291547555942088, 0.0001718530838843435, 0.00017079069220926613, 0.0001718530838843435, 0.0000010623916750773787 ]
{ "id": 7, "code_window": [ "{\n", " \"private\": true,\n", " \"dependencies\": {\n", " \"@playwright/test\": \"1.35.0-alpha-1685046878000\"\n", " }\n", "}" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [ " \"@playwright/test\": \"1.35.0-alpha-1685109821000\"\n" ], "file_path": "tests/playwright-test/stable-test-runner/package.json", "type": "replace", "edit_start_line_idx": 3 }
import { test, expect } from '@playwright/experimental-ct-vue'; import type { HooksConfig } from '../../playwright'; import App from '@/App.vue'; test('navigate to a page by clicking a link', async ({ page, mount }) => { const component = await mount<HooksConfig>(App, { hooksConfig: { routing: true }, }); await expect(component.getByRole('main')).toHaveText('Login'); await expect(page).toHaveURL('/'); await component.getByRole('link', { name: 'Dashboard' }).click(); await expect(component.getByRole('main')).toHaveText('Dashboard'); await expect(page).toHaveURL('/dashboard'); });
tests/components/ct-vue-vite/tests/vue-router/vue-router.spec.ts
0
https://github.com/microsoft/playwright/commit/624e88e504c4855b809c4e0ee3b1b8991f7e85fc
[ 0.00016886596858967096, 0.000167197547852993, 0.0001655291416682303, 0.000167197547852993, 0.0000016684134607203305 ]
{ "id": 7, "code_window": [ "{\n", " \"private\": true,\n", " \"dependencies\": {\n", " \"@playwright/test\": \"1.35.0-alpha-1685046878000\"\n", " }\n", "}" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [ " \"@playwright/test\": \"1.35.0-alpha-1685109821000\"\n" ], "file_path": "tests/playwright-test/stable-test-runner/package.json", "type": "replace", "edit_start_line_idx": 3 }
console.log(3);
tests/assets/jscoverage/script2.js
0
https://github.com/microsoft/playwright/commit/624e88e504c4855b809c4e0ee3b1b8991f7e85fc
[ 0.0001744080800563097, 0.0001744080800563097, 0.0001744080800563097, 0.0001744080800563097, 0 ]
{ "id": 0, "code_window": [ " * Licensed under the MIT License. See License.txt in the project root for license information.\n", " *--------------------------------------------------------------------------------------------*/\n", "\n", "import { Constants } from 'vs/base/common/uint';\n", "import { Range, IRange } from 'vs/editor/common/core/range';\n", "import { TrackedRangeStickiness, IModelDeltaDecoration, IModelDecorationOptions, OverviewRulerLane } from 'vs/editor/common/model';\n", "import { IDebugService, IStackFrame } from 'vs/workbench/contrib/debug/common/debug';\n", "import { registerThemingParticipant, themeColorFromId, ThemeIcon } from 'vs/platform/theme/common/themeService';\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "import { Range } from 'vs/editor/common/core/range';\n" ], "file_path": "src/vs/workbench/contrib/debug/browser/callStackEditorContribution.ts", "type": "replace", "edit_start_line_idx": 6 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { Constants } from 'vs/base/common/uint'; import { Range, IRange } from 'vs/editor/common/core/range'; import { TrackedRangeStickiness, IModelDeltaDecoration, IModelDecorationOptions, OverviewRulerLane } from 'vs/editor/common/model'; import { IDebugService, IStackFrame } from 'vs/workbench/contrib/debug/common/debug'; import { registerThemingParticipant, themeColorFromId, ThemeIcon } from 'vs/platform/theme/common/themeService'; import { registerColor } from 'vs/platform/theme/common/colorRegistry'; import { localize } from 'vs/nls'; import { Event } from 'vs/base/common/event'; import { IDisposable, dispose } from 'vs/base/common/lifecycle'; import { IEditorContribution } from 'vs/editor/common/editorCommon'; import { ICodeEditor } from 'vs/editor/browser/editorBrowser'; import { distinct } from 'vs/base/common/arrays'; import { IUriIdentityService } from 'vs/workbench/services/uriIdentity/common/uriIdentity'; import { debugStackframe, debugStackframeFocused } from 'vs/workbench/contrib/debug/browser/debugIcons'; const topStackFrameColor = registerColor('editor.stackFrameHighlightBackground', { dark: '#ffff0033', light: '#ffff6673', hc: '#ffff0033' }, localize('topStackFrameLineHighlight', 'Background color for the highlight of line at the top stack frame position.')); const focusedStackFrameColor = registerColor('editor.focusedStackFrameHighlightBackground', { dark: '#7abd7a4d', light: '#cee7ce73', hc: '#7abd7a4d' }, localize('focusedStackFrameLineHighlight', 'Background color for the highlight of line at focused stack frame position.')); const stickiness = TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges; // we need a separate decoration for glyph margin, since we do not want it on each line of a multi line statement. const TOP_STACK_FRAME_MARGIN: IModelDecorationOptions = { glyphMarginClassName: ThemeIcon.asClassName(debugStackframe), stickiness, overviewRuler: { position: OverviewRulerLane.Full, color: themeColorFromId(topStackFrameColor) } }; const FOCUSED_STACK_FRAME_MARGIN: IModelDecorationOptions = { glyphMarginClassName: ThemeIcon.asClassName(debugStackframeFocused), stickiness, overviewRuler: { position: OverviewRulerLane.Full, color: themeColorFromId(focusedStackFrameColor) } }; const TOP_STACK_FRAME_DECORATION: IModelDecorationOptions = { isWholeLine: true, className: 'debug-top-stack-frame-line', stickiness }; const TOP_STACK_FRAME_INLINE_DECORATION: IModelDecorationOptions = { beforeContentClassName: 'debug-top-stack-frame-column' }; const FOCUSED_STACK_FRAME_DECORATION: IModelDecorationOptions = { isWholeLine: true, className: 'debug-focused-stack-frame-line', stickiness }; export function createDecorationsForStackFrame(stackFrame: IStackFrame, topStackFrameRange: IRange | undefined, isFocusedSession: boolean): IModelDeltaDecoration[] { // only show decorations for the currently focused thread. const result: IModelDeltaDecoration[] = []; const columnUntilEOLRange = new Range(stackFrame.range.startLineNumber, stackFrame.range.startColumn, stackFrame.range.startLineNumber, Constants.MAX_SAFE_SMALL_INTEGER); const range = new Range(stackFrame.range.startLineNumber, stackFrame.range.startColumn, stackFrame.range.startLineNumber, stackFrame.range.startColumn + 1); // compute how to decorate the editor. Different decorations are used if this is a top stack frame, focused stack frame, // an exception or a stack frame that did not change the line number (we only decorate the columns, not the whole line). const topStackFrame = stackFrame.thread.getTopStackFrame(); if (stackFrame.getId() === topStackFrame?.getId()) { if (isFocusedSession) { result.push({ options: TOP_STACK_FRAME_MARGIN, range }); } result.push({ options: TOP_STACK_FRAME_DECORATION, range: columnUntilEOLRange }); if (topStackFrameRange && topStackFrameRange.startLineNumber === stackFrame.range.startLineNumber && topStackFrameRange.startColumn !== stackFrame.range.startColumn) { result.push({ options: TOP_STACK_FRAME_INLINE_DECORATION, range: columnUntilEOLRange }); } topStackFrameRange = columnUntilEOLRange; } else { if (isFocusedSession) { result.push({ options: FOCUSED_STACK_FRAME_MARGIN, range }); } result.push({ options: FOCUSED_STACK_FRAME_DECORATION, range: columnUntilEOLRange }); } return result; } export class CallStackEditorContribution implements IEditorContribution { private toDispose: IDisposable[] = []; private decorationIds: string[] = []; private topStackFrameRange: Range | undefined; constructor( private readonly editor: ICodeEditor, @IDebugService private readonly debugService: IDebugService, @IUriIdentityService private readonly uriIdentityService: IUriIdentityService ) { const setDecorations = () => this.decorationIds = this.editor.deltaDecorations(this.decorationIds, this.createCallStackDecorations()); this.toDispose.push(Event.any(this.debugService.getViewModel().onDidFocusStackFrame, this.debugService.getModel().onDidChangeCallStack)(() => { setDecorations(); })); this.toDispose.push(this.editor.onDidChangeModel(e => { if (e.newModelUrl) { setDecorations(); } })); } private createCallStackDecorations(): IModelDeltaDecoration[] { const focusedStackFrame = this.debugService.getViewModel().focusedStackFrame; const decorations: IModelDeltaDecoration[] = []; this.debugService.getModel().getSessions().forEach(s => { const isSessionFocused = s === focusedStackFrame?.thread.session; s.getAllThreads().forEach(t => { if (t.stopped) { const callStack = t.getCallStack(); const stackFrames: IStackFrame[] = []; if (callStack.length > 0) { // Always decorate top stack frame, and decorate focused stack frame if it is not the top stack frame if (focusedStackFrame && !focusedStackFrame.equals(callStack[0])) { stackFrames.push(focusedStackFrame); } stackFrames.push(callStack[0]); } stackFrames.forEach(candidateStackFrame => { if (candidateStackFrame && this.uriIdentityService.extUri.isEqual(candidateStackFrame.source.uri, this.editor.getModel()?.uri)) { decorations.push(...createDecorationsForStackFrame(candidateStackFrame, this.topStackFrameRange, isSessionFocused)); } }); } }); }); // Deduplicate same decorations so colors do not stack #109045 return distinct(decorations, d => `${d.options.className} ${d.options.glyphMarginClassName} ${d.range.startLineNumber} ${d.range.startColumn}`); } dispose(): void { this.editor.deltaDecorations(this.decorationIds, []); this.toDispose = dispose(this.toDispose); } } registerThemingParticipant((theme, collector) => { const topStackFrame = theme.getColor(topStackFrameColor); if (topStackFrame) { collector.addRule(`.monaco-editor .view-overlays .debug-top-stack-frame-line { background: ${topStackFrame}; }`); } const focusedStackFrame = theme.getColor(focusedStackFrameColor); if (focusedStackFrame) { collector.addRule(`.monaco-editor .view-overlays .debug-focused-stack-frame-line { background: ${focusedStackFrame}; }`); } });
src/vs/workbench/contrib/debug/browser/callStackEditorContribution.ts
1
https://github.com/microsoft/vscode/commit/f554a745505474ba031a79f5ab4a5c9d1ed3af39
[ 0.002845920156687498, 0.0005063281860202551, 0.00016220797260757536, 0.00017159362323582172, 0.0006984761566855013 ]
{ "id": 0, "code_window": [ " * Licensed under the MIT License. See License.txt in the project root for license information.\n", " *--------------------------------------------------------------------------------------------*/\n", "\n", "import { Constants } from 'vs/base/common/uint';\n", "import { Range, IRange } from 'vs/editor/common/core/range';\n", "import { TrackedRangeStickiness, IModelDeltaDecoration, IModelDecorationOptions, OverviewRulerLane } from 'vs/editor/common/model';\n", "import { IDebugService, IStackFrame } from 'vs/workbench/contrib/debug/common/debug';\n", "import { registerThemingParticipant, themeColorFromId, ThemeIcon } from 'vs/platform/theme/common/themeService';\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "import { Range } from 'vs/editor/common/core/range';\n" ], "file_path": "src/vs/workbench/contrib/debug/browser/callStackEditorContribution.ts", "type": "replace", "edit_start_line_idx": 6 }
#!/usr/bin/env node /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ // @ts-check const http = require('http'); const url = require('url'); const fs = require('fs'); const path = require('path'); const util = require('util'); const opn = require('opn'); const minimist = require('minimist'); const fancyLog = require('fancy-log'); const ansiColors = require('ansi-colors'); const remote = require('gulp-remote-retry-src'); const vfs = require('vinyl-fs'); const uuid = require('uuid'); const extensions = require('../../build/lib/extensions'); const { getBuiltInExtensions } = require('../../build/lib/builtInExtensions'); const APP_ROOT = path.join(__dirname, '..', '..'); const BUILTIN_EXTENSIONS_ROOT = path.join(APP_ROOT, 'extensions'); const BUILTIN_MARKETPLACE_EXTENSIONS_ROOT = path.join(APP_ROOT, '.build', 'builtInExtensions'); const WEB_DEV_EXTENSIONS_ROOT = path.join(APP_ROOT, '.build', 'builtInWebDevExtensions'); const WEB_MAIN = path.join(APP_ROOT, 'src', 'vs', 'code', 'browser', 'workbench', 'workbench-dev.html'); // This is useful to simulate real world CORS const ALLOWED_CORS_ORIGINS = [ 'http://localhost:8081', 'http://127.0.0.1:8081', 'http://localhost:8080', 'http://127.0.0.1:8080', ]; const WEB_PLAYGROUND_VERSION = '0.0.10'; const args = minimist(process.argv, { boolean: [ 'no-launch', 'help', 'verbose', 'wrap-iframe', 'enable-sync', ], string: [ 'scheme', 'host', 'port', 'local_port', 'extension', 'github-auth' ], }); if (args.help) { console.log( 'yarn web [options]\n' + ' --no-launch Do not open VSCode web in the browser\n' + ' --wrap-iframe Wrap the Web Worker Extension Host in an iframe\n' + ' --enable-sync Enable sync by default\n' + ' --scheme Protocol (https or http)\n' + ' --host Remote host\n' + ' --port Remote/Local port\n' + ' --local_port Local port override\n' + ' --secondary-port Secondary port\n' + ' --extension Path of an extension to include\n' + ' --github-auth Github authentication token\n' + ' --verbose Print out more information\n' + ' --help\n' + '[Example]\n' + ' yarn web --scheme https --host example.com --port 8080 --local_port 30000' ); process.exit(0); } const PORT = args.port || process.env.PORT || 8080; const LOCAL_PORT = args.local_port || process.env.LOCAL_PORT || PORT; const SECONDARY_PORT = args['secondary-port'] || (parseInt(PORT, 10) + 1); const SCHEME = args.scheme || process.env.VSCODE_SCHEME || 'http'; const HOST = args.host || 'localhost'; const AUTHORITY = process.env.VSCODE_AUTHORITY || `${HOST}:${PORT}`; const exists = (path) => util.promisify(fs.exists)(path); const readFile = (path) => util.promisify(fs.readFile)(path); async function getBuiltInExtensionInfos() { await getBuiltInExtensions(); const allExtensions = []; /** @type {Object.<string, string>} */ const locations = {}; const [localExtensions, marketplaceExtensions, webDevExtensions] = await Promise.all([ extensions.scanBuiltinExtensions(BUILTIN_EXTENSIONS_ROOT), extensions.scanBuiltinExtensions(BUILTIN_MARKETPLACE_EXTENSIONS_ROOT), ensureWebDevExtensions().then(() => extensions.scanBuiltinExtensions(WEB_DEV_EXTENSIONS_ROOT)) ]); for (const ext of localExtensions) { allExtensions.push(ext); locations[ext.extensionPath] = path.join(BUILTIN_EXTENSIONS_ROOT, ext.extensionPath); } for (const ext of marketplaceExtensions) { allExtensions.push(ext); locations[ext.extensionPath] = path.join(BUILTIN_MARKETPLACE_EXTENSIONS_ROOT, ext.extensionPath); } for (const ext of webDevExtensions) { allExtensions.push(ext); locations[ext.extensionPath] = path.join(WEB_DEV_EXTENSIONS_ROOT, ext.extensionPath); } for (const ext of allExtensions) { if (ext.packageJSON.browser) { let mainFilePath = path.join(locations[ext.extensionPath], ext.packageJSON.browser); if (path.extname(mainFilePath) !== '.js') { mainFilePath += '.js'; } if (!await exists(mainFilePath)) { fancyLog(`${ansiColors.red('Error')}: Could not find ${mainFilePath}. Use ${ansiColors.cyan('yarn watch-web')} to build the built-in extensions.`); } } } return { extensions: allExtensions, locations }; } async function ensureWebDevExtensions() { // Playground (https://github.com/microsoft/vscode-web-playground) const webDevPlaygroundRoot = path.join(WEB_DEV_EXTENSIONS_ROOT, 'vscode-web-playground'); const webDevPlaygroundExists = await exists(webDevPlaygroundRoot); let downloadPlayground = false; if (webDevPlaygroundExists) { try { const webDevPlaygroundPackageJson = JSON.parse(((await readFile(path.join(webDevPlaygroundRoot, 'package.json'))).toString())); if (webDevPlaygroundPackageJson.version !== WEB_PLAYGROUND_VERSION) { downloadPlayground = true; } } catch (error) { downloadPlayground = true; } } else { downloadPlayground = true; } if (downloadPlayground) { if (args.verbose) { fancyLog(`${ansiColors.magenta('Web Development extensions')}: Downloading vscode-web-playground to ${webDevPlaygroundRoot}`); } await new Promise((resolve, reject) => { remote(['package.json', 'dist/extension.js', 'dist/extension.js.map'], { base: 'https://raw.githubusercontent.com/microsoft/vscode-web-playground/main/' }).pipe(vfs.dest(webDevPlaygroundRoot)).on('end', resolve).on('error', reject); }); } else { if (args.verbose) { fancyLog(`${ansiColors.magenta('Web Development extensions')}: Using existing vscode-web-playground in ${webDevPlaygroundRoot}`); } } } async function getCommandlineProvidedExtensionInfos() { const extensions = []; /** @type {Object.<string, string>} */ const locations = {}; let extensionArg = args['extension']; if (!extensionArg) { return { extensions, locations }; } const extensionPaths = Array.isArray(extensionArg) ? extensionArg : [extensionArg]; await Promise.all(extensionPaths.map(async extensionPath => { extensionPath = path.resolve(process.cwd(), extensionPath); const packageJSON = await getExtensionPackageJSON(extensionPath); if (packageJSON) { const extensionId = `${packageJSON.publisher}.${packageJSON.name}`; extensions.push({ packageJSON, extensionLocation: { scheme: SCHEME, authority: AUTHORITY, path: `/extension/${extensionId}` } }); locations[extensionId] = extensionPath; } })); return { extensions, locations }; } async function getExtensionPackageJSON(extensionPath) { const packageJSONPath = path.join(extensionPath, 'package.json'); if (await exists(packageJSONPath)) { try { let packageJSON = JSON.parse((await readFile(packageJSONPath)).toString()); if (packageJSON.main && !packageJSON.browser) { return; // unsupported } const packageNLSPath = path.join(extensionPath, 'package.nls.json'); const packageNLSExists = await exists(packageNLSPath); if (packageNLSExists) { packageJSON = extensions.translatePackageJSON(packageJSON, packageNLSPath); // temporary, until fixed in core } return packageJSON; } catch (e) { console.log(e); } } return undefined; } const builtInExtensionsPromise = getBuiltInExtensionInfos(); const commandlineProvidedExtensionsPromise = getCommandlineProvidedExtensionInfos(); const mapCallbackUriToRequestId = new Map(); /** * @param req {http.IncomingMessage} * @param res {http.ServerResponse} */ const requestHandler = (req, res) => { const parsedUrl = url.parse(req.url, true); const pathname = parsedUrl.pathname; res.setHeader('Access-Control-Allow-Origin', '*'); try { if (/(\/static)?\/favicon\.ico/.test(pathname)) { // favicon return serveFile(req, res, path.join(APP_ROOT, 'resources', 'win32', 'code.ico')); } if (/(\/static)?\/manifest\.json/.test(pathname)) { // manifest res.writeHead(200, { 'Content-Type': 'application/json' }); return res.end(JSON.stringify({ 'name': 'Code Web - OSS', 'short_name': 'Code Web - OSS', 'start_url': '/', 'lang': 'en-US', 'display': 'standalone' })); } if (/^\/static\//.test(pathname)) { // static requests return handleStatic(req, res, parsedUrl); } if (/^\/extension\//.test(pathname)) { // default extension requests return handleExtension(req, res, parsedUrl); } if (pathname === '/') { // main web return handleRoot(req, res); } else if (pathname === '/callback') { // callback support return handleCallback(req, res, parsedUrl); } else if (pathname === '/fetch-callback') { // callback fetch support return handleFetchCallback(req, res, parsedUrl); } return serveError(req, res, 404, 'Not found.'); } catch (error) { console.error(error.toString()); return serveError(req, res, 500, 'Internal Server Error.'); } }; const server = http.createServer(requestHandler); server.listen(LOCAL_PORT, () => { if (LOCAL_PORT !== PORT) { console.log(`Operating location at http://0.0.0.0:${LOCAL_PORT}`); } console.log(`Web UI available at ${SCHEME}://${AUTHORITY}`); }); server.on('error', err => { console.error(`Error occurred in server:`); console.error(err); }); const secondaryServer = http.createServer(requestHandler); secondaryServer.listen(SECONDARY_PORT, () => { console.log(`Secondary server available at ${SCHEME}://${HOST}:${SECONDARY_PORT}`); }); secondaryServer.on('error', err => { console.error(`Error occurred in server:`); console.error(err); }); /** * @param {import('http').IncomingMessage} req */ function addCORSReplyHeader(req) { if (typeof req.headers['origin'] !== 'string') { // not a CORS request return false; } return (ALLOWED_CORS_ORIGINS.indexOf(req.headers['origin']) >= 0); } /** * @param {import('http').IncomingMessage} req * @param {import('http').ServerResponse} res * @param {import('url').UrlWithParsedQuery} parsedUrl */ async function handleStatic(req, res, parsedUrl) { if (/^\/static\/extensions\//.test(parsedUrl.pathname)) { const relativePath = decodeURIComponent(parsedUrl.pathname.substr('/static/extensions/'.length)); const filePath = getExtensionFilePath(relativePath, (await builtInExtensionsPromise).locations); const responseHeaders = {}; if (addCORSReplyHeader(req)) { responseHeaders['Access-Control-Allow-Origin'] = '*'; } if (!filePath) { return serveError(req, res, 400, `Bad request.`, responseHeaders); } return serveFile(req, res, filePath, responseHeaders); } // Strip `/static/` from the path const relativeFilePath = path.normalize(decodeURIComponent(parsedUrl.pathname.substr('/static/'.length))); return serveFile(req, res, path.join(APP_ROOT, relativeFilePath)); } /** * @param {import('http').IncomingMessage} req * @param {import('http').ServerResponse} res * @param {import('url').UrlWithParsedQuery} parsedUrl */ async function handleExtension(req, res, parsedUrl) { // Strip `/extension/` from the path const relativePath = decodeURIComponent(parsedUrl.pathname.substr('/extension/'.length)); const filePath = getExtensionFilePath(relativePath, (await commandlineProvidedExtensionsPromise).locations); const responseHeaders = {}; if (addCORSReplyHeader(req)) { responseHeaders['Access-Control-Allow-Origin'] = '*'; } if (!filePath) { return serveError(req, res, 400, `Bad request.`, responseHeaders); } return serveFile(req, res, filePath, responseHeaders); } /** * @param {import('http').IncomingMessage} req * @param {import('http').ServerResponse} res */ async function handleRoot(req, res) { let folderUri = { scheme: 'memfs', path: `/sample-folder` }; const match = req.url && req.url.match(/\?([^#]+)/); if (match) { const qs = new URLSearchParams(match[1]); let gh = qs.get('gh'); if (gh) { if (gh.startsWith('/')) { gh = gh.substr(1); } const [owner, repo, ...branch] = gh.split('/', 3); const ref = branch.join('/'); folderUri = { scheme: 'github', authority: `${owner}+${repo}${ref ? `+${ref}` : ''}`, path: '/' }; } else { let cs = qs.get('cs'); if (cs) { if (cs.startsWith('/')) { cs = cs.substr(1); } const [owner, repo, ...branch] = cs.split('/'); const ref = branch.join('/'); folderUri = { scheme: 'codespace', authority: `${owner}+${repo}${ref ? `+${ref}` : ''}`, path: '/' }; } } } const { extensions: builtInExtensions } = await builtInExtensionsPromise; const { extensions: staticExtensions, locations: staticLocations } = await commandlineProvidedExtensionsPromise; const dedupedBuiltInExtensions = []; for (const builtInExtension of builtInExtensions) { const extensionId = `${builtInExtension.packageJSON.publisher}.${builtInExtension.packageJSON.name}`; if (staticLocations[extensionId]) { fancyLog(`${ansiColors.magenta('BuiltIn extensions')}: Ignoring built-in ${extensionId} because it was overridden via --extension argument`); continue; } dedupedBuiltInExtensions.push(builtInExtension); } if (args.verbose) { fancyLog(`${ansiColors.magenta('BuiltIn extensions')}: ${dedupedBuiltInExtensions.map(e => path.basename(e.extensionPath)).join(', ')}`); fancyLog(`${ansiColors.magenta('Additional extensions')}: ${staticExtensions.map(e => path.basename(e.extensionLocation.path)).join(', ') || 'None'}`); } const secondaryHost = ( req.headers['host'] ? req.headers['host'].replace(':' + PORT, ':' + SECONDARY_PORT) : `${HOST}:${SECONDARY_PORT}` ); const webConfigJSON = { folderUri: folderUri, staticExtensions, settingsSyncOptions: { enabled: args['enable-sync'] }, webWorkerExtensionHostIframeSrc: `${SCHEME}://${secondaryHost}/static/out/vs/workbench/services/extensions/worker/httpWebWorkerExtensionHostIframe.html` }; if (args['wrap-iframe']) { webConfigJSON._wrapWebWorkerExtHostInIframe = true; } if (req.headers['x-forwarded-host']) { // support for running in codespace => no iframe wrapping delete webConfigJSON.webWorkerExtensionHostIframeSrc; } const authSessionInfo = args['github-auth'] ? { id: uuid.v4(), providerId: 'github', accessToken: args['github-auth'], scopes: [['user:email'], ['repo']] } : undefined; const data = (await readFile(WEB_MAIN)).toString() .replace('{{WORKBENCH_WEB_CONFIGURATION}}', () => escapeAttribute(JSON.stringify(webConfigJSON))) // use a replace function to avoid that regexp replace patterns ($&, $0, ...) are applied .replace('{{WORKBENCH_BUILTIN_EXTENSIONS}}', () => escapeAttribute(JSON.stringify(dedupedBuiltInExtensions))) .replace('{{WORKBENCH_AUTH_SESSION}}', () => authSessionInfo ? escapeAttribute(JSON.stringify(authSessionInfo)) : '') .replace('{{WEBVIEW_ENDPOINT}}', ''); const headers = { 'Content-Type': 'text/html', 'Content-Security-Policy': 'require-trusted-types-for \'script\';' }; res.writeHead(200, headers); return res.end(data); } /** * Handle HTTP requests for /callback * @param {import('http').IncomingMessage} req * @param {import('http').ServerResponse} res * @param {import('url').UrlWithParsedQuery} parsedUrl */ async function handleCallback(req, res, parsedUrl) { const wellKnownKeys = ['vscode-requestId', 'vscode-scheme', 'vscode-authority', 'vscode-path', 'vscode-query', 'vscode-fragment']; const [requestId, vscodeScheme, vscodeAuthority, vscodePath, vscodeQuery, vscodeFragment] = wellKnownKeys.map(key => { const value = getFirstQueryValue(parsedUrl, key); if (value) { return decodeURIComponent(value); } return value; }); if (!requestId) { res.writeHead(400, { 'Content-Type': 'text/plain' }); return res.end(`Bad request.`); } // merge over additional query values that we got let query = vscodeQuery; let index = 0; getFirstQueryValues(parsedUrl, wellKnownKeys).forEach((value, key) => { if (!query) { query = ''; } const prefix = (index++ === 0) ? '' : '&'; query += `${prefix}${key}=${value}`; }); // add to map of known callbacks mapCallbackUriToRequestId.set(requestId, JSON.stringify({ scheme: vscodeScheme || 'code-oss', authority: vscodeAuthority, path: vscodePath, query, fragment: vscodeFragment })); return serveFile(req, res, path.join(APP_ROOT, 'resources', 'web', 'callback.html'), { 'Content-Type': 'text/html' }); } /** * Handle HTTP requests for /fetch-callback * @param {import('http').IncomingMessage} req * @param {import('http').ServerResponse} res * @param {import('url').UrlWithParsedQuery} parsedUrl */ async function handleFetchCallback(req, res, parsedUrl) { const requestId = getFirstQueryValue(parsedUrl, 'vscode-requestId'); if (!requestId) { res.writeHead(400, { 'Content-Type': 'text/plain' }); return res.end(`Bad request.`); } const knownCallbackUri = mapCallbackUriToRequestId.get(requestId); if (knownCallbackUri) { mapCallbackUriToRequestId.delete(requestId); } res.writeHead(200, { 'Content-Type': 'text/json' }); return res.end(knownCallbackUri); } /** * @param {import('url').UrlWithParsedQuery} parsedUrl * @param {string} key * @returns {string | undefined} */ function getFirstQueryValue(parsedUrl, key) { const result = parsedUrl.query[key]; return Array.isArray(result) ? result[0] : result; } /** * @param {import('url').UrlWithParsedQuery} parsedUrl * @param {string[] | undefined} ignoreKeys * @returns {Map<string, string>} */ function getFirstQueryValues(parsedUrl, ignoreKeys) { const queryValues = new Map(); for (const key in parsedUrl.query) { if (ignoreKeys && ignoreKeys.indexOf(key) >= 0) { continue; } const value = getFirstQueryValue(parsedUrl, key); if (typeof value === 'string') { queryValues.set(key, value); } } return queryValues; } /** * @param {string} value */ function escapeAttribute(value) { return value.replace(/"/g, '&quot;'); } /** * @param {string} relativePath * @param {Object.<string, string>} locations * @returns {string | undefined} */ function getExtensionFilePath(relativePath, locations) { const firstSlash = relativePath.indexOf('/'); if (firstSlash === -1) { return undefined; } const extensionId = relativePath.substr(0, firstSlash); const extensionPath = locations[extensionId]; if (!extensionPath) { return undefined; } return path.join(extensionPath, relativePath.substr(firstSlash + 1)); } /** * @param {import('http').IncomingMessage} req * @param {import('http').ServerResponse} res * @param {string} errorMessage */ function serveError(req, res, errorCode, errorMessage, responseHeaders = Object.create(null)) { responseHeaders['Content-Type'] = 'text/plain'; res.writeHead(errorCode, responseHeaders); res.end(errorMessage); } const textMimeType = { '.html': 'text/html', '.js': 'text/javascript', '.json': 'application/json', '.css': 'text/css', '.svg': 'image/svg+xml', }; const mapExtToMediaMimes = { '.bmp': 'image/bmp', '.gif': 'image/gif', '.ico': 'image/x-icon', '.jpe': 'image/jpg', '.jpeg': 'image/jpg', '.jpg': 'image/jpg', '.png': 'image/png', '.tga': 'image/x-tga', '.tif': 'image/tiff', '.tiff': 'image/tiff', '.woff': 'application/font-woff' }; /** * @param {string} forPath */ function getMediaMime(forPath) { const ext = path.extname(forPath); return mapExtToMediaMimes[ext.toLowerCase()]; } /** * @param {import('http').IncomingMessage} req * @param {import('http').ServerResponse} res * @param {string} filePath */ async function serveFile(req, res, filePath, responseHeaders = Object.create(null)) { try { // Sanity checks filePath = path.normalize(filePath); // ensure no "." and ".." const stat = await util.promisify(fs.stat)(filePath); // Check if file modified since const etag = `W/"${[stat.ino, stat.size, stat.mtime.getTime()].join('-')}"`; // weak validator (https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/ETag) if (req.headers['if-none-match'] === etag) { res.writeHead(304); return res.end(); } // Headers responseHeaders['Content-Type'] = textMimeType[path.extname(filePath)] || getMediaMime(filePath) || 'text/plain'; responseHeaders['Etag'] = etag; res.writeHead(200, responseHeaders); // Data fs.createReadStream(filePath).pipe(res); } catch (error) { console.error(error.toString()); responseHeaders['Content-Type'] = 'text/plain'; res.writeHead(404, responseHeaders); return res.end('Not found'); } } if (args.launch !== false) { opn(`${SCHEME}://${HOST}:${PORT}`); }
resources/web/code-web.js
0
https://github.com/microsoft/vscode/commit/f554a745505474ba031a79f5ab4a5c9d1ed3af39
[ 0.0011394048342481256, 0.00018775904027279466, 0.00016336279804818332, 0.00017266275244764984, 0.00011909468594240025 ]
{ "id": 0, "code_window": [ " * Licensed under the MIT License. See License.txt in the project root for license information.\n", " *--------------------------------------------------------------------------------------------*/\n", "\n", "import { Constants } from 'vs/base/common/uint';\n", "import { Range, IRange } from 'vs/editor/common/core/range';\n", "import { TrackedRangeStickiness, IModelDeltaDecoration, IModelDecorationOptions, OverviewRulerLane } from 'vs/editor/common/model';\n", "import { IDebugService, IStackFrame } from 'vs/workbench/contrib/debug/common/debug';\n", "import { registerThemingParticipant, themeColorFromId, ThemeIcon } from 'vs/platform/theme/common/themeService';\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "import { Range } from 'vs/editor/common/core/range';\n" ], "file_path": "src/vs/workbench/contrib/debug/browser/callStackEditorContribution.ts", "type": "replace", "edit_start_line_idx": 6 }
{ "name": "vscode-test-resolver", "description": "Test resolver for VS Code", "version": "0.0.1", "publisher": "vscode", "license": "MIT", "enableProposedApi": true, "private": true, "engines": { "vscode": "^1.25.0" }, "extensionKind": [ "ui" ], "scripts": { "compile": "node ./node_modules/vscode/bin/compile -watch -p ./", "vscode:prepublish": "node ../../node_modules/gulp/bin/gulp.js --gulpfile ../../build/gulpfile.extensions.js compile-extension:vscode-test-resolver" }, "activationEvents": [ "onResolveRemoteAuthority:test", "onCommand:vscode-testresolver.newWindow", "onCommand:vscode-testresolver.newWindowWithError", "onCommand:vscode-testresolver.showLog", "onCommand:vscode-testresolver.openTunnel", "onCommand:vscode-testresolver.startRemoteServer" ], "main": "./out/extension", "devDependencies": { "@types/node": "^12.19.9" }, "contributes": { "resourceLabelFormatters": [ { "scheme": "vscode-remote", "authority": "test+*", "formatting": { "label": "${path}", "separator": "/", "tildify": true, "workspaceSuffix": "TestResolver" } } ], "commands": [ { "title": "New Window", "category": "Remote-TestResolver", "command": "vscode-testresolver.newWindow" }, { "title": "Show Log", "category": "Remote-TestResolver", "command": "vscode-testresolver.showLog" }, { "title": "Kill Server and Trigger Handled Error", "category": "Remote-TestResolver", "command": "vscode-testresolver.killServerAndTriggerHandledError" }, { "title": "Open Tunnel...", "category": "Remote-TestResolver", "command": "vscode-testresolver.openTunnel" }, { "title": "Open Remote Server...", "category": "Remote-TestResolver", "command": "vscode-testresolver.startRemoteServer" } ], "menus": { "commandPalette": [ { "command": "vscode-testresolver.openTunnel", "when": "remoteName == test" }, { "command": "vscode-testresolver.startRemoteServer", "when": "remoteName == test" } ], "statusBar/windowIndicator": [ { "command": "vscode-testresolver.newWindow", "when": "!remoteName", "group": "9_local_testresolver@2" }, { "command": "vscode-testresolver.showLog", "when": "remoteName == test", "group": "1_remote_testresolver_open@3" }, { "command": "vscode-testresolver.newWindow", "when": "remoteName == test", "group": "1_remote_testresolver_open@1" }, { "command": "vscode-testresolver.openTunnel", "when": "remoteName == test", "group": "1_remote_testresolver_open@4" }, { "command": "vscode-testresolver.startRemoteServer", "when": "remoteName == test", "group": "1_remote_testresolver_open@5" } ] }, "configuration": { "properties": { "testresolver.startupDelay": { "description": "If set, the resolver will delay for the given amount of seconds. Use ths setting for testing a slow resolver", "type": "number", "default": 0 }, "testresolver.startupError": { "description": "If set, the resolver will fail. Use ths setting for testing the failure of a resolver.", "type": "boolean", "default": false }, "testresolver.pause": { "description": "If set, connection is paused", "type": "boolean", "default": false }, "testresolver.supportPublicPorts": { "description": "If set, the test resolver tunnel factory will support mock public ports. Forwarded ports will not actually be public. Requires reload.", "type": "boolean", "default": false } } } }, "repository": { "type": "git", "url": "https://github.com/microsoft/vscode.git" } }
extensions/vscode-test-resolver/package.json
0
https://github.com/microsoft/vscode/commit/f554a745505474ba031a79f5ab4a5c9d1ed3af39
[ 0.00017522736743558198, 0.0001726466725813225, 0.00017110315093304962, 0.00017243402544409037, 0.0000010322180514776846 ]
{ "id": 0, "code_window": [ " * Licensed under the MIT License. See License.txt in the project root for license information.\n", " *--------------------------------------------------------------------------------------------*/\n", "\n", "import { Constants } from 'vs/base/common/uint';\n", "import { Range, IRange } from 'vs/editor/common/core/range';\n", "import { TrackedRangeStickiness, IModelDeltaDecoration, IModelDecorationOptions, OverviewRulerLane } from 'vs/editor/common/model';\n", "import { IDebugService, IStackFrame } from 'vs/workbench/contrib/debug/common/debug';\n", "import { registerThemingParticipant, themeColorFromId, ThemeIcon } from 'vs/platform/theme/common/themeService';\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "import { Range } from 'vs/editor/common/core/range';\n" ], "file_path": "src/vs/workbench/contrib/debug/browser/callStackEditorContribution.ts", "type": "replace", "edit_start_line_idx": 6 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as strings from 'vs/base/common/strings'; import * as streams from 'vs/base/common/stream'; declare const Buffer: any; const hasBuffer = (typeof Buffer !== 'undefined'); const hasTextEncoder = (typeof TextEncoder !== 'undefined'); const hasTextDecoder = (typeof TextDecoder !== 'undefined'); let textEncoder: TextEncoder | null; let textDecoder: TextDecoder | null; export class VSBuffer { static alloc(byteLength: number): VSBuffer { if (hasBuffer) { return new VSBuffer(Buffer.allocUnsafe(byteLength)); } else { return new VSBuffer(new Uint8Array(byteLength)); } } static wrap(actual: Uint8Array): VSBuffer { if (hasBuffer && !(Buffer.isBuffer(actual))) { // https://nodejs.org/dist/latest-v10.x/docs/api/buffer.html#buffer_class_method_buffer_from_arraybuffer_byteoffset_length // Create a zero-copy Buffer wrapper around the ArrayBuffer pointed to by the Uint8Array actual = Buffer.from(actual.buffer, actual.byteOffset, actual.byteLength); } return new VSBuffer(actual); } static fromString(source: string, options?: { dontUseNodeBuffer?: boolean; }): VSBuffer { const dontUseNodeBuffer = options?.dontUseNodeBuffer || false; if (!dontUseNodeBuffer && hasBuffer) { return new VSBuffer(Buffer.from(source)); } else if (hasTextEncoder) { if (!textEncoder) { textEncoder = new TextEncoder(); } return new VSBuffer(textEncoder.encode(source)); } else { return new VSBuffer(strings.encodeUTF8(source)); } } static concat(buffers: VSBuffer[], totalLength?: number): VSBuffer { if (typeof totalLength === 'undefined') { totalLength = 0; for (let i = 0, len = buffers.length; i < len; i++) { totalLength += buffers[i].byteLength; } } const ret = VSBuffer.alloc(totalLength); let offset = 0; for (let i = 0, len = buffers.length; i < len; i++) { const element = buffers[i]; ret.set(element, offset); offset += element.byteLength; } return ret; } readonly buffer: Uint8Array; readonly byteLength: number; private constructor(buffer: Uint8Array) { this.buffer = buffer; this.byteLength = this.buffer.byteLength; } toString(): string { if (hasBuffer) { return this.buffer.toString(); } else if (hasTextDecoder) { if (!textDecoder) { textDecoder = new TextDecoder(); } return textDecoder.decode(this.buffer); } else { return strings.decodeUTF8(this.buffer); } } slice(start?: number, end?: number): VSBuffer { // IMPORTANT: use subarray instead of slice because TypedArray#slice // creates shallow copy and NodeBuffer#slice doesn't. The use of subarray // ensures the same, performant, behaviour. return new VSBuffer(this.buffer.subarray(start!/*bad lib.d.ts*/, end)); } set(array: VSBuffer, offset?: number): void; set(array: Uint8Array, offset?: number): void; set(array: VSBuffer | Uint8Array, offset?: number): void { if (array instanceof VSBuffer) { this.buffer.set(array.buffer, offset); } else { this.buffer.set(array, offset); } } readUInt32BE(offset: number): number { return readUInt32BE(this.buffer, offset); } writeUInt32BE(value: number, offset: number): void { writeUInt32BE(this.buffer, value, offset); } readUInt32LE(offset: number): number { return readUInt32LE(this.buffer, offset); } writeUInt32LE(value: number, offset: number): void { writeUInt32LE(this.buffer, value, offset); } readUInt8(offset: number): number { return readUInt8(this.buffer, offset); } writeUInt8(value: number, offset: number): void { writeUInt8(this.buffer, value, offset); } } export function readUInt16LE(source: Uint8Array, offset: number): number { return ( ((source[offset + 0] << 0) >>> 0) | ((source[offset + 1] << 8) >>> 0) ); } export function writeUInt16LE(destination: Uint8Array, value: number, offset: number): void { destination[offset + 0] = (value & 0b11111111); value = value >>> 8; destination[offset + 1] = (value & 0b11111111); } export function readUInt32BE(source: Uint8Array, offset: number): number { return ( source[offset] * 2 ** 24 + source[offset + 1] * 2 ** 16 + source[offset + 2] * 2 ** 8 + source[offset + 3] ); } export function writeUInt32BE(destination: Uint8Array, value: number, offset: number): void { destination[offset + 3] = value; value = value >>> 8; destination[offset + 2] = value; value = value >>> 8; destination[offset + 1] = value; value = value >>> 8; destination[offset] = value; } export function readUInt32LE(source: Uint8Array, offset: number): number { return ( ((source[offset + 0] << 0) >>> 0) | ((source[offset + 1] << 8) >>> 0) | ((source[offset + 2] << 16) >>> 0) | ((source[offset + 3] << 24) >>> 0) ); } export function writeUInt32LE(destination: Uint8Array, value: number, offset: number): void { destination[offset + 0] = (value & 0b11111111); value = value >>> 8; destination[offset + 1] = (value & 0b11111111); value = value >>> 8; destination[offset + 2] = (value & 0b11111111); value = value >>> 8; destination[offset + 3] = (value & 0b11111111); } export function readUInt8(source: Uint8Array, offset: number): number { return source[offset]; } export function writeUInt8(destination: Uint8Array, value: number, offset: number): void { destination[offset] = value; } export interface VSBufferReadable extends streams.Readable<VSBuffer> { } export interface VSBufferReadableStream extends streams.ReadableStream<VSBuffer> { } export interface VSBufferWriteableStream extends streams.WriteableStream<VSBuffer> { } export interface VSBufferReadableBufferedStream extends streams.ReadableBufferedStream<VSBuffer> { } export function readableToBuffer(readable: VSBufferReadable): VSBuffer { return streams.consumeReadable<VSBuffer>(readable, chunks => VSBuffer.concat(chunks)); } export function bufferToReadable(buffer: VSBuffer): VSBufferReadable { return streams.toReadable<VSBuffer>(buffer); } export function streamToBuffer(stream: streams.ReadableStream<VSBuffer>): Promise<VSBuffer> { return streams.consumeStream<VSBuffer>(stream, chunks => VSBuffer.concat(chunks)); } export async function bufferedStreamToBuffer(bufferedStream: streams.ReadableBufferedStream<VSBuffer>): Promise<VSBuffer> { if (bufferedStream.ended) { return VSBuffer.concat(bufferedStream.buffer); } return VSBuffer.concat([ // Include already read chunks... ...bufferedStream.buffer, // ...and all additional chunks await streamToBuffer(bufferedStream.stream) ]); } export function bufferToStream(buffer: VSBuffer): streams.ReadableStream<VSBuffer> { return streams.toStream<VSBuffer>(buffer, chunks => VSBuffer.concat(chunks)); } export function streamToBufferReadableStream(stream: streams.ReadableStreamEvents<Uint8Array | string>): streams.ReadableStream<VSBuffer> { return streams.transform<Uint8Array | string, VSBuffer>(stream, { data: data => typeof data === 'string' ? VSBuffer.fromString(data) : VSBuffer.wrap(data) }, chunks => VSBuffer.concat(chunks)); } export function newWriteableBufferStream(options?: streams.WriteableStreamOptions): streams.WriteableStream<VSBuffer> { return streams.newWriteableStream<VSBuffer>(chunks => VSBuffer.concat(chunks), options); }
src/vs/base/common/buffer.ts
0
https://github.com/microsoft/vscode/commit/f554a745505474ba031a79f5ab4a5c9d1ed3af39
[ 0.0001772587129380554, 0.0001718001876724884, 0.0001654798979870975, 0.0001729550422169268, 0.000003342740228617913 ]
{ "id": 1, "code_window": [ "\tclassName: 'debug-focused-stack-frame-line',\n", "\tstickiness\n", "};\n", "\n", "export function createDecorationsForStackFrame(stackFrame: IStackFrame, topStackFrameRange: IRange | undefined, isFocusedSession: boolean): IModelDeltaDecoration[] {\n", "\t// only show decorations for the currently focused thread.\n", "\tconst result: IModelDeltaDecoration[] = [];\n", "\tconst columnUntilEOLRange = new Range(stackFrame.range.startLineNumber, stackFrame.range.startColumn, stackFrame.range.startLineNumber, Constants.MAX_SAFE_SMALL_INTEGER);\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "export function createDecorationsForStackFrame(stackFrame: IStackFrame, isFocusedSession: boolean): IModelDeltaDecoration[] {\n" ], "file_path": "src/vs/workbench/contrib/debug/browser/callStackEditorContribution.ts", "type": "replace", "edit_start_line_idx": 55 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as assert from 'assert'; import { DebugModel, StackFrame, Thread } from 'vs/workbench/contrib/debug/common/debugModel'; import * as sinon from 'sinon'; import { MockRawSession, createMockDebugModel, mockUriIdentityService } from 'vs/workbench/contrib/debug/test/browser/mockDebug'; import { Source } from 'vs/workbench/contrib/debug/common/debugSource'; import { DebugSession } from 'vs/workbench/contrib/debug/browser/debugSession'; import { Range } from 'vs/editor/common/core/range'; import { IDebugSessionOptions, State, IDebugService } from 'vs/workbench/contrib/debug/common/debug'; import { NullOpenerService } from 'vs/platform/opener/common/opener'; import { createDecorationsForStackFrame } from 'vs/workbench/contrib/debug/browser/callStackEditorContribution'; import { Constants } from 'vs/base/common/uint'; import { getContext, getContextForContributedActions, getSpecificSourceName } from 'vs/workbench/contrib/debug/browser/callStackView'; import { getStackFrameThreadAndSessionToFocus } from 'vs/workbench/contrib/debug/browser/debugService'; import { generateUuid } from 'vs/base/common/uuid'; import { debugStackframe, debugStackframeFocused } from 'vs/workbench/contrib/debug/browser/debugIcons'; import { ThemeIcon } from 'vs/platform/theme/common/themeService'; import { TestConfigurationService } from 'vs/platform/configuration/test/common/testConfigurationService'; const mockWorkspaceContextService = { getWorkspace: () => { return { folders: [] }; } } as any; export function createMockSession(model: DebugModel, name = 'mockSession', options?: IDebugSessionOptions): DebugSession { return new DebugSession(generateUuid(), { resolved: { name, type: 'node', request: 'launch' }, unresolved: undefined }, undefined!, model, options, { getViewModel(): any { return { updateViews(): void { // noop } }; } } as IDebugService, undefined!, undefined!, new TestConfigurationService({ debug: { console: { collapseIdenticalLines: true } } }), undefined!, mockWorkspaceContextService, undefined!, undefined!, NullOpenerService, undefined!, undefined!, mockUriIdentityService, undefined!); } function createTwoStackFrames(session: DebugSession): { firstStackFrame: StackFrame, secondStackFrame: StackFrame } { let firstStackFrame: StackFrame; let secondStackFrame: StackFrame; const thread = new class extends Thread { public getCallStack(): StackFrame[] { return [firstStackFrame, secondStackFrame]; } }(session, 'mockthread', 1); const firstSource = new Source({ name: 'internalModule.js', path: 'a/b/c/d/internalModule.js', sourceReference: 10, }, 'aDebugSessionId', mockUriIdentityService); const secondSource = new Source({ name: 'internalModule.js', path: 'z/x/c/d/internalModule.js', sourceReference: 11, }, 'aDebugSessionId', mockUriIdentityService); firstStackFrame = new StackFrame(thread, 0, firstSource, 'app.js', 'normal', { startLineNumber: 1, startColumn: 1, endLineNumber: 1, endColumn: 10 }, 0, true); secondStackFrame = new StackFrame(thread, 1, secondSource, 'app2.js', 'normal', { startLineNumber: 1, startColumn: 1, endLineNumber: 1, endColumn: 10 }, 1, true); return { firstStackFrame, secondStackFrame }; } suite('Debug - CallStack', () => { let model: DebugModel; let rawSession: MockRawSession; setup(() => { model = createMockDebugModel(); rawSession = new MockRawSession(); }); // Threads test('threads simple', () => { const threadId = 1; const threadName = 'firstThread'; const session = createMockSession(model); model.addSession(session); assert.strictEqual(model.getSessions(true).length, 1); model.rawUpdate({ sessionId: session.getId(), threads: [{ id: threadId, name: threadName }] }); assert.strictEqual(session.getThread(threadId)!.name, threadName); model.clearThreads(session.getId(), true); assert.strictEqual(session.getThread(threadId), undefined); assert.strictEqual(model.getSessions(true).length, 1); }); test('threads multiple wtih allThreadsStopped', async () => { const threadId1 = 1; const threadName1 = 'firstThread'; const threadId2 = 2; const threadName2 = 'secondThread'; const stoppedReason = 'breakpoint'; // Add the threads const session = createMockSession(model); model.addSession(session); session['raw'] = <any>rawSession; model.rawUpdate({ sessionId: session.getId(), threads: [{ id: threadId1, name: threadName1 }] }); // Stopped event with all threads stopped model.rawUpdate({ sessionId: session.getId(), threads: [{ id: threadId1, name: threadName1 }, { id: threadId2, name: threadName2 }], stoppedDetails: { reason: stoppedReason, threadId: 1, allThreadsStopped: true }, }); const thread1 = session.getThread(threadId1)!; const thread2 = session.getThread(threadId2)!; // at the beginning, callstacks are obtainable but not available assert.strictEqual(session.getAllThreads().length, 2); assert.strictEqual(thread1.name, threadName1); assert.strictEqual(thread1.stopped, true); assert.strictEqual(thread1.getCallStack().length, 0); assert.strictEqual(thread1.stoppedDetails!.reason, stoppedReason); assert.strictEqual(thread2.name, threadName2); assert.strictEqual(thread2.stopped, true); assert.strictEqual(thread2.getCallStack().length, 0); assert.strictEqual(thread2.stoppedDetails!.reason, undefined); // after calling getCallStack, the callstack becomes available // and results in a request for the callstack in the debug adapter await thread1.fetchCallStack(); assert.notStrictEqual(thread1.getCallStack().length, 0); await thread2.fetchCallStack(); assert.notStrictEqual(thread2.getCallStack().length, 0); // calling multiple times getCallStack doesn't result in multiple calls // to the debug adapter await thread1.fetchCallStack(); await thread2.fetchCallStack(); // clearing the callstack results in the callstack not being available thread1.clearCallStack(); assert.strictEqual(thread1.stopped, true); assert.strictEqual(thread1.getCallStack().length, 0); thread2.clearCallStack(); assert.strictEqual(thread2.stopped, true); assert.strictEqual(thread2.getCallStack().length, 0); model.clearThreads(session.getId(), true); assert.strictEqual(session.getThread(threadId1), undefined); assert.strictEqual(session.getThread(threadId2), undefined); assert.strictEqual(session.getAllThreads().length, 0); }); test('threads mutltiple without allThreadsStopped', async () => { const sessionStub = sinon.spy(rawSession, 'stackTrace'); const stoppedThreadId = 1; const stoppedThreadName = 'stoppedThread'; const runningThreadId = 2; const runningThreadName = 'runningThread'; const stoppedReason = 'breakpoint'; const session = createMockSession(model); model.addSession(session); session['raw'] = <any>rawSession; // Add the threads model.rawUpdate({ sessionId: session.getId(), threads: [{ id: stoppedThreadId, name: stoppedThreadName }] }); // Stopped event with only one thread stopped model.rawUpdate({ sessionId: session.getId(), threads: [{ id: 1, name: stoppedThreadName }, { id: runningThreadId, name: runningThreadName }], stoppedDetails: { reason: stoppedReason, threadId: 1, allThreadsStopped: false } }); const stoppedThread = session.getThread(stoppedThreadId)!; const runningThread = session.getThread(runningThreadId)!; // the callstack for the stopped thread is obtainable but not available // the callstack for the running thread is not obtainable nor available assert.strictEqual(stoppedThread.name, stoppedThreadName); assert.strictEqual(stoppedThread.stopped, true); assert.strictEqual(session.getAllThreads().length, 2); assert.strictEqual(stoppedThread.getCallStack().length, 0); assert.strictEqual(stoppedThread.stoppedDetails!.reason, stoppedReason); assert.strictEqual(runningThread.name, runningThreadName); assert.strictEqual(runningThread.stopped, false); assert.strictEqual(runningThread.getCallStack().length, 0); assert.strictEqual(runningThread.stoppedDetails, undefined); // after calling getCallStack, the callstack becomes available // and results in a request for the callstack in the debug adapter await stoppedThread.fetchCallStack(); assert.notStrictEqual(stoppedThread.getCallStack().length, 0); assert.strictEqual(runningThread.getCallStack().length, 0); assert.strictEqual(sessionStub.callCount, 1); // calling getCallStack on the running thread returns empty array // and does not return in a request for the callstack in the debug // adapter await runningThread.fetchCallStack(); assert.strictEqual(runningThread.getCallStack().length, 0); assert.strictEqual(sessionStub.callCount, 1); // clearing the callstack results in the callstack not being available stoppedThread.clearCallStack(); assert.strictEqual(stoppedThread.stopped, true); assert.strictEqual(stoppedThread.getCallStack().length, 0); model.clearThreads(session.getId(), true); assert.strictEqual(session.getThread(stoppedThreadId), undefined); assert.strictEqual(session.getThread(runningThreadId), undefined); assert.strictEqual(session.getAllThreads().length, 0); }); test('stack frame get specific source name', () => { const session = createMockSession(model); model.addSession(session); const { firstStackFrame, secondStackFrame } = createTwoStackFrames(session); assert.strictEqual(getSpecificSourceName(firstStackFrame), '.../b/c/d/internalModule.js'); assert.strictEqual(getSpecificSourceName(secondStackFrame), '.../x/c/d/internalModule.js'); }); test('stack frame toString()', () => { const session = createMockSession(model); const thread = new Thread(session, 'mockthread', 1); const firstSource = new Source({ name: 'internalModule.js', path: 'a/b/c/d/internalModule.js', sourceReference: 10, }, 'aDebugSessionId', mockUriIdentityService); const stackFrame = new StackFrame(thread, 1, firstSource, 'app', 'normal', { startLineNumber: 1, startColumn: 1, endLineNumber: 1, endColumn: 10 }, 1, true); assert.strictEqual(stackFrame.toString(), 'app (internalModule.js:1)'); const secondSource = new Source(undefined, 'aDebugSessionId', mockUriIdentityService); const stackFrame2 = new StackFrame(thread, 2, secondSource, 'module', 'normal', { startLineNumber: undefined!, startColumn: undefined!, endLineNumber: undefined!, endColumn: undefined! }, 2, true); assert.strictEqual(stackFrame2.toString(), 'module'); }); test('debug child sessions are added in correct order', () => { const session = createMockSession(model); model.addSession(session); const secondSession = createMockSession(model, 'mockSession2'); model.addSession(secondSession); const firstChild = createMockSession(model, 'firstChild', { parentSession: session }); model.addSession(firstChild); const secondChild = createMockSession(model, 'secondChild', { parentSession: session }); model.addSession(secondChild); const thirdSession = createMockSession(model, 'mockSession3'); model.addSession(thirdSession); const anotherChild = createMockSession(model, 'secondChild', { parentSession: secondSession }); model.addSession(anotherChild); const sessions = model.getSessions(); assert.strictEqual(sessions[0].getId(), session.getId()); assert.strictEqual(sessions[1].getId(), firstChild.getId()); assert.strictEqual(sessions[2].getId(), secondChild.getId()); assert.strictEqual(sessions[3].getId(), secondSession.getId()); assert.strictEqual(sessions[4].getId(), anotherChild.getId()); assert.strictEqual(sessions[5].getId(), thirdSession.getId()); }); test('decorations', () => { const session = createMockSession(model); model.addSession(session); const { firstStackFrame, secondStackFrame } = createTwoStackFrames(session); let decorations = createDecorationsForStackFrame(firstStackFrame, firstStackFrame.range, true); assert.strictEqual(decorations.length, 2); assert.deepStrictEqual(decorations[0].range, new Range(1, 2, 1, 1)); assert.strictEqual(decorations[0].options.glyphMarginClassName, ThemeIcon.asClassName(debugStackframe)); assert.deepStrictEqual(decorations[1].range, new Range(1, Constants.MAX_SAFE_SMALL_INTEGER, 1, 1)); assert.strictEqual(decorations[1].options.className, 'debug-top-stack-frame-line'); assert.strictEqual(decorations[1].options.isWholeLine, true); decorations = createDecorationsForStackFrame(secondStackFrame, firstStackFrame.range, true); assert.strictEqual(decorations.length, 2); assert.deepStrictEqual(decorations[0].range, new Range(1, 2, 1, 1)); assert.strictEqual(decorations[0].options.glyphMarginClassName, ThemeIcon.asClassName(debugStackframeFocused)); assert.deepStrictEqual(decorations[1].range, new Range(1, Constants.MAX_SAFE_SMALL_INTEGER, 1, 1)); assert.strictEqual(decorations[1].options.className, 'debug-focused-stack-frame-line'); assert.strictEqual(decorations[1].options.isWholeLine, true); decorations = createDecorationsForStackFrame(firstStackFrame, new Range(1, 5, 1, 6), true); assert.strictEqual(decorations.length, 3); assert.deepStrictEqual(decorations[0].range, new Range(1, 2, 1, 1)); assert.strictEqual(decorations[0].options.glyphMarginClassName, ThemeIcon.asClassName(debugStackframe)); assert.deepStrictEqual(decorations[1].range, new Range(1, Constants.MAX_SAFE_SMALL_INTEGER, 1, 1)); assert.strictEqual(decorations[1].options.className, 'debug-top-stack-frame-line'); assert.strictEqual(decorations[1].options.isWholeLine, true); // Inline decoration gets rendered in this case assert.strictEqual(decorations[2].options.beforeContentClassName, 'debug-top-stack-frame-column'); assert.deepStrictEqual(decorations[2].range, new Range(1, Constants.MAX_SAFE_SMALL_INTEGER, 1, 1)); }); test('contexts', () => { const session = createMockSession(model); model.addSession(session); const { firstStackFrame, secondStackFrame } = createTwoStackFrames(session); let context = getContext(firstStackFrame); assert.strictEqual(context.sessionId, firstStackFrame.thread.session.getId()); assert.strictEqual(context.threadId, firstStackFrame.thread.getId()); assert.strictEqual(context.frameId, firstStackFrame.getId()); context = getContext(secondStackFrame.thread); assert.strictEqual(context.sessionId, secondStackFrame.thread.session.getId()); assert.strictEqual(context.threadId, secondStackFrame.thread.getId()); assert.strictEqual(context.frameId, undefined); context = getContext(session); assert.strictEqual(context.sessionId, session.getId()); assert.strictEqual(context.threadId, undefined); assert.strictEqual(context.frameId, undefined); let contributedContext = getContextForContributedActions(firstStackFrame); assert.strictEqual(contributedContext, firstStackFrame.source.raw.path); contributedContext = getContextForContributedActions(firstStackFrame.thread); assert.strictEqual(contributedContext, firstStackFrame.thread.threadId); contributedContext = getContextForContributedActions(session); assert.strictEqual(contributedContext, session.getId()); }); test('focusStackFrameThreadAndSesion', () => { const threadId1 = 1; const threadName1 = 'firstThread'; const threadId2 = 2; const threadName2 = 'secondThread'; const stoppedReason = 'breakpoint'; // Add the threads const session = new class extends DebugSession { get state(): State { return State.Stopped; } }(generateUuid(), { resolved: { name: 'stoppedSession', type: 'node', request: 'launch' }, unresolved: undefined }, undefined!, model, undefined, undefined!, undefined!, undefined!, undefined!, undefined!, mockWorkspaceContextService, undefined!, undefined!, NullOpenerService, undefined!, undefined!, mockUriIdentityService, undefined!); const runningSession = createMockSession(model); model.addSession(runningSession); model.addSession(session); session['raw'] = <any>rawSession; model.rawUpdate({ sessionId: session.getId(), threads: [{ id: threadId1, name: threadName1 }] }); // Stopped event with all threads stopped model.rawUpdate({ sessionId: session.getId(), threads: [{ id: threadId1, name: threadName1 }, { id: threadId2, name: threadName2 }], stoppedDetails: { reason: stoppedReason, threadId: 1, allThreadsStopped: true }, }); const thread = session.getThread(threadId1)!; const runningThread = session.getThread(threadId2); let toFocus = getStackFrameThreadAndSessionToFocus(model, undefined); // Verify stopped session and stopped thread get focused assert.deepStrictEqual(toFocus, { stackFrame: undefined, thread: thread, session: session }); toFocus = getStackFrameThreadAndSessionToFocus(model, undefined, undefined, runningSession); assert.deepStrictEqual(toFocus, { stackFrame: undefined, thread: undefined, session: runningSession }); toFocus = getStackFrameThreadAndSessionToFocus(model, undefined, thread); assert.deepStrictEqual(toFocus, { stackFrame: undefined, thread: thread, session: session }); toFocus = getStackFrameThreadAndSessionToFocus(model, undefined, runningThread); assert.deepStrictEqual(toFocus, { stackFrame: undefined, thread: runningThread, session: session }); const stackFrame = new StackFrame(thread, 5, undefined!, 'stackframename2', undefined, undefined!, 1, true); toFocus = getStackFrameThreadAndSessionToFocus(model, stackFrame); assert.deepStrictEqual(toFocus, { stackFrame: stackFrame, thread: thread, session: session }); }); });
src/vs/workbench/contrib/debug/test/browser/callStack.test.ts
1
https://github.com/microsoft/vscode/commit/f554a745505474ba031a79f5ab4a5c9d1ed3af39
[ 0.9989979863166809, 0.06869793683290482, 0.00016411941032856703, 0.00017115991795435548, 0.2514604330062866 ]
{ "id": 1, "code_window": [ "\tclassName: 'debug-focused-stack-frame-line',\n", "\tstickiness\n", "};\n", "\n", "export function createDecorationsForStackFrame(stackFrame: IStackFrame, topStackFrameRange: IRange | undefined, isFocusedSession: boolean): IModelDeltaDecoration[] {\n", "\t// only show decorations for the currently focused thread.\n", "\tconst result: IModelDeltaDecoration[] = [];\n", "\tconst columnUntilEOLRange = new Range(stackFrame.range.startLineNumber, stackFrame.range.startColumn, stackFrame.range.startLineNumber, Constants.MAX_SAFE_SMALL_INTEGER);\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "export function createDecorationsForStackFrame(stackFrame: IStackFrame, isFocusedSession: boolean): IModelDeltaDecoration[] {\n" ], "file_path": "src/vs/workbench/contrib/debug/browser/callStackEditorContribution.ts", "type": "replace", "edit_start_line_idx": 55 }
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <script> Polymer({ is: "chat-messages", properties: { user: {}, friend: { observer: "_friendChanged" } }, }); </script> </head> <body> </body> </html>
extensions/html-language-features/server/src/test/fixtures/inputs/19813.html
0
https://github.com/microsoft/vscode/commit/f554a745505474ba031a79f5ab4a5c9d1ed3af39
[ 0.0001703937741694972, 0.00017027216381393373, 0.0001701505680102855, 0.00017027216381393373, 1.216030796058476e-7 ]
{ "id": 1, "code_window": [ "\tclassName: 'debug-focused-stack-frame-line',\n", "\tstickiness\n", "};\n", "\n", "export function createDecorationsForStackFrame(stackFrame: IStackFrame, topStackFrameRange: IRange | undefined, isFocusedSession: boolean): IModelDeltaDecoration[] {\n", "\t// only show decorations for the currently focused thread.\n", "\tconst result: IModelDeltaDecoration[] = [];\n", "\tconst columnUntilEOLRange = new Range(stackFrame.range.startLineNumber, stackFrame.range.startColumn, stackFrame.range.startLineNumber, Constants.MAX_SAFE_SMALL_INTEGER);\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "export function createDecorationsForStackFrame(stackFrame: IStackFrame, isFocusedSession: boolean): IModelDeltaDecoration[] {\n" ], "file_path": "src/vs/workbench/contrib/debug/browser/callStackEditorContribution.ts", "type": "replace", "edit_start_line_idx": 55 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { basename } from 'vs/base/common/path'; import * as Json from 'vs/base/common/json'; import { Color } from 'vs/base/common/color'; import { ExtensionData, ITokenColorCustomizations, ITextMateThemingRule, IWorkbenchColorTheme, IColorMap, IThemeExtensionPoint, VS_LIGHT_THEME, VS_HC_THEME, IColorCustomizations, ISemanticTokenRules, ISemanticTokenColorizationSetting, ISemanticTokenColorCustomizations, IExperimentalSemanticTokenColorCustomizations } from 'vs/workbench/services/themes/common/workbenchThemeService'; import { convertSettings } from 'vs/workbench/services/themes/common/themeCompatibility'; import * as nls from 'vs/nls'; import * as types from 'vs/base/common/types'; import * as resources from 'vs/base/common/resources'; import { Extensions as ColorRegistryExtensions, IColorRegistry, ColorIdentifier, editorBackground, editorForeground } from 'vs/platform/theme/common/colorRegistry'; import { ITokenStyle, getThemeTypeSelector } from 'vs/platform/theme/common/themeService'; import { Registry } from 'vs/platform/registry/common/platform'; import { getParseErrorMessage } from 'vs/base/common/jsonErrorMessages'; import { URI } from 'vs/base/common/uri'; import { parse as parsePList } from 'vs/workbench/services/themes/common/plistParser'; import { TokenStyle, SemanticTokenRule, ProbeScope, getTokenClassificationRegistry, TokenStyleValue, TokenStyleData, parseClassifierString } from 'vs/platform/theme/common/tokenClassificationRegistry'; import { MatcherWithPriority, Matcher, createMatchers } from 'vs/workbench/services/themes/common/textMateScopeMatcher'; import { IExtensionResourceLoaderService } from 'vs/workbench/services/extensionResourceLoader/common/extensionResourceLoader'; import { CharCode } from 'vs/base/common/charCode'; import { StorageScope, IStorageService, StorageTarget } from 'vs/platform/storage/common/storage'; import { ThemeConfiguration } from 'vs/workbench/services/themes/common/themeConfiguration'; import { ColorScheme } from 'vs/platform/theme/common/theme'; let colorRegistry = Registry.as<IColorRegistry>(ColorRegistryExtensions.ColorContribution); let tokenClassificationRegistry = getTokenClassificationRegistry(); const tokenGroupToScopesMap = { comments: ['comment', 'punctuation.definition.comment'], strings: ['string', 'meta.embedded.assembly'], keywords: ['keyword - keyword.operator', 'keyword.control', 'storage', 'storage.type'], numbers: ['constant.numeric'], types: ['entity.name.type', 'entity.name.class', 'support.type', 'support.class'], functions: ['entity.name.function', 'support.function'], variables: ['variable', 'entity.name.variable'] }; export type TokenStyleDefinition = SemanticTokenRule | ProbeScope[] | TokenStyleValue; export type TokenStyleDefinitions = { [P in keyof TokenStyleData]?: TokenStyleDefinition | undefined }; export type TextMateThemingRuleDefinitions = { [P in keyof TokenStyleData]?: ITextMateThemingRule | undefined; } & { scope?: ProbeScope; }; export class ColorThemeData implements IWorkbenchColorTheme { static readonly STORAGE_KEY = 'colorThemeData'; id: string; label: string; settingsId: string; description?: string; isLoaded: boolean; location?: URI; // only set for extension from the registry, not for themes restored from the storage watch?: boolean; extensionData?: ExtensionData; private themeSemanticHighlighting: boolean | undefined; private customSemanticHighlighting: boolean | undefined; private customSemanticHighlightingDeprecated: boolean | undefined; private themeTokenColors: ITextMateThemingRule[] = []; private customTokenColors: ITextMateThemingRule[] = []; private colorMap: IColorMap = {}; private customColorMap: IColorMap = {}; private semanticTokenRules: SemanticTokenRule[] = []; private customSemanticTokenRules: SemanticTokenRule[] = []; private themeTokenScopeMatchers: Matcher<ProbeScope>[] | undefined; private customTokenScopeMatchers: Matcher<ProbeScope>[] | undefined; private textMateThemingRules: ITextMateThemingRule[] | undefined = undefined; // created on demand private tokenColorIndex: TokenColorIndex | undefined = undefined; // created on demand private constructor(id: string, label: string, settingsId: string) { this.id = id; this.label = label; this.settingsId = settingsId; this.isLoaded = false; } get semanticHighlighting(): boolean { if (this.customSemanticHighlighting !== undefined) { return this.customSemanticHighlighting; } if (this.customSemanticHighlightingDeprecated !== undefined) { return this.customSemanticHighlightingDeprecated; } return !!this.themeSemanticHighlighting; } get tokenColors(): ITextMateThemingRule[] { if (!this.textMateThemingRules) { const result: ITextMateThemingRule[] = []; // the default rule (scope empty) is always the first rule. Ignore all other default rules. const foreground = this.getColor(editorForeground) || this.getDefault(editorForeground)!; const background = this.getColor(editorBackground) || this.getDefault(editorBackground)!; result.push({ settings: { foreground: normalizeColor(foreground), background: normalizeColor(background) } }); let hasDefaultTokens = false; function addRule(rule: ITextMateThemingRule) { if (rule.scope && rule.settings) { if (rule.scope === 'token.info-token') { hasDefaultTokens = true; } result.push({ scope: rule.scope, settings: { foreground: normalizeColor(rule.settings.foreground), background: normalizeColor(rule.settings.background), fontStyle: rule.settings.fontStyle } }); } } this.themeTokenColors.forEach(addRule); // Add the custom colors after the theme colors // so that they will override them this.customTokenColors.forEach(addRule); if (!hasDefaultTokens) { defaultThemeColors[this.type].forEach(addRule); } this.textMateThemingRules = result; } return this.textMateThemingRules; } public getColor(colorId: ColorIdentifier, useDefault?: boolean): Color | undefined { let color: Color | undefined = this.customColorMap[colorId]; if (color) { return color; } color = this.colorMap[colorId]; if (useDefault !== false && types.isUndefined(color)) { color = this.getDefault(colorId); } return color; } private getTokenStyle(type: string, modifiers: string[], language: string, useDefault = true, definitions: TokenStyleDefinitions = {}): TokenStyle | undefined { let result: any = { foreground: undefined, bold: undefined, underline: undefined, italic: undefined }; let score = { foreground: -1, bold: -1, underline: -1, italic: -1 }; function _processStyle(matchScore: number, style: TokenStyle, definition: TokenStyleDefinition) { if (style.foreground && score.foreground <= matchScore) { score.foreground = matchScore; result.foreground = style.foreground; definitions.foreground = definition; } for (let p of ['bold', 'underline', 'italic']) { const property = p as keyof TokenStyle; const info = style[property]; if (info !== undefined) { if (score[property] <= matchScore) { score[property] = matchScore; result[property] = info; definitions[property] = definition; } } } } function _processSemanticTokenRule(rule: SemanticTokenRule) { const matchScore = rule.selector.match(type, modifiers, language); if (matchScore >= 0) { _processStyle(matchScore, rule.style, rule); } } this.semanticTokenRules.forEach(_processSemanticTokenRule); this.customSemanticTokenRules.forEach(_processSemanticTokenRule); let hasUndefinedStyleProperty = false; for (let k in score) { const key = k as keyof TokenStyle; if (score[key] === -1) { hasUndefinedStyleProperty = true; } else { score[key] = Number.MAX_VALUE; // set it to the max, so it won't be replaced by a default } } if (hasUndefinedStyleProperty) { for (const rule of tokenClassificationRegistry.getTokenStylingDefaultRules()) { const matchScore = rule.selector.match(type, modifiers, language); if (matchScore >= 0) { let style: TokenStyle | undefined; if (rule.defaults.scopesToProbe) { style = this.resolveScopes(rule.defaults.scopesToProbe); if (style) { _processStyle(matchScore, style, rule.defaults.scopesToProbe); } } if (!style && useDefault !== false) { const tokenStyleValue = rule.defaults[this.type]; style = this.resolveTokenStyleValue(tokenStyleValue); if (style) { _processStyle(matchScore, style, tokenStyleValue!); } } } } } return TokenStyle.fromData(result); } /** * @param tokenStyleValue Resolve a tokenStyleValue in the context of a theme */ public resolveTokenStyleValue(tokenStyleValue: TokenStyleValue | undefined): TokenStyle | undefined { if (tokenStyleValue === undefined) { return undefined; } else if (typeof tokenStyleValue === 'string') { const { type, modifiers, language } = parseClassifierString(tokenStyleValue, ''); return this.getTokenStyle(type, modifiers, language); } else if (typeof tokenStyleValue === 'object') { return tokenStyleValue; } return undefined; } private getTokenColorIndex(): TokenColorIndex { // collect all colors that tokens can have if (!this.tokenColorIndex) { const index = new TokenColorIndex(); this.tokenColors.forEach(rule => { index.add(rule.settings.foreground); index.add(rule.settings.background); }); this.semanticTokenRules.forEach(r => index.add(r.style.foreground)); tokenClassificationRegistry.getTokenStylingDefaultRules().forEach(r => { const defaultColor = r.defaults[this.type]; if (defaultColor && typeof defaultColor === 'object') { index.add(defaultColor.foreground); } }); this.customSemanticTokenRules.forEach(r => index.add(r.style.foreground)); this.tokenColorIndex = index; } return this.tokenColorIndex; } public get tokenColorMap(): string[] { return this.getTokenColorIndex().asArray(); } public getTokenStyleMetadata(typeWithLanguage: string, modifiers: string[], defaultLanguage: string, useDefault = true, definitions: TokenStyleDefinitions = {}): ITokenStyle | undefined { const { type, language } = parseClassifierString(typeWithLanguage, defaultLanguage); let style = this.getTokenStyle(type, modifiers, language, useDefault, definitions); if (!style) { return undefined; } return { foreground: this.getTokenColorIndex().get(style.foreground), bold: style.bold, underline: style.underline, italic: style.italic }; } public getTokenStylingRuleScope(rule: SemanticTokenRule): 'setting' | 'theme' | undefined { if (this.customSemanticTokenRules.indexOf(rule) !== -1) { return 'setting'; } if (this.semanticTokenRules.indexOf(rule) !== -1) { return 'theme'; } return undefined; } public getDefault(colorId: ColorIdentifier): Color | undefined { return colorRegistry.resolveDefaultColor(colorId, this); } public resolveScopes(scopes: ProbeScope[], definitions?: TextMateThemingRuleDefinitions): TokenStyle | undefined { if (!this.themeTokenScopeMatchers) { this.themeTokenScopeMatchers = this.themeTokenColors.map(getScopeMatcher); } if (!this.customTokenScopeMatchers) { this.customTokenScopeMatchers = this.customTokenColors.map(getScopeMatcher); } for (let scope of scopes) { let foreground: string | undefined = undefined; let fontStyle: string | undefined = undefined; let foregroundScore = -1; let fontStyleScore = -1; let fontStyleThemingRule: ITextMateThemingRule | undefined = undefined; let foregroundThemingRule: ITextMateThemingRule | undefined = undefined; function findTokenStyleForScopeInScopes(scopeMatchers: Matcher<ProbeScope>[], themingRules: ITextMateThemingRule[]) { for (let i = 0; i < scopeMatchers.length; i++) { const score = scopeMatchers[i](scope); if (score >= 0) { const themingRule = themingRules[i]; const settings = themingRules[i].settings; if (score >= foregroundScore && settings.foreground) { foreground = settings.foreground; foregroundScore = score; foregroundThemingRule = themingRule; } if (score >= fontStyleScore && types.isString(settings.fontStyle)) { fontStyle = settings.fontStyle; fontStyleScore = score; fontStyleThemingRule = themingRule; } } } } findTokenStyleForScopeInScopes(this.themeTokenScopeMatchers, this.themeTokenColors); findTokenStyleForScopeInScopes(this.customTokenScopeMatchers, this.customTokenColors); if (foreground !== undefined || fontStyle !== undefined) { if (definitions) { definitions.foreground = foregroundThemingRule; definitions.bold = definitions.italic = definitions.underline = fontStyleThemingRule; definitions.scope = scope; } return TokenStyle.fromSettings(foreground, fontStyle); } } return undefined; } public defines(colorId: ColorIdentifier): boolean { return this.customColorMap.hasOwnProperty(colorId) || this.colorMap.hasOwnProperty(colorId); } public setCustomizations(settings: ThemeConfiguration) { this.setCustomColors(settings.colorCustomizations); this.setCustomTokenColors(settings.tokenColorCustomizations); this.setCustomSemanticTokenColors(settings.semanticTokenColorCustomizations, settings.experimentalSemanticTokenColorCustomizations); } public setCustomColors(colors: IColorCustomizations) { this.customColorMap = {}; this.overwriteCustomColors(colors); const themeSpecificColors = colors[`[${this.settingsId}]`] as IColorCustomizations; if (types.isObject(themeSpecificColors)) { this.overwriteCustomColors(themeSpecificColors); } this.tokenColorIndex = undefined; this.textMateThemingRules = undefined; this.customTokenScopeMatchers = undefined; } private overwriteCustomColors(colors: IColorCustomizations) { for (let id in colors) { let colorVal = colors[id]; if (typeof colorVal === 'string') { this.customColorMap[id] = Color.fromHex(colorVal); } } } public setCustomTokenColors(customTokenColors: ITokenColorCustomizations) { this.customTokenColors = []; this.customSemanticHighlightingDeprecated = undefined; // first add the non-theme specific settings this.addCustomTokenColors(customTokenColors); // append theme specific settings. Last rules will win. const themeSpecificTokenColors = customTokenColors[`[${this.settingsId}]`] as ITokenColorCustomizations; if (types.isObject(themeSpecificTokenColors)) { this.addCustomTokenColors(themeSpecificTokenColors); } this.tokenColorIndex = undefined; this.textMateThemingRules = undefined; this.customTokenScopeMatchers = undefined; } public setCustomSemanticTokenColors(semanticTokenColors: ISemanticTokenColorCustomizations | undefined, experimental?: IExperimentalSemanticTokenColorCustomizations) { this.customSemanticTokenRules = []; this.customSemanticHighlighting = undefined; if (experimental) { // apply deprecated settings first this.readSemanticTokenRules(experimental); const themeSpecificColors = experimental[`[${this.settingsId}]`] as IExperimentalSemanticTokenColorCustomizations; if (types.isObject(themeSpecificColors)) { this.readSemanticTokenRules(themeSpecificColors); } } if (semanticTokenColors) { this.customSemanticHighlighting = semanticTokenColors.enabled; if (semanticTokenColors.rules) { this.readSemanticTokenRules(semanticTokenColors.rules); } const themeSpecificColors = semanticTokenColors[`[${this.settingsId}]`] as ISemanticTokenColorCustomizations; if (types.isObject(themeSpecificColors)) { if (themeSpecificColors.enabled !== undefined) { this.customSemanticHighlighting = themeSpecificColors.enabled; } if (themeSpecificColors.rules) { this.readSemanticTokenRules(themeSpecificColors.rules); } } } this.tokenColorIndex = undefined; this.textMateThemingRules = undefined; } private readSemanticTokenRules(tokenStylingRuleSection: ISemanticTokenRules) { for (let key in tokenStylingRuleSection) { if (key[0] !== '[') { // still do this test until experimental settings are gone try { const rule = readSemanticTokenRule(key, tokenStylingRuleSection[key]); if (rule) { this.customSemanticTokenRules.push(rule); } } catch (e) { // invalid selector, ignore } } } } private addCustomTokenColors(customTokenColors: ITokenColorCustomizations) { // Put the general customizations such as comments, strings, etc. first so that // they can be overridden by specific customizations like "string.interpolated" for (let tokenGroup in tokenGroupToScopesMap) { const group = <keyof typeof tokenGroupToScopesMap>tokenGroup; // TS doesn't type 'tokenGroup' properly let value = customTokenColors[group]; if (value) { let settings = typeof value === 'string' ? { foreground: value } : value; let scopes = tokenGroupToScopesMap[group]; for (let scope of scopes) { this.customTokenColors.push({ scope, settings }); } } } // specific customizations if (Array.isArray(customTokenColors.textMateRules)) { for (let rule of customTokenColors.textMateRules) { if (rule.scope && rule.settings) { this.customTokenColors.push(rule); } } } if (customTokenColors.semanticHighlighting !== undefined) { this.customSemanticHighlightingDeprecated = customTokenColors.semanticHighlighting; } } public ensureLoaded(extensionResourceLoaderService: IExtensionResourceLoaderService): Promise<void> { return !this.isLoaded ? this.load(extensionResourceLoaderService) : Promise.resolve(undefined); } public reload(extensionResourceLoaderService: IExtensionResourceLoaderService): Promise<void> { return this.load(extensionResourceLoaderService); } private load(extensionResourceLoaderService: IExtensionResourceLoaderService): Promise<void> { if (!this.location) { return Promise.resolve(undefined); } this.themeTokenColors = []; this.clearCaches(); const result = { colors: {}, textMateRules: [], semanticTokenRules: [], semanticHighlighting: false }; return _loadColorTheme(extensionResourceLoaderService, this.location, result).then(_ => { this.isLoaded = true; this.semanticTokenRules = result.semanticTokenRules; this.colorMap = result.colors; this.themeTokenColors = result.textMateRules; this.themeSemanticHighlighting = result.semanticHighlighting; }); } public clearCaches() { this.tokenColorIndex = undefined; this.textMateThemingRules = undefined; this.themeTokenScopeMatchers = undefined; this.customTokenScopeMatchers = undefined; } toStorage(storageService: IStorageService) { let colorMapData: { [key: string]: string } = {}; for (let key in this.colorMap) { colorMapData[key] = Color.Format.CSS.formatHexA(this.colorMap[key], true); } // no need to persist custom colors, they will be taken from the settings const value = JSON.stringify({ id: this.id, label: this.label, settingsId: this.settingsId, themeTokenColors: this.themeTokenColors.map(tc => ({ settings: tc.settings, scope: tc.scope })), // don't persist names semanticTokenRules: this.semanticTokenRules.map(SemanticTokenRule.toJSONObject), extensionData: ExtensionData.toJSONObject(this.extensionData), themeSemanticHighlighting: this.themeSemanticHighlighting, colorMap: colorMapData, watch: this.watch }); // roam persisted color theme colors. Don't enable for icons as they contain references to fonts and images. storageService.store(ColorThemeData.STORAGE_KEY, value, StorageScope.GLOBAL, StorageTarget.USER); } get baseTheme(): string { return this.classNames[0]; } get classNames(): string[] { return this.id.split(' '); } get type(): ColorScheme { switch (this.baseTheme) { case VS_LIGHT_THEME: return ColorScheme.LIGHT; case VS_HC_THEME: return ColorScheme.HIGH_CONTRAST; default: return ColorScheme.DARK; } } // constructors static createUnloadedThemeForThemeType(themeType: ColorScheme, colorMap?: { [id: string]: string }): ColorThemeData { return ColorThemeData.createUnloadedTheme(getThemeTypeSelector(themeType), colorMap); } static createUnloadedTheme(id: string, colorMap?: { [id: string]: string }): ColorThemeData { let themeData = new ColorThemeData(id, '', '__' + id); themeData.isLoaded = false; themeData.themeTokenColors = []; themeData.watch = false; if (colorMap) { for (let id in colorMap) { themeData.colorMap[id] = Color.fromHex(colorMap[id]); } } return themeData; } static createLoadedEmptyTheme(id: string, settingsId: string): ColorThemeData { let themeData = new ColorThemeData(id, '', settingsId); themeData.isLoaded = true; themeData.themeTokenColors = []; themeData.watch = false; return themeData; } static fromStorageData(storageService: IStorageService): ColorThemeData | undefined { const input = storageService.get(ColorThemeData.STORAGE_KEY, StorageScope.GLOBAL); if (!input) { return undefined; } try { let data = JSON.parse(input); let theme = new ColorThemeData('', '', ''); for (let key in data) { switch (key) { case 'colorMap': let colorMapData = data[key]; for (let id in colorMapData) { theme.colorMap[id] = Color.fromHex(colorMapData[id]); } break; case 'themeTokenColors': case 'id': case 'label': case 'settingsId': case 'watch': case 'themeSemanticHighlighting': (theme as any)[key] = data[key]; break; case 'semanticTokenRules': const rulesData = data[key]; if (Array.isArray(rulesData)) { for (let d of rulesData) { const rule = SemanticTokenRule.fromJSONObject(tokenClassificationRegistry, d); if (rule) { theme.semanticTokenRules.push(rule); } } } break; case 'location': // ignore, no longer restore break; case 'extensionData': theme.extensionData = ExtensionData.fromJSONObject(data.extensionData); break; } } if (!theme.id || !theme.settingsId) { return undefined; } return theme; } catch (e) { return undefined; } } static fromExtensionTheme(theme: IThemeExtensionPoint, colorThemeLocation: URI, extensionData: ExtensionData): ColorThemeData { const baseTheme: string = theme['uiTheme'] || 'vs-dark'; const themeSelector = toCSSSelector(extensionData.extensionId, theme.path); const id = `${baseTheme} ${themeSelector}`; const label = theme.label || basename(theme.path); const settingsId = theme.id || label; const themeData = new ColorThemeData(id, label, settingsId); themeData.description = theme.description; themeData.watch = theme._watch === true; themeData.location = colorThemeLocation; themeData.extensionData = extensionData; themeData.isLoaded = false; return themeData; } } function toCSSSelector(extensionId: string, path: string) { if (path.startsWith('./')) { path = path.substr(2); } let str = `${extensionId}-${path}`; //remove all characters that are not allowed in css str = str.replace(/[^_\-a-zA-Z0-9]/g, '-'); if (str.charAt(0).match(/[0-9\-]/)) { str = '_' + str; } return str; } async function _loadColorTheme(extensionResourceLoaderService: IExtensionResourceLoaderService, themeLocation: URI, result: { textMateRules: ITextMateThemingRule[], colors: IColorMap, semanticTokenRules: SemanticTokenRule[], semanticHighlighting: boolean }): Promise<any> { if (resources.extname(themeLocation) === '.json') { const content = await extensionResourceLoaderService.readExtensionResource(themeLocation); let errors: Json.ParseError[] = []; let contentValue = Json.parse(content, errors); if (errors.length > 0) { return Promise.reject(new Error(nls.localize('error.cannotparsejson', "Problems parsing JSON theme file: {0}", errors.map(e => getParseErrorMessage(e.error)).join(', ')))); } else if (Json.getNodeType(contentValue) !== 'object') { return Promise.reject(new Error(nls.localize('error.invalidformat', "Invalid format for JSON theme file: Object expected."))); } if (contentValue.include) { await _loadColorTheme(extensionResourceLoaderService, resources.joinPath(resources.dirname(themeLocation), contentValue.include), result); } if (Array.isArray(contentValue.settings)) { convertSettings(contentValue.settings, result); return null; } result.semanticHighlighting = result.semanticHighlighting || contentValue.semanticHighlighting; let colors = contentValue.colors; if (colors) { if (typeof colors !== 'object') { return Promise.reject(new Error(nls.localize({ key: 'error.invalidformat.colors', comment: ['{0} will be replaced by a path. Values in quotes should not be translated.'] }, "Problem parsing color theme file: {0}. Property 'colors' is not of type 'object'.", themeLocation.toString()))); } // new JSON color themes format for (let colorId in colors) { let colorHex = colors[colorId]; if (typeof colorHex === 'string') { // ignore colors tht are null result.colors[colorId] = Color.fromHex(colors[colorId]); } } } let tokenColors = contentValue.tokenColors; if (tokenColors) { if (Array.isArray(tokenColors)) { result.textMateRules.push(...tokenColors); } else if (typeof tokenColors === 'string') { await _loadSyntaxTokens(extensionResourceLoaderService, resources.joinPath(resources.dirname(themeLocation), tokenColors), result); } else { return Promise.reject(new Error(nls.localize({ key: 'error.invalidformat.tokenColors', comment: ['{0} will be replaced by a path. Values in quotes should not be translated.'] }, "Problem parsing color theme file: {0}. Property 'tokenColors' should be either an array specifying colors or a path to a TextMate theme file", themeLocation.toString()))); } } let semanticTokenColors = contentValue.semanticTokenColors; if (semanticTokenColors && typeof semanticTokenColors === 'object') { for (let key in semanticTokenColors) { try { const rule = readSemanticTokenRule(key, semanticTokenColors[key]); if (rule) { result.semanticTokenRules.push(rule); } } catch (e) { return Promise.reject(new Error(nls.localize({ key: 'error.invalidformat.semanticTokenColors', comment: ['{0} will be replaced by a path. Values in quotes should not be translated.'] }, "Problem parsing color theme file: {0}. Property 'semanticTokenColors' contains a invalid selector", themeLocation.toString()))); } } } } else { return _loadSyntaxTokens(extensionResourceLoaderService, themeLocation, result); } } function _loadSyntaxTokens(extensionResourceLoaderService: IExtensionResourceLoaderService, themeLocation: URI, result: { textMateRules: ITextMateThemingRule[], colors: IColorMap }): Promise<any> { return extensionResourceLoaderService.readExtensionResource(themeLocation).then(content => { try { let contentValue = parsePList(content); let settings: ITextMateThemingRule[] = contentValue.settings; if (!Array.isArray(settings)) { return Promise.reject(new Error(nls.localize('error.plist.invalidformat', "Problem parsing tmTheme file: {0}. 'settings' is not array."))); } convertSettings(settings, result); return Promise.resolve(null); } catch (e) { return Promise.reject(new Error(nls.localize('error.cannotparse', "Problems parsing tmTheme file: {0}", e.message))); } }, error => { return Promise.reject(new Error(nls.localize('error.cannotload', "Problems loading tmTheme file {0}: {1}", themeLocation.toString(), error.message))); }); } let defaultThemeColors: { [baseTheme: string]: ITextMateThemingRule[] } = { 'light': [ { scope: 'token.info-token', settings: { foreground: '#316bcd' } }, { scope: 'token.warn-token', settings: { foreground: '#cd9731' } }, { scope: 'token.error-token', settings: { foreground: '#cd3131' } }, { scope: 'token.debug-token', settings: { foreground: '#800080' } } ], 'dark': [ { scope: 'token.info-token', settings: { foreground: '#6796e6' } }, { scope: 'token.warn-token', settings: { foreground: '#cd9731' } }, { scope: 'token.error-token', settings: { foreground: '#f44747' } }, { scope: 'token.debug-token', settings: { foreground: '#b267e6' } } ], 'hc': [ { scope: 'token.info-token', settings: { foreground: '#6796e6' } }, { scope: 'token.warn-token', settings: { foreground: '#008000' } }, { scope: 'token.error-token', settings: { foreground: '#FF0000' } }, { scope: 'token.debug-token', settings: { foreground: '#b267e6' } } ], }; const noMatch = (_scope: ProbeScope) => -1; function nameMatcher(identifers: string[], scope: ProbeScope): number { function findInIdents(s: string, lastIndent: number): number { for (let i = lastIndent - 1; i >= 0; i--) { if (scopesAreMatching(s, identifers[i])) { return i; } } return -1; } if (scope.length < identifers.length) { return -1; } let lastScopeIndex = scope.length - 1; let lastIdentifierIndex = findInIdents(scope[lastScopeIndex--], identifers.length); if (lastIdentifierIndex >= 0) { const score = (lastIdentifierIndex + 1) * 0x10000 + identifers[lastIdentifierIndex].length; while (lastScopeIndex >= 0) { lastIdentifierIndex = findInIdents(scope[lastScopeIndex--], lastIdentifierIndex); if (lastIdentifierIndex === -1) { return -1; } } return score; } return -1; } function scopesAreMatching(thisScopeName: string, scopeName: string): boolean { if (!thisScopeName) { return false; } if (thisScopeName === scopeName) { return true; } const len = scopeName.length; return thisScopeName.length > len && thisScopeName.substr(0, len) === scopeName && thisScopeName[len] === '.'; } function getScopeMatcher(rule: ITextMateThemingRule): Matcher<ProbeScope> { const ruleScope = rule.scope; if (!ruleScope || !rule.settings) { return noMatch; } const matchers: MatcherWithPriority<ProbeScope>[] = []; if (Array.isArray(ruleScope)) { for (let rs of ruleScope) { createMatchers(rs, nameMatcher, matchers); } } else { createMatchers(ruleScope, nameMatcher, matchers); } if (matchers.length === 0) { return noMatch; } return (scope: ProbeScope) => { let max = matchers[0].matcher(scope); for (let i = 1; i < matchers.length; i++) { max = Math.max(max, matchers[i].matcher(scope)); } return max; }; } function readSemanticTokenRule(selectorString: string, settings: ISemanticTokenColorizationSetting | string | boolean | undefined): SemanticTokenRule | undefined { const selector = tokenClassificationRegistry.parseTokenSelector(selectorString); let style: TokenStyle | undefined; if (typeof settings === 'string') { style = TokenStyle.fromSettings(settings, undefined); } else if (isSemanticTokenColorizationSetting(settings)) { style = TokenStyle.fromSettings(settings.foreground, settings.fontStyle, settings.bold, settings.underline, settings.italic); } if (style) { return { selector, style }; } return undefined; } function isSemanticTokenColorizationSetting(style: any): style is ISemanticTokenColorizationSetting { return style && (types.isString(style.foreground) || types.isString(style.fontStyle) || types.isBoolean(style.italic) || types.isBoolean(style.underline) || types.isBoolean(style.bold)); } class TokenColorIndex { private _lastColorId: number; private _id2color: string[]; private _color2id: { [color: string]: number; }; constructor() { this._lastColorId = 0; this._id2color = []; this._color2id = Object.create(null); } public add(color: string | Color | undefined): number { color = normalizeColor(color); if (color === undefined) { return 0; } let value = this._color2id[color]; if (value) { return value; } value = ++this._lastColorId; this._color2id[color] = value; this._id2color[value] = color; return value; } public get(color: string | Color | undefined): number { color = normalizeColor(color); if (color === undefined) { return 0; } let value = this._color2id[color]; if (value) { return value; } console.log(`Color ${color} not in index.`); return 0; } public asArray(): string[] { return this._id2color.slice(0); } } function normalizeColor(color: string | Color | undefined | null): string | undefined { if (!color) { return undefined; } if (typeof color !== 'string') { color = Color.Format.CSS.formatHexA(color, true); } const len = color.length; if (color.charCodeAt(0) !== CharCode.Hash || (len !== 4 && len !== 5 && len !== 7 && len !== 9)) { return undefined; } let result = [CharCode.Hash]; for (let i = 1; i < len; i++) { const upper = hexUpper(color.charCodeAt(i)); if (!upper) { return undefined; } result.push(upper); if (len === 4 || len === 5) { result.push(upper); } } if (result.length === 9 && result[7] === CharCode.F && result[8] === CharCode.F) { result.length = 7; } return String.fromCharCode(...result); } function hexUpper(charCode: CharCode): number { if (charCode >= CharCode.Digit0 && charCode <= CharCode.Digit9 || charCode >= CharCode.A && charCode <= CharCode.F) { return charCode; } else if (charCode >= CharCode.a && charCode <= CharCode.f) { return charCode - CharCode.a + CharCode.A; } return 0; }
src/vs/workbench/services/themes/common/colorThemeData.ts
0
https://github.com/microsoft/vscode/commit/f554a745505474ba031a79f5ab4a5c9d1ed3af39
[ 0.0022702221758663654, 0.0001947814889717847, 0.00016464666987303644, 0.00017018869402818382, 0.00021722815290559083 ]
{ "id": 1, "code_window": [ "\tclassName: 'debug-focused-stack-frame-line',\n", "\tstickiness\n", "};\n", "\n", "export function createDecorationsForStackFrame(stackFrame: IStackFrame, topStackFrameRange: IRange | undefined, isFocusedSession: boolean): IModelDeltaDecoration[] {\n", "\t// only show decorations for the currently focused thread.\n", "\tconst result: IModelDeltaDecoration[] = [];\n", "\tconst columnUntilEOLRange = new Range(stackFrame.range.startLineNumber, stackFrame.range.startColumn, stackFrame.range.startLineNumber, Constants.MAX_SAFE_SMALL_INTEGER);\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "export function createDecorationsForStackFrame(stackFrame: IStackFrame, isFocusedSession: boolean): IModelDeltaDecoration[] {\n" ], "file_path": "src/vs/workbench/contrib/debug/browser/callStackEditorContribution.ts", "type": "replace", "edit_start_line_idx": 55 }
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>com.apple.security.cs.allow-jit</key> <true/> <key>com.apple.security.cs.allow-unsigned-executable-memory</key> <true/> <key>com.apple.security.cs.allow-dyld-environment-variables</key> <true/> </dict> </plist>
build/azure-pipelines/darwin/app-entitlements.plist
0
https://github.com/microsoft/vscode/commit/f554a745505474ba031a79f5ab4a5c9d1ed3af39
[ 0.00017342949286103249, 0.00017095849034376442, 0.0001684875023784116, 0.00017095849034376442, 0.0000024709952413104475 ]
{ "id": 2, "code_window": [ "\t\t\trange: columnUntilEOLRange\n", "\t\t});\n", "\n", "\t\tif (topStackFrameRange && topStackFrameRange.startLineNumber === stackFrame.range.startLineNumber && topStackFrameRange.startColumn !== stackFrame.range.startColumn) {\n", "\t\t\tresult.push({\n", "\t\t\t\toptions: TOP_STACK_FRAME_INLINE_DECORATION,\n", "\t\t\t\trange: columnUntilEOLRange\n", "\t\t\t});\n", "\t\t}\n", "\t\ttopStackFrameRange = columnUntilEOLRange;\n", "\t} else {\n", "\t\tif (isFocusedSession) {\n", "\t\t\tresult.push({\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\tresult.push({\n", "\t\t\toptions: TOP_STACK_FRAME_INLINE_DECORATION,\n", "\t\t\trange: columnUntilEOLRange\n", "\t\t});\n" ], "file_path": "src/vs/workbench/contrib/debug/browser/callStackEditorContribution.ts", "type": "replace", "edit_start_line_idx": 77 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as assert from 'assert'; import { DebugModel, StackFrame, Thread } from 'vs/workbench/contrib/debug/common/debugModel'; import * as sinon from 'sinon'; import { MockRawSession, createMockDebugModel, mockUriIdentityService } from 'vs/workbench/contrib/debug/test/browser/mockDebug'; import { Source } from 'vs/workbench/contrib/debug/common/debugSource'; import { DebugSession } from 'vs/workbench/contrib/debug/browser/debugSession'; import { Range } from 'vs/editor/common/core/range'; import { IDebugSessionOptions, State, IDebugService } from 'vs/workbench/contrib/debug/common/debug'; import { NullOpenerService } from 'vs/platform/opener/common/opener'; import { createDecorationsForStackFrame } from 'vs/workbench/contrib/debug/browser/callStackEditorContribution'; import { Constants } from 'vs/base/common/uint'; import { getContext, getContextForContributedActions, getSpecificSourceName } from 'vs/workbench/contrib/debug/browser/callStackView'; import { getStackFrameThreadAndSessionToFocus } from 'vs/workbench/contrib/debug/browser/debugService'; import { generateUuid } from 'vs/base/common/uuid'; import { debugStackframe, debugStackframeFocused } from 'vs/workbench/contrib/debug/browser/debugIcons'; import { ThemeIcon } from 'vs/platform/theme/common/themeService'; import { TestConfigurationService } from 'vs/platform/configuration/test/common/testConfigurationService'; const mockWorkspaceContextService = { getWorkspace: () => { return { folders: [] }; } } as any; export function createMockSession(model: DebugModel, name = 'mockSession', options?: IDebugSessionOptions): DebugSession { return new DebugSession(generateUuid(), { resolved: { name, type: 'node', request: 'launch' }, unresolved: undefined }, undefined!, model, options, { getViewModel(): any { return { updateViews(): void { // noop } }; } } as IDebugService, undefined!, undefined!, new TestConfigurationService({ debug: { console: { collapseIdenticalLines: true } } }), undefined!, mockWorkspaceContextService, undefined!, undefined!, NullOpenerService, undefined!, undefined!, mockUriIdentityService, undefined!); } function createTwoStackFrames(session: DebugSession): { firstStackFrame: StackFrame, secondStackFrame: StackFrame } { let firstStackFrame: StackFrame; let secondStackFrame: StackFrame; const thread = new class extends Thread { public getCallStack(): StackFrame[] { return [firstStackFrame, secondStackFrame]; } }(session, 'mockthread', 1); const firstSource = new Source({ name: 'internalModule.js', path: 'a/b/c/d/internalModule.js', sourceReference: 10, }, 'aDebugSessionId', mockUriIdentityService); const secondSource = new Source({ name: 'internalModule.js', path: 'z/x/c/d/internalModule.js', sourceReference: 11, }, 'aDebugSessionId', mockUriIdentityService); firstStackFrame = new StackFrame(thread, 0, firstSource, 'app.js', 'normal', { startLineNumber: 1, startColumn: 1, endLineNumber: 1, endColumn: 10 }, 0, true); secondStackFrame = new StackFrame(thread, 1, secondSource, 'app2.js', 'normal', { startLineNumber: 1, startColumn: 1, endLineNumber: 1, endColumn: 10 }, 1, true); return { firstStackFrame, secondStackFrame }; } suite('Debug - CallStack', () => { let model: DebugModel; let rawSession: MockRawSession; setup(() => { model = createMockDebugModel(); rawSession = new MockRawSession(); }); // Threads test('threads simple', () => { const threadId = 1; const threadName = 'firstThread'; const session = createMockSession(model); model.addSession(session); assert.strictEqual(model.getSessions(true).length, 1); model.rawUpdate({ sessionId: session.getId(), threads: [{ id: threadId, name: threadName }] }); assert.strictEqual(session.getThread(threadId)!.name, threadName); model.clearThreads(session.getId(), true); assert.strictEqual(session.getThread(threadId), undefined); assert.strictEqual(model.getSessions(true).length, 1); }); test('threads multiple wtih allThreadsStopped', async () => { const threadId1 = 1; const threadName1 = 'firstThread'; const threadId2 = 2; const threadName2 = 'secondThread'; const stoppedReason = 'breakpoint'; // Add the threads const session = createMockSession(model); model.addSession(session); session['raw'] = <any>rawSession; model.rawUpdate({ sessionId: session.getId(), threads: [{ id: threadId1, name: threadName1 }] }); // Stopped event with all threads stopped model.rawUpdate({ sessionId: session.getId(), threads: [{ id: threadId1, name: threadName1 }, { id: threadId2, name: threadName2 }], stoppedDetails: { reason: stoppedReason, threadId: 1, allThreadsStopped: true }, }); const thread1 = session.getThread(threadId1)!; const thread2 = session.getThread(threadId2)!; // at the beginning, callstacks are obtainable but not available assert.strictEqual(session.getAllThreads().length, 2); assert.strictEqual(thread1.name, threadName1); assert.strictEqual(thread1.stopped, true); assert.strictEqual(thread1.getCallStack().length, 0); assert.strictEqual(thread1.stoppedDetails!.reason, stoppedReason); assert.strictEqual(thread2.name, threadName2); assert.strictEqual(thread2.stopped, true); assert.strictEqual(thread2.getCallStack().length, 0); assert.strictEqual(thread2.stoppedDetails!.reason, undefined); // after calling getCallStack, the callstack becomes available // and results in a request for the callstack in the debug adapter await thread1.fetchCallStack(); assert.notStrictEqual(thread1.getCallStack().length, 0); await thread2.fetchCallStack(); assert.notStrictEqual(thread2.getCallStack().length, 0); // calling multiple times getCallStack doesn't result in multiple calls // to the debug adapter await thread1.fetchCallStack(); await thread2.fetchCallStack(); // clearing the callstack results in the callstack not being available thread1.clearCallStack(); assert.strictEqual(thread1.stopped, true); assert.strictEqual(thread1.getCallStack().length, 0); thread2.clearCallStack(); assert.strictEqual(thread2.stopped, true); assert.strictEqual(thread2.getCallStack().length, 0); model.clearThreads(session.getId(), true); assert.strictEqual(session.getThread(threadId1), undefined); assert.strictEqual(session.getThread(threadId2), undefined); assert.strictEqual(session.getAllThreads().length, 0); }); test('threads mutltiple without allThreadsStopped', async () => { const sessionStub = sinon.spy(rawSession, 'stackTrace'); const stoppedThreadId = 1; const stoppedThreadName = 'stoppedThread'; const runningThreadId = 2; const runningThreadName = 'runningThread'; const stoppedReason = 'breakpoint'; const session = createMockSession(model); model.addSession(session); session['raw'] = <any>rawSession; // Add the threads model.rawUpdate({ sessionId: session.getId(), threads: [{ id: stoppedThreadId, name: stoppedThreadName }] }); // Stopped event with only one thread stopped model.rawUpdate({ sessionId: session.getId(), threads: [{ id: 1, name: stoppedThreadName }, { id: runningThreadId, name: runningThreadName }], stoppedDetails: { reason: stoppedReason, threadId: 1, allThreadsStopped: false } }); const stoppedThread = session.getThread(stoppedThreadId)!; const runningThread = session.getThread(runningThreadId)!; // the callstack for the stopped thread is obtainable but not available // the callstack for the running thread is not obtainable nor available assert.strictEqual(stoppedThread.name, stoppedThreadName); assert.strictEqual(stoppedThread.stopped, true); assert.strictEqual(session.getAllThreads().length, 2); assert.strictEqual(stoppedThread.getCallStack().length, 0); assert.strictEqual(stoppedThread.stoppedDetails!.reason, stoppedReason); assert.strictEqual(runningThread.name, runningThreadName); assert.strictEqual(runningThread.stopped, false); assert.strictEqual(runningThread.getCallStack().length, 0); assert.strictEqual(runningThread.stoppedDetails, undefined); // after calling getCallStack, the callstack becomes available // and results in a request for the callstack in the debug adapter await stoppedThread.fetchCallStack(); assert.notStrictEqual(stoppedThread.getCallStack().length, 0); assert.strictEqual(runningThread.getCallStack().length, 0); assert.strictEqual(sessionStub.callCount, 1); // calling getCallStack on the running thread returns empty array // and does not return in a request for the callstack in the debug // adapter await runningThread.fetchCallStack(); assert.strictEqual(runningThread.getCallStack().length, 0); assert.strictEqual(sessionStub.callCount, 1); // clearing the callstack results in the callstack not being available stoppedThread.clearCallStack(); assert.strictEqual(stoppedThread.stopped, true); assert.strictEqual(stoppedThread.getCallStack().length, 0); model.clearThreads(session.getId(), true); assert.strictEqual(session.getThread(stoppedThreadId), undefined); assert.strictEqual(session.getThread(runningThreadId), undefined); assert.strictEqual(session.getAllThreads().length, 0); }); test('stack frame get specific source name', () => { const session = createMockSession(model); model.addSession(session); const { firstStackFrame, secondStackFrame } = createTwoStackFrames(session); assert.strictEqual(getSpecificSourceName(firstStackFrame), '.../b/c/d/internalModule.js'); assert.strictEqual(getSpecificSourceName(secondStackFrame), '.../x/c/d/internalModule.js'); }); test('stack frame toString()', () => { const session = createMockSession(model); const thread = new Thread(session, 'mockthread', 1); const firstSource = new Source({ name: 'internalModule.js', path: 'a/b/c/d/internalModule.js', sourceReference: 10, }, 'aDebugSessionId', mockUriIdentityService); const stackFrame = new StackFrame(thread, 1, firstSource, 'app', 'normal', { startLineNumber: 1, startColumn: 1, endLineNumber: 1, endColumn: 10 }, 1, true); assert.strictEqual(stackFrame.toString(), 'app (internalModule.js:1)'); const secondSource = new Source(undefined, 'aDebugSessionId', mockUriIdentityService); const stackFrame2 = new StackFrame(thread, 2, secondSource, 'module', 'normal', { startLineNumber: undefined!, startColumn: undefined!, endLineNumber: undefined!, endColumn: undefined! }, 2, true); assert.strictEqual(stackFrame2.toString(), 'module'); }); test('debug child sessions are added in correct order', () => { const session = createMockSession(model); model.addSession(session); const secondSession = createMockSession(model, 'mockSession2'); model.addSession(secondSession); const firstChild = createMockSession(model, 'firstChild', { parentSession: session }); model.addSession(firstChild); const secondChild = createMockSession(model, 'secondChild', { parentSession: session }); model.addSession(secondChild); const thirdSession = createMockSession(model, 'mockSession3'); model.addSession(thirdSession); const anotherChild = createMockSession(model, 'secondChild', { parentSession: secondSession }); model.addSession(anotherChild); const sessions = model.getSessions(); assert.strictEqual(sessions[0].getId(), session.getId()); assert.strictEqual(sessions[1].getId(), firstChild.getId()); assert.strictEqual(sessions[2].getId(), secondChild.getId()); assert.strictEqual(sessions[3].getId(), secondSession.getId()); assert.strictEqual(sessions[4].getId(), anotherChild.getId()); assert.strictEqual(sessions[5].getId(), thirdSession.getId()); }); test('decorations', () => { const session = createMockSession(model); model.addSession(session); const { firstStackFrame, secondStackFrame } = createTwoStackFrames(session); let decorations = createDecorationsForStackFrame(firstStackFrame, firstStackFrame.range, true); assert.strictEqual(decorations.length, 2); assert.deepStrictEqual(decorations[0].range, new Range(1, 2, 1, 1)); assert.strictEqual(decorations[0].options.glyphMarginClassName, ThemeIcon.asClassName(debugStackframe)); assert.deepStrictEqual(decorations[1].range, new Range(1, Constants.MAX_SAFE_SMALL_INTEGER, 1, 1)); assert.strictEqual(decorations[1].options.className, 'debug-top-stack-frame-line'); assert.strictEqual(decorations[1].options.isWholeLine, true); decorations = createDecorationsForStackFrame(secondStackFrame, firstStackFrame.range, true); assert.strictEqual(decorations.length, 2); assert.deepStrictEqual(decorations[0].range, new Range(1, 2, 1, 1)); assert.strictEqual(decorations[0].options.glyphMarginClassName, ThemeIcon.asClassName(debugStackframeFocused)); assert.deepStrictEqual(decorations[1].range, new Range(1, Constants.MAX_SAFE_SMALL_INTEGER, 1, 1)); assert.strictEqual(decorations[1].options.className, 'debug-focused-stack-frame-line'); assert.strictEqual(decorations[1].options.isWholeLine, true); decorations = createDecorationsForStackFrame(firstStackFrame, new Range(1, 5, 1, 6), true); assert.strictEqual(decorations.length, 3); assert.deepStrictEqual(decorations[0].range, new Range(1, 2, 1, 1)); assert.strictEqual(decorations[0].options.glyphMarginClassName, ThemeIcon.asClassName(debugStackframe)); assert.deepStrictEqual(decorations[1].range, new Range(1, Constants.MAX_SAFE_SMALL_INTEGER, 1, 1)); assert.strictEqual(decorations[1].options.className, 'debug-top-stack-frame-line'); assert.strictEqual(decorations[1].options.isWholeLine, true); // Inline decoration gets rendered in this case assert.strictEqual(decorations[2].options.beforeContentClassName, 'debug-top-stack-frame-column'); assert.deepStrictEqual(decorations[2].range, new Range(1, Constants.MAX_SAFE_SMALL_INTEGER, 1, 1)); }); test('contexts', () => { const session = createMockSession(model); model.addSession(session); const { firstStackFrame, secondStackFrame } = createTwoStackFrames(session); let context = getContext(firstStackFrame); assert.strictEqual(context.sessionId, firstStackFrame.thread.session.getId()); assert.strictEqual(context.threadId, firstStackFrame.thread.getId()); assert.strictEqual(context.frameId, firstStackFrame.getId()); context = getContext(secondStackFrame.thread); assert.strictEqual(context.sessionId, secondStackFrame.thread.session.getId()); assert.strictEqual(context.threadId, secondStackFrame.thread.getId()); assert.strictEqual(context.frameId, undefined); context = getContext(session); assert.strictEqual(context.sessionId, session.getId()); assert.strictEqual(context.threadId, undefined); assert.strictEqual(context.frameId, undefined); let contributedContext = getContextForContributedActions(firstStackFrame); assert.strictEqual(contributedContext, firstStackFrame.source.raw.path); contributedContext = getContextForContributedActions(firstStackFrame.thread); assert.strictEqual(contributedContext, firstStackFrame.thread.threadId); contributedContext = getContextForContributedActions(session); assert.strictEqual(contributedContext, session.getId()); }); test('focusStackFrameThreadAndSesion', () => { const threadId1 = 1; const threadName1 = 'firstThread'; const threadId2 = 2; const threadName2 = 'secondThread'; const stoppedReason = 'breakpoint'; // Add the threads const session = new class extends DebugSession { get state(): State { return State.Stopped; } }(generateUuid(), { resolved: { name: 'stoppedSession', type: 'node', request: 'launch' }, unresolved: undefined }, undefined!, model, undefined, undefined!, undefined!, undefined!, undefined!, undefined!, mockWorkspaceContextService, undefined!, undefined!, NullOpenerService, undefined!, undefined!, mockUriIdentityService, undefined!); const runningSession = createMockSession(model); model.addSession(runningSession); model.addSession(session); session['raw'] = <any>rawSession; model.rawUpdate({ sessionId: session.getId(), threads: [{ id: threadId1, name: threadName1 }] }); // Stopped event with all threads stopped model.rawUpdate({ sessionId: session.getId(), threads: [{ id: threadId1, name: threadName1 }, { id: threadId2, name: threadName2 }], stoppedDetails: { reason: stoppedReason, threadId: 1, allThreadsStopped: true }, }); const thread = session.getThread(threadId1)!; const runningThread = session.getThread(threadId2); let toFocus = getStackFrameThreadAndSessionToFocus(model, undefined); // Verify stopped session and stopped thread get focused assert.deepStrictEqual(toFocus, { stackFrame: undefined, thread: thread, session: session }); toFocus = getStackFrameThreadAndSessionToFocus(model, undefined, undefined, runningSession); assert.deepStrictEqual(toFocus, { stackFrame: undefined, thread: undefined, session: runningSession }); toFocus = getStackFrameThreadAndSessionToFocus(model, undefined, thread); assert.deepStrictEqual(toFocus, { stackFrame: undefined, thread: thread, session: session }); toFocus = getStackFrameThreadAndSessionToFocus(model, undefined, runningThread); assert.deepStrictEqual(toFocus, { stackFrame: undefined, thread: runningThread, session: session }); const stackFrame = new StackFrame(thread, 5, undefined!, 'stackframename2', undefined, undefined!, 1, true); toFocus = getStackFrameThreadAndSessionToFocus(model, stackFrame); assert.deepStrictEqual(toFocus, { stackFrame: stackFrame, thread: thread, session: session }); }); });
src/vs/workbench/contrib/debug/test/browser/callStack.test.ts
1
https://github.com/microsoft/vscode/commit/f554a745505474ba031a79f5ab4a5c9d1ed3af39
[ 0.0019202224211767316, 0.0002443896373733878, 0.0001629683974897489, 0.00017082426347769797, 0.0003300615062471479 ]
{ "id": 2, "code_window": [ "\t\t\trange: columnUntilEOLRange\n", "\t\t});\n", "\n", "\t\tif (topStackFrameRange && topStackFrameRange.startLineNumber === stackFrame.range.startLineNumber && topStackFrameRange.startColumn !== stackFrame.range.startColumn) {\n", "\t\t\tresult.push({\n", "\t\t\t\toptions: TOP_STACK_FRAME_INLINE_DECORATION,\n", "\t\t\t\trange: columnUntilEOLRange\n", "\t\t\t});\n", "\t\t}\n", "\t\ttopStackFrameRange = columnUntilEOLRange;\n", "\t} else {\n", "\t\tif (isFocusedSession) {\n", "\t\t\tresult.push({\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\tresult.push({\n", "\t\t\toptions: TOP_STACK_FRAME_INLINE_DECORATION,\n", "\t\t\trange: columnUntilEOLRange\n", "\t\t});\n" ], "file_path": "src/vs/workbench/contrib/debug/browser/callStackEditorContribution.ts", "type": "replace", "edit_start_line_idx": 77 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as assert from 'assert'; import { IMatch } from 'vs/base/common/filters'; import { matchesFuzzyIconAware, parseLabelWithIcons, IParsedLabelWithIcons, stripIcons, escapeIcons, markdownEscapeEscapedIcons } from 'vs/base/common/iconLabels'; export interface IIconFilter { // Returns null if word doesn't match. (query: string, target: IParsedLabelWithIcons): IMatch[] | null; } function filterOk(filter: IIconFilter, word: string, target: IParsedLabelWithIcons, highlights?: { start: number; end: number; }[]) { let r = filter(word, target); assert(r); if (highlights) { assert.deepEqual(r, highlights); } } suite('Icon Labels', () => { test('matchesFuzzyIconAware', () => { // Camel Case filterOk(matchesFuzzyIconAware, 'ccr', parseLabelWithIcons('$(codicon)CamelCaseRocks$(codicon)'), [ { start: 10, end: 11 }, { start: 15, end: 16 }, { start: 19, end: 20 } ]); filterOk(matchesFuzzyIconAware, 'ccr', parseLabelWithIcons('$(codicon) CamelCaseRocks $(codicon)'), [ { start: 11, end: 12 }, { start: 16, end: 17 }, { start: 20, end: 21 } ]); filterOk(matchesFuzzyIconAware, 'iut', parseLabelWithIcons('$(codicon) Indent $(octico) Using $(octic) Tpaces'), [ { start: 11, end: 12 }, { start: 28, end: 29 }, { start: 43, end: 44 }, ]); // Prefix filterOk(matchesFuzzyIconAware, 'using', parseLabelWithIcons('$(codicon) Indent Using Spaces'), [ { start: 18, end: 23 }, ]); // Broken Codicon filterOk(matchesFuzzyIconAware, 'codicon', parseLabelWithIcons('This $(codicon Indent Using Spaces'), [ { start: 7, end: 14 }, ]); filterOk(matchesFuzzyIconAware, 'indent', parseLabelWithIcons('This $codicon Indent Using Spaces'), [ { start: 14, end: 20 }, ]); // Testing #59343 filterOk(matchesFuzzyIconAware, 'unt', parseLabelWithIcons('$(primitive-dot) $(file-text) Untitled-1'), [ { start: 30, end: 33 }, ]); }); test('stripIcons', () => { assert.strictEqual(stripIcons('Hello World'), 'Hello World'); assert.strictEqual(stripIcons('$(Hello World'), '$(Hello World'); assert.strictEqual(stripIcons('$(Hello) World'), ' World'); assert.strictEqual(stripIcons('$(Hello) W$(oi)rld'), ' Wrld'); }); test('escapeIcons', () => { assert.strictEqual(escapeIcons('Hello World'), 'Hello World'); assert.strictEqual(escapeIcons('$(Hello World'), '$(Hello World'); assert.strictEqual(escapeIcons('$(Hello) World'), '\\$(Hello) World'); assert.strictEqual(escapeIcons('\\$(Hello) W$(oi)rld'), '\\$(Hello) W\\$(oi)rld'); }); test('markdownEscapeEscapedIcons', () => { assert.strictEqual(markdownEscapeEscapedIcons('Hello World'), 'Hello World'); assert.strictEqual(markdownEscapeEscapedIcons('$(Hello) World'), '$(Hello) World'); assert.strictEqual(markdownEscapeEscapedIcons('\\$(Hello) World'), '\\\\$(Hello) World'); }); });
src/vs/base/test/common/iconLabels.test.ts
0
https://github.com/microsoft/vscode/commit/f554a745505474ba031a79f5ab4a5c9d1ed3af39
[ 0.00017440575174987316, 0.00017269507225137204, 0.00017045423737727106, 0.00017285678768530488, 0.0000013902036926083383 ]