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": 3, "code_window": [ "\t\t\tif err != nil {\n", "\t\t\t\tlogger.Error(\"Unable to get labelsHash\", \"error\", err.Error(), s.AlertRuleUID)\n", "\t\t\t}\n", "\n" ], "labels": [ "keep", "replace", "keep", "keep" ], "after_edit": [ "\t\t\t\tlogger.Error(\"Unable to get alert instance key to delete it from database. Ignoring\", \"error\", err.Error())\n", "\t\t\t} else {\n", "\t\t\t\ttoDelete = append(toDelete, key)\n" ], "file_path": "pkg/services/ngalert/state/manager.go", "type": "replace", "edit_start_line_idx": 357 }
--- aliases: - /docs/grafana/latest/alerting/pause-an-alert-rule/ - /docs/grafana/latest/old-alerting/pause-an-alert-rule/ description: Pause an existing alert rule draft: true keywords: - grafana - alerting - guide - rules - view title: Pause alert rule weight: 400 --- # Pause an alert rule Pausing the evaluation of an alert rule can sometimes be useful. For example, during a maintenance window, pausing alert rules can avoid triggering a flood of alerts. 1. In the Grafana side bar, hover your cursor over the Alerting (bell) icon and then click **Alert Rules**. All configured alert rules are listed, along with their current state. 1. Find your alert in the list, and click the **Pause** icon on the right. The **Pause** icon turns into a **Play** icon. 1. Click the **Play** icon to resume evaluation of your alert.
docs/sources/old-alerting/pause-an-alert-rule.md
0
https://github.com/grafana/grafana/commit/623de12e354c8f92fd49802a04bafe5970fba0e9
[ 0.00023222692834679037, 0.0001998837833525613, 0.00016597150533925742, 0.00020145296002738178, 0.000027071411750512198 ]
{ "id": 3, "code_window": [ "\t\t\tif err != nil {\n", "\t\t\t\tlogger.Error(\"Unable to get labelsHash\", \"error\", err.Error(), s.AlertRuleUID)\n", "\t\t\t}\n", "\n" ], "labels": [ "keep", "replace", "keep", "keep" ], "after_edit": [ "\t\t\t\tlogger.Error(\"Unable to get alert instance key to delete it from database. Ignoring\", \"error\", err.Error())\n", "\t\t\t} else {\n", "\t\t\t\ttoDelete = append(toDelete, key)\n" ], "file_path": "pkg/services/ngalert/state/manager.go", "type": "replace", "edit_start_line_idx": 357 }
package querylibrary_tests import ( "fmt" "testing" apikeygenprefix "github.com/grafana/grafana/pkg/components/apikeygenprefixed" "github.com/grafana/grafana/pkg/server" "github.com/grafana/grafana/pkg/services/featuremgmt" "github.com/grafana/grafana/pkg/services/org" saAPI "github.com/grafana/grafana/pkg/services/serviceaccounts/api" saTests "github.com/grafana/grafana/pkg/services/serviceaccounts/tests" "github.com/grafana/grafana/pkg/services/user" "github.com/grafana/grafana/pkg/tests/testinfra" "github.com/stretchr/testify/require" ) func createServiceAccountAdminToken(t *testing.T, name string, env *server.TestEnv) (string, *user.SignedInUser) { t.Helper() account := saTests.SetupUserServiceAccount(t, env.SQLStore, saTests.TestUser{ Name: name, Role: string(org.RoleAdmin), Login: name, IsServiceAccount: true, OrgID: 1, }) keyGen, err := apikeygenprefix.New(saAPI.ServiceID) require.NoError(t, err) _ = saTests.SetupApiKey(t, env.SQLStore, saTests.TestApiKey{ Name: name, Role: org.RoleAdmin, OrgId: account.OrgID, Key: keyGen.HashedKey, ServiceAccountID: &account.ID, }) return keyGen.ClientSecret, &user.SignedInUser{ UserID: account.ID, Email: account.Email, Name: account.Name, Login: account.Login, OrgID: account.OrgID, IsServiceAccount: true, } } type testContext struct { authToken string client *queryLibraryAPIClient user *user.SignedInUser } func createTestContext(t *testing.T) testContext { t.Helper() dir, path := testinfra.CreateGrafDir(t, testinfra.GrafanaOpts{ EnableFeatureToggles: []string{featuremgmt.FlagPanelTitleSearch, featuremgmt.FlagQueryLibrary}, QueryRetries: 3, }) grafanaListedAddr, env := testinfra.StartGrafanaEnv(t, dir, path) authToken, serviceAccountUser := createServiceAccountAdminToken(t, "query-library", env) client := newQueryLibraryAPIClient(authToken, fmt.Sprintf("http://%s/api", grafanaListedAddr), serviceAccountUser, env.SQLStore) return testContext{ authToken: authToken, client: client, user: serviceAccountUser, } }
pkg/services/querylibrary/tests/common.go
0
https://github.com/grafana/grafana/commit/623de12e354c8f92fd49802a04bafe5970fba0e9
[ 0.00017091351037379354, 0.0001690490753389895, 0.00016599982336629182, 0.00016984187823254615, 0.000001730441113068082 ]
{ "id": 4, "code_window": [ "\t\t\t}\n", "\n", "\t\t\ttoDelete = append(toDelete, ngModels.AlertInstanceKey{RuleOrgID: s.OrgID, RuleUID: s.AlertRuleUID, LabelsHash: labelsHash})\n", "\n", "\t\t\tif s.State == eval.Alerting {\n", "\t\t\t\toldState := s.State\n", "\t\t\t\toldReason := s.StateReason\n", "\n" ], "labels": [ "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "pkg/services/ngalert/state/manager.go", "type": "replace", "edit_start_line_idx": 360 }
package state import ( "context" "net/url" "time" "github.com/benbjohnson/clock" "github.com/grafana/grafana-plugin-sdk-go/data" "github.com/grafana/grafana/pkg/infra/log" "github.com/grafana/grafana/pkg/services/ngalert/eval" "github.com/grafana/grafana/pkg/services/ngalert/image" "github.com/grafana/grafana/pkg/services/ngalert/metrics" ngModels "github.com/grafana/grafana/pkg/services/ngalert/models" ) var ( ResendDelay = 30 * time.Second MetricsScrapeInterval = 15 * time.Second // TODO: parameterize? // Setting to a reasonable default scrape interval for Prometheus. ) // AlertInstanceManager defines the interface for querying the current alert instances. type AlertInstanceManager interface { GetAll(orgID int64) []*State GetStatesForRuleUID(orgID int64, alertRuleUID string) []*State } type Manager struct { log log.Logger metrics *metrics.State clock clock.Clock cache *cache ResendDelay time.Duration instanceStore InstanceStore imageService image.ImageService historian Historian externalURL *url.URL } func NewManager(metrics *metrics.State, externalURL *url.URL, instanceStore InstanceStore, imageService image.ImageService, clock clock.Clock, historian Historian) *Manager { return &Manager{ cache: newCache(), ResendDelay: ResendDelay, // TODO: make this configurable log: log.New("ngalert.state.manager"), metrics: metrics, instanceStore: instanceStore, imageService: imageService, historian: historian, clock: clock, externalURL: externalURL, } } func (st *Manager) Run(ctx context.Context) error { ticker := st.clock.Ticker(MetricsScrapeInterval) for { select { case <-ticker.C: st.log.Debug("Recording state cache metrics", "now", st.clock.Now()) st.cache.recordMetrics(st.metrics) case <-ctx.Done(): st.log.Debug("Stopping") ticker.Stop() return ctx.Err() } } } func (st *Manager) Warm(ctx context.Context, rulesReader RuleReader) { if st.instanceStore == nil { st.log.Info("Skip warming the state because instance store is not configured") return } startTime := time.Now() st.log.Info("Warming state cache for startup") orgIds, err := st.instanceStore.FetchOrgIds(ctx) if err != nil { st.log.Error("Unable to fetch orgIds", "error", err) } statesCount := 0 states := make(map[int64]map[string]*ruleStates, len(orgIds)) for _, orgId := range orgIds { // Get Rules ruleCmd := ngModels.ListAlertRulesQuery{ OrgID: orgId, } if err := rulesReader.ListAlertRules(ctx, &ruleCmd); err != nil { st.log.Error("Unable to fetch previous state", "error", err) } ruleByUID := make(map[string]*ngModels.AlertRule, len(ruleCmd.Result)) for _, rule := range ruleCmd.Result { ruleByUID[rule.UID] = rule } orgStates := make(map[string]*ruleStates, len(ruleByUID)) states[orgId] = orgStates // Get Instances cmd := ngModels.ListAlertInstancesQuery{ RuleOrgID: orgId, } if err := st.instanceStore.ListAlertInstances(ctx, &cmd); err != nil { st.log.Error("Unable to fetch previous state", "error", err) } for _, entry := range cmd.Result { ruleForEntry, ok := ruleByUID[entry.RuleUID] if !ok { // TODO Should we delete the orphaned state from the db? continue } rulesStates, ok := orgStates[entry.RuleUID] if !ok { rulesStates = &ruleStates{states: make(map[string]*State)} orgStates[entry.RuleUID] = rulesStates } lbs := map[string]string(entry.Labels) cacheID, err := entry.Labels.StringKey() if err != nil { st.log.Error("Error getting cacheId for entry", "error", err) } rulesStates.states[cacheID] = &State{ AlertRuleUID: entry.RuleUID, OrgID: entry.RuleOrgID, CacheID: cacheID, Labels: lbs, State: translateInstanceState(entry.CurrentState), StateReason: entry.CurrentReason, LastEvaluationString: "", StartsAt: entry.CurrentStateSince, EndsAt: entry.CurrentStateEnd, LastEvaluationTime: entry.LastEvalTime, Annotations: ruleForEntry.Annotations, } statesCount++ } } st.cache.setAllStates(states) st.log.Info("State cache has been initialized", "states", statesCount, "duration", time.Since(startTime)) } func (st *Manager) Get(orgID int64, alertRuleUID, stateId string) *State { return st.cache.get(orgID, alertRuleUID, stateId) } // ResetStateByRuleUID deletes all entries in the state manager that match the given rule UID. func (st *Manager) ResetStateByRuleUID(ctx context.Context, ruleKey ngModels.AlertRuleKey) []*State { logger := st.log.New(ruleKey.LogContext()...) logger.Debug("Resetting state of the rule") states := st.cache.removeByRuleUID(ruleKey.OrgID, ruleKey.UID) if len(states) > 0 && st.instanceStore != nil { err := st.instanceStore.DeleteAlertInstancesByRule(ctx, ruleKey) if err != nil { logger.Error("Failed to delete states that belong to a rule from database", "error", err) } } logger.Info("Rules state was reset", "states", len(states)) return states } // ProcessEvalResults updates the current states that belong to a rule with the evaluation results. // if extraLabels is not empty, those labels will be added to every state. The extraLabels take precedence over rule labels and result labels func (st *Manager) ProcessEvalResults(ctx context.Context, evaluatedAt time.Time, alertRule *ngModels.AlertRule, results eval.Results, extraLabels data.Labels) []*State { logger := st.log.FromContext(ctx) logger.Debug("State manager processing evaluation results", "resultCount", len(results)) var states []StateTransition processedResults := make(map[string]*State, len(results)) for _, result := range results { s := st.setNextState(ctx, alertRule, result, extraLabels, logger) states = append(states, s) processedResults[s.State.CacheID] = s.State } resolvedStates := st.staleResultsHandler(ctx, evaluatedAt, alertRule, processedResults, logger) st.saveAlertStates(ctx, logger, states...) changedStates := make([]StateTransition, 0, len(states)) for _, s := range states { if s.changed() { changedStates = append(changedStates, s) } } if st.historian != nil { st.historian.RecordStates(ctx, alertRule, changedStates) } deltas := append(states, resolvedStates...) nextStates := make([]*State, 0, len(states)) for _, s := range deltas { nextStates = append(nextStates, s.State) } return nextStates } // Set the current state based on evaluation results func (st *Manager) setNextState(ctx context.Context, alertRule *ngModels.AlertRule, result eval.Result, extraLabels data.Labels, logger log.Logger) StateTransition { currentState := st.cache.getOrCreate(ctx, st.log, alertRule, result, extraLabels, st.externalURL) currentState.LastEvaluationTime = result.EvaluatedAt currentState.EvaluationDuration = result.EvaluationDuration currentState.Results = append(currentState.Results, Evaluation{ EvaluationTime: result.EvaluatedAt, EvaluationState: result.State, Values: NewEvaluationValues(result.Values), Condition: alertRule.Condition, }) currentState.LastEvaluationString = result.EvaluationString currentState.TrimResults(alertRule) oldState := currentState.State oldReason := currentState.StateReason logger.Debug("Setting alert state") switch result.State { case eval.Normal: currentState.resultNormal(alertRule, result) case eval.Alerting: currentState.resultAlerting(alertRule, result) case eval.Error: currentState.resultError(alertRule, result) case eval.NoData: currentState.resultNoData(alertRule, result) case eval.Pending: // we do not emit results with this state } // Set reason iff: result is different than state, reason is not Alerting or Normal currentState.StateReason = "" if currentState.State != result.State && result.State != eval.Normal && result.State != eval.Alerting { currentState.StateReason = result.State.String() } // Set Resolved property so the scheduler knows to send a postable alert // to Alertmanager. currentState.Resolved = oldState == eval.Alerting && currentState.State == eval.Normal if shouldTakeImage(currentState.State, oldState, currentState.Image, currentState.Resolved) { image, err := takeImage(ctx, st.imageService, alertRule) if err != nil { logger.Warn("Failed to take an image", "dashboard", alertRule.DashboardUID, "panel", alertRule.PanelID, "error", err) } else if image != nil { currentState.Image = image } } st.cache.set(currentState) nextState := StateTransition{ State: currentState, PreviousState: oldState, PreviousStateReason: oldReason, } return nextState } func (st *Manager) GetAll(orgID int64) []*State { return st.cache.getAll(orgID) } func (st *Manager) GetStatesForRuleUID(orgID int64, alertRuleUID string) []*State { return st.cache.getStatesForRuleUID(orgID, alertRuleUID) } func (st *Manager) Put(states []*State) { for _, s := range states { st.cache.set(s) } } // TODO: Is the `State` type necessary? Should it embed the instance? func (st *Manager) saveAlertStates(ctx context.Context, logger log.Logger, states ...StateTransition) { if st.instanceStore == nil { return } logger.Debug("Saving alert states", "count", len(states)) instances := make([]ngModels.AlertInstance, 0, len(states)) for _, s := range states { labels := ngModels.InstanceLabels(s.Labels) _, hash, err := labels.StringAndHash() if err != nil { logger.Error("Failed to create a key for alert state to save it to database. The state will be ignored ", "cacheID", s.CacheID, "error", err) continue } fields := ngModels.AlertInstance{ AlertInstanceKey: ngModels.AlertInstanceKey{ RuleOrgID: s.OrgID, RuleUID: s.AlertRuleUID, LabelsHash: hash, }, Labels: ngModels.InstanceLabels(s.Labels), CurrentState: ngModels.InstanceStateType(s.State.State.String()), CurrentReason: s.StateReason, LastEvalTime: s.LastEvaluationTime, CurrentStateSince: s.StartsAt, CurrentStateEnd: s.EndsAt, } instances = append(instances, fields) } if err := st.instanceStore.SaveAlertInstances(ctx, instances...); err != nil { type debugInfo struct { State string Labels string } debug := make([]debugInfo, 0) for _, inst := range instances { debug = append(debug, debugInfo{string(inst.CurrentState), data.Labels(inst.Labels).String()}) } logger.Error("Failed to save alert states", "states", debug, "error", err) } } // TODO: why wouldn't you allow other types like NoData or Error? func translateInstanceState(state ngModels.InstanceStateType) eval.State { switch { case state == ngModels.InstanceStateFiring: return eval.Alerting case state == ngModels.InstanceStateNormal: return eval.Normal default: return eval.Error } } func (st *Manager) staleResultsHandler(ctx context.Context, evaluatedAt time.Time, alertRule *ngModels.AlertRule, states map[string]*State, logger log.Logger) []StateTransition { // If we are removing two or more stale series it makes sense to share the resolved image as the alert rule is the same. // TODO: We will need to change this when we support images without screenshots as each series will have a different image var resolvedImage *ngModels.Image var resolvedStates []StateTransition allStates := st.GetStatesForRuleUID(alertRule.OrgID, alertRule.UID) toDelete := make([]ngModels.AlertInstanceKey, 0) for _, s := range allStates { // Is the cached state in our recently processed results? If not, is it stale? if _, ok := states[s.CacheID]; !ok && stateIsStale(evaluatedAt, s.LastEvaluationTime, alertRule.IntervalSeconds) { logger.Info("Removing stale state entry", "cacheID", s.CacheID, "state", s.State, "reason", s.StateReason) st.cache.deleteEntry(s.OrgID, s.AlertRuleUID, s.CacheID) ilbs := ngModels.InstanceLabels(s.Labels) _, labelsHash, err := ilbs.StringAndHash() if err != nil { logger.Error("Unable to get labelsHash", "error", err.Error(), s.AlertRuleUID) } toDelete = append(toDelete, ngModels.AlertInstanceKey{RuleOrgID: s.OrgID, RuleUID: s.AlertRuleUID, LabelsHash: labelsHash}) if s.State == eval.Alerting { oldState := s.State oldReason := s.StateReason s.State = eval.Normal s.StateReason = ngModels.StateReasonMissingSeries s.EndsAt = evaluatedAt s.Resolved = true s.LastEvaluationTime = evaluatedAt record := StateTransition{ State: s, PreviousState: oldState, PreviousStateReason: oldReason, } // If there is no resolved image for this rule then take one if resolvedImage == nil { image, err := takeImage(ctx, st.imageService, alertRule) if err != nil { logger.Warn("Failed to take an image", "dashboard", alertRule.DashboardUID, "panel", alertRule.PanelID, "error", err) } else if image != nil { resolvedImage = image } } s.Image = resolvedImage resolvedStates = append(resolvedStates, record) } } } if st.historian != nil { st.historian.RecordStates(ctx, alertRule, resolvedStates) } if st.instanceStore != nil { if err := st.instanceStore.DeleteAlertInstances(ctx, toDelete...); err != nil { logger.Error("Unable to delete stale instances from database", "error", err, "count", len(toDelete)) } } return resolvedStates } func stateIsStale(evaluatedAt time.Time, lastEval time.Time, intervalSeconds int64) bool { return !lastEval.Add(2 * time.Duration(intervalSeconds) * time.Second).After(evaluatedAt) }
pkg/services/ngalert/state/manager.go
1
https://github.com/grafana/grafana/commit/623de12e354c8f92fd49802a04bafe5970fba0e9
[ 0.9985710382461548, 0.11986427009105682, 0.00016452489944640547, 0.0004120271769352257, 0.3201676607131958 ]
{ "id": 4, "code_window": [ "\t\t\t}\n", "\n", "\t\t\ttoDelete = append(toDelete, ngModels.AlertInstanceKey{RuleOrgID: s.OrgID, RuleUID: s.AlertRuleUID, LabelsHash: labelsHash})\n", "\n", "\t\t\tif s.State == eval.Alerting {\n", "\t\t\t\toldState := s.State\n", "\t\t\t\toldReason := s.StateReason\n", "\n" ], "labels": [ "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "pkg/services/ngalert/state/manager.go", "type": "replace", "edit_start_line_idx": 360 }
import React from 'react'; import { useAsync } from 'react-use'; import { NavModelItem } from '@grafana/data'; import { withErrorBoundary } from '@grafana/ui'; import { GrafanaRouteComponentProps } from 'app/core/navigation/types'; import { useDispatch } from 'app/types'; import { AlertWarning } from './AlertWarning'; import { ExistingRuleEditor } from './ExistingRuleEditor'; import { AlertingPageWrapper } from './components/AlertingPageWrapper'; import { AlertRuleForm } from './components/rule-editor/AlertRuleForm'; import { fetchAllPromBuildInfoAction } from './state/actions'; import { useRulesAccess } from './utils/accessControlHooks'; import * as ruleId from './utils/rule-id'; type RuleEditorProps = GrafanaRouteComponentProps<{ id?: string }>; const defaultPageNav: Partial<NavModelItem> = { icon: 'bell', id: 'alert-rule-view', breadcrumbs: [{ title: 'Alert rules', url: 'alerting/list' }], }; const getPageNav = (state: 'edit' | 'add') => { if (state === 'edit') { return { ...defaultPageNav, id: 'alert-rule-edit', text: 'Edit rule' }; } else if (state === 'add') { return { ...defaultPageNav, id: 'alert-rule-add', text: 'Add rule' }; } return undefined; }; const RuleEditor = ({ match }: RuleEditorProps) => { const dispatch = useDispatch(); const { id } = match.params; const identifier = ruleId.tryParse(id, true); const { loading = true } = useAsync(async () => { await dispatch(fetchAllPromBuildInfoAction()); }, [dispatch]); const { canCreateGrafanaRules, canCreateCloudRules, canEditRules } = useRulesAccess(); const getContent = () => { if (loading) { return; } if (!identifier && !canCreateGrafanaRules && !canCreateCloudRules) { return <AlertWarning title="Cannot create rules">Sorry! You are not allowed to create rules.</AlertWarning>; } if (identifier && !canEditRules(identifier.ruleSourceName)) { return <AlertWarning title="Cannot edit rules">Sorry! You are not allowed to edit rules.</AlertWarning>; } if (identifier) { return <ExistingRuleEditor key={id} identifier={identifier} />; } return <AlertRuleForm />; }; return ( <AlertingPageWrapper isLoading={loading} pageId="alert-list" pageNav={getPageNav(identifier ? 'edit' : 'add')}> {getContent()} </AlertingPageWrapper> ); }; export default withErrorBoundary(RuleEditor, { style: 'page' });
public/app/features/alerting/unified/RuleEditor.tsx
0
https://github.com/grafana/grafana/commit/623de12e354c8f92fd49802a04bafe5970fba0e9
[ 0.0002032854245044291, 0.00017339106125291437, 0.0001636491942917928, 0.00016986028640531003, 0.000011948630344704725 ]
{ "id": 4, "code_window": [ "\t\t\t}\n", "\n", "\t\t\ttoDelete = append(toDelete, ngModels.AlertInstanceKey{RuleOrgID: s.OrgID, RuleUID: s.AlertRuleUID, LabelsHash: labelsHash})\n", "\n", "\t\t\tif s.State == eval.Alerting {\n", "\t\t\t\toldState := s.State\n", "\t\t\t\toldReason := s.StateReason\n", "\n" ], "labels": [ "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "pkg/services/ngalert/state/manager.go", "type": "replace", "edit_start_line_idx": 360 }
{ "annotations": { "list": [ { "builtIn": 1, "datasource": "-- Grafana --", "enable": true, "hide": true, "iconColor": "rgba(0, 211, 255, 1)", "name": "Annotations & Alerts", "type": "dashboard" } ] }, "editable": true, "gnetId": null, "graphTooltip": 0, "id": null, "iteration": 1601526910610, "links": [ { "icon": "external link", "includeVars": true, "tags": [], "title": "Grafana", "tooltip": "", "type": "link", "url": "http://www.grafana.com" }, { "asDropdown": true, "icon": "external link", "includeVars": true, "tags": ["templating"], "title": "Link as DropDown", "type": "dashboards" }, { "icon": "external link", "includeVars": true, "tags": ["demo"], "type": "dashboards" } ], "panels": [ { "description": "", "fieldConfig": { "defaults": { "custom": {} }, "overrides": [] }, "gridPos": { "h": 9, "w": 12, "x": 0, "y": 0 }, "id": 2, "options": { "content": "# ${custom.text}\n ", "mode": "markdown" }, "pluginVersion": "7.3.0-pre", "targets": [ { "refId": "A", "scenarioId": "random_walk" } ], "timeFrom": null, "timeShift": null, "title": "${custom.text}", "type": "text" } ], "schemaVersion": 26, "style": "dark", "tags": ["gdev", "templating"], "templating": { "list": [ { "allValue": null, "current": { "selected": false, "text": "All", "value": "$__all" }, "hide": 0, "includeAll": true, "label": null, "multi": true, "name": "custom", "options": [ { "selected": true, "text": "All", "value": "$__all" }, { "selected": false, "text": "p1", "value": "p1" }, { "selected": false, "text": "p2", "value": "p2" }, { "selected": false, "text": "p3", "value": "p3" } ], "query": "p1,p2,p3", "skipUrlSync": false, "type": "custom" } ] }, "time": { "from": "now-6h", "to": "now" }, "timepicker": {}, "timezone": "", "title": "Templating - Dashboard Links and Variables", "uid": "yBCC3aKGk", "version": 7 }
devenv/dev-dashboards/feature-templating/templating-dashboard-links-and-variables.json
0
https://github.com/grafana/grafana/commit/623de12e354c8f92fd49802a04bafe5970fba0e9
[ 0.00017874533659778535, 0.00017650309018790722, 0.0001738026476232335, 0.00017651449888944626, 0.0000012411726402206114 ]
{ "id": 4, "code_window": [ "\t\t\t}\n", "\n", "\t\t\ttoDelete = append(toDelete, ngModels.AlertInstanceKey{RuleOrgID: s.OrgID, RuleUID: s.AlertRuleUID, LabelsHash: labelsHash})\n", "\n", "\t\t\tif s.State == eval.Alerting {\n", "\t\t\t\toldState := s.State\n", "\t\t\t\toldReason := s.StateReason\n", "\n" ], "labels": [ "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "pkg/services/ngalert/state/manager.go", "type": "replace", "edit_start_line_idx": 360 }
.page-loader-wrapper { padding-top: 100px; display: flex; align-items: center; justify-content: center; flex-direction: column; &__spinner { font-size: 32px; margin-bottom: $space-sm; } &__text { font-size: 14px; } }
public/sass/components/_page_loader.scss
0
https://github.com/grafana/grafana/commit/623de12e354c8f92fd49802a04bafe5970fba0e9
[ 0.00017832127923611552, 0.00017703937191981822, 0.00017575746460352093, 0.00017703937191981822, 0.0000012819073162972927 ]
{ "id": 5, "code_window": [ "\t}\n", "}\n", "\n", "// StateTransition describes the transition from one state to another.\n", "type StateTransition struct {\n", "\t*State\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "func (a *State) GetAlertInstanceKey() (models.AlertInstanceKey, error) {\n", "\tinstanceLabels := models.InstanceLabels(a.Labels)\n", "\t_, labelsHash, err := instanceLabels.StringAndHash()\n", "\tif err != nil {\n", "\t\treturn models.AlertInstanceKey{}, err\n", "\t}\n", "\treturn models.AlertInstanceKey{RuleOrgID: a.OrgID, RuleUID: a.AlertRuleUID, LabelsHash: labelsHash}, nil\n", "}\n", "\n" ], "file_path": "pkg/services/ngalert/state/state.go", "type": "add", "edit_start_line_idx": 75 }
package state import ( "context" "net/url" "time" "github.com/benbjohnson/clock" "github.com/grafana/grafana-plugin-sdk-go/data" "github.com/grafana/grafana/pkg/infra/log" "github.com/grafana/grafana/pkg/services/ngalert/eval" "github.com/grafana/grafana/pkg/services/ngalert/image" "github.com/grafana/grafana/pkg/services/ngalert/metrics" ngModels "github.com/grafana/grafana/pkg/services/ngalert/models" ) var ( ResendDelay = 30 * time.Second MetricsScrapeInterval = 15 * time.Second // TODO: parameterize? // Setting to a reasonable default scrape interval for Prometheus. ) // AlertInstanceManager defines the interface for querying the current alert instances. type AlertInstanceManager interface { GetAll(orgID int64) []*State GetStatesForRuleUID(orgID int64, alertRuleUID string) []*State } type Manager struct { log log.Logger metrics *metrics.State clock clock.Clock cache *cache ResendDelay time.Duration instanceStore InstanceStore imageService image.ImageService historian Historian externalURL *url.URL } func NewManager(metrics *metrics.State, externalURL *url.URL, instanceStore InstanceStore, imageService image.ImageService, clock clock.Clock, historian Historian) *Manager { return &Manager{ cache: newCache(), ResendDelay: ResendDelay, // TODO: make this configurable log: log.New("ngalert.state.manager"), metrics: metrics, instanceStore: instanceStore, imageService: imageService, historian: historian, clock: clock, externalURL: externalURL, } } func (st *Manager) Run(ctx context.Context) error { ticker := st.clock.Ticker(MetricsScrapeInterval) for { select { case <-ticker.C: st.log.Debug("Recording state cache metrics", "now", st.clock.Now()) st.cache.recordMetrics(st.metrics) case <-ctx.Done(): st.log.Debug("Stopping") ticker.Stop() return ctx.Err() } } } func (st *Manager) Warm(ctx context.Context, rulesReader RuleReader) { if st.instanceStore == nil { st.log.Info("Skip warming the state because instance store is not configured") return } startTime := time.Now() st.log.Info("Warming state cache for startup") orgIds, err := st.instanceStore.FetchOrgIds(ctx) if err != nil { st.log.Error("Unable to fetch orgIds", "error", err) } statesCount := 0 states := make(map[int64]map[string]*ruleStates, len(orgIds)) for _, orgId := range orgIds { // Get Rules ruleCmd := ngModels.ListAlertRulesQuery{ OrgID: orgId, } if err := rulesReader.ListAlertRules(ctx, &ruleCmd); err != nil { st.log.Error("Unable to fetch previous state", "error", err) } ruleByUID := make(map[string]*ngModels.AlertRule, len(ruleCmd.Result)) for _, rule := range ruleCmd.Result { ruleByUID[rule.UID] = rule } orgStates := make(map[string]*ruleStates, len(ruleByUID)) states[orgId] = orgStates // Get Instances cmd := ngModels.ListAlertInstancesQuery{ RuleOrgID: orgId, } if err := st.instanceStore.ListAlertInstances(ctx, &cmd); err != nil { st.log.Error("Unable to fetch previous state", "error", err) } for _, entry := range cmd.Result { ruleForEntry, ok := ruleByUID[entry.RuleUID] if !ok { // TODO Should we delete the orphaned state from the db? continue } rulesStates, ok := orgStates[entry.RuleUID] if !ok { rulesStates = &ruleStates{states: make(map[string]*State)} orgStates[entry.RuleUID] = rulesStates } lbs := map[string]string(entry.Labels) cacheID, err := entry.Labels.StringKey() if err != nil { st.log.Error("Error getting cacheId for entry", "error", err) } rulesStates.states[cacheID] = &State{ AlertRuleUID: entry.RuleUID, OrgID: entry.RuleOrgID, CacheID: cacheID, Labels: lbs, State: translateInstanceState(entry.CurrentState), StateReason: entry.CurrentReason, LastEvaluationString: "", StartsAt: entry.CurrentStateSince, EndsAt: entry.CurrentStateEnd, LastEvaluationTime: entry.LastEvalTime, Annotations: ruleForEntry.Annotations, } statesCount++ } } st.cache.setAllStates(states) st.log.Info("State cache has been initialized", "states", statesCount, "duration", time.Since(startTime)) } func (st *Manager) Get(orgID int64, alertRuleUID, stateId string) *State { return st.cache.get(orgID, alertRuleUID, stateId) } // ResetStateByRuleUID deletes all entries in the state manager that match the given rule UID. func (st *Manager) ResetStateByRuleUID(ctx context.Context, ruleKey ngModels.AlertRuleKey) []*State { logger := st.log.New(ruleKey.LogContext()...) logger.Debug("Resetting state of the rule") states := st.cache.removeByRuleUID(ruleKey.OrgID, ruleKey.UID) if len(states) > 0 && st.instanceStore != nil { err := st.instanceStore.DeleteAlertInstancesByRule(ctx, ruleKey) if err != nil { logger.Error("Failed to delete states that belong to a rule from database", "error", err) } } logger.Info("Rules state was reset", "states", len(states)) return states } // ProcessEvalResults updates the current states that belong to a rule with the evaluation results. // if extraLabels is not empty, those labels will be added to every state. The extraLabels take precedence over rule labels and result labels func (st *Manager) ProcessEvalResults(ctx context.Context, evaluatedAt time.Time, alertRule *ngModels.AlertRule, results eval.Results, extraLabels data.Labels) []*State { logger := st.log.FromContext(ctx) logger.Debug("State manager processing evaluation results", "resultCount", len(results)) var states []StateTransition processedResults := make(map[string]*State, len(results)) for _, result := range results { s := st.setNextState(ctx, alertRule, result, extraLabels, logger) states = append(states, s) processedResults[s.State.CacheID] = s.State } resolvedStates := st.staleResultsHandler(ctx, evaluatedAt, alertRule, processedResults, logger) st.saveAlertStates(ctx, logger, states...) changedStates := make([]StateTransition, 0, len(states)) for _, s := range states { if s.changed() { changedStates = append(changedStates, s) } } if st.historian != nil { st.historian.RecordStates(ctx, alertRule, changedStates) } deltas := append(states, resolvedStates...) nextStates := make([]*State, 0, len(states)) for _, s := range deltas { nextStates = append(nextStates, s.State) } return nextStates } // Set the current state based on evaluation results func (st *Manager) setNextState(ctx context.Context, alertRule *ngModels.AlertRule, result eval.Result, extraLabels data.Labels, logger log.Logger) StateTransition { currentState := st.cache.getOrCreate(ctx, st.log, alertRule, result, extraLabels, st.externalURL) currentState.LastEvaluationTime = result.EvaluatedAt currentState.EvaluationDuration = result.EvaluationDuration currentState.Results = append(currentState.Results, Evaluation{ EvaluationTime: result.EvaluatedAt, EvaluationState: result.State, Values: NewEvaluationValues(result.Values), Condition: alertRule.Condition, }) currentState.LastEvaluationString = result.EvaluationString currentState.TrimResults(alertRule) oldState := currentState.State oldReason := currentState.StateReason logger.Debug("Setting alert state") switch result.State { case eval.Normal: currentState.resultNormal(alertRule, result) case eval.Alerting: currentState.resultAlerting(alertRule, result) case eval.Error: currentState.resultError(alertRule, result) case eval.NoData: currentState.resultNoData(alertRule, result) case eval.Pending: // we do not emit results with this state } // Set reason iff: result is different than state, reason is not Alerting or Normal currentState.StateReason = "" if currentState.State != result.State && result.State != eval.Normal && result.State != eval.Alerting { currentState.StateReason = result.State.String() } // Set Resolved property so the scheduler knows to send a postable alert // to Alertmanager. currentState.Resolved = oldState == eval.Alerting && currentState.State == eval.Normal if shouldTakeImage(currentState.State, oldState, currentState.Image, currentState.Resolved) { image, err := takeImage(ctx, st.imageService, alertRule) if err != nil { logger.Warn("Failed to take an image", "dashboard", alertRule.DashboardUID, "panel", alertRule.PanelID, "error", err) } else if image != nil { currentState.Image = image } } st.cache.set(currentState) nextState := StateTransition{ State: currentState, PreviousState: oldState, PreviousStateReason: oldReason, } return nextState } func (st *Manager) GetAll(orgID int64) []*State { return st.cache.getAll(orgID) } func (st *Manager) GetStatesForRuleUID(orgID int64, alertRuleUID string) []*State { return st.cache.getStatesForRuleUID(orgID, alertRuleUID) } func (st *Manager) Put(states []*State) { for _, s := range states { st.cache.set(s) } } // TODO: Is the `State` type necessary? Should it embed the instance? func (st *Manager) saveAlertStates(ctx context.Context, logger log.Logger, states ...StateTransition) { if st.instanceStore == nil { return } logger.Debug("Saving alert states", "count", len(states)) instances := make([]ngModels.AlertInstance, 0, len(states)) for _, s := range states { labels := ngModels.InstanceLabels(s.Labels) _, hash, err := labels.StringAndHash() if err != nil { logger.Error("Failed to create a key for alert state to save it to database. The state will be ignored ", "cacheID", s.CacheID, "error", err) continue } fields := ngModels.AlertInstance{ AlertInstanceKey: ngModels.AlertInstanceKey{ RuleOrgID: s.OrgID, RuleUID: s.AlertRuleUID, LabelsHash: hash, }, Labels: ngModels.InstanceLabels(s.Labels), CurrentState: ngModels.InstanceStateType(s.State.State.String()), CurrentReason: s.StateReason, LastEvalTime: s.LastEvaluationTime, CurrentStateSince: s.StartsAt, CurrentStateEnd: s.EndsAt, } instances = append(instances, fields) } if err := st.instanceStore.SaveAlertInstances(ctx, instances...); err != nil { type debugInfo struct { State string Labels string } debug := make([]debugInfo, 0) for _, inst := range instances { debug = append(debug, debugInfo{string(inst.CurrentState), data.Labels(inst.Labels).String()}) } logger.Error("Failed to save alert states", "states", debug, "error", err) } } // TODO: why wouldn't you allow other types like NoData or Error? func translateInstanceState(state ngModels.InstanceStateType) eval.State { switch { case state == ngModels.InstanceStateFiring: return eval.Alerting case state == ngModels.InstanceStateNormal: return eval.Normal default: return eval.Error } } func (st *Manager) staleResultsHandler(ctx context.Context, evaluatedAt time.Time, alertRule *ngModels.AlertRule, states map[string]*State, logger log.Logger) []StateTransition { // If we are removing two or more stale series it makes sense to share the resolved image as the alert rule is the same. // TODO: We will need to change this when we support images without screenshots as each series will have a different image var resolvedImage *ngModels.Image var resolvedStates []StateTransition allStates := st.GetStatesForRuleUID(alertRule.OrgID, alertRule.UID) toDelete := make([]ngModels.AlertInstanceKey, 0) for _, s := range allStates { // Is the cached state in our recently processed results? If not, is it stale? if _, ok := states[s.CacheID]; !ok && stateIsStale(evaluatedAt, s.LastEvaluationTime, alertRule.IntervalSeconds) { logger.Info("Removing stale state entry", "cacheID", s.CacheID, "state", s.State, "reason", s.StateReason) st.cache.deleteEntry(s.OrgID, s.AlertRuleUID, s.CacheID) ilbs := ngModels.InstanceLabels(s.Labels) _, labelsHash, err := ilbs.StringAndHash() if err != nil { logger.Error("Unable to get labelsHash", "error", err.Error(), s.AlertRuleUID) } toDelete = append(toDelete, ngModels.AlertInstanceKey{RuleOrgID: s.OrgID, RuleUID: s.AlertRuleUID, LabelsHash: labelsHash}) if s.State == eval.Alerting { oldState := s.State oldReason := s.StateReason s.State = eval.Normal s.StateReason = ngModels.StateReasonMissingSeries s.EndsAt = evaluatedAt s.Resolved = true s.LastEvaluationTime = evaluatedAt record := StateTransition{ State: s, PreviousState: oldState, PreviousStateReason: oldReason, } // If there is no resolved image for this rule then take one if resolvedImage == nil { image, err := takeImage(ctx, st.imageService, alertRule) if err != nil { logger.Warn("Failed to take an image", "dashboard", alertRule.DashboardUID, "panel", alertRule.PanelID, "error", err) } else if image != nil { resolvedImage = image } } s.Image = resolvedImage resolvedStates = append(resolvedStates, record) } } } if st.historian != nil { st.historian.RecordStates(ctx, alertRule, resolvedStates) } if st.instanceStore != nil { if err := st.instanceStore.DeleteAlertInstances(ctx, toDelete...); err != nil { logger.Error("Unable to delete stale instances from database", "error", err, "count", len(toDelete)) } } return resolvedStates } func stateIsStale(evaluatedAt time.Time, lastEval time.Time, intervalSeconds int64) bool { return !lastEval.Add(2 * time.Duration(intervalSeconds) * time.Second).After(evaluatedAt) }
pkg/services/ngalert/state/manager.go
1
https://github.com/grafana/grafana/commit/623de12e354c8f92fd49802a04bafe5970fba0e9
[ 0.9986338019371033, 0.16741535067558289, 0.00016457056335639209, 0.0009078168077394366, 0.3674740195274353 ]
{ "id": 5, "code_window": [ "\t}\n", "}\n", "\n", "// StateTransition describes the transition from one state to another.\n", "type StateTransition struct {\n", "\t*State\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "func (a *State) GetAlertInstanceKey() (models.AlertInstanceKey, error) {\n", "\tinstanceLabels := models.InstanceLabels(a.Labels)\n", "\t_, labelsHash, err := instanceLabels.StringAndHash()\n", "\tif err != nil {\n", "\t\treturn models.AlertInstanceKey{}, err\n", "\t}\n", "\treturn models.AlertInstanceKey{RuleOrgID: a.OrgID, RuleUID: a.AlertRuleUID, LabelsHash: labelsHash}, nil\n", "}\n", "\n" ], "file_path": "pkg/services/ngalert/state/state.go", "type": "add", "edit_start_line_idx": 75 }
import { interval, Observable, of, throwError } from 'rxjs'; import { map, mergeMap, take } from 'rxjs/operators'; import { OBSERVABLE_TEST_TIMEOUT_IN_MS } from './types'; describe('toEmitValuesWith matcher', () => { describe('failing tests', () => { describe('passing null in expect', () => { it('should fail with correct message', async () => { const observable = null as unknown as Observable<number>; const rejects = expect(() => expect(observable).toEmitValuesWith((received) => { expect(received).toEqual([1, 2, 3]); }) ).rejects; await rejects.toThrow(); }); }); describe('passing undefined in expect', () => { it('should fail with correct message', async () => { const observable = undefined as unknown as Observable<number>; const rejects = expect(() => expect(observable).toEmitValuesWith((received) => { expect(received).toEqual([1, 2, 3]); }) ).rejects; await rejects.toThrow(); }); }); describe('passing number instead of Observable in expect', () => { it('should fail with correct message', async () => { const observable = 1 as unknown as Observable<number>; const rejects = expect(() => expect(observable).toEmitValuesWith((received) => { expect(received).toEqual([1, 2, 3]); }) ).rejects; await rejects.toThrow(); }); }); describe('wrong number of emitted values', () => { it('should fail with correct message', async () => { const observable = interval(10).pipe(take(3)); const rejects = expect(() => expect(observable).toEmitValuesWith((received) => { expect(received).toEqual([0, 1]); }) ).rejects; await rejects.toThrow(); }); }); describe('wrong emitted values', () => { it('should fail with correct message', async () => { const observable = interval(10).pipe(take(3)); const rejects = expect(() => expect(observable).toEmitValuesWith((received) => { expect(received).toEqual([1, 2, 3]); }) ).rejects; await rejects.toThrow(); }); }); describe('wrong emitted value types', () => { it('should fail with correct message', async () => { const observable = interval(10).pipe(take(3)) as unknown as Observable<string>; const rejects = expect(() => expect(observable).toEmitValuesWith((received) => { expect(received).toEqual(['0', '1', '2']); }) ).rejects; await rejects.toThrow(); }); }); describe(`observable that does not complete within ${OBSERVABLE_TEST_TIMEOUT_IN_MS}ms`, () => { it('should fail with correct message', async () => { const observable = interval(600); const rejects = expect(() => expect(observable).toEmitValuesWith((received) => { expect(received).toEqual([0]); }) ).rejects; await rejects.toThrow(); }); }); }); describe('passing tests', () => { describe('correct emitted values', () => { it('should pass with correct message', async () => { const observable = interval(10).pipe(take(3)); await expect(observable).toEmitValuesWith((received) => { expect(received).toEqual([0, 1, 2]); }); }); }); describe('correct emitted values with throw', () => { it('should pass with correct message', async () => { const observable = interval(10).pipe( map((interval) => { if (interval > 1) { throw 'an error'; } return interval; }) ); await expect(observable).toEmitValuesWith((received) => { expect(received).toEqual([0, 1, 'an error']); }); }); }); describe('correct emitted values with throwError', () => { it('should pass with correct message', async () => { const observable = interval(10).pipe( mergeMap((interval) => { if (interval === 1) { return throwError('an error'); } return of(interval); }) ); await expect(observable).toEmitValuesWith((received) => { expect(received).toEqual([0, 'an error']); }); }); }); }); });
public/test/matchers/toEmitValuesWith.test.ts
0
https://github.com/grafana/grafana/commit/623de12e354c8f92fd49802a04bafe5970fba0e9
[ 0.00025560203357599676, 0.00017627966008149087, 0.00016576227790210396, 0.00016955591854639351, 0.0000215257841773564 ]
{ "id": 5, "code_window": [ "\t}\n", "}\n", "\n", "// StateTransition describes the transition from one state to another.\n", "type StateTransition struct {\n", "\t*State\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "func (a *State) GetAlertInstanceKey() (models.AlertInstanceKey, error) {\n", "\tinstanceLabels := models.InstanceLabels(a.Labels)\n", "\t_, labelsHash, err := instanceLabels.StringAndHash()\n", "\tif err != nil {\n", "\t\treturn models.AlertInstanceKey{}, err\n", "\t}\n", "\treturn models.AlertInstanceKey{RuleOrgID: a.OrgID, RuleUID: a.AlertRuleUID, LabelsHash: labelsHash}, nil\n", "}\n", "\n" ], "file_path": "pkg/services/ngalert/state/state.go", "type": "add", "edit_start_line_idx": 75 }
package api import ( "net/http" "time" "github.com/getsentry/sentry-go" "golang.org/x/time/rate" "github.com/grafana/grafana/pkg/api/frontendlogging" "github.com/grafana/grafana/pkg/infra/log" "github.com/grafana/grafana/pkg/web" ) var frontendLogger = log.New("frontend") type frontendLogMessageHandler func(hs *HTTPServer, c *web.Context) const sentryLogEndpointPath = "/log" const grafanaJavascriptAgentEndpointPath = "/log-grafana-javascript-agent" func NewFrontendLogMessageHandler(store *frontendlogging.SourceMapStore) frontendLogMessageHandler { return func(hs *HTTPServer, c *web.Context) { event := frontendlogging.FrontendSentryEvent{} if err := web.Bind(c.Req, &event); err != nil { c.Resp.WriteHeader(http.StatusBadRequest) _, err = c.Resp.Write([]byte("bad request data")) if err != nil { hs.log.Error("could not write to response", "err", err) } return } var msg = "unknown" if len(event.Message) > 0 { msg = event.Message } else if event.Exception != nil && len(event.Exception.Values) > 0 { msg = event.Exception.Values[0].FmtMessage() } var ctx = event.ToLogContext(store) switch event.Level { case sentry.LevelError: frontendLogger.Error(msg, ctx...) case sentry.LevelWarning: frontendLogger.Warn(msg, ctx...) case sentry.LevelDebug: frontendLogger.Debug(msg, ctx...) default: frontendLogger.Info(msg, ctx...) } c.Resp.WriteHeader(http.StatusAccepted) _, err := c.Resp.Write([]byte("OK")) if err != nil { hs.log.Error("could not write to response", "err", err) } } } func GrafanaJavascriptAgentLogMessageHandler(store *frontendlogging.SourceMapStore) frontendLogMessageHandler { return func(hs *HTTPServer, c *web.Context) { event := frontendlogging.FrontendGrafanaJavascriptAgentEvent{} if err := web.Bind(c.Req, &event); err != nil { c.Resp.WriteHeader(http.StatusBadRequest) _, err = c.Resp.Write([]byte("bad request data")) if err != nil { hs.log.Error("could not write to response", "err", err) } } // Meta object is standard across event types, adding it globally. if event.Logs != nil && len(event.Logs) > 0 { for _, logEntry := range event.Logs { var ctx = frontendlogging.CtxVector{} ctx = event.AddMetaToContext(ctx) ctx = append(ctx, "kind", "log", "original_timestamp", logEntry.Timestamp) for k, v := range frontendlogging.KeyValToInterfaceMap(logEntry.KeyValContext()) { ctx = append(ctx, k, v) } switch logEntry.LogLevel { case frontendlogging.LogLevelDebug, frontendlogging.LogLevelTrace: { ctx = append(ctx, "original_log_level", logEntry.LogLevel) frontendLogger.Debug(logEntry.Message, ctx...) } case frontendlogging.LogLevelError: { ctx = append(ctx, "original_log_level", logEntry.LogLevel) frontendLogger.Error(logEntry.Message, ctx...) } case frontendlogging.LogLevelWarning: { ctx = append(ctx, "original_log_level", logEntry.LogLevel) frontendLogger.Warn(logEntry.Message, ctx...) } default: { ctx = append(ctx, "original_log_level", logEntry.LogLevel) frontendLogger.Info(logEntry.Message, ctx...) } } } } if event.Measurements != nil && len(event.Measurements) > 0 { for _, measurementEntry := range event.Measurements { for measurementName, measurementValue := range measurementEntry.Values { var ctx = frontendlogging.CtxVector{} ctx = event.AddMetaToContext(ctx) ctx = append(ctx, measurementName, measurementValue) ctx = append(ctx, "kind", "measurement", "original_timestamp", measurementEntry.Timestamp) frontendLogger.Info("Measurement: "+measurementEntry.Type, ctx...) } } } if event.Exceptions != nil && len(event.Exceptions) > 0 { for _, exception := range event.Exceptions { var ctx = frontendlogging.CtxVector{} ctx = event.AddMetaToContext(ctx) exception := exception transformedException := frontendlogging.TransformException(&exception, store) ctx = append(ctx, "kind", "exception", "type", transformedException.Type, "value", transformedException.Value, "stacktrace", transformedException.String()) ctx = append(ctx, "original_timestamp", exception.Timestamp) frontendLogger.Error(exception.Message(), ctx...) } } c.Resp.WriteHeader(http.StatusAccepted) _, err := c.Resp.Write([]byte("OK")) if err != nil { hs.log.Error("could not write to response", "err", err) } } } // setupFrontendLogHandlers will set up handlers for logs incoming from frontend. // handlers are setup even if frontend logging is disabled, but in this case do nothing // this is to avoid reporting errors in case config was changes but there are browser // sessions still open with older config func (hs *HTTPServer) frontendLogEndpoints() web.Handler { if !(hs.Cfg.GrafanaJavascriptAgent.Enabled || hs.Cfg.Sentry.Enabled) { return func(ctx *web.Context) { if ctx.Req.Method == http.MethodPost && (ctx.Req.URL.Path == sentryLogEndpointPath || ctx.Req.URL.Path == grafanaJavascriptAgentEndpointPath) { ctx.Resp.WriteHeader(http.StatusAccepted) _, err := ctx.Resp.Write([]byte("OK")) if err != nil { hs.log.Error("could not write to response", "err", err) } } } } sourceMapStore := frontendlogging.NewSourceMapStore(hs.Cfg, hs.pluginStaticRouteResolver, frontendlogging.ReadSourceMapFromFS) var rateLimiter *rate.Limiter var handler frontendLogMessageHandler handlerEndpoint := "" dummyEndpoint := "" if hs.Cfg.GrafanaJavascriptAgent.Enabled { rateLimiter = rate.NewLimiter(rate.Limit(hs.Cfg.GrafanaJavascriptAgent.EndpointRPS), hs.Cfg.GrafanaJavascriptAgent.EndpointBurst) handler = GrafanaJavascriptAgentLogMessageHandler(sourceMapStore) handlerEndpoint = grafanaJavascriptAgentEndpointPath dummyEndpoint = sentryLogEndpointPath } else { rateLimiter = rate.NewLimiter(rate.Limit(hs.Cfg.Sentry.EndpointRPS), hs.Cfg.Sentry.EndpointBurst) handler = NewFrontendLogMessageHandler(sourceMapStore) handlerEndpoint = sentryLogEndpointPath dummyEndpoint = grafanaJavascriptAgentEndpointPath } return func(ctx *web.Context) { if ctx.Req.Method == http.MethodPost && ctx.Req.URL.Path == dummyEndpoint { ctx.Resp.WriteHeader(http.StatusAccepted) _, err := ctx.Resp.Write([]byte("OK")) if err != nil { hs.log.Error("could not write to response", "err", err) } } if ctx.Req.Method == http.MethodPost && ctx.Req.URL.Path == handlerEndpoint { if !rateLimiter.AllowN(time.Now(), 1) { ctx.Resp.WriteHeader(http.StatusTooManyRequests) return } handler(hs, ctx) } } }
pkg/api/frontend_logging.go
0
https://github.com/grafana/grafana/commit/623de12e354c8f92fd49802a04bafe5970fba0e9
[ 0.00022986147087067366, 0.00017155536625068635, 0.00016452348791062832, 0.00016832229448482394, 0.000013581508937932085 ]
{ "id": 5, "code_window": [ "\t}\n", "}\n", "\n", "// StateTransition describes the transition from one state to another.\n", "type StateTransition struct {\n", "\t*State\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "func (a *State) GetAlertInstanceKey() (models.AlertInstanceKey, error) {\n", "\tinstanceLabels := models.InstanceLabels(a.Labels)\n", "\t_, labelsHash, err := instanceLabels.StringAndHash()\n", "\tif err != nil {\n", "\t\treturn models.AlertInstanceKey{}, err\n", "\t}\n", "\treturn models.AlertInstanceKey{RuleOrgID: a.OrgID, RuleUID: a.AlertRuleUID, LabelsHash: labelsHash}, nil\n", "}\n", "\n" ], "file_path": "pkg/services/ngalert/state/state.go", "type": "add", "edit_start_line_idx": 75 }
import angular from 'angular'; import { GrafanaRootScope } from 'app/angular/GrafanaCtrl'; import coreModule from './core_module'; export class DeltaCtrl { observer: any; /** @ngInject */ constructor() { const waitForCompile = () => {}; this.observer = new MutationObserver(waitForCompile); const observerConfig = { attributes: true, attributeFilter: ['class'], characterData: false, childList: true, subtree: false, }; this.observer.observe(angular.element('.delta-html')[0], observerConfig); } $onDestroy() { this.observer.disconnect(); } } export function delta() { return { controller: DeltaCtrl, replace: false, restrict: 'A', }; } coreModule.directive('diffDelta', delta); // Link to JSON line number export class LinkJSONCtrl { /** @ngInject */ constructor(private $scope: any, private $rootScope: GrafanaRootScope, private $anchorScroll: any) {} goToLine(line: number) { let unbind: () => void; const scroll = () => { this.$anchorScroll(`l${line}`); unbind(); }; this.$scope.switchView().then(() => { unbind = this.$rootScope.$on('json-diff-ready', scroll.bind(this)); }); } } export function linkJson() { return { controller: LinkJSONCtrl, controllerAs: 'ctrl', replace: true, restrict: 'E', scope: { line: '@lineDisplay', link: '@lineLink', switchView: '&', }, template: `<a class="diff-linenum btn btn-inverse btn-small" ng-click="ctrl.goToLine(link)">Line {{ line }}</a>`, }; } coreModule.directive('diffLinkJson', linkJson);
public/app/angular/diff-view.ts
0
https://github.com/grafana/grafana/commit/623de12e354c8f92fd49802a04bafe5970fba0e9
[ 0.00017440174997318536, 0.00017114964430220425, 0.00016799486184027046, 0.00017062136612366885, 0.0000023363404579868075 ]
{ "id": 0, "code_window": [ " */\n", " metadata?: unknown;\n", "\n", " /**\n", " * Time spent updating the program graph, in milliseconds.\n", " */\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " /* @internal */\n", " performanceData?: PerformanceData;\n", " }\n", "\n", " /* @internal */\n", " export interface PerformanceData {\n" ], "file_path": "src/server/protocol.ts", "type": "add", "edit_start_line_idx": 239 }
namespace ts.server { const _chai: typeof import("chai") = require("chai"); const expect: typeof _chai.expect = _chai.expect; let lastWrittenToHost: string; const noopFileWatcher: FileWatcher = { close: noop }; const mockHost: ServerHost = { args: [], newLine: "\n", useCaseSensitiveFileNames: true, write(s): void { lastWrittenToHost = s; }, readFile: returnUndefined, writeFile: noop, resolvePath(): string { return undefined!; }, // TODO: GH#18217 fileExists: () => false, directoryExists: () => false, getDirectories: () => [], createDirectory: noop, getExecutingFilePath(): string { return ""; }, getCurrentDirectory(): string { return ""; }, getEnvironmentVariable(): string { return ""; }, readDirectory() { return []; }, exit: noop, setTimeout() { return 0; }, clearTimeout: noop, setImmediate: () => 0, clearImmediate: noop, createHash: Harness.mockHash, watchFile: () => noopFileWatcher, watchDirectory: () => noopFileWatcher }; class TestSession extends Session { getProjectService() { return this.projectService; } } describe("unittests:: tsserver:: Session:: General functionality", () => { let session: TestSession; let lastSent: protocol.Message; function createSession(): TestSession { const opts: SessionOptions = { host: mockHost, cancellationToken: nullCancellationToken, useSingleInferredProject: false, useInferredProjectPerProjectRoot: false, typingsInstaller: undefined!, // TODO: GH#18217 byteLength: Utils.byteLength, hrtime: process.hrtime, logger: projectSystem.nullLogger, canUseEvents: true }; return new TestSession(opts); } // Disable sourcemap support for the duration of the test, as sourcemapping the errors generated during this test is slow and not something we care to test let oldPrepare: AnyFunction; before(() => { oldPrepare = (Error as any).prepareStackTrace; delete (Error as any).prepareStackTrace; }); after(() => { (Error as any).prepareStackTrace = oldPrepare; }); beforeEach(() => { session = createSession(); session.send = (msg: protocol.Message) => { lastSent = msg; }; }); describe("executeCommand", () => { it("should throw when commands are executed with invalid arguments", () => { const req: protocol.FileRequest = { command: CommandNames.Open, seq: 0, type: "request", arguments: { file: undefined! // TODO: GH#18217 } }; expect(() => session.executeCommand(req)).to.throw(); }); it("should output an error response when a command does not exist", () => { const req: protocol.Request = { command: "foobar", seq: 0, type: "request" }; session.executeCommand(req); const expected: protocol.Response = { command: CommandNames.Unknown, type: "response", seq: 0, message: "Unrecognized JSON command: foobar", request_seq: 0, success: false, updateGraphDurationMs: undefined, }; expect(lastSent).to.deep.equal(expected); }); it("should return a tuple containing the response and if a response is required on success", () => { const req: protocol.ConfigureRequest = { command: CommandNames.Configure, seq: 0, type: "request", arguments: { hostInfo: "unit test", formatOptions: { newLineCharacter: "`n" } } }; expect(session.executeCommand(req)).to.deep.equal({ responseRequired: false }); expect(lastSent).to.deep.equal({ command: CommandNames.Configure, type: "response", success: true, request_seq: 0, seq: 0, body: undefined, updateGraphDurationMs: undefined, }); }); it("should handle literal types in request", () => { const configureRequest: protocol.ConfigureRequest = { command: CommandNames.Configure, seq: 0, type: "request", arguments: { formatOptions: { indentStyle: protocol.IndentStyle.Block, } } }; session.onMessage(JSON.stringify(configureRequest)); assert.equal(session.getProjectService().getFormatCodeOptions("" as NormalizedPath).indentStyle, IndentStyle.Block); const setOptionsRequest: protocol.SetCompilerOptionsForInferredProjectsRequest = { command: CommandNames.CompilerOptionsForInferredProjects, seq: 1, type: "request", arguments: { options: { module: protocol.ModuleKind.System, target: protocol.ScriptTarget.ES5, jsx: protocol.JsxEmit.React, newLine: protocol.NewLineKind.Lf, moduleResolution: protocol.ModuleResolutionKind.Node, } } }; session.onMessage(JSON.stringify(setOptionsRequest)); assert.deepEqual( session.getProjectService().getCompilerOptionsForInferredProjects(), <CompilerOptions>{ module: ModuleKind.System, target: ScriptTarget.ES5, jsx: JsxEmit.React, newLine: NewLineKind.LineFeed, moduleResolution: ModuleResolutionKind.NodeJs, allowNonTsExtensions: true // injected by tsserver }); }); it("Status request gives ts.version", () => { const req: protocol.StatusRequest = { command: CommandNames.Status, seq: 0, type: "request" }; const expected: protocol.StatusResponseBody = { version: ts.version, // eslint-disable-line @typescript-eslint/no-unnecessary-qualifier }; assert.deepEqual(session.executeCommand(req).response, expected); }); }); describe("onMessage", () => { const allCommandNames: CommandNames[] = [ CommandNames.Brace, CommandNames.BraceFull, CommandNames.BraceCompletion, CommandNames.Change, CommandNames.Close, CommandNames.Completions, CommandNames.CompletionsFull, CommandNames.CompletionDetails, CommandNames.CompileOnSaveAffectedFileList, CommandNames.Configure, CommandNames.Definition, CommandNames.DefinitionFull, CommandNames.DefinitionAndBoundSpan, CommandNames.DefinitionAndBoundSpanFull, CommandNames.Implementation, CommandNames.ImplementationFull, CommandNames.Exit, CommandNames.Format, CommandNames.Formatonkey, CommandNames.FormatFull, CommandNames.FormatonkeyFull, CommandNames.FormatRangeFull, CommandNames.Geterr, CommandNames.GeterrForProject, CommandNames.SemanticDiagnosticsSync, CommandNames.SyntacticDiagnosticsSync, CommandNames.SuggestionDiagnosticsSync, CommandNames.NavBar, CommandNames.NavBarFull, CommandNames.Navto, CommandNames.NavtoFull, CommandNames.NavTree, CommandNames.NavTreeFull, CommandNames.Occurrences, CommandNames.DocumentHighlights, CommandNames.DocumentHighlightsFull, CommandNames.JsxClosingTag, CommandNames.Open, CommandNames.Quickinfo, CommandNames.QuickinfoFull, CommandNames.References, CommandNames.ReferencesFull, CommandNames.Reload, CommandNames.Rename, CommandNames.RenameInfoFull, CommandNames.RenameLocationsFull, CommandNames.Saveto, CommandNames.SignatureHelp, CommandNames.SignatureHelpFull, CommandNames.Status, CommandNames.TypeDefinition, CommandNames.ProjectInfo, CommandNames.ReloadProjects, CommandNames.Unknown, CommandNames.OpenExternalProject, CommandNames.CloseExternalProject, CommandNames.SynchronizeProjectList, CommandNames.ApplyChangedToOpenFiles, CommandNames.EncodedSemanticClassificationsFull, CommandNames.Cleanup, CommandNames.OutliningSpans, CommandNames.TodoComments, CommandNames.Indentation, CommandNames.DocCommentTemplate, CommandNames.CompilerOptionsDiagnosticsFull, CommandNames.NameOrDottedNameSpan, CommandNames.BreakpointStatement, CommandNames.CompilerOptionsForInferredProjects, CommandNames.GetCodeFixes, CommandNames.GetCodeFixesFull, CommandNames.GetSupportedCodeFixes, CommandNames.GetApplicableRefactors, CommandNames.GetEditsForRefactor, CommandNames.GetEditsForRefactorFull, CommandNames.OrganizeImports, CommandNames.OrganizeImportsFull, CommandNames.GetEditsForFileRename, CommandNames.GetEditsForFileRenameFull, CommandNames.SelectionRange, CommandNames.PrepareCallHierarchy, CommandNames.ProvideCallHierarchyIncomingCalls, CommandNames.ProvideCallHierarchyOutgoingCalls, ]; it("should not throw when commands are executed with invalid arguments", () => { let i = 0; for (const name of allCommandNames) { const req: protocol.Request = { command: name, seq: i, type: "request" }; i++; session.onMessage(JSON.stringify(req)); req.seq = i; i++; req.arguments = {}; session.onMessage(JSON.stringify(req)); req.seq = i; i++; req.arguments = null; // eslint-disable-line no-null/no-null session.onMessage(JSON.stringify(req)); req.seq = i; i++; req.arguments = ""; session.onMessage(JSON.stringify(req)); req.seq = i; i++; req.arguments = 0; session.onMessage(JSON.stringify(req)); req.seq = i; i++; req.arguments = []; session.onMessage(JSON.stringify(req)); } session.onMessage("GARBAGE NON_JSON DATA"); }); it("should output the response for a correctly handled message", () => { const req: protocol.ConfigureRequest = { command: CommandNames.Configure, seq: 0, type: "request", arguments: { hostInfo: "unit test", formatOptions: { newLineCharacter: "`n" } } }; session.onMessage(JSON.stringify(req)); expect(lastSent).to.deep.equal(<protocol.ConfigureResponse>{ command: CommandNames.Configure, type: "response", success: true, request_seq: 0, seq: 0, body: undefined, updateGraphDurationMs: undefined, }); }); }); describe("send", () => { it("is an overrideable handle which sends protocol messages over the wire", () => { const msg: protocol.Request = { seq: 0, type: "request", command: "" }; const strmsg = JSON.stringify(msg); const len = 1 + Utils.byteLength(strmsg, "utf8"); const resultMsg = `Content-Length: ${len}\r\n\r\n${strmsg}\n`; session.send = Session.prototype.send; assert(session.send); expect(session.send(msg)).to.not.exist; // eslint-disable-line no-unused-expressions expect(lastWrittenToHost).to.equal(resultMsg); }); }); describe("addProtocolHandler", () => { it("can add protocol handlers", () => { const respBody = { item: false }; const command = "newhandle"; const result: HandlerResponse = { response: respBody, responseRequired: true }; session.addProtocolHandler(command, () => result); expect(session.executeCommand({ command, seq: 0, type: "request" })).to.deep.equal(result); }); it("throws when a duplicate handler is passed", () => { const respBody = { item: false }; const resp: HandlerResponse = { response: respBody, responseRequired: true }; const command = "newhandle"; session.addProtocolHandler(command, () => resp); expect(() => session.addProtocolHandler(command, () => resp)) .to.throw(`Protocol handler already exists for command "${command}"`); }); }); describe("event", () => { it("can format event responses and send them", () => { const evt = "notify-test"; const info = { test: true }; session.event(info, evt); expect(lastSent).to.deep.equal({ type: "event", seq: 0, event: evt, body: info }); }); }); describe("output", () => { it("can format command responses and send them", () => { const body = { block: { key: "value" } }; const command = "test"; session.output(body, command, /*reqSeq*/ 0); expect(lastSent).to.deep.equal({ seq: 0, request_seq: 0, type: "response", command, body, success: true, updateGraphDurationMs: undefined, }); }); }); }); describe("unittests:: tsserver:: Session:: exceptions", () => { // Disable sourcemap support for the duration of the test, as sourcemapping the errors generated during this test is slow and not something we care to test let oldPrepare: AnyFunction; let oldStackTraceLimit: number; before(() => { oldStackTraceLimit = (Error as any).stackTraceLimit; oldPrepare = (Error as any).prepareStackTrace; delete (Error as any).prepareStackTrace; (Error as any).stackTraceLimit = 10; }); after(() => { (Error as any).prepareStackTrace = oldPrepare; (Error as any).stackTraceLimit = oldStackTraceLimit; }); const command = "testhandler"; class TestSession extends Session { lastSent: protocol.Message | undefined; private exceptionRaisingHandler(_request: protocol.Request): { response?: any, responseRequired: boolean } { f1(); return Debug.fail(); // unreachable, throw to make compiler happy function f1() { throw new Error("myMessage"); } } constructor() { super({ host: mockHost, cancellationToken: nullCancellationToken, useSingleInferredProject: false, useInferredProjectPerProjectRoot: false, typingsInstaller: undefined!, // TODO: GH#18217 byteLength: Utils.byteLength, hrtime: process.hrtime, logger: projectSystem.nullLogger, canUseEvents: true }); this.addProtocolHandler(command, this.exceptionRaisingHandler); } send(msg: protocol.Message) { this.lastSent = msg; } } it("raised in a protocol handler generate an event", () => { const session = new TestSession(); const request = { command, seq: 0, type: "request" }; session.onMessage(JSON.stringify(request)); const lastSent = session.lastSent as protocol.Response; expect(lastSent).to.contain({ seq: 0, type: "response", command, success: false }); expect(lastSent.message).has.string("myMessage").and.has.string("f1"); }); }); describe("unittests:: tsserver:: Session:: how Session is extendable via subclassing", () => { class TestSession extends Session { lastSent: protocol.Message | undefined; customHandler = "testhandler"; constructor() { super({ host: mockHost, cancellationToken: nullCancellationToken, useSingleInferredProject: false, useInferredProjectPerProjectRoot: false, typingsInstaller: undefined!, // TODO: GH#18217 byteLength: Utils.byteLength, hrtime: process.hrtime, logger: projectSystem.createHasErrorMessageLogger().logger, canUseEvents: true }); this.addProtocolHandler(this.customHandler, () => { return { response: undefined, responseRequired: true }; }); } send(msg: protocol.Message) { this.lastSent = msg; } } it("can override methods such as send", () => { const session = new TestSession(); const body = { block: { key: "value" } }; const command = "test"; session.output(body, command, /*reqSeq*/ 0); expect(session.lastSent).to.deep.equal({ seq: 0, request_seq: 0, type: "response", command, body, success: true, updateGraphDurationMs: undefined, }); }); it("can add and respond to new protocol handlers", () => { const session = new TestSession(); expect(session.executeCommand({ seq: 0, type: "request", command: session.customHandler })).to.deep.equal({ response: undefined, responseRequired: true }); }); it("has access to the project service", () => { new class extends TestSession { constructor() { super(); assert(this.projectService); expect(this.projectService).to.be.instanceOf(ProjectService); } }(); }); }); describe("unittests:: tsserver:: Session:: an example of using the Session API to create an in-process server", () => { class InProcSession extends Session { private queue: protocol.Request[] = []; constructor(private client: InProcClient) { super({ host: mockHost, cancellationToken: nullCancellationToken, useSingleInferredProject: false, useInferredProjectPerProjectRoot: false, typingsInstaller: undefined!, // TODO: GH#18217 byteLength: Utils.byteLength, hrtime: process.hrtime, logger: projectSystem.createHasErrorMessageLogger().logger, canUseEvents: true }); this.addProtocolHandler("echo", (req: protocol.Request) => ({ response: req.arguments, responseRequired: true })); } send(msg: protocol.Message) { this.client.handle(msg); } enqueue(msg: protocol.Request) { this.queue.unshift(msg); } handleRequest(msg: protocol.Request) { let response: protocol.Response; try { response = this.executeCommand(msg).response as protocol.Response; } catch (e) { this.output(undefined, msg.command, msg.seq, e.toString()); return; } if (response) { this.output(response, msg.command, msg.seq); } } consumeQueue() { while (this.queue.length > 0) { const elem = this.queue.pop()!; this.handleRequest(elem); } } } class InProcClient { private server: InProcSession | undefined; private seq = 0; private callbacks: ((resp: protocol.Response) => void)[] = []; private eventHandlers = createMap<(args: any) => void>(); handle(msg: protocol.Message): void { if (msg.type === "response") { const response = <protocol.Response>msg; const handler = this.callbacks[response.request_seq]; if (handler) { handler(response); delete this.callbacks[response.request_seq]; } } else if (msg.type === "event") { const event = <protocol.Event>msg; this.emit(event.event, event.body); } } emit(name: string, args: any): void { const handler = this.eventHandlers.get(name); if (handler) { handler(args); } } on(name: string, handler: (args: any) => void): void { this.eventHandlers.set(name, handler); } connect(session: InProcSession): void { this.server = session; } execute(command: string, args: any, callback: (resp: protocol.Response) => void): void { if (!this.server) { return; } this.seq++; this.server.enqueue({ seq: this.seq, type: "request", command, arguments: args }); this.callbacks[this.seq] = callback; } } it("can be constructed and respond to commands", (done) => { const cli = new InProcClient(); const session = new InProcSession(cli); const toEcho = { data: true }; const toEvent = { data: false }; let responses = 0; // Connect the client cli.connect(session); // Add an event handler cli.on("testevent", (eventinfo) => { expect(eventinfo).to.equal(toEvent); responses++; expect(responses).to.equal(1); }); // Trigger said event from the server session.event(toEvent, "testevent"); // Queue an echo command cli.execute("echo", toEcho, (resp) => { assert(resp.success, resp.message); responses++; expect(responses).to.equal(2); expect(resp.body).to.deep.equal(toEcho); }); // Queue a configure command cli.execute("configure", { hostInfo: "unit test", formatOptions: { newLineCharacter: "`n" } }, (resp) => { assert(resp.success, resp.message); responses++; expect(responses).to.equal(3); done(); }); // Consume the queue and trigger the callbacks session.consumeQueue(); }); }); describe("unittests:: tsserver:: Session:: helpers", () => { it(getLocationInNewDocument.name, () => { const text = `// blank line\nconst x = 0;`; const renameLocationInOldText = text.indexOf("0"); const fileName = "/a.ts"; const edits: FileTextChanges = { fileName, textChanges: [ { span: { start: 0, length: 0 }, newText: "const newLocal = 0;\n\n", }, { span: { start: renameLocationInOldText, length: 1 }, newText: "newLocal", }, ], }; const renameLocationInNewText = renameLocationInOldText + edits.textChanges[0].newText.length; const res = getLocationInNewDocument(text, fileName, renameLocationInNewText, [edits]); assert.deepEqual(res, { line: 4, offset: 11 }); }); }); }
src/testRunner/unittests/tsserver/session.ts
1
https://github.com/microsoft/TypeScript/commit/f99072593dc130e0073762d3071aa64882be0823
[ 0.000174016720848158, 0.00016837056318763644, 0.00016315326502081007, 0.00016814358241390437, 0.0000017967745407077018 ]
{ "id": 0, "code_window": [ " */\n", " metadata?: unknown;\n", "\n", " /**\n", " * Time spent updating the program graph, in milliseconds.\n", " */\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " /* @internal */\n", " performanceData?: PerformanceData;\n", " }\n", "\n", " /* @internal */\n", " export interface PerformanceData {\n" ], "file_path": "src/server/protocol.ts", "type": "add", "edit_start_line_idx": 239 }
// @target: es2017 export async function get(): Promise<[]> { let emails = []; return emails; }
tests/cases/compiler/promiseEmptyTupleNoException.ts
0
https://github.com/microsoft/TypeScript/commit/f99072593dc130e0073762d3071aa64882be0823
[ 0.00017252615361940116, 0.00017252615361940116, 0.00017252615361940116, 0.00017252615361940116, 0 ]
{ "id": 0, "code_window": [ " */\n", " metadata?: unknown;\n", "\n", " /**\n", " * Time spent updating the program graph, in milliseconds.\n", " */\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " /* @internal */\n", " performanceData?: PerformanceData;\n", " }\n", "\n", " /* @internal */\n", " export interface PerformanceData {\n" ], "file_path": "src/server/protocol.ts", "type": "add", "edit_start_line_idx": 239 }
tests/cases/conformance/salsa/bug24934.js(2,1): error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node`. ==== tests/cases/conformance/salsa/bug24934.js (1 errors) ==== export function abc(a, b, c) { return 5; } module.exports = { abc }; ~~~~~~ !!! error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node`. ==== tests/cases/conformance/salsa/use.js (0 errors) ==== import { abc } from './bug24934'; abc(1, 2, 3);
tests/baselines/reference/conflictingCommonJSES2015Exports.errors.txt
0
https://github.com/microsoft/TypeScript/commit/f99072593dc130e0073762d3071aa64882be0823
[ 0.00017476300126872957, 0.00017329154070466757, 0.00017182006558869034, 0.00017329154070466757, 0.0000014714678400196135 ]
{ "id": 0, "code_window": [ " */\n", " metadata?: unknown;\n", "\n", " /**\n", " * Time spent updating the program graph, in milliseconds.\n", " */\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " /* @internal */\n", " performanceData?: PerformanceData;\n", " }\n", "\n", " /* @internal */\n", " export interface PerformanceData {\n" ], "file_path": "src/server/protocol.ts", "type": "add", "edit_start_line_idx": 239 }
=== tests/cases/conformance/es6/modules/t1.ts === var v = 1; >v : Symbol(v, Decl(t1.ts, 0, 3)) function f() { } >f : Symbol(f, Decl(t1.ts, 0, 10)) class C { >C : Symbol(C, Decl(t1.ts, 1, 16)) } interface I { >I : Symbol(I, Decl(t1.ts, 3, 1)) } enum E { >E : Symbol(E, Decl(t1.ts, 5, 1)) A, B, C >A : Symbol(E.A, Decl(t1.ts, 6, 8)) >B : Symbol(E.B, Decl(t1.ts, 7, 6)) >C : Symbol(E.C, Decl(t1.ts, 7, 9)) } const enum D { >D : Symbol(D, Decl(t1.ts, 8, 1)) A, B, C >A : Symbol(D.A, Decl(t1.ts, 9, 14)) >B : Symbol(D.B, Decl(t1.ts, 10, 6)) >C : Symbol(D.C, Decl(t1.ts, 10, 9)) } module M { >M : Symbol(M, Decl(t1.ts, 11, 1)) export var x; >x : Symbol(x, Decl(t1.ts, 13, 14)) } module N { >N : Symbol(N, Decl(t1.ts, 14, 1)) export interface I { >I : Symbol(I, Decl(t1.ts, 15, 10)) } } type T = number; >T : Symbol(T, Decl(t1.ts, 18, 1)) import a = M.x; >a : Symbol(a, Decl(t1.ts, 19, 16)) >M : Symbol(M, Decl(t1.ts, 11, 1)) >x : Symbol(a, Decl(t1.ts, 13, 14)) export { v, f, C, I, E, D, M, N, T, a }; >v : Symbol(v, Decl(t1.ts, 22, 8)) >f : Symbol(f, Decl(t1.ts, 22, 11)) >C : Symbol(C, Decl(t1.ts, 22, 14)) >I : Symbol(I, Decl(t1.ts, 22, 17)) >E : Symbol(E, Decl(t1.ts, 22, 20)) >D : Symbol(D, Decl(t1.ts, 22, 23)) >M : Symbol(M, Decl(t1.ts, 22, 26)) >N : Symbol(N, Decl(t1.ts, 22, 29)) >T : Symbol(T, Decl(t1.ts, 22, 32)) >a : Symbol(a, Decl(t1.ts, 22, 35)) === tests/cases/conformance/es6/modules/t2.ts === export { v, f, C, I, E, D, M, N, T, a } from "./t1"; >v : Symbol(v, Decl(t2.ts, 0, 8)) >f : Symbol(f, Decl(t2.ts, 0, 11)) >C : Symbol(C, Decl(t2.ts, 0, 14)) >I : Symbol(I, Decl(t2.ts, 0, 17)) >E : Symbol(E, Decl(t2.ts, 0, 20)) >D : Symbol(D, Decl(t2.ts, 0, 23)) >M : Symbol(M, Decl(t2.ts, 0, 26)) >N : Symbol(N, Decl(t2.ts, 0, 29)) >T : Symbol(T, Decl(t2.ts, 0, 32)) >a : Symbol(a, Decl(t2.ts, 0, 35)) === tests/cases/conformance/es6/modules/t3.ts === import { v, f, C, I, E, D, M, N, T, a } from "./t1"; >v : Symbol(v, Decl(t3.ts, 0, 8)) >f : Symbol(f, Decl(t3.ts, 0, 11)) >C : Symbol(C, Decl(t3.ts, 0, 14)) >I : Symbol(I, Decl(t3.ts, 0, 17)) >E : Symbol(E, Decl(t3.ts, 0, 20)) >D : Symbol(D, Decl(t3.ts, 0, 23)) >M : Symbol(M, Decl(t3.ts, 0, 26)) >N : Symbol(N, Decl(t3.ts, 0, 29)) >T : Symbol(T, Decl(t3.ts, 0, 32)) >a : Symbol(a, Decl(t3.ts, 0, 35)) export { v, f, C, I, E, D, M, N, T, a }; >v : Symbol(v, Decl(t3.ts, 1, 8)) >f : Symbol(f, Decl(t3.ts, 1, 11)) >C : Symbol(C, Decl(t3.ts, 1, 14)) >I : Symbol(I, Decl(t3.ts, 1, 17)) >E : Symbol(E, Decl(t3.ts, 1, 20)) >D : Symbol(D, Decl(t3.ts, 1, 23)) >M : Symbol(M, Decl(t3.ts, 1, 26)) >N : Symbol(N, Decl(t3.ts, 1, 29)) >T : Symbol(T, Decl(t3.ts, 1, 32)) >a : Symbol(a, Decl(t3.ts, 1, 35))
tests/baselines/reference/exportsAndImports1-amd.symbols
0
https://github.com/microsoft/TypeScript/commit/f99072593dc130e0073762d3071aa64882be0823
[ 0.00017629237845540047, 0.00017289561219513416, 0.00016711170610506088, 0.00017367640975862741, 0.000002668316710696672 ]
{ "id": 1, "code_window": [ " /**\n", " * Time spent updating the program graph, in milliseconds.\n", " */\n", " /* @internal */\n", " updateGraphDurationMs?: number;\n", " }\n", "\n", " /**\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/server/protocol.ts", "type": "replace", "edit_start_line_idx": 242 }
namespace ts.server { const _chai: typeof import("chai") = require("chai"); const expect: typeof _chai.expect = _chai.expect; let lastWrittenToHost: string; const noopFileWatcher: FileWatcher = { close: noop }; const mockHost: ServerHost = { args: [], newLine: "\n", useCaseSensitiveFileNames: true, write(s): void { lastWrittenToHost = s; }, readFile: returnUndefined, writeFile: noop, resolvePath(): string { return undefined!; }, // TODO: GH#18217 fileExists: () => false, directoryExists: () => false, getDirectories: () => [], createDirectory: noop, getExecutingFilePath(): string { return ""; }, getCurrentDirectory(): string { return ""; }, getEnvironmentVariable(): string { return ""; }, readDirectory() { return []; }, exit: noop, setTimeout() { return 0; }, clearTimeout: noop, setImmediate: () => 0, clearImmediate: noop, createHash: Harness.mockHash, watchFile: () => noopFileWatcher, watchDirectory: () => noopFileWatcher }; class TestSession extends Session { getProjectService() { return this.projectService; } } describe("unittests:: tsserver:: Session:: General functionality", () => { let session: TestSession; let lastSent: protocol.Message; function createSession(): TestSession { const opts: SessionOptions = { host: mockHost, cancellationToken: nullCancellationToken, useSingleInferredProject: false, useInferredProjectPerProjectRoot: false, typingsInstaller: undefined!, // TODO: GH#18217 byteLength: Utils.byteLength, hrtime: process.hrtime, logger: projectSystem.nullLogger, canUseEvents: true }; return new TestSession(opts); } // Disable sourcemap support for the duration of the test, as sourcemapping the errors generated during this test is slow and not something we care to test let oldPrepare: AnyFunction; before(() => { oldPrepare = (Error as any).prepareStackTrace; delete (Error as any).prepareStackTrace; }); after(() => { (Error as any).prepareStackTrace = oldPrepare; }); beforeEach(() => { session = createSession(); session.send = (msg: protocol.Message) => { lastSent = msg; }; }); describe("executeCommand", () => { it("should throw when commands are executed with invalid arguments", () => { const req: protocol.FileRequest = { command: CommandNames.Open, seq: 0, type: "request", arguments: { file: undefined! // TODO: GH#18217 } }; expect(() => session.executeCommand(req)).to.throw(); }); it("should output an error response when a command does not exist", () => { const req: protocol.Request = { command: "foobar", seq: 0, type: "request" }; session.executeCommand(req); const expected: protocol.Response = { command: CommandNames.Unknown, type: "response", seq: 0, message: "Unrecognized JSON command: foobar", request_seq: 0, success: false, updateGraphDurationMs: undefined, }; expect(lastSent).to.deep.equal(expected); }); it("should return a tuple containing the response and if a response is required on success", () => { const req: protocol.ConfigureRequest = { command: CommandNames.Configure, seq: 0, type: "request", arguments: { hostInfo: "unit test", formatOptions: { newLineCharacter: "`n" } } }; expect(session.executeCommand(req)).to.deep.equal({ responseRequired: false }); expect(lastSent).to.deep.equal({ command: CommandNames.Configure, type: "response", success: true, request_seq: 0, seq: 0, body: undefined, updateGraphDurationMs: undefined, }); }); it("should handle literal types in request", () => { const configureRequest: protocol.ConfigureRequest = { command: CommandNames.Configure, seq: 0, type: "request", arguments: { formatOptions: { indentStyle: protocol.IndentStyle.Block, } } }; session.onMessage(JSON.stringify(configureRequest)); assert.equal(session.getProjectService().getFormatCodeOptions("" as NormalizedPath).indentStyle, IndentStyle.Block); const setOptionsRequest: protocol.SetCompilerOptionsForInferredProjectsRequest = { command: CommandNames.CompilerOptionsForInferredProjects, seq: 1, type: "request", arguments: { options: { module: protocol.ModuleKind.System, target: protocol.ScriptTarget.ES5, jsx: protocol.JsxEmit.React, newLine: protocol.NewLineKind.Lf, moduleResolution: protocol.ModuleResolutionKind.Node, } } }; session.onMessage(JSON.stringify(setOptionsRequest)); assert.deepEqual( session.getProjectService().getCompilerOptionsForInferredProjects(), <CompilerOptions>{ module: ModuleKind.System, target: ScriptTarget.ES5, jsx: JsxEmit.React, newLine: NewLineKind.LineFeed, moduleResolution: ModuleResolutionKind.NodeJs, allowNonTsExtensions: true // injected by tsserver }); }); it("Status request gives ts.version", () => { const req: protocol.StatusRequest = { command: CommandNames.Status, seq: 0, type: "request" }; const expected: protocol.StatusResponseBody = { version: ts.version, // eslint-disable-line @typescript-eslint/no-unnecessary-qualifier }; assert.deepEqual(session.executeCommand(req).response, expected); }); }); describe("onMessage", () => { const allCommandNames: CommandNames[] = [ CommandNames.Brace, CommandNames.BraceFull, CommandNames.BraceCompletion, CommandNames.Change, CommandNames.Close, CommandNames.Completions, CommandNames.CompletionsFull, CommandNames.CompletionDetails, CommandNames.CompileOnSaveAffectedFileList, CommandNames.Configure, CommandNames.Definition, CommandNames.DefinitionFull, CommandNames.DefinitionAndBoundSpan, CommandNames.DefinitionAndBoundSpanFull, CommandNames.Implementation, CommandNames.ImplementationFull, CommandNames.Exit, CommandNames.Format, CommandNames.Formatonkey, CommandNames.FormatFull, CommandNames.FormatonkeyFull, CommandNames.FormatRangeFull, CommandNames.Geterr, CommandNames.GeterrForProject, CommandNames.SemanticDiagnosticsSync, CommandNames.SyntacticDiagnosticsSync, CommandNames.SuggestionDiagnosticsSync, CommandNames.NavBar, CommandNames.NavBarFull, CommandNames.Navto, CommandNames.NavtoFull, CommandNames.NavTree, CommandNames.NavTreeFull, CommandNames.Occurrences, CommandNames.DocumentHighlights, CommandNames.DocumentHighlightsFull, CommandNames.JsxClosingTag, CommandNames.Open, CommandNames.Quickinfo, CommandNames.QuickinfoFull, CommandNames.References, CommandNames.ReferencesFull, CommandNames.Reload, CommandNames.Rename, CommandNames.RenameInfoFull, CommandNames.RenameLocationsFull, CommandNames.Saveto, CommandNames.SignatureHelp, CommandNames.SignatureHelpFull, CommandNames.Status, CommandNames.TypeDefinition, CommandNames.ProjectInfo, CommandNames.ReloadProjects, CommandNames.Unknown, CommandNames.OpenExternalProject, CommandNames.CloseExternalProject, CommandNames.SynchronizeProjectList, CommandNames.ApplyChangedToOpenFiles, CommandNames.EncodedSemanticClassificationsFull, CommandNames.Cleanup, CommandNames.OutliningSpans, CommandNames.TodoComments, CommandNames.Indentation, CommandNames.DocCommentTemplate, CommandNames.CompilerOptionsDiagnosticsFull, CommandNames.NameOrDottedNameSpan, CommandNames.BreakpointStatement, CommandNames.CompilerOptionsForInferredProjects, CommandNames.GetCodeFixes, CommandNames.GetCodeFixesFull, CommandNames.GetSupportedCodeFixes, CommandNames.GetApplicableRefactors, CommandNames.GetEditsForRefactor, CommandNames.GetEditsForRefactorFull, CommandNames.OrganizeImports, CommandNames.OrganizeImportsFull, CommandNames.GetEditsForFileRename, CommandNames.GetEditsForFileRenameFull, CommandNames.SelectionRange, CommandNames.PrepareCallHierarchy, CommandNames.ProvideCallHierarchyIncomingCalls, CommandNames.ProvideCallHierarchyOutgoingCalls, ]; it("should not throw when commands are executed with invalid arguments", () => { let i = 0; for (const name of allCommandNames) { const req: protocol.Request = { command: name, seq: i, type: "request" }; i++; session.onMessage(JSON.stringify(req)); req.seq = i; i++; req.arguments = {}; session.onMessage(JSON.stringify(req)); req.seq = i; i++; req.arguments = null; // eslint-disable-line no-null/no-null session.onMessage(JSON.stringify(req)); req.seq = i; i++; req.arguments = ""; session.onMessage(JSON.stringify(req)); req.seq = i; i++; req.arguments = 0; session.onMessage(JSON.stringify(req)); req.seq = i; i++; req.arguments = []; session.onMessage(JSON.stringify(req)); } session.onMessage("GARBAGE NON_JSON DATA"); }); it("should output the response for a correctly handled message", () => { const req: protocol.ConfigureRequest = { command: CommandNames.Configure, seq: 0, type: "request", arguments: { hostInfo: "unit test", formatOptions: { newLineCharacter: "`n" } } }; session.onMessage(JSON.stringify(req)); expect(lastSent).to.deep.equal(<protocol.ConfigureResponse>{ command: CommandNames.Configure, type: "response", success: true, request_seq: 0, seq: 0, body: undefined, updateGraphDurationMs: undefined, }); }); }); describe("send", () => { it("is an overrideable handle which sends protocol messages over the wire", () => { const msg: protocol.Request = { seq: 0, type: "request", command: "" }; const strmsg = JSON.stringify(msg); const len = 1 + Utils.byteLength(strmsg, "utf8"); const resultMsg = `Content-Length: ${len}\r\n\r\n${strmsg}\n`; session.send = Session.prototype.send; assert(session.send); expect(session.send(msg)).to.not.exist; // eslint-disable-line no-unused-expressions expect(lastWrittenToHost).to.equal(resultMsg); }); }); describe("addProtocolHandler", () => { it("can add protocol handlers", () => { const respBody = { item: false }; const command = "newhandle"; const result: HandlerResponse = { response: respBody, responseRequired: true }; session.addProtocolHandler(command, () => result); expect(session.executeCommand({ command, seq: 0, type: "request" })).to.deep.equal(result); }); it("throws when a duplicate handler is passed", () => { const respBody = { item: false }; const resp: HandlerResponse = { response: respBody, responseRequired: true }; const command = "newhandle"; session.addProtocolHandler(command, () => resp); expect(() => session.addProtocolHandler(command, () => resp)) .to.throw(`Protocol handler already exists for command "${command}"`); }); }); describe("event", () => { it("can format event responses and send them", () => { const evt = "notify-test"; const info = { test: true }; session.event(info, evt); expect(lastSent).to.deep.equal({ type: "event", seq: 0, event: evt, body: info }); }); }); describe("output", () => { it("can format command responses and send them", () => { const body = { block: { key: "value" } }; const command = "test"; session.output(body, command, /*reqSeq*/ 0); expect(lastSent).to.deep.equal({ seq: 0, request_seq: 0, type: "response", command, body, success: true, updateGraphDurationMs: undefined, }); }); }); }); describe("unittests:: tsserver:: Session:: exceptions", () => { // Disable sourcemap support for the duration of the test, as sourcemapping the errors generated during this test is slow and not something we care to test let oldPrepare: AnyFunction; let oldStackTraceLimit: number; before(() => { oldStackTraceLimit = (Error as any).stackTraceLimit; oldPrepare = (Error as any).prepareStackTrace; delete (Error as any).prepareStackTrace; (Error as any).stackTraceLimit = 10; }); after(() => { (Error as any).prepareStackTrace = oldPrepare; (Error as any).stackTraceLimit = oldStackTraceLimit; }); const command = "testhandler"; class TestSession extends Session { lastSent: protocol.Message | undefined; private exceptionRaisingHandler(_request: protocol.Request): { response?: any, responseRequired: boolean } { f1(); return Debug.fail(); // unreachable, throw to make compiler happy function f1() { throw new Error("myMessage"); } } constructor() { super({ host: mockHost, cancellationToken: nullCancellationToken, useSingleInferredProject: false, useInferredProjectPerProjectRoot: false, typingsInstaller: undefined!, // TODO: GH#18217 byteLength: Utils.byteLength, hrtime: process.hrtime, logger: projectSystem.nullLogger, canUseEvents: true }); this.addProtocolHandler(command, this.exceptionRaisingHandler); } send(msg: protocol.Message) { this.lastSent = msg; } } it("raised in a protocol handler generate an event", () => { const session = new TestSession(); const request = { command, seq: 0, type: "request" }; session.onMessage(JSON.stringify(request)); const lastSent = session.lastSent as protocol.Response; expect(lastSent).to.contain({ seq: 0, type: "response", command, success: false }); expect(lastSent.message).has.string("myMessage").and.has.string("f1"); }); }); describe("unittests:: tsserver:: Session:: how Session is extendable via subclassing", () => { class TestSession extends Session { lastSent: protocol.Message | undefined; customHandler = "testhandler"; constructor() { super({ host: mockHost, cancellationToken: nullCancellationToken, useSingleInferredProject: false, useInferredProjectPerProjectRoot: false, typingsInstaller: undefined!, // TODO: GH#18217 byteLength: Utils.byteLength, hrtime: process.hrtime, logger: projectSystem.createHasErrorMessageLogger().logger, canUseEvents: true }); this.addProtocolHandler(this.customHandler, () => { return { response: undefined, responseRequired: true }; }); } send(msg: protocol.Message) { this.lastSent = msg; } } it("can override methods such as send", () => { const session = new TestSession(); const body = { block: { key: "value" } }; const command = "test"; session.output(body, command, /*reqSeq*/ 0); expect(session.lastSent).to.deep.equal({ seq: 0, request_seq: 0, type: "response", command, body, success: true, updateGraphDurationMs: undefined, }); }); it("can add and respond to new protocol handlers", () => { const session = new TestSession(); expect(session.executeCommand({ seq: 0, type: "request", command: session.customHandler })).to.deep.equal({ response: undefined, responseRequired: true }); }); it("has access to the project service", () => { new class extends TestSession { constructor() { super(); assert(this.projectService); expect(this.projectService).to.be.instanceOf(ProjectService); } }(); }); }); describe("unittests:: tsserver:: Session:: an example of using the Session API to create an in-process server", () => { class InProcSession extends Session { private queue: protocol.Request[] = []; constructor(private client: InProcClient) { super({ host: mockHost, cancellationToken: nullCancellationToken, useSingleInferredProject: false, useInferredProjectPerProjectRoot: false, typingsInstaller: undefined!, // TODO: GH#18217 byteLength: Utils.byteLength, hrtime: process.hrtime, logger: projectSystem.createHasErrorMessageLogger().logger, canUseEvents: true }); this.addProtocolHandler("echo", (req: protocol.Request) => ({ response: req.arguments, responseRequired: true })); } send(msg: protocol.Message) { this.client.handle(msg); } enqueue(msg: protocol.Request) { this.queue.unshift(msg); } handleRequest(msg: protocol.Request) { let response: protocol.Response; try { response = this.executeCommand(msg).response as protocol.Response; } catch (e) { this.output(undefined, msg.command, msg.seq, e.toString()); return; } if (response) { this.output(response, msg.command, msg.seq); } } consumeQueue() { while (this.queue.length > 0) { const elem = this.queue.pop()!; this.handleRequest(elem); } } } class InProcClient { private server: InProcSession | undefined; private seq = 0; private callbacks: ((resp: protocol.Response) => void)[] = []; private eventHandlers = createMap<(args: any) => void>(); handle(msg: protocol.Message): void { if (msg.type === "response") { const response = <protocol.Response>msg; const handler = this.callbacks[response.request_seq]; if (handler) { handler(response); delete this.callbacks[response.request_seq]; } } else if (msg.type === "event") { const event = <protocol.Event>msg; this.emit(event.event, event.body); } } emit(name: string, args: any): void { const handler = this.eventHandlers.get(name); if (handler) { handler(args); } } on(name: string, handler: (args: any) => void): void { this.eventHandlers.set(name, handler); } connect(session: InProcSession): void { this.server = session; } execute(command: string, args: any, callback: (resp: protocol.Response) => void): void { if (!this.server) { return; } this.seq++; this.server.enqueue({ seq: this.seq, type: "request", command, arguments: args }); this.callbacks[this.seq] = callback; } } it("can be constructed and respond to commands", (done) => { const cli = new InProcClient(); const session = new InProcSession(cli); const toEcho = { data: true }; const toEvent = { data: false }; let responses = 0; // Connect the client cli.connect(session); // Add an event handler cli.on("testevent", (eventinfo) => { expect(eventinfo).to.equal(toEvent); responses++; expect(responses).to.equal(1); }); // Trigger said event from the server session.event(toEvent, "testevent"); // Queue an echo command cli.execute("echo", toEcho, (resp) => { assert(resp.success, resp.message); responses++; expect(responses).to.equal(2); expect(resp.body).to.deep.equal(toEcho); }); // Queue a configure command cli.execute("configure", { hostInfo: "unit test", formatOptions: { newLineCharacter: "`n" } }, (resp) => { assert(resp.success, resp.message); responses++; expect(responses).to.equal(3); done(); }); // Consume the queue and trigger the callbacks session.consumeQueue(); }); }); describe("unittests:: tsserver:: Session:: helpers", () => { it(getLocationInNewDocument.name, () => { const text = `// blank line\nconst x = 0;`; const renameLocationInOldText = text.indexOf("0"); const fileName = "/a.ts"; const edits: FileTextChanges = { fileName, textChanges: [ { span: { start: 0, length: 0 }, newText: "const newLocal = 0;\n\n", }, { span: { start: renameLocationInOldText, length: 1 }, newText: "newLocal", }, ], }; const renameLocationInNewText = renameLocationInOldText + edits.textChanges[0].newText.length; const res = getLocationInNewDocument(text, fileName, renameLocationInNewText, [edits]); assert.deepEqual(res, { line: 4, offset: 11 }); }); }); }
src/testRunner/unittests/tsserver/session.ts
1
https://github.com/microsoft/TypeScript/commit/f99072593dc130e0073762d3071aa64882be0823
[ 0.001742528285831213, 0.0002379115903750062, 0.00016378048167098314, 0.00017133350775111467, 0.0002800322254188359 ]
{ "id": 1, "code_window": [ " /**\n", " * Time spent updating the program graph, in milliseconds.\n", " */\n", " /* @internal */\n", " updateGraphDurationMs?: number;\n", " }\n", "\n", " /**\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/server/protocol.ts", "type": "replace", "edit_start_line_idx": 242 }
//// [tests/cases/compiler/chainedImportAlias.ts] //// //// [chainedImportAlias_file0.ts] export module m { export function foo() { } } //// [chainedImportAlias_file1.ts] import x = require('./chainedImportAlias_file0'); import y = x; y.m.foo(); //// [chainedImportAlias_file0.js] "use strict"; exports.__esModule = true; var m; (function (m) { function foo() { } m.foo = foo; })(m = exports.m || (exports.m = {})); //// [chainedImportAlias_file1.js] "use strict"; exports.__esModule = true; var x = require("./chainedImportAlias_file0"); var y = x; y.m.foo();
tests/baselines/reference/chainedImportAlias.js
0
https://github.com/microsoft/TypeScript/commit/f99072593dc130e0073762d3071aa64882be0823
[ 0.00017723503697197884, 0.00017539884720463306, 0.00017266850045416504, 0.00017629304784350097, 0.0000019685851384565467 ]
{ "id": 1, "code_window": [ " /**\n", " * Time spent updating the program graph, in milliseconds.\n", " */\n", " /* @internal */\n", " updateGraphDurationMs?: number;\n", " }\n", "\n", " /**\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/server/protocol.ts", "type": "replace", "edit_start_line_idx": 242 }
{ "scenario": "[Sourcemap]/[Sourceroot-AbsolutePath]: outputdir_module_subfolder: no outdir", "projectRoot": "tests/cases/projects/outputdir_module_subfolder", "inputFiles": [ "test.ts" ], "sourceMap": true, "declaration": true, "baselineCheck": true, "sourceRoot": "tests/cases/projects/outputdir_module_subfolder/src", "resolveSourceRoot": true, "resolvedInputFiles": [ "lib.es5.d.ts", "ref/m1.ts", "test.ts" ], "emittedFiles": [ "ref/m1.js.map", "ref/m1.js", "ref/m1.d.ts", "test.js.map", "test.js", "test.d.ts" ] }
tests/baselines/reference/project/sourceRootAbsolutePathModuleSubfolderNoOutdir/amd/sourceRootAbsolutePathModuleSubfolderNoOutdir.json
0
https://github.com/microsoft/TypeScript/commit/f99072593dc130e0073762d3071aa64882be0823
[ 0.00017715379362925887, 0.0001758152066031471, 0.00017444483819417655, 0.00017584700253792107, 0.0000011061548548241262 ]
{ "id": 1, "code_window": [ " /**\n", " * Time spent updating the program graph, in milliseconds.\n", " */\n", " /* @internal */\n", " updateGraphDurationMs?: number;\n", " }\n", "\n", " /**\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/server/protocol.ts", "type": "replace", "edit_start_line_idx": 242 }
=== tests/cases/conformance/parser/ecmascript5/ArrayLiteralExpressions/parserArrayLiteralExpression3.ts === var v = [,,]; >v : Symbol(v, Decl(parserArrayLiteralExpression3.ts, 0, 3))
tests/baselines/reference/parserArrayLiteralExpression3.symbols
0
https://github.com/microsoft/TypeScript/commit/f99072593dc130e0073762d3071aa64882be0823
[ 0.0001741239393595606, 0.0001741239393595606, 0.0001741239393595606, 0.0001741239393595606, 0 ]
{ "id": 3, "code_window": [ " message: \"Unrecognized JSON command: foobar\",\n", " request_seq: 0,\n", " success: false,\n", " updateGraphDurationMs: undefined,\n", " };\n", " expect(lastSent).to.deep.equal(expected);\n", " });\n", " it(\"should return a tuple containing the response and if a response is required on success\", () => {\n", " const req: protocol.ConfigureRequest = {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " performanceData: undefined,\n" ], "file_path": "src/testRunner/unittests/tsserver/session.ts", "type": "replace", "edit_start_line_idx": 103 }
namespace ts.server { const _chai: typeof import("chai") = require("chai"); const expect: typeof _chai.expect = _chai.expect; let lastWrittenToHost: string; const noopFileWatcher: FileWatcher = { close: noop }; const mockHost: ServerHost = { args: [], newLine: "\n", useCaseSensitiveFileNames: true, write(s): void { lastWrittenToHost = s; }, readFile: returnUndefined, writeFile: noop, resolvePath(): string { return undefined!; }, // TODO: GH#18217 fileExists: () => false, directoryExists: () => false, getDirectories: () => [], createDirectory: noop, getExecutingFilePath(): string { return ""; }, getCurrentDirectory(): string { return ""; }, getEnvironmentVariable(): string { return ""; }, readDirectory() { return []; }, exit: noop, setTimeout() { return 0; }, clearTimeout: noop, setImmediate: () => 0, clearImmediate: noop, createHash: Harness.mockHash, watchFile: () => noopFileWatcher, watchDirectory: () => noopFileWatcher }; class TestSession extends Session { getProjectService() { return this.projectService; } } describe("unittests:: tsserver:: Session:: General functionality", () => { let session: TestSession; let lastSent: protocol.Message; function createSession(): TestSession { const opts: SessionOptions = { host: mockHost, cancellationToken: nullCancellationToken, useSingleInferredProject: false, useInferredProjectPerProjectRoot: false, typingsInstaller: undefined!, // TODO: GH#18217 byteLength: Utils.byteLength, hrtime: process.hrtime, logger: projectSystem.nullLogger, canUseEvents: true }; return new TestSession(opts); } // Disable sourcemap support for the duration of the test, as sourcemapping the errors generated during this test is slow and not something we care to test let oldPrepare: AnyFunction; before(() => { oldPrepare = (Error as any).prepareStackTrace; delete (Error as any).prepareStackTrace; }); after(() => { (Error as any).prepareStackTrace = oldPrepare; }); beforeEach(() => { session = createSession(); session.send = (msg: protocol.Message) => { lastSent = msg; }; }); describe("executeCommand", () => { it("should throw when commands are executed with invalid arguments", () => { const req: protocol.FileRequest = { command: CommandNames.Open, seq: 0, type: "request", arguments: { file: undefined! // TODO: GH#18217 } }; expect(() => session.executeCommand(req)).to.throw(); }); it("should output an error response when a command does not exist", () => { const req: protocol.Request = { command: "foobar", seq: 0, type: "request" }; session.executeCommand(req); const expected: protocol.Response = { command: CommandNames.Unknown, type: "response", seq: 0, message: "Unrecognized JSON command: foobar", request_seq: 0, success: false, updateGraphDurationMs: undefined, }; expect(lastSent).to.deep.equal(expected); }); it("should return a tuple containing the response and if a response is required on success", () => { const req: protocol.ConfigureRequest = { command: CommandNames.Configure, seq: 0, type: "request", arguments: { hostInfo: "unit test", formatOptions: { newLineCharacter: "`n" } } }; expect(session.executeCommand(req)).to.deep.equal({ responseRequired: false }); expect(lastSent).to.deep.equal({ command: CommandNames.Configure, type: "response", success: true, request_seq: 0, seq: 0, body: undefined, updateGraphDurationMs: undefined, }); }); it("should handle literal types in request", () => { const configureRequest: protocol.ConfigureRequest = { command: CommandNames.Configure, seq: 0, type: "request", arguments: { formatOptions: { indentStyle: protocol.IndentStyle.Block, } } }; session.onMessage(JSON.stringify(configureRequest)); assert.equal(session.getProjectService().getFormatCodeOptions("" as NormalizedPath).indentStyle, IndentStyle.Block); const setOptionsRequest: protocol.SetCompilerOptionsForInferredProjectsRequest = { command: CommandNames.CompilerOptionsForInferredProjects, seq: 1, type: "request", arguments: { options: { module: protocol.ModuleKind.System, target: protocol.ScriptTarget.ES5, jsx: protocol.JsxEmit.React, newLine: protocol.NewLineKind.Lf, moduleResolution: protocol.ModuleResolutionKind.Node, } } }; session.onMessage(JSON.stringify(setOptionsRequest)); assert.deepEqual( session.getProjectService().getCompilerOptionsForInferredProjects(), <CompilerOptions>{ module: ModuleKind.System, target: ScriptTarget.ES5, jsx: JsxEmit.React, newLine: NewLineKind.LineFeed, moduleResolution: ModuleResolutionKind.NodeJs, allowNonTsExtensions: true // injected by tsserver }); }); it("Status request gives ts.version", () => { const req: protocol.StatusRequest = { command: CommandNames.Status, seq: 0, type: "request" }; const expected: protocol.StatusResponseBody = { version: ts.version, // eslint-disable-line @typescript-eslint/no-unnecessary-qualifier }; assert.deepEqual(session.executeCommand(req).response, expected); }); }); describe("onMessage", () => { const allCommandNames: CommandNames[] = [ CommandNames.Brace, CommandNames.BraceFull, CommandNames.BraceCompletion, CommandNames.Change, CommandNames.Close, CommandNames.Completions, CommandNames.CompletionsFull, CommandNames.CompletionDetails, CommandNames.CompileOnSaveAffectedFileList, CommandNames.Configure, CommandNames.Definition, CommandNames.DefinitionFull, CommandNames.DefinitionAndBoundSpan, CommandNames.DefinitionAndBoundSpanFull, CommandNames.Implementation, CommandNames.ImplementationFull, CommandNames.Exit, CommandNames.Format, CommandNames.Formatonkey, CommandNames.FormatFull, CommandNames.FormatonkeyFull, CommandNames.FormatRangeFull, CommandNames.Geterr, CommandNames.GeterrForProject, CommandNames.SemanticDiagnosticsSync, CommandNames.SyntacticDiagnosticsSync, CommandNames.SuggestionDiagnosticsSync, CommandNames.NavBar, CommandNames.NavBarFull, CommandNames.Navto, CommandNames.NavtoFull, CommandNames.NavTree, CommandNames.NavTreeFull, CommandNames.Occurrences, CommandNames.DocumentHighlights, CommandNames.DocumentHighlightsFull, CommandNames.JsxClosingTag, CommandNames.Open, CommandNames.Quickinfo, CommandNames.QuickinfoFull, CommandNames.References, CommandNames.ReferencesFull, CommandNames.Reload, CommandNames.Rename, CommandNames.RenameInfoFull, CommandNames.RenameLocationsFull, CommandNames.Saveto, CommandNames.SignatureHelp, CommandNames.SignatureHelpFull, CommandNames.Status, CommandNames.TypeDefinition, CommandNames.ProjectInfo, CommandNames.ReloadProjects, CommandNames.Unknown, CommandNames.OpenExternalProject, CommandNames.CloseExternalProject, CommandNames.SynchronizeProjectList, CommandNames.ApplyChangedToOpenFiles, CommandNames.EncodedSemanticClassificationsFull, CommandNames.Cleanup, CommandNames.OutliningSpans, CommandNames.TodoComments, CommandNames.Indentation, CommandNames.DocCommentTemplate, CommandNames.CompilerOptionsDiagnosticsFull, CommandNames.NameOrDottedNameSpan, CommandNames.BreakpointStatement, CommandNames.CompilerOptionsForInferredProjects, CommandNames.GetCodeFixes, CommandNames.GetCodeFixesFull, CommandNames.GetSupportedCodeFixes, CommandNames.GetApplicableRefactors, CommandNames.GetEditsForRefactor, CommandNames.GetEditsForRefactorFull, CommandNames.OrganizeImports, CommandNames.OrganizeImportsFull, CommandNames.GetEditsForFileRename, CommandNames.GetEditsForFileRenameFull, CommandNames.SelectionRange, CommandNames.PrepareCallHierarchy, CommandNames.ProvideCallHierarchyIncomingCalls, CommandNames.ProvideCallHierarchyOutgoingCalls, ]; it("should not throw when commands are executed with invalid arguments", () => { let i = 0; for (const name of allCommandNames) { const req: protocol.Request = { command: name, seq: i, type: "request" }; i++; session.onMessage(JSON.stringify(req)); req.seq = i; i++; req.arguments = {}; session.onMessage(JSON.stringify(req)); req.seq = i; i++; req.arguments = null; // eslint-disable-line no-null/no-null session.onMessage(JSON.stringify(req)); req.seq = i; i++; req.arguments = ""; session.onMessage(JSON.stringify(req)); req.seq = i; i++; req.arguments = 0; session.onMessage(JSON.stringify(req)); req.seq = i; i++; req.arguments = []; session.onMessage(JSON.stringify(req)); } session.onMessage("GARBAGE NON_JSON DATA"); }); it("should output the response for a correctly handled message", () => { const req: protocol.ConfigureRequest = { command: CommandNames.Configure, seq: 0, type: "request", arguments: { hostInfo: "unit test", formatOptions: { newLineCharacter: "`n" } } }; session.onMessage(JSON.stringify(req)); expect(lastSent).to.deep.equal(<protocol.ConfigureResponse>{ command: CommandNames.Configure, type: "response", success: true, request_seq: 0, seq: 0, body: undefined, updateGraphDurationMs: undefined, }); }); }); describe("send", () => { it("is an overrideable handle which sends protocol messages over the wire", () => { const msg: protocol.Request = { seq: 0, type: "request", command: "" }; const strmsg = JSON.stringify(msg); const len = 1 + Utils.byteLength(strmsg, "utf8"); const resultMsg = `Content-Length: ${len}\r\n\r\n${strmsg}\n`; session.send = Session.prototype.send; assert(session.send); expect(session.send(msg)).to.not.exist; // eslint-disable-line no-unused-expressions expect(lastWrittenToHost).to.equal(resultMsg); }); }); describe("addProtocolHandler", () => { it("can add protocol handlers", () => { const respBody = { item: false }; const command = "newhandle"; const result: HandlerResponse = { response: respBody, responseRequired: true }; session.addProtocolHandler(command, () => result); expect(session.executeCommand({ command, seq: 0, type: "request" })).to.deep.equal(result); }); it("throws when a duplicate handler is passed", () => { const respBody = { item: false }; const resp: HandlerResponse = { response: respBody, responseRequired: true }; const command = "newhandle"; session.addProtocolHandler(command, () => resp); expect(() => session.addProtocolHandler(command, () => resp)) .to.throw(`Protocol handler already exists for command "${command}"`); }); }); describe("event", () => { it("can format event responses and send them", () => { const evt = "notify-test"; const info = { test: true }; session.event(info, evt); expect(lastSent).to.deep.equal({ type: "event", seq: 0, event: evt, body: info }); }); }); describe("output", () => { it("can format command responses and send them", () => { const body = { block: { key: "value" } }; const command = "test"; session.output(body, command, /*reqSeq*/ 0); expect(lastSent).to.deep.equal({ seq: 0, request_seq: 0, type: "response", command, body, success: true, updateGraphDurationMs: undefined, }); }); }); }); describe("unittests:: tsserver:: Session:: exceptions", () => { // Disable sourcemap support for the duration of the test, as sourcemapping the errors generated during this test is slow and not something we care to test let oldPrepare: AnyFunction; let oldStackTraceLimit: number; before(() => { oldStackTraceLimit = (Error as any).stackTraceLimit; oldPrepare = (Error as any).prepareStackTrace; delete (Error as any).prepareStackTrace; (Error as any).stackTraceLimit = 10; }); after(() => { (Error as any).prepareStackTrace = oldPrepare; (Error as any).stackTraceLimit = oldStackTraceLimit; }); const command = "testhandler"; class TestSession extends Session { lastSent: protocol.Message | undefined; private exceptionRaisingHandler(_request: protocol.Request): { response?: any, responseRequired: boolean } { f1(); return Debug.fail(); // unreachable, throw to make compiler happy function f1() { throw new Error("myMessage"); } } constructor() { super({ host: mockHost, cancellationToken: nullCancellationToken, useSingleInferredProject: false, useInferredProjectPerProjectRoot: false, typingsInstaller: undefined!, // TODO: GH#18217 byteLength: Utils.byteLength, hrtime: process.hrtime, logger: projectSystem.nullLogger, canUseEvents: true }); this.addProtocolHandler(command, this.exceptionRaisingHandler); } send(msg: protocol.Message) { this.lastSent = msg; } } it("raised in a protocol handler generate an event", () => { const session = new TestSession(); const request = { command, seq: 0, type: "request" }; session.onMessage(JSON.stringify(request)); const lastSent = session.lastSent as protocol.Response; expect(lastSent).to.contain({ seq: 0, type: "response", command, success: false }); expect(lastSent.message).has.string("myMessage").and.has.string("f1"); }); }); describe("unittests:: tsserver:: Session:: how Session is extendable via subclassing", () => { class TestSession extends Session { lastSent: protocol.Message | undefined; customHandler = "testhandler"; constructor() { super({ host: mockHost, cancellationToken: nullCancellationToken, useSingleInferredProject: false, useInferredProjectPerProjectRoot: false, typingsInstaller: undefined!, // TODO: GH#18217 byteLength: Utils.byteLength, hrtime: process.hrtime, logger: projectSystem.createHasErrorMessageLogger().logger, canUseEvents: true }); this.addProtocolHandler(this.customHandler, () => { return { response: undefined, responseRequired: true }; }); } send(msg: protocol.Message) { this.lastSent = msg; } } it("can override methods such as send", () => { const session = new TestSession(); const body = { block: { key: "value" } }; const command = "test"; session.output(body, command, /*reqSeq*/ 0); expect(session.lastSent).to.deep.equal({ seq: 0, request_seq: 0, type: "response", command, body, success: true, updateGraphDurationMs: undefined, }); }); it("can add and respond to new protocol handlers", () => { const session = new TestSession(); expect(session.executeCommand({ seq: 0, type: "request", command: session.customHandler })).to.deep.equal({ response: undefined, responseRequired: true }); }); it("has access to the project service", () => { new class extends TestSession { constructor() { super(); assert(this.projectService); expect(this.projectService).to.be.instanceOf(ProjectService); } }(); }); }); describe("unittests:: tsserver:: Session:: an example of using the Session API to create an in-process server", () => { class InProcSession extends Session { private queue: protocol.Request[] = []; constructor(private client: InProcClient) { super({ host: mockHost, cancellationToken: nullCancellationToken, useSingleInferredProject: false, useInferredProjectPerProjectRoot: false, typingsInstaller: undefined!, // TODO: GH#18217 byteLength: Utils.byteLength, hrtime: process.hrtime, logger: projectSystem.createHasErrorMessageLogger().logger, canUseEvents: true }); this.addProtocolHandler("echo", (req: protocol.Request) => ({ response: req.arguments, responseRequired: true })); } send(msg: protocol.Message) { this.client.handle(msg); } enqueue(msg: protocol.Request) { this.queue.unshift(msg); } handleRequest(msg: protocol.Request) { let response: protocol.Response; try { response = this.executeCommand(msg).response as protocol.Response; } catch (e) { this.output(undefined, msg.command, msg.seq, e.toString()); return; } if (response) { this.output(response, msg.command, msg.seq); } } consumeQueue() { while (this.queue.length > 0) { const elem = this.queue.pop()!; this.handleRequest(elem); } } } class InProcClient { private server: InProcSession | undefined; private seq = 0; private callbacks: ((resp: protocol.Response) => void)[] = []; private eventHandlers = createMap<(args: any) => void>(); handle(msg: protocol.Message): void { if (msg.type === "response") { const response = <protocol.Response>msg; const handler = this.callbacks[response.request_seq]; if (handler) { handler(response); delete this.callbacks[response.request_seq]; } } else if (msg.type === "event") { const event = <protocol.Event>msg; this.emit(event.event, event.body); } } emit(name: string, args: any): void { const handler = this.eventHandlers.get(name); if (handler) { handler(args); } } on(name: string, handler: (args: any) => void): void { this.eventHandlers.set(name, handler); } connect(session: InProcSession): void { this.server = session; } execute(command: string, args: any, callback: (resp: protocol.Response) => void): void { if (!this.server) { return; } this.seq++; this.server.enqueue({ seq: this.seq, type: "request", command, arguments: args }); this.callbacks[this.seq] = callback; } } it("can be constructed and respond to commands", (done) => { const cli = new InProcClient(); const session = new InProcSession(cli); const toEcho = { data: true }; const toEvent = { data: false }; let responses = 0; // Connect the client cli.connect(session); // Add an event handler cli.on("testevent", (eventinfo) => { expect(eventinfo).to.equal(toEvent); responses++; expect(responses).to.equal(1); }); // Trigger said event from the server session.event(toEvent, "testevent"); // Queue an echo command cli.execute("echo", toEcho, (resp) => { assert(resp.success, resp.message); responses++; expect(responses).to.equal(2); expect(resp.body).to.deep.equal(toEcho); }); // Queue a configure command cli.execute("configure", { hostInfo: "unit test", formatOptions: { newLineCharacter: "`n" } }, (resp) => { assert(resp.success, resp.message); responses++; expect(responses).to.equal(3); done(); }); // Consume the queue and trigger the callbacks session.consumeQueue(); }); }); describe("unittests:: tsserver:: Session:: helpers", () => { it(getLocationInNewDocument.name, () => { const text = `// blank line\nconst x = 0;`; const renameLocationInOldText = text.indexOf("0"); const fileName = "/a.ts"; const edits: FileTextChanges = { fileName, textChanges: [ { span: { start: 0, length: 0 }, newText: "const newLocal = 0;\n\n", }, { span: { start: renameLocationInOldText, length: 1 }, newText: "newLocal", }, ], }; const renameLocationInNewText = renameLocationInOldText + edits.textChanges[0].newText.length; const res = getLocationInNewDocument(text, fileName, renameLocationInNewText, [edits]); assert.deepEqual(res, { line: 4, offset: 11 }); }); }); }
src/testRunner/unittests/tsserver/session.ts
1
https://github.com/microsoft/TypeScript/commit/f99072593dc130e0073762d3071aa64882be0823
[ 0.9981289505958557, 0.023487485945224762, 0.00016125600086525083, 0.000312910124193877, 0.12497967481613159 ]
{ "id": 3, "code_window": [ " message: \"Unrecognized JSON command: foobar\",\n", " request_seq: 0,\n", " success: false,\n", " updateGraphDurationMs: undefined,\n", " };\n", " expect(lastSent).to.deep.equal(expected);\n", " });\n", " it(\"should return a tuple containing the response and if a response is required on success\", () => {\n", " const req: protocol.ConfigureRequest = {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " performanceData: undefined,\n" ], "file_path": "src/testRunner/unittests/tsserver/session.ts", "type": "replace", "edit_start_line_idx": 103 }
=================================================================== JsFile: sourceMapValidationDestructuringParametertArrayBindingPatternDefaultValues.js mapUrl: sourceMapValidationDestructuringParametertArrayBindingPatternDefaultValues.js.map sourceRoot: sources: sourceMapValidationDestructuringParametertArrayBindingPatternDefaultValues.ts =================================================================== ------------------------------------------------------------------- emittedFile:tests/cases/compiler/sourceMapValidationDestructuringParametertArrayBindingPatternDefaultValues.js sourceFile:sourceMapValidationDestructuringParametertArrayBindingPatternDefaultValues.ts ------------------------------------------------------------------- >>>var robotA = [1, "mower", "mowing"]; 1 > 2 >^^^^ 3 > ^^^^^^ 4 > ^^^ 5 > ^ 6 > ^ 7 > ^^ 8 > ^^^^^^^ 9 > ^^ 10> ^^^^^^^^ 11> ^ 12> ^ 1 >declare var console: { > log(msg: any): void; >} >type Robot = [number, string, string]; > 2 >var 3 > robotA 4 > : Robot = 5 > [ 6 > 1 7 > , 8 > "mower" 9 > , 10> "mowing" 11> ] 12> ; 1 >Emitted(1, 1) Source(5, 1) + SourceIndex(0) 2 >Emitted(1, 5) Source(5, 5) + SourceIndex(0) 3 >Emitted(1, 11) Source(5, 11) + SourceIndex(0) 4 >Emitted(1, 14) Source(5, 21) + SourceIndex(0) 5 >Emitted(1, 15) Source(5, 22) + SourceIndex(0) 6 >Emitted(1, 16) Source(5, 23) + SourceIndex(0) 7 >Emitted(1, 18) Source(5, 25) + SourceIndex(0) 8 >Emitted(1, 25) Source(5, 32) + SourceIndex(0) 9 >Emitted(1, 27) Source(5, 34) + SourceIndex(0) 10>Emitted(1, 35) Source(5, 42) + SourceIndex(0) 11>Emitted(1, 36) Source(5, 43) + SourceIndex(0) 12>Emitted(1, 37) Source(5, 44) + SourceIndex(0) --- >>>function foo1(_a) { 1 > 2 >^^^^^^^^^ 3 > ^^^^ 4 > ^ 5 > ^^ 6 > ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^-> 1 > > > 2 >function 3 > foo1 4 > ( 5 > [, nameA = "noName"]: Robot = [-1, "name", "skill"] 1 >Emitted(2, 1) Source(7, 1) + SourceIndex(0) 2 >Emitted(2, 10) Source(7, 10) + SourceIndex(0) 3 >Emitted(2, 14) Source(7, 14) + SourceIndex(0) 4 >Emitted(2, 15) Source(7, 15) + SourceIndex(0) 5 >Emitted(2, 17) Source(7, 66) + SourceIndex(0) --- >>> var _b = _a === void 0 ? [-1, "name", "skill"] : _a, _c = _b[1], nameA = _c === void 0 ? "noName" : _c; 1->^^^^^^^^ 2 > ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 3 > ^^ 4 > ^^^^^^^^^^ 5 > ^^ 6 > ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 1-> 2 > [, nameA = "noName"]: Robot = [-1, "name", "skill"] 3 > 4 > nameA = "noName" 5 > 6 > nameA = "noName" 1->Emitted(3, 9) Source(7, 15) + SourceIndex(0) 2 >Emitted(3, 56) Source(7, 66) + SourceIndex(0) 3 >Emitted(3, 58) Source(7, 18) + SourceIndex(0) 4 >Emitted(3, 68) Source(7, 34) + SourceIndex(0) 5 >Emitted(3, 70) Source(7, 18) + SourceIndex(0) 6 >Emitted(3, 107) Source(7, 34) + SourceIndex(0) --- >>> console.log(nameA); 1 >^^^^ 2 > ^^^^^^^ 3 > ^ 4 > ^^^ 5 > ^ 6 > ^^^^^ 7 > ^ 8 > ^ 1 >]: Robot = [-1, "name", "skill"]) { > 2 > console 3 > . 4 > log 5 > ( 6 > nameA 7 > ) 8 > ; 1 >Emitted(4, 5) Source(8, 5) + SourceIndex(0) 2 >Emitted(4, 12) Source(8, 12) + SourceIndex(0) 3 >Emitted(4, 13) Source(8, 13) + SourceIndex(0) 4 >Emitted(4, 16) Source(8, 16) + SourceIndex(0) 5 >Emitted(4, 17) Source(8, 17) + SourceIndex(0) 6 >Emitted(4, 22) Source(8, 22) + SourceIndex(0) 7 >Emitted(4, 23) Source(8, 23) + SourceIndex(0) 8 >Emitted(4, 24) Source(8, 24) + SourceIndex(0) --- >>>} 1 > 2 >^ 3 > ^^^^^^^^^^^^^^^^^^^-> 1 > > 2 >} 1 >Emitted(5, 1) Source(9, 1) + SourceIndex(0) 2 >Emitted(5, 2) Source(9, 2) + SourceIndex(0) --- >>>function foo2(_a) { 1-> 2 >^^^^^^^^^ 3 > ^^^^ 4 > ^ 5 > ^^ 6 > ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^-> 1-> > > 2 >function 3 > foo2 4 > ( 5 > [numberB = -1]: Robot = [-1, "name", "skill"] 1->Emitted(6, 1) Source(11, 1) + SourceIndex(0) 2 >Emitted(6, 10) Source(11, 10) + SourceIndex(0) 3 >Emitted(6, 14) Source(11, 14) + SourceIndex(0) 4 >Emitted(6, 15) Source(11, 15) + SourceIndex(0) 5 >Emitted(6, 17) Source(11, 60) + SourceIndex(0) --- >>> var _b = (_a === void 0 ? [-1, "name", "skill"] : _a)[0], numberB = _b === void 0 ? -1 : _b; 1->^^^^^^^^ 2 > ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 3 > ^^ 4 > ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 1-> 2 > numberB = -1 3 > 4 > numberB = -1 1->Emitted(7, 9) Source(11, 16) + SourceIndex(0) 2 >Emitted(7, 61) Source(11, 28) + SourceIndex(0) 3 >Emitted(7, 63) Source(11, 16) + SourceIndex(0) 4 >Emitted(7, 96) Source(11, 28) + SourceIndex(0) --- >>> console.log(numberB); 1 >^^^^ 2 > ^^^^^^^ 3 > ^ 4 > ^^^ 5 > ^ 6 > ^^^^^^^ 7 > ^ 8 > ^ 1 >]: Robot = [-1, "name", "skill"]) { > 2 > console 3 > . 4 > log 5 > ( 6 > numberB 7 > ) 8 > ; 1 >Emitted(8, 5) Source(12, 5) + SourceIndex(0) 2 >Emitted(8, 12) Source(12, 12) + SourceIndex(0) 3 >Emitted(8, 13) Source(12, 13) + SourceIndex(0) 4 >Emitted(8, 16) Source(12, 16) + SourceIndex(0) 5 >Emitted(8, 17) Source(12, 17) + SourceIndex(0) 6 >Emitted(8, 24) Source(12, 24) + SourceIndex(0) 7 >Emitted(8, 25) Source(12, 25) + SourceIndex(0) 8 >Emitted(8, 26) Source(12, 26) + SourceIndex(0) --- >>>} 1 > 2 >^ 3 > ^^^^^^^^^^^^^^^^^^^-> 1 > > 2 >} 1 >Emitted(9, 1) Source(13, 1) + SourceIndex(0) 2 >Emitted(9, 2) Source(13, 2) + SourceIndex(0) --- >>>function foo3(_a) { 1-> 2 >^^^^^^^^^ 3 > ^^^^ 4 > ^ 5 > ^^ 6 > ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^-> 1-> > > 2 >function 3 > foo3 4 > ( 5 > [numberA2 = -1, nameA2 = "name", skillA2 = "skill"]: Robot = [-1, "name", "skill"] 1->Emitted(10, 1) Source(15, 1) + SourceIndex(0) 2 >Emitted(10, 10) Source(15, 10) + SourceIndex(0) 3 >Emitted(10, 14) Source(15, 14) + SourceIndex(0) 4 >Emitted(10, 15) Source(15, 15) + SourceIndex(0) 5 >Emitted(10, 17) Source(15, 97) + SourceIndex(0) --- >>> var _b = _a === void 0 ? [-1, "name", "skill"] : _a, _c = _b[0], numberA2 = _c === void 0 ? -1 : _c, _d = _b[1], nameA2 = _d === void 0 ? "name" : _d, _e = _b[2], skillA2 = _e === void 0 ? "skill" : _e; 1->^^^^^^^^ 2 > ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 3 > ^^ 4 > ^^^^^^^^^^ 5 > ^^ 6 > ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 7 > ^^ 8 > ^^^^^^^^^^ 9 > ^^ 10> ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 11> ^^ 12> ^^^^^^^^^^ 13> ^^ 14> ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 1-> 2 > [numberA2 = -1, nameA2 = "name", skillA2 = "skill"]: Robot = [-1, "name", "skill"] 3 > 4 > numberA2 = -1 5 > 6 > numberA2 = -1 7 > , 8 > nameA2 = "name" 9 > 10> nameA2 = "name" 11> , 12> skillA2 = "skill" 13> 14> skillA2 = "skill" 1->Emitted(11, 9) Source(15, 15) + SourceIndex(0) 2 >Emitted(11, 56) Source(15, 97) + SourceIndex(0) 3 >Emitted(11, 58) Source(15, 16) + SourceIndex(0) 4 >Emitted(11, 68) Source(15, 29) + SourceIndex(0) 5 >Emitted(11, 70) Source(15, 16) + SourceIndex(0) 6 >Emitted(11, 104) Source(15, 29) + SourceIndex(0) 7 >Emitted(11, 106) Source(15, 31) + SourceIndex(0) 8 >Emitted(11, 116) Source(15, 46) + SourceIndex(0) 9 >Emitted(11, 118) Source(15, 31) + SourceIndex(0) 10>Emitted(11, 154) Source(15, 46) + SourceIndex(0) 11>Emitted(11, 156) Source(15, 48) + SourceIndex(0) 12>Emitted(11, 166) Source(15, 65) + SourceIndex(0) 13>Emitted(11, 168) Source(15, 48) + SourceIndex(0) 14>Emitted(11, 206) Source(15, 65) + SourceIndex(0) --- >>> console.log(nameA2); 1 >^^^^ 2 > ^^^^^^^ 3 > ^ 4 > ^^^ 5 > ^ 6 > ^^^^^^ 7 > ^ 8 > ^ 1 >]: Robot = [-1, "name", "skill"]) { > 2 > console 3 > . 4 > log 5 > ( 6 > nameA2 7 > ) 8 > ; 1 >Emitted(12, 5) Source(16, 5) + SourceIndex(0) 2 >Emitted(12, 12) Source(16, 12) + SourceIndex(0) 3 >Emitted(12, 13) Source(16, 13) + SourceIndex(0) 4 >Emitted(12, 16) Source(16, 16) + SourceIndex(0) 5 >Emitted(12, 17) Source(16, 17) + SourceIndex(0) 6 >Emitted(12, 23) Source(16, 23) + SourceIndex(0) 7 >Emitted(12, 24) Source(16, 24) + SourceIndex(0) 8 >Emitted(12, 25) Source(16, 25) + SourceIndex(0) --- >>>} 1 > 2 >^ 3 > ^^^^^^^^^^^^^^^^^^^-> 1 > > 2 >} 1 >Emitted(13, 1) Source(17, 1) + SourceIndex(0) 2 >Emitted(13, 2) Source(17, 2) + SourceIndex(0) --- >>>function foo4(_a) { 1-> 2 >^^^^^^^^^ 3 > ^^^^ 4 > ^ 5 > ^^ 6 > ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^-> 1-> > > 2 >function 3 > foo4 4 > ( 5 > [numberA3 = -1, ...robotAInfo]: Robot = [-1, "name", "skill"] 1->Emitted(14, 1) Source(19, 1) + SourceIndex(0) 2 >Emitted(14, 10) Source(19, 10) + SourceIndex(0) 3 >Emitted(14, 14) Source(19, 14) + SourceIndex(0) 4 >Emitted(14, 15) Source(19, 15) + SourceIndex(0) 5 >Emitted(14, 17) Source(19, 76) + SourceIndex(0) --- >>> var _b = _a === void 0 ? [-1, "name", "skill"] : _a, _c = _b[0], numberA3 = _c === void 0 ? -1 : _c, robotAInfo = _b.slice(1); 1->^^^^^^^^ 2 > ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 3 > ^^ 4 > ^^^^^^^^^^ 5 > ^^ 6 > ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 7 > ^^ 8 > ^^^^^^^^^^^^^^^^^^^^^^^^ 1-> 2 > [numberA3 = -1, ...robotAInfo]: Robot = [-1, "name", "skill"] 3 > 4 > numberA3 = -1 5 > 6 > numberA3 = -1 7 > , 8 > ...robotAInfo 1->Emitted(15, 9) Source(19, 15) + SourceIndex(0) 2 >Emitted(15, 56) Source(19, 76) + SourceIndex(0) 3 >Emitted(15, 58) Source(19, 16) + SourceIndex(0) 4 >Emitted(15, 68) Source(19, 29) + SourceIndex(0) 5 >Emitted(15, 70) Source(19, 16) + SourceIndex(0) 6 >Emitted(15, 104) Source(19, 29) + SourceIndex(0) 7 >Emitted(15, 106) Source(19, 31) + SourceIndex(0) 8 >Emitted(15, 130) Source(19, 44) + SourceIndex(0) --- >>> console.log(robotAInfo); 1 >^^^^ 2 > ^^^^^^^ 3 > ^ 4 > ^^^ 5 > ^ 6 > ^^^^^^^^^^ 7 > ^ 8 > ^ 1 >]: Robot = [-1, "name", "skill"]) { > 2 > console 3 > . 4 > log 5 > ( 6 > robotAInfo 7 > ) 8 > ; 1 >Emitted(16, 5) Source(20, 5) + SourceIndex(0) 2 >Emitted(16, 12) Source(20, 12) + SourceIndex(0) 3 >Emitted(16, 13) Source(20, 13) + SourceIndex(0) 4 >Emitted(16, 16) Source(20, 16) + SourceIndex(0) 5 >Emitted(16, 17) Source(20, 17) + SourceIndex(0) 6 >Emitted(16, 27) Source(20, 27) + SourceIndex(0) 7 >Emitted(16, 28) Source(20, 28) + SourceIndex(0) 8 >Emitted(16, 29) Source(20, 29) + SourceIndex(0) --- >>>} 1 > 2 >^ 3 > ^^^^^^^^^^^^^-> 1 > > 2 >} 1 >Emitted(17, 1) Source(21, 1) + SourceIndex(0) 2 >Emitted(17, 2) Source(21, 2) + SourceIndex(0) --- >>>foo1(robotA); 1-> 2 >^^^^ 3 > ^ 4 > ^^^^^^ 5 > ^ 6 > ^ 7 > ^^^^^^^^^^^^^^^^^^^^^-> 1-> > > 2 >foo1 3 > ( 4 > robotA 5 > ) 6 > ; 1->Emitted(18, 1) Source(23, 1) + SourceIndex(0) 2 >Emitted(18, 5) Source(23, 5) + SourceIndex(0) 3 >Emitted(18, 6) Source(23, 6) + SourceIndex(0) 4 >Emitted(18, 12) Source(23, 12) + SourceIndex(0) 5 >Emitted(18, 13) Source(23, 13) + SourceIndex(0) 6 >Emitted(18, 14) Source(23, 14) + SourceIndex(0) --- >>>foo1([2, "trimmer", "trimming"]); 1-> 2 >^^^^ 3 > ^ 4 > ^ 5 > ^ 6 > ^^ 7 > ^^^^^^^^^ 8 > ^^ 9 > ^^^^^^^^^^ 10> ^ 11> ^ 12> ^ 1-> > 2 >foo1 3 > ( 4 > [ 5 > 2 6 > , 7 > "trimmer" 8 > , 9 > "trimming" 10> ] 11> ) 12> ; 1->Emitted(19, 1) Source(24, 1) + SourceIndex(0) 2 >Emitted(19, 5) Source(24, 5) + SourceIndex(0) 3 >Emitted(19, 6) Source(24, 6) + SourceIndex(0) 4 >Emitted(19, 7) Source(24, 7) + SourceIndex(0) 5 >Emitted(19, 8) Source(24, 8) + SourceIndex(0) 6 >Emitted(19, 10) Source(24, 10) + SourceIndex(0) 7 >Emitted(19, 19) Source(24, 19) + SourceIndex(0) 8 >Emitted(19, 21) Source(24, 21) + SourceIndex(0) 9 >Emitted(19, 31) Source(24, 31) + SourceIndex(0) 10>Emitted(19, 32) Source(24, 32) + SourceIndex(0) 11>Emitted(19, 33) Source(24, 33) + SourceIndex(0) 12>Emitted(19, 34) Source(24, 34) + SourceIndex(0) --- >>>foo2(robotA); 1 > 2 >^^^^ 3 > ^ 4 > ^^^^^^ 5 > ^ 6 > ^ 7 > ^^^^^^^^^^^^^^^^^^^^^-> 1 > > > 2 >foo2 3 > ( 4 > robotA 5 > ) 6 > ; 1 >Emitted(20, 1) Source(26, 1) + SourceIndex(0) 2 >Emitted(20, 5) Source(26, 5) + SourceIndex(0) 3 >Emitted(20, 6) Source(26, 6) + SourceIndex(0) 4 >Emitted(20, 12) Source(26, 12) + SourceIndex(0) 5 >Emitted(20, 13) Source(26, 13) + SourceIndex(0) 6 >Emitted(20, 14) Source(26, 14) + SourceIndex(0) --- >>>foo2([2, "trimmer", "trimming"]); 1-> 2 >^^^^ 3 > ^ 4 > ^ 5 > ^ 6 > ^^ 7 > ^^^^^^^^^ 8 > ^^ 9 > ^^^^^^^^^^ 10> ^ 11> ^ 12> ^ 1-> > 2 >foo2 3 > ( 4 > [ 5 > 2 6 > , 7 > "trimmer" 8 > , 9 > "trimming" 10> ] 11> ) 12> ; 1->Emitted(21, 1) Source(27, 1) + SourceIndex(0) 2 >Emitted(21, 5) Source(27, 5) + SourceIndex(0) 3 >Emitted(21, 6) Source(27, 6) + SourceIndex(0) 4 >Emitted(21, 7) Source(27, 7) + SourceIndex(0) 5 >Emitted(21, 8) Source(27, 8) + SourceIndex(0) 6 >Emitted(21, 10) Source(27, 10) + SourceIndex(0) 7 >Emitted(21, 19) Source(27, 19) + SourceIndex(0) 8 >Emitted(21, 21) Source(27, 21) + SourceIndex(0) 9 >Emitted(21, 31) Source(27, 31) + SourceIndex(0) 10>Emitted(21, 32) Source(27, 32) + SourceIndex(0) 11>Emitted(21, 33) Source(27, 33) + SourceIndex(0) 12>Emitted(21, 34) Source(27, 34) + SourceIndex(0) --- >>>foo3(robotA); 1 > 2 >^^^^ 3 > ^ 4 > ^^^^^^ 5 > ^ 6 > ^ 7 > ^^^^^^^^^^^^^^^^^^^^^-> 1 > > > 2 >foo3 3 > ( 4 > robotA 5 > ) 6 > ; 1 >Emitted(22, 1) Source(29, 1) + SourceIndex(0) 2 >Emitted(22, 5) Source(29, 5) + SourceIndex(0) 3 >Emitted(22, 6) Source(29, 6) + SourceIndex(0) 4 >Emitted(22, 12) Source(29, 12) + SourceIndex(0) 5 >Emitted(22, 13) Source(29, 13) + SourceIndex(0) 6 >Emitted(22, 14) Source(29, 14) + SourceIndex(0) --- >>>foo3([2, "trimmer", "trimming"]); 1-> 2 >^^^^ 3 > ^ 4 > ^ 5 > ^ 6 > ^^ 7 > ^^^^^^^^^ 8 > ^^ 9 > ^^^^^^^^^^ 10> ^ 11> ^ 12> ^ 1-> > 2 >foo3 3 > ( 4 > [ 5 > 2 6 > , 7 > "trimmer" 8 > , 9 > "trimming" 10> ] 11> ) 12> ; 1->Emitted(23, 1) Source(30, 1) + SourceIndex(0) 2 >Emitted(23, 5) Source(30, 5) + SourceIndex(0) 3 >Emitted(23, 6) Source(30, 6) + SourceIndex(0) 4 >Emitted(23, 7) Source(30, 7) + SourceIndex(0) 5 >Emitted(23, 8) Source(30, 8) + SourceIndex(0) 6 >Emitted(23, 10) Source(30, 10) + SourceIndex(0) 7 >Emitted(23, 19) Source(30, 19) + SourceIndex(0) 8 >Emitted(23, 21) Source(30, 21) + SourceIndex(0) 9 >Emitted(23, 31) Source(30, 31) + SourceIndex(0) 10>Emitted(23, 32) Source(30, 32) + SourceIndex(0) 11>Emitted(23, 33) Source(30, 33) + SourceIndex(0) 12>Emitted(23, 34) Source(30, 34) + SourceIndex(0) --- >>>foo4(robotA); 1 > 2 >^^^^ 3 > ^ 4 > ^^^^^^ 5 > ^ 6 > ^ 7 > ^^^^^^^^^^^^^^^^^^^^^-> 1 > > > 2 >foo4 3 > ( 4 > robotA 5 > ) 6 > ; 1 >Emitted(24, 1) Source(32, 1) + SourceIndex(0) 2 >Emitted(24, 5) Source(32, 5) + SourceIndex(0) 3 >Emitted(24, 6) Source(32, 6) + SourceIndex(0) 4 >Emitted(24, 12) Source(32, 12) + SourceIndex(0) 5 >Emitted(24, 13) Source(32, 13) + SourceIndex(0) 6 >Emitted(24, 14) Source(32, 14) + SourceIndex(0) --- >>>foo4([2, "trimmer", "trimming"]); 1-> 2 >^^^^ 3 > ^ 4 > ^ 5 > ^ 6 > ^^ 7 > ^^^^^^^^^ 8 > ^^ 9 > ^^^^^^^^^^ 10> ^ 11> ^ 12> ^ 13> ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^-> 1-> > 2 >foo4 3 > ( 4 > [ 5 > 2 6 > , 7 > "trimmer" 8 > , 9 > "trimming" 10> ] 11> ) 12> ; 1->Emitted(25, 1) Source(33, 1) + SourceIndex(0) 2 >Emitted(25, 5) Source(33, 5) + SourceIndex(0) 3 >Emitted(25, 6) Source(33, 6) + SourceIndex(0) 4 >Emitted(25, 7) Source(33, 7) + SourceIndex(0) 5 >Emitted(25, 8) Source(33, 8) + SourceIndex(0) 6 >Emitted(25, 10) Source(33, 10) + SourceIndex(0) 7 >Emitted(25, 19) Source(33, 19) + SourceIndex(0) 8 >Emitted(25, 21) Source(33, 21) + SourceIndex(0) 9 >Emitted(25, 31) Source(33, 31) + SourceIndex(0) 10>Emitted(25, 32) Source(33, 32) + SourceIndex(0) 11>Emitted(25, 33) Source(33, 33) + SourceIndex(0) 12>Emitted(25, 34) Source(33, 34) + SourceIndex(0) --- >>>//# sourceMappingURL=sourceMapValidationDestructuringParametertArrayBindingPatternDefaultValues.js.map
tests/baselines/reference/sourceMapValidationDestructuringParametertArrayBindingPatternDefaultValues.sourcemap.txt
0
https://github.com/microsoft/TypeScript/commit/f99072593dc130e0073762d3071aa64882be0823
[ 0.00017805336392484605, 0.00017369200941175222, 0.00016486126696690917, 0.00017431637388654053, 0.000003430274773563724 ]
{ "id": 3, "code_window": [ " message: \"Unrecognized JSON command: foobar\",\n", " request_seq: 0,\n", " success: false,\n", " updateGraphDurationMs: undefined,\n", " };\n", " expect(lastSent).to.deep.equal(expected);\n", " });\n", " it(\"should return a tuple containing the response and if a response is required on success\", () => {\n", " const req: protocol.ConfigureRequest = {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " performanceData: undefined,\n" ], "file_path": "src/testRunner/unittests/tsserver/session.ts", "type": "replace", "edit_start_line_idx": 103 }
// @target: es5 // @module: commonjs // @declaration: true export default (1 + 2);
tests/cases/compiler/es5ExportDefaultExpression.ts
0
https://github.com/microsoft/TypeScript/commit/f99072593dc130e0073762d3071aa64882be0823
[ 0.00016804052575025707, 0.00016804052575025707, 0.00016804052575025707, 0.00016804052575025707, 0 ]
{ "id": 3, "code_window": [ " message: \"Unrecognized JSON command: foobar\",\n", " request_seq: 0,\n", " success: false,\n", " updateGraphDurationMs: undefined,\n", " };\n", " expect(lastSent).to.deep.equal(expected);\n", " });\n", " it(\"should return a tuple containing the response and if a response is required on success\", () => {\n", " const req: protocol.ConfigureRequest = {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " performanceData: undefined,\n" ], "file_path": "src/testRunner/unittests/tsserver/session.ts", "type": "replace", "edit_start_line_idx": 103 }
=== tests/cases/compiler/redefineArray.ts === Array = function (n:number, s:string) {return n;}; >Array : Symbol(Array, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) >n : Symbol(n, Decl(redefineArray.ts, 0, 18)) >s : Symbol(s, Decl(redefineArray.ts, 0, 27)) >n : Symbol(n, Decl(redefineArray.ts, 0, 18))
tests/baselines/reference/redefineArray.symbols
0
https://github.com/microsoft/TypeScript/commit/f99072593dc130e0073762d3071aa64882be0823
[ 0.00017540437693241984, 0.00017540437693241984, 0.00017540437693241984, 0.00017540437693241984, 0 ]
{ "id": 4, "code_window": [ " type: \"response\",\n", " success: true,\n", " request_seq: 0,\n", " seq: 0,\n", " body: undefined,\n", " updateGraphDurationMs: undefined,\n", " });\n", " });\n", " it(\"should handle literal types in request\", () => {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " performanceData: undefined,\n" ], "file_path": "src/testRunner/unittests/tsserver/session.ts", "type": "replace", "edit_start_line_idx": 130 }
namespace ts.server { const _chai: typeof import("chai") = require("chai"); const expect: typeof _chai.expect = _chai.expect; let lastWrittenToHost: string; const noopFileWatcher: FileWatcher = { close: noop }; const mockHost: ServerHost = { args: [], newLine: "\n", useCaseSensitiveFileNames: true, write(s): void { lastWrittenToHost = s; }, readFile: returnUndefined, writeFile: noop, resolvePath(): string { return undefined!; }, // TODO: GH#18217 fileExists: () => false, directoryExists: () => false, getDirectories: () => [], createDirectory: noop, getExecutingFilePath(): string { return ""; }, getCurrentDirectory(): string { return ""; }, getEnvironmentVariable(): string { return ""; }, readDirectory() { return []; }, exit: noop, setTimeout() { return 0; }, clearTimeout: noop, setImmediate: () => 0, clearImmediate: noop, createHash: Harness.mockHash, watchFile: () => noopFileWatcher, watchDirectory: () => noopFileWatcher }; class TestSession extends Session { getProjectService() { return this.projectService; } } describe("unittests:: tsserver:: Session:: General functionality", () => { let session: TestSession; let lastSent: protocol.Message; function createSession(): TestSession { const opts: SessionOptions = { host: mockHost, cancellationToken: nullCancellationToken, useSingleInferredProject: false, useInferredProjectPerProjectRoot: false, typingsInstaller: undefined!, // TODO: GH#18217 byteLength: Utils.byteLength, hrtime: process.hrtime, logger: projectSystem.nullLogger, canUseEvents: true }; return new TestSession(opts); } // Disable sourcemap support for the duration of the test, as sourcemapping the errors generated during this test is slow and not something we care to test let oldPrepare: AnyFunction; before(() => { oldPrepare = (Error as any).prepareStackTrace; delete (Error as any).prepareStackTrace; }); after(() => { (Error as any).prepareStackTrace = oldPrepare; }); beforeEach(() => { session = createSession(); session.send = (msg: protocol.Message) => { lastSent = msg; }; }); describe("executeCommand", () => { it("should throw when commands are executed with invalid arguments", () => { const req: protocol.FileRequest = { command: CommandNames.Open, seq: 0, type: "request", arguments: { file: undefined! // TODO: GH#18217 } }; expect(() => session.executeCommand(req)).to.throw(); }); it("should output an error response when a command does not exist", () => { const req: protocol.Request = { command: "foobar", seq: 0, type: "request" }; session.executeCommand(req); const expected: protocol.Response = { command: CommandNames.Unknown, type: "response", seq: 0, message: "Unrecognized JSON command: foobar", request_seq: 0, success: false, updateGraphDurationMs: undefined, }; expect(lastSent).to.deep.equal(expected); }); it("should return a tuple containing the response and if a response is required on success", () => { const req: protocol.ConfigureRequest = { command: CommandNames.Configure, seq: 0, type: "request", arguments: { hostInfo: "unit test", formatOptions: { newLineCharacter: "`n" } } }; expect(session.executeCommand(req)).to.deep.equal({ responseRequired: false }); expect(lastSent).to.deep.equal({ command: CommandNames.Configure, type: "response", success: true, request_seq: 0, seq: 0, body: undefined, updateGraphDurationMs: undefined, }); }); it("should handle literal types in request", () => { const configureRequest: protocol.ConfigureRequest = { command: CommandNames.Configure, seq: 0, type: "request", arguments: { formatOptions: { indentStyle: protocol.IndentStyle.Block, } } }; session.onMessage(JSON.stringify(configureRequest)); assert.equal(session.getProjectService().getFormatCodeOptions("" as NormalizedPath).indentStyle, IndentStyle.Block); const setOptionsRequest: protocol.SetCompilerOptionsForInferredProjectsRequest = { command: CommandNames.CompilerOptionsForInferredProjects, seq: 1, type: "request", arguments: { options: { module: protocol.ModuleKind.System, target: protocol.ScriptTarget.ES5, jsx: protocol.JsxEmit.React, newLine: protocol.NewLineKind.Lf, moduleResolution: protocol.ModuleResolutionKind.Node, } } }; session.onMessage(JSON.stringify(setOptionsRequest)); assert.deepEqual( session.getProjectService().getCompilerOptionsForInferredProjects(), <CompilerOptions>{ module: ModuleKind.System, target: ScriptTarget.ES5, jsx: JsxEmit.React, newLine: NewLineKind.LineFeed, moduleResolution: ModuleResolutionKind.NodeJs, allowNonTsExtensions: true // injected by tsserver }); }); it("Status request gives ts.version", () => { const req: protocol.StatusRequest = { command: CommandNames.Status, seq: 0, type: "request" }; const expected: protocol.StatusResponseBody = { version: ts.version, // eslint-disable-line @typescript-eslint/no-unnecessary-qualifier }; assert.deepEqual(session.executeCommand(req).response, expected); }); }); describe("onMessage", () => { const allCommandNames: CommandNames[] = [ CommandNames.Brace, CommandNames.BraceFull, CommandNames.BraceCompletion, CommandNames.Change, CommandNames.Close, CommandNames.Completions, CommandNames.CompletionsFull, CommandNames.CompletionDetails, CommandNames.CompileOnSaveAffectedFileList, CommandNames.Configure, CommandNames.Definition, CommandNames.DefinitionFull, CommandNames.DefinitionAndBoundSpan, CommandNames.DefinitionAndBoundSpanFull, CommandNames.Implementation, CommandNames.ImplementationFull, CommandNames.Exit, CommandNames.Format, CommandNames.Formatonkey, CommandNames.FormatFull, CommandNames.FormatonkeyFull, CommandNames.FormatRangeFull, CommandNames.Geterr, CommandNames.GeterrForProject, CommandNames.SemanticDiagnosticsSync, CommandNames.SyntacticDiagnosticsSync, CommandNames.SuggestionDiagnosticsSync, CommandNames.NavBar, CommandNames.NavBarFull, CommandNames.Navto, CommandNames.NavtoFull, CommandNames.NavTree, CommandNames.NavTreeFull, CommandNames.Occurrences, CommandNames.DocumentHighlights, CommandNames.DocumentHighlightsFull, CommandNames.JsxClosingTag, CommandNames.Open, CommandNames.Quickinfo, CommandNames.QuickinfoFull, CommandNames.References, CommandNames.ReferencesFull, CommandNames.Reload, CommandNames.Rename, CommandNames.RenameInfoFull, CommandNames.RenameLocationsFull, CommandNames.Saveto, CommandNames.SignatureHelp, CommandNames.SignatureHelpFull, CommandNames.Status, CommandNames.TypeDefinition, CommandNames.ProjectInfo, CommandNames.ReloadProjects, CommandNames.Unknown, CommandNames.OpenExternalProject, CommandNames.CloseExternalProject, CommandNames.SynchronizeProjectList, CommandNames.ApplyChangedToOpenFiles, CommandNames.EncodedSemanticClassificationsFull, CommandNames.Cleanup, CommandNames.OutliningSpans, CommandNames.TodoComments, CommandNames.Indentation, CommandNames.DocCommentTemplate, CommandNames.CompilerOptionsDiagnosticsFull, CommandNames.NameOrDottedNameSpan, CommandNames.BreakpointStatement, CommandNames.CompilerOptionsForInferredProjects, CommandNames.GetCodeFixes, CommandNames.GetCodeFixesFull, CommandNames.GetSupportedCodeFixes, CommandNames.GetApplicableRefactors, CommandNames.GetEditsForRefactor, CommandNames.GetEditsForRefactorFull, CommandNames.OrganizeImports, CommandNames.OrganizeImportsFull, CommandNames.GetEditsForFileRename, CommandNames.GetEditsForFileRenameFull, CommandNames.SelectionRange, CommandNames.PrepareCallHierarchy, CommandNames.ProvideCallHierarchyIncomingCalls, CommandNames.ProvideCallHierarchyOutgoingCalls, ]; it("should not throw when commands are executed with invalid arguments", () => { let i = 0; for (const name of allCommandNames) { const req: protocol.Request = { command: name, seq: i, type: "request" }; i++; session.onMessage(JSON.stringify(req)); req.seq = i; i++; req.arguments = {}; session.onMessage(JSON.stringify(req)); req.seq = i; i++; req.arguments = null; // eslint-disable-line no-null/no-null session.onMessage(JSON.stringify(req)); req.seq = i; i++; req.arguments = ""; session.onMessage(JSON.stringify(req)); req.seq = i; i++; req.arguments = 0; session.onMessage(JSON.stringify(req)); req.seq = i; i++; req.arguments = []; session.onMessage(JSON.stringify(req)); } session.onMessage("GARBAGE NON_JSON DATA"); }); it("should output the response for a correctly handled message", () => { const req: protocol.ConfigureRequest = { command: CommandNames.Configure, seq: 0, type: "request", arguments: { hostInfo: "unit test", formatOptions: { newLineCharacter: "`n" } } }; session.onMessage(JSON.stringify(req)); expect(lastSent).to.deep.equal(<protocol.ConfigureResponse>{ command: CommandNames.Configure, type: "response", success: true, request_seq: 0, seq: 0, body: undefined, updateGraphDurationMs: undefined, }); }); }); describe("send", () => { it("is an overrideable handle which sends protocol messages over the wire", () => { const msg: protocol.Request = { seq: 0, type: "request", command: "" }; const strmsg = JSON.stringify(msg); const len = 1 + Utils.byteLength(strmsg, "utf8"); const resultMsg = `Content-Length: ${len}\r\n\r\n${strmsg}\n`; session.send = Session.prototype.send; assert(session.send); expect(session.send(msg)).to.not.exist; // eslint-disable-line no-unused-expressions expect(lastWrittenToHost).to.equal(resultMsg); }); }); describe("addProtocolHandler", () => { it("can add protocol handlers", () => { const respBody = { item: false }; const command = "newhandle"; const result: HandlerResponse = { response: respBody, responseRequired: true }; session.addProtocolHandler(command, () => result); expect(session.executeCommand({ command, seq: 0, type: "request" })).to.deep.equal(result); }); it("throws when a duplicate handler is passed", () => { const respBody = { item: false }; const resp: HandlerResponse = { response: respBody, responseRequired: true }; const command = "newhandle"; session.addProtocolHandler(command, () => resp); expect(() => session.addProtocolHandler(command, () => resp)) .to.throw(`Protocol handler already exists for command "${command}"`); }); }); describe("event", () => { it("can format event responses and send them", () => { const evt = "notify-test"; const info = { test: true }; session.event(info, evt); expect(lastSent).to.deep.equal({ type: "event", seq: 0, event: evt, body: info }); }); }); describe("output", () => { it("can format command responses and send them", () => { const body = { block: { key: "value" } }; const command = "test"; session.output(body, command, /*reqSeq*/ 0); expect(lastSent).to.deep.equal({ seq: 0, request_seq: 0, type: "response", command, body, success: true, updateGraphDurationMs: undefined, }); }); }); }); describe("unittests:: tsserver:: Session:: exceptions", () => { // Disable sourcemap support for the duration of the test, as sourcemapping the errors generated during this test is slow and not something we care to test let oldPrepare: AnyFunction; let oldStackTraceLimit: number; before(() => { oldStackTraceLimit = (Error as any).stackTraceLimit; oldPrepare = (Error as any).prepareStackTrace; delete (Error as any).prepareStackTrace; (Error as any).stackTraceLimit = 10; }); after(() => { (Error as any).prepareStackTrace = oldPrepare; (Error as any).stackTraceLimit = oldStackTraceLimit; }); const command = "testhandler"; class TestSession extends Session { lastSent: protocol.Message | undefined; private exceptionRaisingHandler(_request: protocol.Request): { response?: any, responseRequired: boolean } { f1(); return Debug.fail(); // unreachable, throw to make compiler happy function f1() { throw new Error("myMessage"); } } constructor() { super({ host: mockHost, cancellationToken: nullCancellationToken, useSingleInferredProject: false, useInferredProjectPerProjectRoot: false, typingsInstaller: undefined!, // TODO: GH#18217 byteLength: Utils.byteLength, hrtime: process.hrtime, logger: projectSystem.nullLogger, canUseEvents: true }); this.addProtocolHandler(command, this.exceptionRaisingHandler); } send(msg: protocol.Message) { this.lastSent = msg; } } it("raised in a protocol handler generate an event", () => { const session = new TestSession(); const request = { command, seq: 0, type: "request" }; session.onMessage(JSON.stringify(request)); const lastSent = session.lastSent as protocol.Response; expect(lastSent).to.contain({ seq: 0, type: "response", command, success: false }); expect(lastSent.message).has.string("myMessage").and.has.string("f1"); }); }); describe("unittests:: tsserver:: Session:: how Session is extendable via subclassing", () => { class TestSession extends Session { lastSent: protocol.Message | undefined; customHandler = "testhandler"; constructor() { super({ host: mockHost, cancellationToken: nullCancellationToken, useSingleInferredProject: false, useInferredProjectPerProjectRoot: false, typingsInstaller: undefined!, // TODO: GH#18217 byteLength: Utils.byteLength, hrtime: process.hrtime, logger: projectSystem.createHasErrorMessageLogger().logger, canUseEvents: true }); this.addProtocolHandler(this.customHandler, () => { return { response: undefined, responseRequired: true }; }); } send(msg: protocol.Message) { this.lastSent = msg; } } it("can override methods such as send", () => { const session = new TestSession(); const body = { block: { key: "value" } }; const command = "test"; session.output(body, command, /*reqSeq*/ 0); expect(session.lastSent).to.deep.equal({ seq: 0, request_seq: 0, type: "response", command, body, success: true, updateGraphDurationMs: undefined, }); }); it("can add and respond to new protocol handlers", () => { const session = new TestSession(); expect(session.executeCommand({ seq: 0, type: "request", command: session.customHandler })).to.deep.equal({ response: undefined, responseRequired: true }); }); it("has access to the project service", () => { new class extends TestSession { constructor() { super(); assert(this.projectService); expect(this.projectService).to.be.instanceOf(ProjectService); } }(); }); }); describe("unittests:: tsserver:: Session:: an example of using the Session API to create an in-process server", () => { class InProcSession extends Session { private queue: protocol.Request[] = []; constructor(private client: InProcClient) { super({ host: mockHost, cancellationToken: nullCancellationToken, useSingleInferredProject: false, useInferredProjectPerProjectRoot: false, typingsInstaller: undefined!, // TODO: GH#18217 byteLength: Utils.byteLength, hrtime: process.hrtime, logger: projectSystem.createHasErrorMessageLogger().logger, canUseEvents: true }); this.addProtocolHandler("echo", (req: protocol.Request) => ({ response: req.arguments, responseRequired: true })); } send(msg: protocol.Message) { this.client.handle(msg); } enqueue(msg: protocol.Request) { this.queue.unshift(msg); } handleRequest(msg: protocol.Request) { let response: protocol.Response; try { response = this.executeCommand(msg).response as protocol.Response; } catch (e) { this.output(undefined, msg.command, msg.seq, e.toString()); return; } if (response) { this.output(response, msg.command, msg.seq); } } consumeQueue() { while (this.queue.length > 0) { const elem = this.queue.pop()!; this.handleRequest(elem); } } } class InProcClient { private server: InProcSession | undefined; private seq = 0; private callbacks: ((resp: protocol.Response) => void)[] = []; private eventHandlers = createMap<(args: any) => void>(); handle(msg: protocol.Message): void { if (msg.type === "response") { const response = <protocol.Response>msg; const handler = this.callbacks[response.request_seq]; if (handler) { handler(response); delete this.callbacks[response.request_seq]; } } else if (msg.type === "event") { const event = <protocol.Event>msg; this.emit(event.event, event.body); } } emit(name: string, args: any): void { const handler = this.eventHandlers.get(name); if (handler) { handler(args); } } on(name: string, handler: (args: any) => void): void { this.eventHandlers.set(name, handler); } connect(session: InProcSession): void { this.server = session; } execute(command: string, args: any, callback: (resp: protocol.Response) => void): void { if (!this.server) { return; } this.seq++; this.server.enqueue({ seq: this.seq, type: "request", command, arguments: args }); this.callbacks[this.seq] = callback; } } it("can be constructed and respond to commands", (done) => { const cli = new InProcClient(); const session = new InProcSession(cli); const toEcho = { data: true }; const toEvent = { data: false }; let responses = 0; // Connect the client cli.connect(session); // Add an event handler cli.on("testevent", (eventinfo) => { expect(eventinfo).to.equal(toEvent); responses++; expect(responses).to.equal(1); }); // Trigger said event from the server session.event(toEvent, "testevent"); // Queue an echo command cli.execute("echo", toEcho, (resp) => { assert(resp.success, resp.message); responses++; expect(responses).to.equal(2); expect(resp.body).to.deep.equal(toEcho); }); // Queue a configure command cli.execute("configure", { hostInfo: "unit test", formatOptions: { newLineCharacter: "`n" } }, (resp) => { assert(resp.success, resp.message); responses++; expect(responses).to.equal(3); done(); }); // Consume the queue and trigger the callbacks session.consumeQueue(); }); }); describe("unittests:: tsserver:: Session:: helpers", () => { it(getLocationInNewDocument.name, () => { const text = `// blank line\nconst x = 0;`; const renameLocationInOldText = text.indexOf("0"); const fileName = "/a.ts"; const edits: FileTextChanges = { fileName, textChanges: [ { span: { start: 0, length: 0 }, newText: "const newLocal = 0;\n\n", }, { span: { start: renameLocationInOldText, length: 1 }, newText: "newLocal", }, ], }; const renameLocationInNewText = renameLocationInOldText + edits.textChanges[0].newText.length; const res = getLocationInNewDocument(text, fileName, renameLocationInNewText, [edits]); assert.deepEqual(res, { line: 4, offset: 11 }); }); }); }
src/testRunner/unittests/tsserver/session.ts
1
https://github.com/microsoft/TypeScript/commit/f99072593dc130e0073762d3071aa64882be0823
[ 0.420097678899765, 0.006117284297943115, 0.00016383295587729663, 0.00017277736333198845, 0.048134759068489075 ]
{ "id": 4, "code_window": [ " type: \"response\",\n", " success: true,\n", " request_seq: 0,\n", " seq: 0,\n", " body: undefined,\n", " updateGraphDurationMs: undefined,\n", " });\n", " });\n", " it(\"should handle literal types in request\", () => {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " performanceData: undefined,\n" ], "file_path": "src/testRunner/unittests/tsserver/session.ts", "type": "replace", "edit_start_line_idx": 130 }
//// [thisShadowingErrorSpans.ts] class C { m() { this.m(); function f() { this.m(); } } } //// [thisShadowingErrorSpans.js] "use strict"; var C = /** @class */ (function () { function C() { } C.prototype.m = function () { this.m(); function f() { this.m(); } }; return C; }());
tests/baselines/reference/thisShadowingErrorSpans.js
0
https://github.com/microsoft/TypeScript/commit/f99072593dc130e0073762d3071aa64882be0823
[ 0.00016975952894426882, 0.000166842553880997, 0.00016522085934411734, 0.0001655473024584353, 0.0000020669067453127354 ]
{ "id": 4, "code_window": [ " type: \"response\",\n", " success: true,\n", " request_seq: 0,\n", " seq: 0,\n", " body: undefined,\n", " updateGraphDurationMs: undefined,\n", " });\n", " });\n", " it(\"should handle literal types in request\", () => {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " performanceData: undefined,\n" ], "file_path": "src/testRunner/unittests/tsserver/session.ts", "type": "replace", "edit_start_line_idx": 130 }
tests/cases/conformance/scanner/ecmascript3/scannerES3NumericLiteral4.ts(1,3): error TS1124: Digit expected. ==== tests/cases/conformance/scanner/ecmascript3/scannerES3NumericLiteral4.ts (1 errors) ==== 1e !!! error TS1124: Digit expected.
tests/baselines/reference/scannerES3NumericLiteral4.errors.txt
0
https://github.com/microsoft/TypeScript/commit/f99072593dc130e0073762d3071aa64882be0823
[ 0.00017325561202596873, 0.00017325561202596873, 0.00017325561202596873, 0.00017325561202596873, 0 ]
{ "id": 4, "code_window": [ " type: \"response\",\n", " success: true,\n", " request_seq: 0,\n", " seq: 0,\n", " body: undefined,\n", " updateGraphDurationMs: undefined,\n", " });\n", " });\n", " it(\"should handle literal types in request\", () => {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " performanceData: undefined,\n" ], "file_path": "src/testRunner/unittests/tsserver/session.ts", "type": "replace", "edit_start_line_idx": 130 }
=== tests/cases/compiler/conflictMarkerTrivia4.ts === const x = <div> >x : any ><div> : any <<<<<<< HEAD > : any
tests/baselines/reference/conflictMarkerTrivia4.types
0
https://github.com/microsoft/TypeScript/commit/f99072593dc130e0073762d3071aa64882be0823
[ 0.0001695440587354824, 0.0001695440587354824, 0.0001695440587354824, 0.0001695440587354824, 0 ]
{ "id": 7, "code_window": [ " request_seq: 0,\n", " type: \"response\",\n", " command,\n", " body,\n", " success: true,\n", " updateGraphDurationMs: undefined,\n", " });\n", " });\n", " it(\"can add and respond to new protocol handlers\", () => {\n", " const session = new TestSession();\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " performanceData: undefined,\n" ], "file_path": "src/testRunner/unittests/tsserver/session.ts", "type": "replace", "edit_start_line_idx": 542 }
namespace ts.server { const _chai: typeof import("chai") = require("chai"); const expect: typeof _chai.expect = _chai.expect; let lastWrittenToHost: string; const noopFileWatcher: FileWatcher = { close: noop }; const mockHost: ServerHost = { args: [], newLine: "\n", useCaseSensitiveFileNames: true, write(s): void { lastWrittenToHost = s; }, readFile: returnUndefined, writeFile: noop, resolvePath(): string { return undefined!; }, // TODO: GH#18217 fileExists: () => false, directoryExists: () => false, getDirectories: () => [], createDirectory: noop, getExecutingFilePath(): string { return ""; }, getCurrentDirectory(): string { return ""; }, getEnvironmentVariable(): string { return ""; }, readDirectory() { return []; }, exit: noop, setTimeout() { return 0; }, clearTimeout: noop, setImmediate: () => 0, clearImmediate: noop, createHash: Harness.mockHash, watchFile: () => noopFileWatcher, watchDirectory: () => noopFileWatcher }; class TestSession extends Session { getProjectService() { return this.projectService; } } describe("unittests:: tsserver:: Session:: General functionality", () => { let session: TestSession; let lastSent: protocol.Message; function createSession(): TestSession { const opts: SessionOptions = { host: mockHost, cancellationToken: nullCancellationToken, useSingleInferredProject: false, useInferredProjectPerProjectRoot: false, typingsInstaller: undefined!, // TODO: GH#18217 byteLength: Utils.byteLength, hrtime: process.hrtime, logger: projectSystem.nullLogger, canUseEvents: true }; return new TestSession(opts); } // Disable sourcemap support for the duration of the test, as sourcemapping the errors generated during this test is slow and not something we care to test let oldPrepare: AnyFunction; before(() => { oldPrepare = (Error as any).prepareStackTrace; delete (Error as any).prepareStackTrace; }); after(() => { (Error as any).prepareStackTrace = oldPrepare; }); beforeEach(() => { session = createSession(); session.send = (msg: protocol.Message) => { lastSent = msg; }; }); describe("executeCommand", () => { it("should throw when commands are executed with invalid arguments", () => { const req: protocol.FileRequest = { command: CommandNames.Open, seq: 0, type: "request", arguments: { file: undefined! // TODO: GH#18217 } }; expect(() => session.executeCommand(req)).to.throw(); }); it("should output an error response when a command does not exist", () => { const req: protocol.Request = { command: "foobar", seq: 0, type: "request" }; session.executeCommand(req); const expected: protocol.Response = { command: CommandNames.Unknown, type: "response", seq: 0, message: "Unrecognized JSON command: foobar", request_seq: 0, success: false, updateGraphDurationMs: undefined, }; expect(lastSent).to.deep.equal(expected); }); it("should return a tuple containing the response and if a response is required on success", () => { const req: protocol.ConfigureRequest = { command: CommandNames.Configure, seq: 0, type: "request", arguments: { hostInfo: "unit test", formatOptions: { newLineCharacter: "`n" } } }; expect(session.executeCommand(req)).to.deep.equal({ responseRequired: false }); expect(lastSent).to.deep.equal({ command: CommandNames.Configure, type: "response", success: true, request_seq: 0, seq: 0, body: undefined, updateGraphDurationMs: undefined, }); }); it("should handle literal types in request", () => { const configureRequest: protocol.ConfigureRequest = { command: CommandNames.Configure, seq: 0, type: "request", arguments: { formatOptions: { indentStyle: protocol.IndentStyle.Block, } } }; session.onMessage(JSON.stringify(configureRequest)); assert.equal(session.getProjectService().getFormatCodeOptions("" as NormalizedPath).indentStyle, IndentStyle.Block); const setOptionsRequest: protocol.SetCompilerOptionsForInferredProjectsRequest = { command: CommandNames.CompilerOptionsForInferredProjects, seq: 1, type: "request", arguments: { options: { module: protocol.ModuleKind.System, target: protocol.ScriptTarget.ES5, jsx: protocol.JsxEmit.React, newLine: protocol.NewLineKind.Lf, moduleResolution: protocol.ModuleResolutionKind.Node, } } }; session.onMessage(JSON.stringify(setOptionsRequest)); assert.deepEqual( session.getProjectService().getCompilerOptionsForInferredProjects(), <CompilerOptions>{ module: ModuleKind.System, target: ScriptTarget.ES5, jsx: JsxEmit.React, newLine: NewLineKind.LineFeed, moduleResolution: ModuleResolutionKind.NodeJs, allowNonTsExtensions: true // injected by tsserver }); }); it("Status request gives ts.version", () => { const req: protocol.StatusRequest = { command: CommandNames.Status, seq: 0, type: "request" }; const expected: protocol.StatusResponseBody = { version: ts.version, // eslint-disable-line @typescript-eslint/no-unnecessary-qualifier }; assert.deepEqual(session.executeCommand(req).response, expected); }); }); describe("onMessage", () => { const allCommandNames: CommandNames[] = [ CommandNames.Brace, CommandNames.BraceFull, CommandNames.BraceCompletion, CommandNames.Change, CommandNames.Close, CommandNames.Completions, CommandNames.CompletionsFull, CommandNames.CompletionDetails, CommandNames.CompileOnSaveAffectedFileList, CommandNames.Configure, CommandNames.Definition, CommandNames.DefinitionFull, CommandNames.DefinitionAndBoundSpan, CommandNames.DefinitionAndBoundSpanFull, CommandNames.Implementation, CommandNames.ImplementationFull, CommandNames.Exit, CommandNames.Format, CommandNames.Formatonkey, CommandNames.FormatFull, CommandNames.FormatonkeyFull, CommandNames.FormatRangeFull, CommandNames.Geterr, CommandNames.GeterrForProject, CommandNames.SemanticDiagnosticsSync, CommandNames.SyntacticDiagnosticsSync, CommandNames.SuggestionDiagnosticsSync, CommandNames.NavBar, CommandNames.NavBarFull, CommandNames.Navto, CommandNames.NavtoFull, CommandNames.NavTree, CommandNames.NavTreeFull, CommandNames.Occurrences, CommandNames.DocumentHighlights, CommandNames.DocumentHighlightsFull, CommandNames.JsxClosingTag, CommandNames.Open, CommandNames.Quickinfo, CommandNames.QuickinfoFull, CommandNames.References, CommandNames.ReferencesFull, CommandNames.Reload, CommandNames.Rename, CommandNames.RenameInfoFull, CommandNames.RenameLocationsFull, CommandNames.Saveto, CommandNames.SignatureHelp, CommandNames.SignatureHelpFull, CommandNames.Status, CommandNames.TypeDefinition, CommandNames.ProjectInfo, CommandNames.ReloadProjects, CommandNames.Unknown, CommandNames.OpenExternalProject, CommandNames.CloseExternalProject, CommandNames.SynchronizeProjectList, CommandNames.ApplyChangedToOpenFiles, CommandNames.EncodedSemanticClassificationsFull, CommandNames.Cleanup, CommandNames.OutliningSpans, CommandNames.TodoComments, CommandNames.Indentation, CommandNames.DocCommentTemplate, CommandNames.CompilerOptionsDiagnosticsFull, CommandNames.NameOrDottedNameSpan, CommandNames.BreakpointStatement, CommandNames.CompilerOptionsForInferredProjects, CommandNames.GetCodeFixes, CommandNames.GetCodeFixesFull, CommandNames.GetSupportedCodeFixes, CommandNames.GetApplicableRefactors, CommandNames.GetEditsForRefactor, CommandNames.GetEditsForRefactorFull, CommandNames.OrganizeImports, CommandNames.OrganizeImportsFull, CommandNames.GetEditsForFileRename, CommandNames.GetEditsForFileRenameFull, CommandNames.SelectionRange, CommandNames.PrepareCallHierarchy, CommandNames.ProvideCallHierarchyIncomingCalls, CommandNames.ProvideCallHierarchyOutgoingCalls, ]; it("should not throw when commands are executed with invalid arguments", () => { let i = 0; for (const name of allCommandNames) { const req: protocol.Request = { command: name, seq: i, type: "request" }; i++; session.onMessage(JSON.stringify(req)); req.seq = i; i++; req.arguments = {}; session.onMessage(JSON.stringify(req)); req.seq = i; i++; req.arguments = null; // eslint-disable-line no-null/no-null session.onMessage(JSON.stringify(req)); req.seq = i; i++; req.arguments = ""; session.onMessage(JSON.stringify(req)); req.seq = i; i++; req.arguments = 0; session.onMessage(JSON.stringify(req)); req.seq = i; i++; req.arguments = []; session.onMessage(JSON.stringify(req)); } session.onMessage("GARBAGE NON_JSON DATA"); }); it("should output the response for a correctly handled message", () => { const req: protocol.ConfigureRequest = { command: CommandNames.Configure, seq: 0, type: "request", arguments: { hostInfo: "unit test", formatOptions: { newLineCharacter: "`n" } } }; session.onMessage(JSON.stringify(req)); expect(lastSent).to.deep.equal(<protocol.ConfigureResponse>{ command: CommandNames.Configure, type: "response", success: true, request_seq: 0, seq: 0, body: undefined, updateGraphDurationMs: undefined, }); }); }); describe("send", () => { it("is an overrideable handle which sends protocol messages over the wire", () => { const msg: protocol.Request = { seq: 0, type: "request", command: "" }; const strmsg = JSON.stringify(msg); const len = 1 + Utils.byteLength(strmsg, "utf8"); const resultMsg = `Content-Length: ${len}\r\n\r\n${strmsg}\n`; session.send = Session.prototype.send; assert(session.send); expect(session.send(msg)).to.not.exist; // eslint-disable-line no-unused-expressions expect(lastWrittenToHost).to.equal(resultMsg); }); }); describe("addProtocolHandler", () => { it("can add protocol handlers", () => { const respBody = { item: false }; const command = "newhandle"; const result: HandlerResponse = { response: respBody, responseRequired: true }; session.addProtocolHandler(command, () => result); expect(session.executeCommand({ command, seq: 0, type: "request" })).to.deep.equal(result); }); it("throws when a duplicate handler is passed", () => { const respBody = { item: false }; const resp: HandlerResponse = { response: respBody, responseRequired: true }; const command = "newhandle"; session.addProtocolHandler(command, () => resp); expect(() => session.addProtocolHandler(command, () => resp)) .to.throw(`Protocol handler already exists for command "${command}"`); }); }); describe("event", () => { it("can format event responses and send them", () => { const evt = "notify-test"; const info = { test: true }; session.event(info, evt); expect(lastSent).to.deep.equal({ type: "event", seq: 0, event: evt, body: info }); }); }); describe("output", () => { it("can format command responses and send them", () => { const body = { block: { key: "value" } }; const command = "test"; session.output(body, command, /*reqSeq*/ 0); expect(lastSent).to.deep.equal({ seq: 0, request_seq: 0, type: "response", command, body, success: true, updateGraphDurationMs: undefined, }); }); }); }); describe("unittests:: tsserver:: Session:: exceptions", () => { // Disable sourcemap support for the duration of the test, as sourcemapping the errors generated during this test is slow and not something we care to test let oldPrepare: AnyFunction; let oldStackTraceLimit: number; before(() => { oldStackTraceLimit = (Error as any).stackTraceLimit; oldPrepare = (Error as any).prepareStackTrace; delete (Error as any).prepareStackTrace; (Error as any).stackTraceLimit = 10; }); after(() => { (Error as any).prepareStackTrace = oldPrepare; (Error as any).stackTraceLimit = oldStackTraceLimit; }); const command = "testhandler"; class TestSession extends Session { lastSent: protocol.Message | undefined; private exceptionRaisingHandler(_request: protocol.Request): { response?: any, responseRequired: boolean } { f1(); return Debug.fail(); // unreachable, throw to make compiler happy function f1() { throw new Error("myMessage"); } } constructor() { super({ host: mockHost, cancellationToken: nullCancellationToken, useSingleInferredProject: false, useInferredProjectPerProjectRoot: false, typingsInstaller: undefined!, // TODO: GH#18217 byteLength: Utils.byteLength, hrtime: process.hrtime, logger: projectSystem.nullLogger, canUseEvents: true }); this.addProtocolHandler(command, this.exceptionRaisingHandler); } send(msg: protocol.Message) { this.lastSent = msg; } } it("raised in a protocol handler generate an event", () => { const session = new TestSession(); const request = { command, seq: 0, type: "request" }; session.onMessage(JSON.stringify(request)); const lastSent = session.lastSent as protocol.Response; expect(lastSent).to.contain({ seq: 0, type: "response", command, success: false }); expect(lastSent.message).has.string("myMessage").and.has.string("f1"); }); }); describe("unittests:: tsserver:: Session:: how Session is extendable via subclassing", () => { class TestSession extends Session { lastSent: protocol.Message | undefined; customHandler = "testhandler"; constructor() { super({ host: mockHost, cancellationToken: nullCancellationToken, useSingleInferredProject: false, useInferredProjectPerProjectRoot: false, typingsInstaller: undefined!, // TODO: GH#18217 byteLength: Utils.byteLength, hrtime: process.hrtime, logger: projectSystem.createHasErrorMessageLogger().logger, canUseEvents: true }); this.addProtocolHandler(this.customHandler, () => { return { response: undefined, responseRequired: true }; }); } send(msg: protocol.Message) { this.lastSent = msg; } } it("can override methods such as send", () => { const session = new TestSession(); const body = { block: { key: "value" } }; const command = "test"; session.output(body, command, /*reqSeq*/ 0); expect(session.lastSent).to.deep.equal({ seq: 0, request_seq: 0, type: "response", command, body, success: true, updateGraphDurationMs: undefined, }); }); it("can add and respond to new protocol handlers", () => { const session = new TestSession(); expect(session.executeCommand({ seq: 0, type: "request", command: session.customHandler })).to.deep.equal({ response: undefined, responseRequired: true }); }); it("has access to the project service", () => { new class extends TestSession { constructor() { super(); assert(this.projectService); expect(this.projectService).to.be.instanceOf(ProjectService); } }(); }); }); describe("unittests:: tsserver:: Session:: an example of using the Session API to create an in-process server", () => { class InProcSession extends Session { private queue: protocol.Request[] = []; constructor(private client: InProcClient) { super({ host: mockHost, cancellationToken: nullCancellationToken, useSingleInferredProject: false, useInferredProjectPerProjectRoot: false, typingsInstaller: undefined!, // TODO: GH#18217 byteLength: Utils.byteLength, hrtime: process.hrtime, logger: projectSystem.createHasErrorMessageLogger().logger, canUseEvents: true }); this.addProtocolHandler("echo", (req: protocol.Request) => ({ response: req.arguments, responseRequired: true })); } send(msg: protocol.Message) { this.client.handle(msg); } enqueue(msg: protocol.Request) { this.queue.unshift(msg); } handleRequest(msg: protocol.Request) { let response: protocol.Response; try { response = this.executeCommand(msg).response as protocol.Response; } catch (e) { this.output(undefined, msg.command, msg.seq, e.toString()); return; } if (response) { this.output(response, msg.command, msg.seq); } } consumeQueue() { while (this.queue.length > 0) { const elem = this.queue.pop()!; this.handleRequest(elem); } } } class InProcClient { private server: InProcSession | undefined; private seq = 0; private callbacks: ((resp: protocol.Response) => void)[] = []; private eventHandlers = createMap<(args: any) => void>(); handle(msg: protocol.Message): void { if (msg.type === "response") { const response = <protocol.Response>msg; const handler = this.callbacks[response.request_seq]; if (handler) { handler(response); delete this.callbacks[response.request_seq]; } } else if (msg.type === "event") { const event = <protocol.Event>msg; this.emit(event.event, event.body); } } emit(name: string, args: any): void { const handler = this.eventHandlers.get(name); if (handler) { handler(args); } } on(name: string, handler: (args: any) => void): void { this.eventHandlers.set(name, handler); } connect(session: InProcSession): void { this.server = session; } execute(command: string, args: any, callback: (resp: protocol.Response) => void): void { if (!this.server) { return; } this.seq++; this.server.enqueue({ seq: this.seq, type: "request", command, arguments: args }); this.callbacks[this.seq] = callback; } } it("can be constructed and respond to commands", (done) => { const cli = new InProcClient(); const session = new InProcSession(cli); const toEcho = { data: true }; const toEvent = { data: false }; let responses = 0; // Connect the client cli.connect(session); // Add an event handler cli.on("testevent", (eventinfo) => { expect(eventinfo).to.equal(toEvent); responses++; expect(responses).to.equal(1); }); // Trigger said event from the server session.event(toEvent, "testevent"); // Queue an echo command cli.execute("echo", toEcho, (resp) => { assert(resp.success, resp.message); responses++; expect(responses).to.equal(2); expect(resp.body).to.deep.equal(toEcho); }); // Queue a configure command cli.execute("configure", { hostInfo: "unit test", formatOptions: { newLineCharacter: "`n" } }, (resp) => { assert(resp.success, resp.message); responses++; expect(responses).to.equal(3); done(); }); // Consume the queue and trigger the callbacks session.consumeQueue(); }); }); describe("unittests:: tsserver:: Session:: helpers", () => { it(getLocationInNewDocument.name, () => { const text = `// blank line\nconst x = 0;`; const renameLocationInOldText = text.indexOf("0"); const fileName = "/a.ts"; const edits: FileTextChanges = { fileName, textChanges: [ { span: { start: 0, length: 0 }, newText: "const newLocal = 0;\n\n", }, { span: { start: renameLocationInOldText, length: 1 }, newText: "newLocal", }, ], }; const renameLocationInNewText = renameLocationInOldText + edits.textChanges[0].newText.length; const res = getLocationInNewDocument(text, fileName, renameLocationInNewText, [edits]); assert.deepEqual(res, { line: 4, offset: 11 }); }); }); }
src/testRunner/unittests/tsserver/session.ts
1
https://github.com/microsoft/TypeScript/commit/f99072593dc130e0073762d3071aa64882be0823
[ 0.9978747367858887, 0.18051652610301971, 0.00016462251369375736, 0.0021915638353675604, 0.3615853190422058 ]
{ "id": 7, "code_window": [ " request_seq: 0,\n", " type: \"response\",\n", " command,\n", " body,\n", " success: true,\n", " updateGraphDurationMs: undefined,\n", " });\n", " });\n", " it(\"can add and respond to new protocol handlers\", () => {\n", " const session = new TestSession();\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " performanceData: undefined,\n" ], "file_path": "src/testRunner/unittests/tsserver/session.ts", "type": "replace", "edit_start_line_idx": 542 }
=== tests/cases/compiler/numericIndexerConstraint.ts === class C { >C : Symbol(C, Decl(numericIndexerConstraint.ts, 0, 0)) 0: number; >0 : Symbol(C[0], Decl(numericIndexerConstraint.ts, 0, 9)) [x: number]: RegExp; >x : Symbol(x, Decl(numericIndexerConstraint.ts, 2, 5)) >RegExp : Symbol(RegExp, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) }
tests/baselines/reference/numericIndexerConstraint.symbols
0
https://github.com/microsoft/TypeScript/commit/f99072593dc130e0073762d3071aa64882be0823
[ 0.00017195068357978016, 0.00017048927838914096, 0.00016902785864658654, 0.00017048927838914096, 0.000001461412466596812 ]
{ "id": 7, "code_window": [ " request_seq: 0,\n", " type: \"response\",\n", " command,\n", " body,\n", " success: true,\n", " updateGraphDurationMs: undefined,\n", " });\n", " });\n", " it(\"can add and respond to new protocol handlers\", () => {\n", " const session = new TestSession();\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " performanceData: undefined,\n" ], "file_path": "src/testRunner/unittests/tsserver/session.ts", "type": "replace", "edit_start_line_idx": 542 }
//@jsx: preserve //@filename: test.tsx function Test() { } <Test></Test>
tests/cases/conformance/jsx/tsxAttributeResolution13.tsx
0
https://github.com/microsoft/TypeScript/commit/f99072593dc130e0073762d3071aa64882be0823
[ 0.00016699476691428572, 0.00016699476691428572, 0.00016699476691428572, 0.00016699476691428572, 0 ]
{ "id": 7, "code_window": [ " request_seq: 0,\n", " type: \"response\",\n", " command,\n", " body,\n", " success: true,\n", " updateGraphDurationMs: undefined,\n", " });\n", " });\n", " it(\"can add and respond to new protocol handlers\", () => {\n", " const session = new TestSession();\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " performanceData: undefined,\n" ], "file_path": "src/testRunner/unittests/tsserver/session.ts", "type": "replace", "edit_start_line_idx": 542 }
/// <reference path='fourslash.ts' /> //// const foo = /*a*/a/*b*/ => { return 1; }; goTo.select("a", "b"); edit.applyRefactor({ refactorName: "Add or remove braces in an arrow function", actionName: "Remove braces from arrow function", actionDescription: "Remove braces from arrow function", newContent: `const foo = a => 1;`, });
tests/cases/fourslash/refactorAddOrRemoveBracesToArrowFunction6.ts
0
https://github.com/microsoft/TypeScript/commit/f99072593dc130e0073762d3071aa64882be0823
[ 0.0001752574316924438, 0.0001723714085528627, 0.00016948538541328162, 0.0001723714085528627, 0.0000028860231395810843 ]
{ "id": 0, "code_window": [ "\n", "\tprivate selection: Selection;\n", "\tprivate selectionId: string;\n", "\tprivate cursors: Position[];\n", "\n", "\tconstructor(selection: Selection, cursors: Position[] = []) {\n", "\t\tthis.selection = selection;\n", "\t\tthis.cursors = cursors;\n", "\t}\n", "\n", "\tpublic getEditOperations(model: editorCommon.ITokenizedModel, builder: editorCommon.IEditOperationBuilder): void {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tconstructor(selection: Selection, cursors: Position[]) {\n" ], "file_path": "src/vs/editor/common/commands/trimTrailingWhitespaceCommand.ts", "type": "replace", "edit_start_line_idx": 19 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import * as strings from 'vs/base/common/strings'; import { EditOperation } from 'vs/editor/common/core/editOperation'; import { Range } from 'vs/editor/common/core/range'; import { Position } from 'vs/editor/common/core/position'; import * as editorCommon from 'vs/editor/common/editorCommon'; import { Selection } from 'vs/editor/common/core/selection'; export class TrimTrailingWhitespaceCommand implements editorCommon.ICommand { private selection: Selection; private selectionId: string; private cursors: Position[]; constructor(selection: Selection, cursors: Position[] = []) { this.selection = selection; this.cursors = cursors; } public getEditOperations(model: editorCommon.ITokenizedModel, builder: editorCommon.IEditOperationBuilder): void { let ops = trimTrailingWhitespace(model, this.cursors); for (let i = 0, len = ops.length; i < len; i++) { let op = ops[i]; builder.addEditOperation(op.range, op.text); } this.selectionId = builder.trackSelection(this.selection); } public computeCursorState(model: editorCommon.ITokenizedModel, helper: editorCommon.ICursorStateComputerData): Selection { return helper.getTrackedSelection(this.selectionId); } } /** * Generate commands for trimming trailing whitespace on a model and ignore lines on which cursors are sitting. */ export function trimTrailingWhitespace(model: editorCommon.ITextModel, cursors: Position[]): editorCommon.IIdentifiedSingleEditOperation[] { // Sort cursors ascending cursors.sort((a, b) => { if (a.lineNumber === b.lineNumber) { return a.column - b.column; } return a.lineNumber - b.lineNumber; }); // Reduce multiple cursors on the same line and only keep the last one on the line for (let i = cursors.length - 2; i >= 0; i--) { if (cursors[i].lineNumber === cursors[i + 1].lineNumber) { // Remove cursor at `i` cursors.splice(i, 1); } } let r: editorCommon.IIdentifiedSingleEditOperation[] = []; let rLen = 0; let cursorIndex = 0; let cursorLen = cursors.length; for (let lineNumber = 1, lineCount = model.getLineCount(); lineNumber <= lineCount; lineNumber++) { let lineContent = model.getLineContent(lineNumber); let maxLineColumn = lineContent.length + 1; let minEditColumn = 0; if (cursorIndex < cursorLen && cursors[cursorIndex].lineNumber === lineNumber) { minEditColumn = cursors[cursorIndex].column; cursorIndex++; if (minEditColumn === maxLineColumn) { // The cursor is at the end of the line => no edits for sure on this line continue; } } if (lineContent.length === 0) { continue; } let lastNonWhitespaceIndex = strings.lastNonWhitespaceIndex(lineContent); let fromColumn = 0; if (lastNonWhitespaceIndex === -1) { // Entire line is whitespace fromColumn = 1; } else if (lastNonWhitespaceIndex !== lineContent.length - 1) { // There is trailing whitespace fromColumn = lastNonWhitespaceIndex + 2; } else { // There is no trailing whitespace continue; } fromColumn = Math.max(minEditColumn, fromColumn); r[rLen++] = EditOperation.delete(new Range( lineNumber, fromColumn, lineNumber, maxLineColumn )); } return r; }
src/vs/editor/common/commands/trimTrailingWhitespaceCommand.ts
1
https://github.com/microsoft/vscode/commit/5d3dfe86cd6ac769a66f5473da3ab63c2a6918bf
[ 0.9974610805511475, 0.20191627740859985, 0.00016313490050379187, 0.0052432045340538025, 0.37629103660583496 ]
{ "id": 0, "code_window": [ "\n", "\tprivate selection: Selection;\n", "\tprivate selectionId: string;\n", "\tprivate cursors: Position[];\n", "\n", "\tconstructor(selection: Selection, cursors: Position[] = []) {\n", "\t\tthis.selection = selection;\n", "\t\tthis.cursors = cursors;\n", "\t}\n", "\n", "\tpublic getEditOperations(model: editorCommon.ITokenizedModel, builder: editorCommon.IEditOperationBuilder): void {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tconstructor(selection: Selection, cursors: Position[]) {\n" ], "file_path": "src/vs/editor/common/commands/trimTrailingWhitespaceCommand.ts", "type": "replace", "edit_start_line_idx": 19 }
<?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>fileTypes</key> <array> <string>md</string> <string>mdown</string> <string>markdown</string> <string>markdn</string> </array> <key>keyEquivalent</key> <string>^~M</string> <key>name</key> <string>Markdown</string> <key>patterns</key> <array> <dict> <key>include</key> <string>#frontMatter</string> </dict> <dict> <key>include</key> <string>#block</string> </dict> </array> <key>repository</key> <dict> <key>block</key> <dict> <key>patterns</key> <array> <dict> <key>include</key> <string>#separator</string> </dict> <dict> <key>include</key> <string>#heading</string> </dict> <dict> <key>include</key> <string>#blockquote</string> </dict> <dict> <key>include</key> <string>#lists</string> </dict> {{languageIncludes}} <dict> <key>include</key> <string>#fenced_code_block_unknown</string> </dict> <dict> <key>include</key> <string>#raw_block</string> </dict> <dict> <key>include</key> <string>#link-def</string> </dict> <dict> <key>include</key> <string>#html</string> </dict> <dict> <key>include</key> <string>#paragraph</string> </dict> </array> <key>repository</key> <dict> <key>blockquote</key> <dict> <key>begin</key> <string>(^|\G)[ ]{0,3}(&gt;) ?</string> <key>captures</key> <dict> <key>2</key> <dict> <key>name</key> <string>beginning.punctuation.definition.quote.markdown</string> </dict> </dict> <key>name</key> <string>markup.quote.markdown</string> <key>patterns</key> <array> <dict> <key>include</key> <string>#block</string> </dict> </array> <key>while</key> <string>(^|\G)\s*(&gt;) ?</string> </dict> <key>heading</key> <dict> <key>begin</key> <string>(?:^|\G)[ ]{0,3}(#{1,6})\s*(?=[\S[^#]])</string> <key>captures</key> <dict> <key>1</key> <dict> <key>name</key> <string>punctuation.definition.heading.markdown</string> </dict> </dict> <key>contentName</key> <string>entity.name.section.markdown</string> <key>end</key> <string>\s*(#{1,6})?$\n?</string> <key>name</key> <string>markup.heading.markdown</string> <key>patterns</key> <array> <dict> <key>include</key> <string>#inline</string> </dict> </array> </dict> <key>heading-setext</key> <dict> <key>patterns</key> <array> <dict> <key>match</key> <string>^(={3,})(?=[ \t]*$\n?)</string> <key>name</key> <string>markup.heading.setext.1.markdown</string> </dict> <dict> <key>match</key> <string>^(-{3,})(?=[ \t]*$\n?)</string> <key>name</key> <string>markup.heading.setext.2.markdown</string> </dict> </array> </dict> <key>html</key> <dict> <key>patterns</key> <array> <dict> <key>begin</key> <string>(^|\G)\s*(&lt;!--)</string> <key>end</key> <string>(--&gt;)</string> <key>name</key> <string>comment.block.html</string> <key>captures</key> <dict> <key>1</key> <dict> <key>name</key> <string>punctuation.definition.comment.html</string> </dict> <key>2</key> <dict> <key>name</key> <string>punctuation.definition.comment.html</string> </dict> </dict> </dict> <dict> <key>begin</key> <string>(^|\G)\s*(?=&lt;(script|style|pre)(\s|$|&gt;)(?!.*?&lt;/(script|style|pre)&gt;))</string> <key>patterns</key> <array> <dict> <key>begin</key> <string>(\s*|$)</string> <key>patterns</key> <array> <dict> <key>include</key> <string>text.html.basic</string> </dict> </array> <key>while</key> <string>^(?!.*&lt;/(script|style|pre)&gt;)</string> </dict> </array> <key>end</key> <string>(?=.*&lt;/(script|style|pre)&gt;)</string> </dict> <dict> <key>begin</key> <string>(^|\G)\s*(?=&lt;/?(address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h1|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|section|source|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul)(\s|$|/?&gt;))</string> <key>patterns</key> <array> <dict> <key>include</key> <string>text.html.basic</string> </dict> </array> <key>while</key> <string>^(?!\s*$)</string> </dict> <dict> <key>begin</key> <string>(^|\G)\s*(?=(&lt;[a-zA-Z0-9\-](/?&gt;|\s.*?&gt;)|&lt;/[a-zA-Z0-9\-]&gt;)\s*$)</string> <key>patterns</key> <array> <dict> <key>include</key> <string>text.html.basic</string> </dict> </array> <key>while</key> <string>^(?!\s*$)</string> </dict> </array> </dict> <key>link-def</key> <dict> <key>captures</key> <dict> <key>1</key> <dict> <key>name</key> <string>punctuation.definition.constant.markdown</string> </dict> <key>10</key> <dict> <key>name</key> <string>punctuation.definition.string.end.markdown</string> </dict> <key>11</key> <dict> <key>name</key> <string>string.other.link.description.title.markdown</string> </dict> <key>12</key> <dict> <key>name</key> <string>punctuation.definition.string.begin.markdown</string> </dict> <key>13</key> <dict> <key>name</key> <string>punctuation.definition.string.end.markdown</string> </dict> <key>2</key> <dict> <key>name</key> <string>constant.other.reference.link.markdown</string> </dict> <key>3</key> <dict> <key>name</key> <string>punctuation.definition.constant.markdown</string> </dict> <key>4</key> <dict> <key>name</key> <string>punctuation.separator.key-value.markdown</string> </dict> <key>5</key> <dict> <key>name</key> <string>punctuation.definition.link.markdown</string> </dict> <key>6</key> <dict> <key>name</key> <string>markup.underline.link.markdown</string> </dict> <key>7</key> <dict> <key>name</key> <string>punctuation.definition.link.markdown</string> </dict> <key>8</key> <dict> <key>name</key> <string>string.other.link.description.title.markdown</string> </dict> <key>9</key> <dict> <key>name</key> <string>punctuation.definition.string.begin.markdown</string> </dict> </dict> <key>match</key> <string>^(?x: \s* # Leading whitespace (\[)(.+?)(\])(:) # Reference name [ \t]* # Optional whitespace (&lt;?)(\S+?)(&gt;?) # The url [ \t]* # Optional whitespace (?: ((\().+?(\))) # Match title in quotes… | ((").+?(")) # or in parens. )? # Title is optional \s* # Optional whitespace $ )</string> <key>name</key> <string>meta.link.reference.def.markdown</string> </dict> <key>list_paragraph</key> <dict> <key>begin</key> <string>(^|\G)(?=\S)(?![*+-]\s|[0-9]+\.\s)</string> <key>name</key> <string>meta.paragraph.markdown</string> <key>patterns</key> <array> <dict> <key>include</key> <string>#inline</string> </dict> <dict> <key>include</key> <string>text.html.basic</string> </dict> <dict> <key>include</key> <string>#heading-setext</string> </dict> </array> <key>while</key> <string>(^|\G)(?!\s*$|#|[ ]{0,3}([-*_][ ]{2,}){3,}[ \t]*$\n?|&gt;|[ ]{0,3}[*+-]|[ ]{0,3}[0-9]+\.)</string> </dict> <key>lists</key> <dict> <key>patterns</key> <array> <dict> <key>begin</key> <string>(^|\G)([ ]{0,3})([*+-])([ ]{1,3}|\t)</string> <key>beginCaptures</key> <dict> <key>3</key> <dict> <key>name</key> <string>beginning.punctuation.definition.list.markdown</string> </dict> </dict> <key>comment</key> <string>Currently does not support un-indented second lines.</string> <key>name</key> <string>markup.list.unnumbered.markdown</string> <key>patterns</key> <array> <dict> <key>include</key> <string>#list_paragraph</string> </dict> <dict> <key>include</key> <string>#block</string> </dict> </array> <key>while</key> <string>((^|\G)([ ]{4}|\t))|(^[ \t]*$)</string> </dict> <dict> <key>begin</key> <string>(^|\G)([ ]{0,3})([0-9]+\.)([ ]{1,3}|\t)</string> <key>beginCaptures</key> <dict> <key>3</key> <dict> <key>name</key> <string>beginning.punctuation.definition.list.markdown</string> </dict> </dict> <key>name</key> <string>markup.list.numbered.markdown</string> <key>patterns</key> <array> <dict> <key>include</key> <string>#list_paragraph</string> </dict> <dict> <key>include</key> <string>#block</string> </dict> </array> <key>while</key> <string>((^|\G)([ ]{4}|\t))|(^[ \t]*$)</string> </dict> </array> </dict> <key>paragraph</key> <dict> <key>begin</key> <string>(^|\G)[ ]{0,3}(?=\S)</string> <key>name</key> <string>meta.paragraph.markdown</string> <key>patterns</key> <array> <dict> <key>include</key> <string>#inline</string> </dict> <dict> <key>include</key> <string>text.html.basic</string> </dict> <dict> <key>include</key> <string>#heading-setext</string> </dict> </array> <key>while</key> <string>(^|\G)((?=\s*[-=]{3,}\s*$)|[ ]{4,}(?=\S))</string> </dict> {{languageDefinitions}} <key>fenced_code_block_unknown</key> <dict> <key>name</key> <string>markup.fenced_code.block.markdown</string> <key>begin</key> <string>(^|\G)(\s*)(`{3,}|~{3,})\s*(?=([^`~]*)?$)</string> <key>end</key> <string>(^|\G)(\2|\s{0,3})(\3)\s*$</string> <key>beginCaptures</key> <dict> <key>3</key> <dict> <key>name</key> <string>punctuation.definition.markdown</string> </dict> <key>4</key> <dict> <key>name</key> <string>fenced_code.block.language</string> </dict> </dict> <key>endCaptures</key> <dict> <key>3</key> <dict> <key>name</key> <string>punctuation.definition.markdown</string> </dict> </dict> </dict> <key>raw_block</key> <dict> <key>begin</key> <string>(^|\G)([ ]{4}|\t)</string> <key>name</key> <string>markup.raw.block.markdown</string> <key>while</key> <string>(^|\G)([ ]{4}|\t)</string> </dict> <key>separator</key> <dict> <key>match</key> <string>(^|\G)[ ]{0,3}([*-_])([ ]{0,2}\2){2,}[ \t]*$\n?</string> <key>name</key> <string>meta.separator.markdown</string> </dict> </dict> </dict> <key>inline</key> <dict> <key>patterns</key> <array> <dict> <key>include</key> <string>#ampersand</string> </dict> <dict> <key>include</key> <string>#bracket</string> </dict> <dict> <key>include</key> <string>#bold</string> </dict> <dict> <key>include</key> <string>#italic</string> </dict> <dict> <key>include</key> <string>#raw</string> </dict> <dict> <key>include</key> <string>#escape</string> </dict> <dict> <key>include</key> <string>#image-inline</string> </dict> <dict> <key>include</key> <string>#image-ref</string> </dict> <dict> <key>include</key> <string>#link-email</string> </dict> <dict> <key>include</key> <string>#link-inet</string> </dict> <dict> <key>include</key> <string>#link-inline</string> </dict> <dict> <key>include</key> <string>#link-ref</string> </dict> <dict> <key>include</key> <string>#link-ref-literal</string> </dict> </array> <key>repository</key> <dict> <key>ampersand</key> <dict> <key>comment</key> <string> Markdown will convert this for us. We match it so that the HTML grammar will not mark it up as invalid. </string> <key>match</key> <string>&amp;(?!([a-zA-Z0-9]+|#[0-9]+|#x[0-9a-fA-F]+);)</string> <key>name</key> <string>meta.other.valid-ampersand.markdown</string> </dict> <key>bold</key> <dict> <key>begin</key> <string>(?x) (\*\*|__)(?=\S) # Open (?= ( &lt;[^&gt;]*+&gt; # HTML tags | (?&lt;raw&gt;`+)([^`]|(?!(?&lt;!`)\k&lt;raw&gt;(?!`))`)*+\k&lt;raw&gt; # Raw | \\[\\`*_{}\[\]()#.!+\-&gt;]?+ # Escapes | \[ ( (?&lt;square&gt; # Named group [^\[\]\\] # Match most chars | \\. # Escaped chars | \[ \g&lt;square&gt;*+ \] # Nested brackets )*+ \] ( ( # Reference Link [ ]? # Optional space \[[^\]]*+\] # Ref name ) | ( # Inline Link \( # Opening paren [ \t]*+ # Optional whitespace &lt;?(.*?)&gt;? # URL [ \t]*+ # Optional whitespace ( # Optional Title (?&lt;title&gt;['"]) (.*?) \k&lt;title&gt; )? \) ) ) ) | (?!(?&lt;=\S)\1). # Everything besides # style closer )++ (?&lt;=\S)\1 # Close ) </string> <key>captures</key> <dict> <key>1</key> <dict> <key>name</key> <string>punctuation.definition.bold.markdown</string> </dict> </dict> <key>end</key> <string>(?&lt;=\S)(\1)</string> <key>name</key> <string>markup.bold.markdown</string> <key>patterns</key> <array> <dict> <key>applyEndPatternLast</key> <integer>1</integer> <key>begin</key> <string>(?=&lt;[^&gt;]*?&gt;)</string> <key>end</key> <string>(?&lt;=&gt;)</string> <key>patterns</key> <array> <dict> <key>include</key> <string>text.html.basic</string> </dict> </array> </dict> <dict> <key>include</key> <string>#escape</string> </dict> <dict> <key>include</key> <string>#ampersand</string> </dict> <dict> <key>include</key> <string>#bracket</string> </dict> <dict> <key>include</key> <string>#raw</string> </dict> <dict> <key>include</key> <string>#italic</string> </dict> <dict> <key>include</key> <string>#image-inline</string> </dict> <dict> <key>include</key> <string>#link-inline</string> </dict> <dict> <key>include</key> <string>#link-inet</string> </dict> <dict> <key>include</key> <string>#link-email</string> </dict> <dict> <key>include</key> <string>#image-ref</string> </dict> <dict> <key>include</key> <string>#link-ref-literal</string> </dict> <dict> <key>include</key> <string>#link-ref</string> </dict> </array> </dict> <key>bracket</key> <dict> <key>comment</key> <string> Markdown will convert this for us. We match it so that the HTML grammar will not mark it up as invalid. </string> <key>match</key> <string>&lt;(?![a-z/?\$!])</string> <key>name</key> <string>meta.other.valid-bracket.markdown</string> </dict> <key>escape</key> <dict> <key>match</key> <string>\\[-`*_#+.!(){}\[\]\\&gt;]</string> <key>name</key> <string>constant.character.escape.markdown</string> </dict> <key>image-inline</key> <dict> <key>captures</key> <dict> <key>1</key> <dict> <key>name</key> <string>punctuation.definition.string.begin.markdown</string> </dict> <key>10</key> <dict> <key>name</key> <string>string.other.link.description.title.markdown</string> </dict> <key>11</key> <dict> <key>name</key> <string>punctuation.definition.string.markdown</string> </dict> <key>12</key> <dict> <key>name</key> <string>punctuation.definition.string.markdown</string> </dict> <key>13</key> <dict> <key>name</key> <string>string.other.link.description.title.markdown</string> </dict> <key>14</key> <dict> <key>name</key> <string>punctuation.definition.string.markdown</string> </dict> <key>15</key> <dict> <key>name</key> <string>punctuation.definition.string.markdown</string> </dict> <key>16</key> <dict> <key>name</key> <string>punctuation.definition.metadata.markdown</string> </dict> <key>2</key> <dict> <key>name</key> <string>string.other.link.description.markdown</string> </dict> <key>4</key> <dict> <key>name</key> <string>punctuation.definition.string.end.markdown</string> </dict> <key>5</key> <dict> <key>name</key> <string>invalid.illegal.whitespace.markdown</string> </dict> <key>6</key> <dict> <key>name</key> <string>punctuation.definition.metadata.markdown</string> </dict> <key>7</key> <dict> <key>name</key> <string>punctuation.definition.link.markdown</string> </dict> <key>8</key> <dict> <key>name</key> <string>markup.underline.link.image.markdown</string> </dict> <key>9</key> <dict> <key>name</key> <string>punctuation.definition.link.markdown</string> </dict> </dict> <key>match</key> <string>(?x: (\!\[)((?&lt;square&gt;[^\[\]\\]|\\.|\[\g&lt;square&gt;*+\])*+)(\]) # Match the link text. ([ ])? # Space not allowed (\() # Opening paren for url (&lt;?)(\S+?)(&gt;?) # The url [ \t]* # Optional whitespace (?: ((\().+?(\))) # Match title in parens… | ((").+?(")) # or in quotes. )? # Title is optional \s* # Optional whitespace (\)) )</string> <key>name</key> <string>meta.image.inline.markdown</string> </dict> <key>image-ref</key> <dict> <key>captures</key> <dict> <key>1</key> <dict> <key>name</key> <string>punctuation.definition.string.begin.markdown</string> </dict> <key>2</key> <dict> <key>name</key> <string>string.other.link.description.markdown</string> </dict> <key>4</key> <dict> <key>name</key> <string>punctuation.definition.string.begin.markdown</string> </dict> <key>5</key> <dict> <key>name</key> <string>punctuation.definition.constant.markdown</string> </dict> <key>6</key> <dict> <key>name</key> <string>constant.other.reference.link.markdown</string> </dict> <key>7</key> <dict> <key>name</key> <string>punctuation.definition.constant.markdown</string> </dict> </dict> <key>match</key> <string>(\!\[)((?&lt;square&gt;[^\[\]\\]|\\.|\[\g&lt;square&gt;*+\])*+)(\])[ ]?(\[)(.*?)(\])</string> <key>name</key> <string>meta.image.reference.markdown</string> </dict> <key>italic</key> <dict> <key>begin</key> <string>(?x) (\*|_)(?=\S) # Open (?= ( &lt;[^&gt;]*+&gt; # HTML tags | (?&lt;raw&gt;`+)([^`]|(?!(?&lt;!`)\k&lt;raw&gt;(?!`))`)*+\k&lt;raw&gt; # Raw | \\[\\`*_{}\[\]()#.!+\-&gt;]?+ # Escapes | \[ ( (?&lt;square&gt; # Named group [^\[\]\\] # Match most chars | \\. # Escaped chars | \[ \g&lt;square&gt;*+ \] # Nested brackets )*+ \] ( ( # Reference Link [ ]? # Optional space \[[^\]]*+\] # Ref name ) | ( # Inline Link \( # Opening paren [ \t]*+ # Optional whtiespace &lt;?(.*?)&gt;? # URL [ \t]*+ # Optional whtiespace ( # Optional Title (?&lt;title&gt;['"]) (.*?) \k&lt;title&gt; )? \) ) ) ) | \1\1 # Must be bold closer | (?!(?&lt;=\S)\1). # Everything besides # style closer )++ (?&lt;=\S)\1 # Close ) </string> <key>captures</key> <dict> <key>1</key> <dict> <key>name</key> <string>punctuation.definition.italic.markdown</string> </dict> </dict> <key>end</key> <string>(?&lt;=\S)(\1)((?!\1)|(?=\1\1))</string> <key>name</key> <string>markup.italic.markdown</string> <key>patterns</key> <array> <dict> <key>applyEndPatternLast</key> <integer>1</integer> <key>begin</key> <string>(?=&lt;[^&gt;]*?&gt;)</string> <key>end</key> <string>(?&lt;=&gt;)</string> <key>patterns</key> <array> <dict> <key>include</key> <string>text.html.basic</string> </dict> </array> </dict> <dict> <key>include</key> <string>#escape</string> </dict> <dict> <key>include</key> <string>#ampersand</string> </dict> <dict> <key>include</key> <string>#bracket</string> </dict> <dict> <key>include</key> <string>#raw</string> </dict> <dict> <key>include</key> <string>#bold</string> </dict> <dict> <key>include</key> <string>#image-inline</string> </dict> <dict> <key>include</key> <string>#link-inline</string> </dict> <dict> <key>include</key> <string>#link-inet</string> </dict> <dict> <key>include</key> <string>#link-email</string> </dict> <dict> <key>include</key> <string>#image-ref</string> </dict> <dict> <key>include</key> <string>#link-ref-literal</string> </dict> <dict> <key>include</key> <string>#link-ref</string> </dict> </array> </dict> <key>link-email</key> <dict> <key>captures</key> <dict> <key>1</key> <dict> <key>name</key> <string>punctuation.definition.link.markdown</string> </dict> <key>2</key> <dict> <key>name</key> <string>markup.underline.link.markdown</string> </dict> <key>4</key> <dict> <key>name</key> <string>punctuation.definition.link.markdown</string> </dict> </dict> <key>match</key> <string>(&lt;)((?:mailto:)?[-.\w]+@[-a-z0-9]+(\.[-a-z0-9]+)*\.[a-z]+)(&gt;)</string> <key>name</key> <string>meta.link.email.lt-gt.markdown</string> </dict> <key>link-inet</key> <dict> <key>captures</key> <dict> <key>1</key> <dict> <key>name</key> <string>punctuation.definition.link.markdown</string> </dict> <key>2</key> <dict> <key>name</key> <string>markup.underline.link.markdown</string> </dict> <key>3</key> <dict> <key>name</key> <string>punctuation.definition.link.markdown</string> </dict> </dict> <key>match</key> <string>(&lt;)((?:https?|ftp)://.*?)(&gt;)</string> <key>name</key> <string>meta.link.inet.markdown</string> </dict> <key>link-inline</key> <dict> <key>captures</key> <dict> <key>1</key> <dict> <key>name</key> <string>punctuation.definition.string.begin.markdown</string> </dict> <key>10</key> <dict> <key>name</key> <string>string.other.link.description.title.markdown</string> </dict> <key>11</key> <dict> <key>name</key> <string>punctuation.definition.string.begin.markdown</string> </dict> <key>12</key> <dict> <key>name</key> <string>punctuation.definition.string.end.markdown</string> </dict> <key>13</key> <dict> <key>name</key> <string>string.other.link.description.title.markdown</string> </dict> <key>14</key> <dict> <key>name</key> <string>punctuation.definition.string.begin.markdown</string> </dict> <key>15</key> <dict> <key>name</key> <string>punctuation.definition.string.end.markdown</string> </dict> <key>16</key> <dict> <key>name</key> <string>punctuation.definition.metadata.markdown</string> </dict> <key>2</key> <dict> <key>name</key> <string>string.other.link.title.markdown</string> </dict> <key>4</key> <dict> <key>name</key> <string>punctuation.definition.string.end.markdown</string> </dict> <key>5</key> <dict> <key>name</key> <string>invalid.illegal.whitespace.markdown</string> </dict> <key>6</key> <dict> <key>name</key> <string>punctuation.definition.metadata.markdown</string> </dict> <key>7</key> <dict> <key>name</key> <string>punctuation.definition.link.markdown</string> </dict> <key>8</key> <dict> <key>name</key> <string>markup.underline.link.markdown</string> </dict> <key>9</key> <dict> <key>name</key> <string>punctuation.definition.link.markdown</string> </dict> </dict> <key>match</key> <string>(?x: (\[)((?&lt;square&gt;[^\[\]\\]|\\.|\[\g&lt;square&gt;*+\])*+)(\]) # Match the link text. ([ ])? # Space not allowed (\() # Opening paren for url (&lt;?)(.*?)(&gt;?) # The url [ \t]* # Optional whitespace (?: ((\().+?(\))) # Match title in parens… | ((").+?(")) # or in quotes. )? # Title is optional \s* # Optional whitespace (\)) )</string> <key>name</key> <string>meta.link.inline.markdown</string> </dict> <key>link-ref</key> <dict> <key>captures</key> <dict> <key>1</key> <dict> <key>name</key> <string>punctuation.definition.string.begin.markdown</string> </dict> <key>2</key> <dict> <key>name</key> <string>string.other.link.title.markdown</string> </dict> <key>4</key> <dict> <key>name</key> <string>punctuation.definition.string.end.markdown</string> </dict> <key>5</key> <dict> <key>name</key> <string>punctuation.definition.constant.begin.markdown</string> </dict> <key>6</key> <dict> <key>name</key> <string>constant.other.reference.link.markdown</string> </dict> <key>7</key> <dict> <key>name</key> <string>punctuation.definition.constant.end.markdown</string> </dict> </dict> <key>match</key> <string>(\[)((?&lt;square&gt;[^\[\]\\]|\\.|\[\g&lt;square&gt;*+\])*+)(\])(\[)([^\]]*+)(\])</string> <key>name</key> <string>meta.link.reference.markdown</string> </dict> <key>link-ref-literal</key> <dict> <key>captures</key> <dict> <key>1</key> <dict> <key>name</key> <string>punctuation.definition.string.begin.markdown</string> </dict> <key>2</key> <dict> <key>name</key> <string>string.other.link.title.markdown</string> </dict> <key>4</key> <dict> <key>name</key> <string>punctuation.definition.string.end.markdown</string> </dict> <key>5</key> <dict> <key>name</key> <string>punctuation.definition.constant.begin.markdown</string> </dict> <key>6</key> <dict> <key>name</key> <string>punctuation.definition.constant.end.markdown</string> </dict> </dict> <key>match</key> <string>(\[)((?&lt;square&gt;[^\[\]\\]|\\.|\[\g&lt;square&gt;*+\])*+)(\])[ ]?(\[)(\])</string> <key>name</key> <string>meta.link.reference.literal.markdown</string> </dict> <key>raw</key> <dict> <key>captures</key> <dict> <key>1</key> <dict> <key>name</key> <string>punctuation.definition.raw.markdown</string> </dict> <key>3</key> <dict> <key>name</key> <string>punctuation.definition.raw.markdown</string> </dict> </dict> <key>match</key> <string>(`+)([^`]|(?!(?&lt;!`)\1(?!`))`)*+(\1)</string> <key>name</key> <string>markup.inline.raw.string.markdown</string> </dict> </dict> </dict> <key>frontMatter</key> <dict> <key>begin</key> <string>\A-{3}\s*$</string> <key>while</key> <string>^(?!(-{3}|\.{3})\s*$)</string> <key>patterns</key> <array> <dict> <key>include</key> <string>source.yaml</string> </dict> </array> </dict> </dict> <key>scopeName</key> <string>text.html.markdown</string> <key>uuid</key> <string>0A1D9874-B448-11D9-BD50-000D93B6E43C</string> </dict> </plist>
extensions/markdown/syntaxes/markdown.tmLanguage.base
0
https://github.com/microsoft/vscode/commit/5d3dfe86cd6ac769a66f5473da3ab63c2a6918bf
[ 0.0001784182240953669, 0.00017365123494528234, 0.00016473194409627467, 0.00017423521785531193, 0.0000023089728529157583 ]
{ "id": 0, "code_window": [ "\n", "\tprivate selection: Selection;\n", "\tprivate selectionId: string;\n", "\tprivate cursors: Position[];\n", "\n", "\tconstructor(selection: Selection, cursors: Position[] = []) {\n", "\t\tthis.selection = selection;\n", "\t\tthis.cursors = cursors;\n", "\t}\n", "\n", "\tpublic getEditOperations(model: editorCommon.ITokenizedModel, builder: editorCommon.IEditOperationBuilder): void {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tconstructor(selection: Selection, cursors: Position[]) {\n" ], "file_path": "src/vs/editor/common/commands/trimTrailingWhitespaceCommand.ts", "type": "replace", "edit_start_line_idx": 19 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ // Do not edit this file. It is machine generated. { "patchedWindowTitle": "[지원되지 않음]", "devExtensionWindowTitlePrefix": "[확장 개발 호스트]" }
i18n/kor/src/vs/workbench/browser/parts/titlebar/titlebarPart.i18n.json
0
https://github.com/microsoft/vscode/commit/5d3dfe86cd6ac769a66f5473da3ab63c2a6918bf
[ 0.00017465953715145588, 0.00017465953715145588, 0.00017465953715145588, 0.00017465953715145588, 0 ]
{ "id": 0, "code_window": [ "\n", "\tprivate selection: Selection;\n", "\tprivate selectionId: string;\n", "\tprivate cursors: Position[];\n", "\n", "\tconstructor(selection: Selection, cursors: Position[] = []) {\n", "\t\tthis.selection = selection;\n", "\t\tthis.cursors = cursors;\n", "\t}\n", "\n", "\tpublic getEditOperations(model: editorCommon.ITokenizedModel, builder: editorCommon.IEditOperationBuilder): void {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tconstructor(selection: Selection, cursors: Position[]) {\n" ], "file_path": "src/vs/editor/common/commands/trimTrailingWhitespaceCommand.ts", "type": "replace", "edit_start_line_idx": 19 }
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16"><path fill="#C5C5C5" d="M15 4v6h-2.276c.113-.318.187-.653.226-1h1.05v-5h-2v-2h-4v2.051c-.347.038-.681.112-1 .225v-3.276h5l3 3zm-7 8.949v1.051h-6v-7h2.276c.126-.354.28-.693.485-1h-3.761v9h8v-2.051c-.166.02-.329.051-.5.051l-.5-.051z"/><path fill="#75BEFF" d="M12 8.5c0-1.933-1.567-3.5-3.5-3.5s-3.5 1.567-3.5 3.5 1.567 3.5 3.5 3.5c.711 0 1.369-.215 1.922-.578l3.578 3.578 1-1-3.578-3.578c.363-.553.578-1.211.578-1.922zm-3.5 2.5c-1.381 0-2.5-1.119-2.5-2.5s1.119-2.5 2.5-2.5 2.5 1.119 2.5 2.5-1.119 2.5-2.5 2.5z"/></svg>
extensions/git/resources/icons/dark/open-change.svg
0
https://github.com/microsoft/vscode/commit/5d3dfe86cd6ac769a66f5473da3ab63c2a6918bf
[ 0.00016638015222270042, 0.00016638015222270042, 0.00016638015222270042, 0.00016638015222270042, 0 ]
{ "id": 1, "code_window": [ "\t}\n", "\n", "\tpublic run(accessor: ServicesAccessor, editor: ICommonCodeEditor, args: any): void {\n", "\n", "\t\tvar cursors: Position[];\n", "\t\tif (args.reason === 'auto-save') {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ "\t\tlet cursors: Position[] = [];\n" ], "file_path": "src/vs/editor/contrib/linesOperations/common/linesOperations.ts", "type": "replace", "edit_start_line_idx": 211 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import * as nls from 'vs/nls'; import { KeyCode, KeyMod, KeyChord } from 'vs/base/common/keyCodes'; import { SortLinesCommand } from 'vs/editor/contrib/linesOperations/common/sortLinesCommand'; import { EditOperation } from 'vs/editor/common/core/editOperation'; import { TrimTrailingWhitespaceCommand } from 'vs/editor/common/commands/trimTrailingWhitespaceCommand'; import { ICommand, ICommonCodeEditor, IIdentifiedSingleEditOperation } from 'vs/editor/common/editorCommon'; import { EditorContextKeys } from 'vs/editor/common/editorContextKeys'; import { ReplaceCommand, ReplaceCommandThatPreservesSelection } from 'vs/editor/common/commands/replaceCommand'; import { Range } from 'vs/editor/common/core/range'; import { Selection } from 'vs/editor/common/core/selection'; import { Position } from 'vs/editor/common/core/position'; import { editorAction, ServicesAccessor, IActionOptions, EditorAction } from 'vs/editor/common/editorCommonExtensions'; import { CopyLinesCommand } from './copyLinesCommand'; import { DeleteLinesCommand } from './deleteLinesCommand'; import { MoveLinesCommand } from './moveLinesCommand'; import { TypeOperations } from 'vs/editor/common/controller/cursorTypeOperations'; import { CoreEditingCommands } from 'vs/editor/common/controller/coreCommands'; // copy lines abstract class AbstractCopyLinesAction extends EditorAction { private down: boolean; constructor(down: boolean, opts: IActionOptions) { super(opts); this.down = down; } public run(accessor: ServicesAccessor, editor: ICommonCodeEditor): void { var commands: ICommand[] = []; var selections = editor.getSelections(); for (var i = 0; i < selections.length; i++) { commands.push(new CopyLinesCommand(selections[i], this.down)); } editor.pushUndoStop(); editor.executeCommands(this.id, commands); editor.pushUndoStop(); } } @editorAction class CopyLinesUpAction extends AbstractCopyLinesAction { constructor() { super(false, { id: 'editor.action.copyLinesUpAction', label: nls.localize('lines.copyUp', "Copy Line Up"), alias: 'Copy Line Up', precondition: EditorContextKeys.writable, kbOpts: { kbExpr: EditorContextKeys.textFocus, primary: KeyMod.Alt | KeyMod.Shift | KeyCode.UpArrow, linux: { primary: KeyMod.CtrlCmd | KeyMod.Alt | KeyMod.Shift | KeyCode.UpArrow } } }); } } @editorAction class CopyLinesDownAction extends AbstractCopyLinesAction { constructor() { super(true, { id: 'editor.action.copyLinesDownAction', label: nls.localize('lines.copyDown', "Copy Line Down"), alias: 'Copy Line Down', precondition: EditorContextKeys.writable, kbOpts: { kbExpr: EditorContextKeys.textFocus, primary: KeyMod.Alt | KeyMod.Shift | KeyCode.DownArrow, linux: { primary: KeyMod.CtrlCmd | KeyMod.Alt | KeyMod.Shift | KeyCode.DownArrow } } }); } } // move lines abstract class AbstractMoveLinesAction extends EditorAction { private down: boolean; constructor(down: boolean, opts: IActionOptions) { super(opts); this.down = down; } public run(accessor: ServicesAccessor, editor: ICommonCodeEditor): void { var commands: ICommand[] = []; var selections = editor.getSelections(); var autoIndent = editor.getConfiguration().autoIndent; for (var i = 0; i < selections.length; i++) { commands.push(new MoveLinesCommand(selections[i], this.down, autoIndent)); } editor.pushUndoStop(); editor.executeCommands(this.id, commands); editor.pushUndoStop(); } } @editorAction class MoveLinesUpAction extends AbstractMoveLinesAction { constructor() { super(false, { id: 'editor.action.moveLinesUpAction', label: nls.localize('lines.moveUp', "Move Line Up"), alias: 'Move Line Up', precondition: EditorContextKeys.writable, kbOpts: { kbExpr: EditorContextKeys.textFocus, primary: KeyMod.Alt | KeyCode.UpArrow, linux: { primary: KeyMod.Alt | KeyCode.UpArrow } } }); } } @editorAction class MoveLinesDownAction extends AbstractMoveLinesAction { constructor() { super(true, { id: 'editor.action.moveLinesDownAction', label: nls.localize('lines.moveDown', "Move Line Down"), alias: 'Move Line Down', precondition: EditorContextKeys.writable, kbOpts: { kbExpr: EditorContextKeys.textFocus, primary: KeyMod.Alt | KeyCode.DownArrow, linux: { primary: KeyMod.Alt | KeyCode.DownArrow } } }); } } abstract class AbstractSortLinesAction extends EditorAction { private descending: boolean; constructor(descending: boolean, opts: IActionOptions) { super(opts); this.descending = descending; } public run(accessor: ServicesAccessor, editor: ICommonCodeEditor): void { if (!SortLinesCommand.canRun(editor.getModel(), editor.getSelection(), this.descending)) { return; } var command = new SortLinesCommand(editor.getSelection(), this.descending); editor.pushUndoStop(); editor.executeCommands(this.id, [command]); editor.pushUndoStop(); } } @editorAction class SortLinesAscendingAction extends AbstractSortLinesAction { constructor() { super(false, { id: 'editor.action.sortLinesAscending', label: nls.localize('lines.sortAscending', "Sort Lines Ascending"), alias: 'Sort Lines Ascending', precondition: EditorContextKeys.writable }); } } @editorAction class SortLinesDescendingAction extends AbstractSortLinesAction { constructor() { super(true, { id: 'editor.action.sortLinesDescending', label: nls.localize('lines.sortDescending', "Sort Lines Descending"), alias: 'Sort Lines Descending', precondition: EditorContextKeys.writable }); } } @editorAction export class TrimTrailingWhitespaceAction extends EditorAction { public static ID = 'editor.action.trimTrailingWhitespace'; constructor() { super({ id: TrimTrailingWhitespaceAction.ID, label: nls.localize('lines.trimTrailingWhitespace', "Trim Trailing Whitespace"), alias: 'Trim Trailing Whitespace', precondition: EditorContextKeys.writable, kbOpts: { kbExpr: EditorContextKeys.textFocus, primary: KeyChord(KeyMod.CtrlCmd | KeyCode.KEY_K, KeyMod.CtrlCmd | KeyCode.KEY_X) } }); } public run(accessor: ServicesAccessor, editor: ICommonCodeEditor, args: any): void { var cursors: Position[]; if (args.reason === 'auto-save') { cursors = editor.getSelections().map(s => new Position(s.positionLineNumber, s.positionColumn)); } var command = new TrimTrailingWhitespaceCommand(editor.getSelection(), cursors); editor.pushUndoStop(); editor.executeCommands(this.id, [command]); editor.pushUndoStop(); } } // delete lines interface IDeleteLinesOperation { startLineNumber: number; endLineNumber: number; positionColumn: number; } abstract class AbstractRemoveLinesAction extends EditorAction { _getLinesToRemove(editor: ICommonCodeEditor): IDeleteLinesOperation[] { // Construct delete operations var operations: IDeleteLinesOperation[] = editor.getSelections().map((s) => { var endLineNumber = s.endLineNumber; if (s.startLineNumber < s.endLineNumber && s.endColumn === 1) { endLineNumber -= 1; } return { startLineNumber: s.startLineNumber, endLineNumber: endLineNumber, positionColumn: s.positionColumn }; }); // Sort delete operations operations.sort((a, b) => { return a.startLineNumber - b.startLineNumber; }); // Merge delete operations on consecutive lines var mergedOperations: IDeleteLinesOperation[] = []; var previousOperation = operations[0]; for (var i = 1; i < operations.length; i++) { if (previousOperation.endLineNumber + 1 === operations[i].startLineNumber) { // Merge current operations into the previous one previousOperation.endLineNumber = operations[i].endLineNumber; } else { // Push previous operation mergedOperations.push(previousOperation); previousOperation = operations[i]; } } // Push the last operation mergedOperations.push(previousOperation); return mergedOperations; } } @editorAction class DeleteLinesAction extends AbstractRemoveLinesAction { constructor() { super({ id: 'editor.action.deleteLines', label: nls.localize('lines.delete', "Delete Line"), alias: 'Delete Line', precondition: EditorContextKeys.writable, kbOpts: { kbExpr: EditorContextKeys.textFocus, primary: KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.KEY_K } }); } public run(accessor: ServicesAccessor, editor: ICommonCodeEditor): void { var ops = this._getLinesToRemove(editor); // Finally, construct the delete lines commands var commands: ICommand[] = ops.map((op) => { return new DeleteLinesCommand(op.startLineNumber, op.endLineNumber, op.positionColumn); }); editor.pushUndoStop(); editor.executeCommands(this.id, commands); editor.pushUndoStop(); } } @editorAction export class IndentLinesAction extends EditorAction { constructor() { super({ id: 'editor.action.indentLines', label: nls.localize('lines.indent', "Indent Line"), alias: 'Indent Line', precondition: EditorContextKeys.writable, kbOpts: { kbExpr: EditorContextKeys.textFocus, primary: KeyMod.CtrlCmd | KeyCode.US_CLOSE_SQUARE_BRACKET } }); } public run(accessor: ServicesAccessor, editor: ICommonCodeEditor): void { editor.pushUndoStop(); editor.executeCommands(this.id, TypeOperations.indent(editor._getCursorConfiguration(), editor.getModel(), editor.getSelections())); editor.pushUndoStop(); } } @editorAction class OutdentLinesAction extends EditorAction { constructor() { super({ id: 'editor.action.outdentLines', label: nls.localize('lines.outdent', "Outdent Line"), alias: 'Outdent Line', precondition: EditorContextKeys.writable, kbOpts: { kbExpr: EditorContextKeys.textFocus, primary: KeyMod.CtrlCmd | KeyCode.US_OPEN_SQUARE_BRACKET } }); } public run(accessor: ServicesAccessor, editor: ICommonCodeEditor): void { CoreEditingCommands.Outdent.runEditorCommand(null, editor, null); } } @editorAction export class InsertLineBeforeAction extends EditorAction { constructor() { super({ id: 'editor.action.insertLineBefore', label: nls.localize('lines.insertBefore', "Insert Line Above"), alias: 'Insert Line Above', precondition: EditorContextKeys.writable, kbOpts: { kbExpr: EditorContextKeys.textFocus, primary: KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.Enter } }); } public run(accessor: ServicesAccessor, editor: ICommonCodeEditor): void { editor.pushUndoStop(); editor.executeCommands(this.id, TypeOperations.lineInsertBefore(editor._getCursorConfiguration(), editor.getModel(), editor.getSelections())); } } @editorAction export class InsertLineAfterAction extends EditorAction { constructor() { super({ id: 'editor.action.insertLineAfter', label: nls.localize('lines.insertAfter', "Insert Line Below"), alias: 'Insert Line Below', precondition: EditorContextKeys.writable, kbOpts: { kbExpr: EditorContextKeys.textFocus, primary: KeyMod.CtrlCmd | KeyCode.Enter } }); } public run(accessor: ServicesAccessor, editor: ICommonCodeEditor): void { editor.pushUndoStop(); editor.executeCommands(this.id, TypeOperations.lineInsertAfter(editor._getCursorConfiguration(), editor.getModel(), editor.getSelections())); } } export abstract class AbstractDeleteAllToBoundaryAction extends EditorAction { public run(accessor: ServicesAccessor, editor: ICommonCodeEditor): void { const primaryCursor = editor.getSelection(); let rangesToDelete = this._getRangesToDelete(editor); // merge overlapping selections let effectiveRanges: Range[] = []; for (let i = 0, count = rangesToDelete.length - 1; i < count; i++) { let range = rangesToDelete[i]; let nextRange = rangesToDelete[i + 1]; if (Range.intersectRanges(range, nextRange) === null) { effectiveRanges.push(range); } else { rangesToDelete[i + 1] = Range.plusRange(range, nextRange); } } effectiveRanges.push(rangesToDelete[rangesToDelete.length - 1]); let endCursorState = this._getEndCursorState(primaryCursor, effectiveRanges); let edits: IIdentifiedSingleEditOperation[] = effectiveRanges.map(range => { endCursorState.push(new Selection(range.startLineNumber, range.startColumn, range.startLineNumber, range.startColumn)); return EditOperation.replace(range, ''); }); editor.executeEdits(this.id, edits, endCursorState); } /** * Compute the cursor state after the edit operations were applied. */ protected abstract _getEndCursorState(primaryCursor: Range, rangesToDelete: Range[]): Selection[]; protected abstract _getRangesToDelete(editor: ICommonCodeEditor): Range[]; } @editorAction export class DeleteAllLeftAction extends AbstractDeleteAllToBoundaryAction { constructor() { super({ id: 'deleteAllLeft', label: nls.localize('lines.deleteAllLeft', "Delete All Left"), alias: 'Delete All Left', precondition: EditorContextKeys.writable, kbOpts: { kbExpr: EditorContextKeys.textFocus, primary: null, mac: { primary: KeyMod.CtrlCmd | KeyCode.Backspace } } }); } _getEndCursorState(primaryCursor: Range, rangesToDelete: Range[]): Selection[] { let endPrimaryCursor: Selection; let endCursorState: Selection[] = []; for (let i = 0, len = rangesToDelete.length; i < len; i++) { let range = rangesToDelete[i]; let endCursor = new Selection(rangesToDelete[i].startLineNumber, rangesToDelete[i].startColumn, rangesToDelete[i].startLineNumber, rangesToDelete[i].startColumn); if (range.intersectRanges(primaryCursor)) { endPrimaryCursor = endCursor; } else { endCursorState.push(endCursor); } } if (endPrimaryCursor) { endCursorState.unshift(endPrimaryCursor); } return endCursorState; } _getRangesToDelete(editor: ICommonCodeEditor): Range[] { let rangesToDelete: Range[] = editor.getSelections(); rangesToDelete.sort(Range.compareRangesUsingStarts); rangesToDelete = rangesToDelete.map(selection => { if (selection.isEmpty()) { return new Range(selection.startLineNumber, 1, selection.startLineNumber, selection.startColumn); } else { return selection; } }); return rangesToDelete; } } @editorAction export class DeleteAllRightAction extends AbstractDeleteAllToBoundaryAction { constructor() { super({ id: 'deleteAllRight', label: nls.localize('lines.deleteAllRight', "Delete All Right"), alias: 'Delete All Right', precondition: EditorContextKeys.writable, kbOpts: { kbExpr: EditorContextKeys.textFocus, primary: null, mac: { primary: KeyMod.WinCtrl | KeyCode.KEY_K, secondary: [KeyMod.CtrlCmd | KeyCode.Delete] } } }); } _getEndCursorState(primaryCursor: Range, rangesToDelete: Range[]): Selection[] { let endPrimaryCursor: Selection; let endCursorState: Selection[] = []; for (let i = 0, len = rangesToDelete.length, offset = 0; i < len; i++) { let range = rangesToDelete[i]; let endCursor = new Selection(range.startLineNumber - offset, range.startColumn, range.startLineNumber - offset, range.startColumn); if (range.intersectRanges(primaryCursor)) { endPrimaryCursor = endCursor; } else { endCursorState.push(endCursor); } } if (endPrimaryCursor) { endCursorState.unshift(endPrimaryCursor); } return endCursorState; } _getRangesToDelete(editor: ICommonCodeEditor): Range[] { let model = editor.getModel(); let rangesToDelete: Range[] = editor.getSelections().map((sel) => { if (sel.isEmpty()) { const maxColumn = model.getLineMaxColumn(sel.startLineNumber); if (sel.startColumn === maxColumn) { return new Range(sel.startLineNumber, sel.startColumn, sel.startLineNumber + 1, 1); } else { return new Range(sel.startLineNumber, sel.startColumn, sel.startLineNumber, maxColumn); } } return sel; }); rangesToDelete.sort(Range.compareRangesUsingStarts); return rangesToDelete; } } @editorAction export class JoinLinesAction extends EditorAction { constructor() { super({ id: 'editor.action.joinLines', label: nls.localize('lines.joinLines', "Join Lines"), alias: 'Join Lines', precondition: EditorContextKeys.writable, kbOpts: { kbExpr: EditorContextKeys.textFocus, primary: 0, mac: { primary: KeyMod.WinCtrl | KeyCode.KEY_J } } }); } public run(accessor: ServicesAccessor, editor: ICommonCodeEditor): void { let selections = editor.getSelections(); let primaryCursor = editor.getSelection(); selections.sort(Range.compareRangesUsingStarts); let reducedSelections: Selection[] = []; let lastSelection = selections.reduce((previousValue, currentValue) => { if (previousValue.isEmpty()) { if (previousValue.endLineNumber === currentValue.startLineNumber) { if (primaryCursor.equalsSelection(previousValue)) { primaryCursor = currentValue; } return currentValue; } if (currentValue.startLineNumber > previousValue.endLineNumber + 1) { reducedSelections.push(previousValue); return currentValue; } else { return new Selection(previousValue.startLineNumber, previousValue.startColumn, currentValue.endLineNumber, currentValue.endColumn); } } else { if (currentValue.startLineNumber > previousValue.endLineNumber) { reducedSelections.push(previousValue); return currentValue; } else { return new Selection(previousValue.startLineNumber, previousValue.startColumn, currentValue.endLineNumber, currentValue.endColumn); } } }); reducedSelections.push(lastSelection); let model = editor.getModel(); let edits = []; let endCursorState = []; let endPrimaryCursor = primaryCursor; let lineOffset = 0; for (let i = 0, len = reducedSelections.length; i < len; i++) { let selection = reducedSelections[i]; let startLineNumber = selection.startLineNumber; let startColumn = 1; let endLineNumber: number, endColumn: number, columnDeltaOffset: number; let selectionEndPositionOffset = model.getLineContent(selection.endLineNumber).length - selection.endColumn; if (selection.isEmpty() || selection.startLineNumber === selection.endLineNumber) { let position = selection.getStartPosition(); if (position.lineNumber < model.getLineCount()) { endLineNumber = startLineNumber + 1; endColumn = model.getLineMaxColumn(endLineNumber); } else { endLineNumber = position.lineNumber; endColumn = model.getLineMaxColumn(position.lineNumber); } } else { endLineNumber = selection.endLineNumber; endColumn = model.getLineMaxColumn(endLineNumber); } let trimmedLinesContent = model.getLineContent(startLineNumber); for (let i = startLineNumber + 1; i <= endLineNumber; i++) { let lineText = model.getLineContent(i); let firstNonWhitespaceIdx = model.getLineFirstNonWhitespaceColumn(i); if (firstNonWhitespaceIdx >= 1) { let insertSpace = true; if (trimmedLinesContent === '') { insertSpace = false; } if (insertSpace && (trimmedLinesContent.charAt(trimmedLinesContent.length - 1) === ' ' || trimmedLinesContent.charAt(trimmedLinesContent.length - 1) === '\t')) { insertSpace = false; trimmedLinesContent = trimmedLinesContent.replace(/[\s\uFEFF\xA0]+$/g, ' '); } let lineTextWithoutIndent = lineText.substr(firstNonWhitespaceIdx - 1); trimmedLinesContent += (insertSpace ? ' ' : '') + lineTextWithoutIndent; if (insertSpace) { columnDeltaOffset = lineTextWithoutIndent.length + 1; } else { columnDeltaOffset = lineTextWithoutIndent.length; } } else { columnDeltaOffset = 0; } } let deleteSelection = new Range(startLineNumber, startColumn, endLineNumber, endColumn); if (!deleteSelection.isEmpty()) { let resultSelection: Selection; if (selection.isEmpty()) { edits.push(EditOperation.replace(deleteSelection, trimmedLinesContent)); resultSelection = new Selection(deleteSelection.startLineNumber - lineOffset, trimmedLinesContent.length - columnDeltaOffset + 1, startLineNumber - lineOffset, trimmedLinesContent.length - columnDeltaOffset + 1); } else { if (selection.startLineNumber === selection.endLineNumber) { edits.push(EditOperation.replace(deleteSelection, trimmedLinesContent)); resultSelection = new Selection(selection.startLineNumber - lineOffset, selection.startColumn, selection.endLineNumber - lineOffset, selection.endColumn); } else { edits.push(EditOperation.replace(deleteSelection, trimmedLinesContent)); resultSelection = new Selection(selection.startLineNumber - lineOffset, selection.startColumn, selection.startLineNumber - lineOffset, trimmedLinesContent.length - selectionEndPositionOffset); } } if (Range.intersectRanges(deleteSelection, primaryCursor) !== null) { endPrimaryCursor = resultSelection; } else { endCursorState.push(resultSelection); } } lineOffset += deleteSelection.endLineNumber - deleteSelection.startLineNumber; } endCursorState.unshift(endPrimaryCursor); editor.executeEdits(this.id, edits, endCursorState); } } @editorAction export class TransposeAction extends EditorAction { constructor() { super({ id: 'editor.action.transpose', label: nls.localize('editor.transpose', "Transpose characters around the cursor"), alias: 'Transpose characters around the cursor', precondition: EditorContextKeys.writable }); } public run(accessor: ServicesAccessor, editor: ICommonCodeEditor): void { let selections = editor.getSelections(); let model = editor.getModel(); let commands: ICommand[] = []; for (let i = 0, len = selections.length; i < len; i++) { let selection = selections[i]; if (!selection.isEmpty()) { continue; } let cursor = selection.getStartPosition(); let maxColumn = model.getLineMaxColumn(cursor.lineNumber); if (cursor.column >= maxColumn) { if (cursor.lineNumber === model.getLineCount()) { continue; } // The cursor is at the end of current line and current line is not empty // then we transpose the character before the cursor and the line break if there is any following line. let deleteSelection = new Range(cursor.lineNumber, Math.max(1, cursor.column - 1), cursor.lineNumber + 1, 1); let chars = model.getValueInRange(deleteSelection).split('').reverse().join(''); commands.push(new ReplaceCommand(new Selection(cursor.lineNumber, Math.max(1, cursor.column - 1), cursor.lineNumber + 1, 1), chars)); } else { let deleteSelection = new Range(cursor.lineNumber, Math.max(1, cursor.column - 1), cursor.lineNumber, cursor.column + 1); let chars = model.getValueInRange(deleteSelection).split('').reverse().join(''); commands.push(new ReplaceCommandThatPreservesSelection(deleteSelection, chars, new Selection(cursor.lineNumber, cursor.column + 1, cursor.lineNumber, cursor.column + 1))); } } editor.pushUndoStop(); editor.executeCommands(this.id, commands); editor.pushUndoStop(); } } export abstract class AbstractCaseAction extends EditorAction { public run(accessor: ServicesAccessor, editor: ICommonCodeEditor): void { let selections = editor.getSelections(); let model = editor.getModel(); let commands: ICommand[] = []; for (let i = 0, len = selections.length; i < len; i++) { let selection = selections[i]; if (selection.isEmpty()) { let cursor = selection.getStartPosition(); let word = model.getWordAtPosition(cursor); if (!word) { continue; } let wordRange = new Range(cursor.lineNumber, word.startColumn, cursor.lineNumber, word.endColumn); let text = model.getValueInRange(wordRange); commands.push(new ReplaceCommandThatPreservesSelection(wordRange, this._modifyText(text), new Selection(cursor.lineNumber, cursor.column, cursor.lineNumber, cursor.column))); } else { let text = model.getValueInRange(selection); commands.push(new ReplaceCommandThatPreservesSelection(selection, this._modifyText(text), selection)); } } editor.pushUndoStop(); editor.executeCommands(this.id, commands); editor.pushUndoStop(); } protected abstract _modifyText(text: string): string; } @editorAction export class UpperCaseAction extends AbstractCaseAction { constructor() { super({ id: 'editor.action.transformToUppercase', label: nls.localize('editor.transformToUppercase', "Transform to Uppercase"), alias: 'Transform to Uppercase', precondition: EditorContextKeys.writable }); } protected _modifyText(text: string): string { return text.toLocaleUpperCase(); } } @editorAction export class LowerCaseAction extends AbstractCaseAction { constructor() { super({ id: 'editor.action.transformToLowercase', label: nls.localize('editor.transformToLowercase', "Transform to Lowercase"), alias: 'Transform to Lowercase', precondition: EditorContextKeys.writable }); } protected _modifyText(text: string): string { return text.toLocaleLowerCase(); } }
src/vs/editor/contrib/linesOperations/common/linesOperations.ts
1
https://github.com/microsoft/vscode/commit/5d3dfe86cd6ac769a66f5473da3ab63c2a6918bf
[ 0.9983659386634827, 0.01534248236566782, 0.0001654145889915526, 0.00017080664110835642, 0.11051737517118454 ]
{ "id": 1, "code_window": [ "\t}\n", "\n", "\tpublic run(accessor: ServicesAccessor, editor: ICommonCodeEditor, args: any): void {\n", "\n", "\t\tvar cursors: Position[];\n", "\t\tif (args.reason === 'auto-save') {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ "\t\tlet cursors: Position[] = [];\n" ], "file_path": "src/vs/editor/contrib/linesOperations/common/linesOperations.ts", "type": "replace", "edit_start_line_idx": 211 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ // Do not edit this file. It is machine generated. { "watermark.showCommands": "Afficher toutes les commandes", "watermark.quickOpen": "Accéder au fichier", "watermark.openFile": "Ouvrir le fichier", "watermark.openFolder": "Ouvrir le dossier", "watermark.openFileFolder": "Ouvrir un fichier ou un dossier", "watermark.openRecent": "Ouvrir les éléments récents", "watermark.newUntitledFile": "Nouveau fichier sans titre", "watermark.toggleTerminal": "Activer/désactiver le terminal", "watermark.findInFiles": "Chercher dans les fichiers", "watermark.startDebugging": "Démarrer le débogage", "watermark.unboundCommand": "indépendant", "workbenchConfigurationTitle": "Banc d'essai", "tips.enabled": "Si cette option est activée, les conseils en filigrane s'affichent quand aucun éditeur n'est ouvert." }
i18n/fra/src/vs/workbench/parts/watermark/electron-browser/watermark.i18n.json
0
https://github.com/microsoft/vscode/commit/5d3dfe86cd6ac769a66f5473da3ab63c2a6918bf
[ 0.00017668212240096182, 0.00017492694314569235, 0.00017229007789865136, 0.0001758086000336334, 0.0000018983353129442548 ]
{ "id": 1, "code_window": [ "\t}\n", "\n", "\tpublic run(accessor: ServicesAccessor, editor: ICommonCodeEditor, args: any): void {\n", "\n", "\t\tvar cursors: Position[];\n", "\t\tif (args.reason === 'auto-save') {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ "\t\tlet cursors: Position[] = [];\n" ], "file_path": "src/vs/editor/contrib/linesOperations/common/linesOperations.ts", "type": "replace", "edit_start_line_idx": 211 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ // Do not edit this file. It is machine generated. { "collapse": "Comprimi" }
i18n/ita/src/vs/base/parts/tree/browser/treeDefaults.i18n.json
0
https://github.com/microsoft/vscode/commit/5d3dfe86cd6ac769a66f5473da3ab63c2a6918bf
[ 0.00017728863167576492, 0.00017728863167576492, 0.00017728863167576492, 0.00017728863167576492, 0 ]
{ "id": 1, "code_window": [ "\t}\n", "\n", "\tpublic run(accessor: ServicesAccessor, editor: ICommonCodeEditor, args: any): void {\n", "\n", "\t\tvar cursors: Position[];\n", "\t\tif (args.reason === 'auto-save') {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ "\t\tlet cursors: Position[] = [];\n" ], "file_path": "src/vs/editor/contrib/linesOperations/common/linesOperations.ts", "type": "replace", "edit_start_line_idx": 211 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ // Do not edit this file. It is machine generated. { "splitJoinTag": "Emmet: 태그 분할/조인" }
i18n/kor/src/vs/workbench/parts/emmet/electron-browser/actions/splitJoinTag.i18n.json
0
https://github.com/microsoft/vscode/commit/5d3dfe86cd6ac769a66f5473da3ab63c2a6918bf
[ 0.00017571458010934293, 0.00017571458010934293, 0.00017571458010934293, 0.00017571458010934293, 0 ]
{ "id": 2, "code_window": [ "\t\tif (args.reason === 'auto-save') {\n", "\t\t\tcursors = editor.getSelections().map(s => new Position(s.positionLineNumber, s.positionColumn));\n", "\t\t}\n", "\n" ], "labels": [ "add", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t// See https://github.com/editorconfig/editorconfig-vscode/issues/47\n", "\t\t\t// It is very convenient for the editor config extension to invoke this action.\n", "\t\t\t// So, if we get a reason:'auto-save' passed in, let's preserve cursor positions.\n" ], "file_path": "src/vs/editor/contrib/linesOperations/common/linesOperations.ts", "type": "add", "edit_start_line_idx": 213 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import * as strings from 'vs/base/common/strings'; import { EditOperation } from 'vs/editor/common/core/editOperation'; import { Range } from 'vs/editor/common/core/range'; import { Position } from 'vs/editor/common/core/position'; import * as editorCommon from 'vs/editor/common/editorCommon'; import { Selection } from 'vs/editor/common/core/selection'; export class TrimTrailingWhitespaceCommand implements editorCommon.ICommand { private selection: Selection; private selectionId: string; private cursors: Position[]; constructor(selection: Selection, cursors: Position[] = []) { this.selection = selection; this.cursors = cursors; } public getEditOperations(model: editorCommon.ITokenizedModel, builder: editorCommon.IEditOperationBuilder): void { let ops = trimTrailingWhitespace(model, this.cursors); for (let i = 0, len = ops.length; i < len; i++) { let op = ops[i]; builder.addEditOperation(op.range, op.text); } this.selectionId = builder.trackSelection(this.selection); } public computeCursorState(model: editorCommon.ITokenizedModel, helper: editorCommon.ICursorStateComputerData): Selection { return helper.getTrackedSelection(this.selectionId); } } /** * Generate commands for trimming trailing whitespace on a model and ignore lines on which cursors are sitting. */ export function trimTrailingWhitespace(model: editorCommon.ITextModel, cursors: Position[]): editorCommon.IIdentifiedSingleEditOperation[] { // Sort cursors ascending cursors.sort((a, b) => { if (a.lineNumber === b.lineNumber) { return a.column - b.column; } return a.lineNumber - b.lineNumber; }); // Reduce multiple cursors on the same line and only keep the last one on the line for (let i = cursors.length - 2; i >= 0; i--) { if (cursors[i].lineNumber === cursors[i + 1].lineNumber) { // Remove cursor at `i` cursors.splice(i, 1); } } let r: editorCommon.IIdentifiedSingleEditOperation[] = []; let rLen = 0; let cursorIndex = 0; let cursorLen = cursors.length; for (let lineNumber = 1, lineCount = model.getLineCount(); lineNumber <= lineCount; lineNumber++) { let lineContent = model.getLineContent(lineNumber); let maxLineColumn = lineContent.length + 1; let minEditColumn = 0; if (cursorIndex < cursorLen && cursors[cursorIndex].lineNumber === lineNumber) { minEditColumn = cursors[cursorIndex].column; cursorIndex++; if (minEditColumn === maxLineColumn) { // The cursor is at the end of the line => no edits for sure on this line continue; } } if (lineContent.length === 0) { continue; } let lastNonWhitespaceIndex = strings.lastNonWhitespaceIndex(lineContent); let fromColumn = 0; if (lastNonWhitespaceIndex === -1) { // Entire line is whitespace fromColumn = 1; } else if (lastNonWhitespaceIndex !== lineContent.length - 1) { // There is trailing whitespace fromColumn = lastNonWhitespaceIndex + 2; } else { // There is no trailing whitespace continue; } fromColumn = Math.max(minEditColumn, fromColumn); r[rLen++] = EditOperation.delete(new Range( lineNumber, fromColumn, lineNumber, maxLineColumn )); } return r; }
src/vs/editor/common/commands/trimTrailingWhitespaceCommand.ts
1
https://github.com/microsoft/vscode/commit/5d3dfe86cd6ac769a66f5473da3ab63c2a6918bf
[ 0.9987002611160278, 0.4486843943595886, 0.0001655357627896592, 0.0012506513157859445, 0.49135124683380127 ]
{ "id": 2, "code_window": [ "\t\tif (args.reason === 'auto-save') {\n", "\t\t\tcursors = editor.getSelections().map(s => new Position(s.positionLineNumber, s.positionColumn));\n", "\t\t}\n", "\n" ], "labels": [ "add", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t// See https://github.com/editorconfig/editorconfig-vscode/issues/47\n", "\t\t\t// It is very convenient for the editor config extension to invoke this action.\n", "\t\t\t// So, if we get a reason:'auto-save' passed in, let's preserve cursor positions.\n" ], "file_path": "src/vs/editor/contrib/linesOperations/common/linesOperations.ts", "type": "add", "edit_start_line_idx": 213 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ // Do not edit this file. It is machine generated. { "removeBreakpoints": "중단점 제거", "removeBreakpointOnColumn": "{0} 열에서 중단점 제거", "removeLineBreakpoint": "줄 중단점 제거", "editBreakpoints": "중단점 편집", "editBreakpointOnColumn": "{0} 열에서 중단점 편집", "editLineBrekapoint": "줄 중단점 편집", "enableDisableBreakpoints": "중단점 사용/사용 안 함", "disableColumnBreakpoint": "{0} 열에서 중단점 사용 안 함", "disableBreakpointOnLine": "줄 중단점 사용 안 함", "enableBreakpoints": "{0} 열에서 중단점 사용", "enableBreakpointOnLine": "줄 중단점 사용", "addBreakpoint": "중단점 추가", "addConfiguration": "구성 추가..." }
i18n/kor/src/vs/workbench/parts/debug/electron-browser/debugEditorContribution.i18n.json
0
https://github.com/microsoft/vscode/commit/5d3dfe86cd6ac769a66f5473da3ab63c2a6918bf
[ 0.00018006679601967335, 0.0001744543988024816, 0.00017037054931279272, 0.0001729258510749787, 0.000004103384071640903 ]
{ "id": 2, "code_window": [ "\t\tif (args.reason === 'auto-save') {\n", "\t\t\tcursors = editor.getSelections().map(s => new Position(s.positionLineNumber, s.positionColumn));\n", "\t\t}\n", "\n" ], "labels": [ "add", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t// See https://github.com/editorconfig/editorconfig-vscode/issues/47\n", "\t\t\t// It is very convenient for the editor config extension to invoke this action.\n", "\t\t\t// So, if we get a reason:'auto-save' passed in, let's preserve cursor positions.\n" ], "file_path": "src/vs/editor/contrib/linesOperations/common/linesOperations.ts", "type": "add", "edit_start_line_idx": 213 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ // Do not edit this file. It is machine generated. { "noWorkspace": "작업 영역이 없습니다." }
i18n/kor/src/vs/platform/extensionManagement/common/extensionEnablementService.i18n.json
0
https://github.com/microsoft/vscode/commit/5d3dfe86cd6ac769a66f5473da3ab63c2a6918bf
[ 0.00017755456792656332, 0.00017755456792656332, 0.00017755456792656332, 0.00017755456792656332, 0 ]
{ "id": 2, "code_window": [ "\t\tif (args.reason === 'auto-save') {\n", "\t\t\tcursors = editor.getSelections().map(s => new Position(s.positionLineNumber, s.positionColumn));\n", "\t\t}\n", "\n" ], "labels": [ "add", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t// See https://github.com/editorconfig/editorconfig-vscode/issues/47\n", "\t\t\t// It is very convenient for the editor config extension to invoke this action.\n", "\t\t\t// So, if we get a reason:'auto-save' passed in, let's preserve cursor positions.\n" ], "file_path": "src/vs/editor/contrib/linesOperations/common/linesOperations.ts", "type": "add", "edit_start_line_idx": 213 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { createDecorator } from 'vs/platform/instantiation/common/instantiation'; export interface ParsedArgs { [arg: string]: any; _: string[]; help?: boolean; version?: boolean; wait?: boolean; waitMarkerFilePath?: string; diff?: boolean; add?: boolean; goto?: boolean; 'new-window'?: boolean; 'unity-launch'?: boolean; // Always open a new window, except if opening the first window or opening a file or folder as part of the launch. 'reuse-window'?: boolean; locale?: string; 'user-data-dir'?: string; performance?: boolean; 'prof-startup'?: string; verbose?: boolean; logExtensionHostCommunication?: boolean; 'disable-extensions'?: boolean; 'extensions-dir'?: string; extensionDevelopmentPath?: string; extensionTestsPath?: string; debugPluginHost?: string; debugBrkPluginHost?: string; debugId?: string; debugSearch?: string; debugBrkSearch?: string; 'list-extensions'?: boolean; 'show-versions'?: boolean; 'install-extension'?: string | string[]; 'uninstall-extension'?: string | string[]; 'enable-proposed-api'?: string | string[]; 'open-url'?: string | string[]; 'skip-getting-started'?: boolean; 'sticky-quickopen'?: boolean; 'disable-telemetry'?: boolean; 'export-default-configuration'?: string; 'install-source'?: string; } export const IEnvironmentService = createDecorator<IEnvironmentService>('environmentService'); export interface IDebugParams { port: number; break: boolean; } export interface IExtensionHostDebugParams extends IDebugParams { debugId: string; } export interface IEnvironmentService { _serviceBrand: any; args: ParsedArgs; execPath: string; appRoot: string; userHome: string; userDataPath: string; appNameLong: string; appQuality: string; appSettingsHome: string; appSettingsPath: string; appKeybindingsPath: string; machineUUID: string; backupHome: string; backupWorkspacesPath: string; workspacesHome: string; isExtensionDevelopment: boolean; disableExtensions: boolean; extensionsPath: string; extensionDevelopmentPath: string; extensionTestsPath: string; debugExtensionHost: IExtensionHostDebugParams; debugSearch: IDebugParams; logExtensionHostCommunication: boolean; isBuilt: boolean; verbose: boolean; wait: boolean; performance: boolean; profileStartup: { prefix: string, dir: string } | undefined; skipGettingStarted: boolean | undefined; mainIPCHandle: string; sharedIPCHandle: string; nodeCachedDataDir: string; installSource: string; }
src/vs/platform/environment/common/environment.ts
0
https://github.com/microsoft/vscode/commit/5d3dfe86cd6ac769a66f5473da3ab63c2a6918bf
[ 0.00031078141182661057, 0.00018455773533787578, 0.00016456835146527737, 0.000173767504747957, 0.00004007481038570404 ]
{ "id": 3, "code_window": [ "import { withEditorModel } from 'vs/editor/test/common/editorTestUtils';\n", "\n", "function assertTrimTrailingWhitespaceCommand(text: string[], expected: IIdentifiedSingleEditOperation[]): void {\n", "\treturn withEditorModel(text, (model) => {\n", "\t\tvar op = new TrimTrailingWhitespaceCommand(new Selection(1, 1, 1, 1));\n", "\t\tvar actual = getEditOperation(model, op);\n", "\t\tassert.deepEqual(actual, expected);\n", "\t});\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\tvar op = new TrimTrailingWhitespaceCommand(new Selection(1, 1, 1, 1), []);\n" ], "file_path": "src/vs/editor/test/common/commands/trimTrailingWhitespaceCommand.test.ts", "type": "replace", "edit_start_line_idx": 16 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import * as nls from 'vs/nls'; import { KeyCode, KeyMod, KeyChord } from 'vs/base/common/keyCodes'; import { SortLinesCommand } from 'vs/editor/contrib/linesOperations/common/sortLinesCommand'; import { EditOperation } from 'vs/editor/common/core/editOperation'; import { TrimTrailingWhitespaceCommand } from 'vs/editor/common/commands/trimTrailingWhitespaceCommand'; import { ICommand, ICommonCodeEditor, IIdentifiedSingleEditOperation } from 'vs/editor/common/editorCommon'; import { EditorContextKeys } from 'vs/editor/common/editorContextKeys'; import { ReplaceCommand, ReplaceCommandThatPreservesSelection } from 'vs/editor/common/commands/replaceCommand'; import { Range } from 'vs/editor/common/core/range'; import { Selection } from 'vs/editor/common/core/selection'; import { Position } from 'vs/editor/common/core/position'; import { editorAction, ServicesAccessor, IActionOptions, EditorAction } from 'vs/editor/common/editorCommonExtensions'; import { CopyLinesCommand } from './copyLinesCommand'; import { DeleteLinesCommand } from './deleteLinesCommand'; import { MoveLinesCommand } from './moveLinesCommand'; import { TypeOperations } from 'vs/editor/common/controller/cursorTypeOperations'; import { CoreEditingCommands } from 'vs/editor/common/controller/coreCommands'; // copy lines abstract class AbstractCopyLinesAction extends EditorAction { private down: boolean; constructor(down: boolean, opts: IActionOptions) { super(opts); this.down = down; } public run(accessor: ServicesAccessor, editor: ICommonCodeEditor): void { var commands: ICommand[] = []; var selections = editor.getSelections(); for (var i = 0; i < selections.length; i++) { commands.push(new CopyLinesCommand(selections[i], this.down)); } editor.pushUndoStop(); editor.executeCommands(this.id, commands); editor.pushUndoStop(); } } @editorAction class CopyLinesUpAction extends AbstractCopyLinesAction { constructor() { super(false, { id: 'editor.action.copyLinesUpAction', label: nls.localize('lines.copyUp', "Copy Line Up"), alias: 'Copy Line Up', precondition: EditorContextKeys.writable, kbOpts: { kbExpr: EditorContextKeys.textFocus, primary: KeyMod.Alt | KeyMod.Shift | KeyCode.UpArrow, linux: { primary: KeyMod.CtrlCmd | KeyMod.Alt | KeyMod.Shift | KeyCode.UpArrow } } }); } } @editorAction class CopyLinesDownAction extends AbstractCopyLinesAction { constructor() { super(true, { id: 'editor.action.copyLinesDownAction', label: nls.localize('lines.copyDown', "Copy Line Down"), alias: 'Copy Line Down', precondition: EditorContextKeys.writable, kbOpts: { kbExpr: EditorContextKeys.textFocus, primary: KeyMod.Alt | KeyMod.Shift | KeyCode.DownArrow, linux: { primary: KeyMod.CtrlCmd | KeyMod.Alt | KeyMod.Shift | KeyCode.DownArrow } } }); } } // move lines abstract class AbstractMoveLinesAction extends EditorAction { private down: boolean; constructor(down: boolean, opts: IActionOptions) { super(opts); this.down = down; } public run(accessor: ServicesAccessor, editor: ICommonCodeEditor): void { var commands: ICommand[] = []; var selections = editor.getSelections(); var autoIndent = editor.getConfiguration().autoIndent; for (var i = 0; i < selections.length; i++) { commands.push(new MoveLinesCommand(selections[i], this.down, autoIndent)); } editor.pushUndoStop(); editor.executeCommands(this.id, commands); editor.pushUndoStop(); } } @editorAction class MoveLinesUpAction extends AbstractMoveLinesAction { constructor() { super(false, { id: 'editor.action.moveLinesUpAction', label: nls.localize('lines.moveUp', "Move Line Up"), alias: 'Move Line Up', precondition: EditorContextKeys.writable, kbOpts: { kbExpr: EditorContextKeys.textFocus, primary: KeyMod.Alt | KeyCode.UpArrow, linux: { primary: KeyMod.Alt | KeyCode.UpArrow } } }); } } @editorAction class MoveLinesDownAction extends AbstractMoveLinesAction { constructor() { super(true, { id: 'editor.action.moveLinesDownAction', label: nls.localize('lines.moveDown', "Move Line Down"), alias: 'Move Line Down', precondition: EditorContextKeys.writable, kbOpts: { kbExpr: EditorContextKeys.textFocus, primary: KeyMod.Alt | KeyCode.DownArrow, linux: { primary: KeyMod.Alt | KeyCode.DownArrow } } }); } } abstract class AbstractSortLinesAction extends EditorAction { private descending: boolean; constructor(descending: boolean, opts: IActionOptions) { super(opts); this.descending = descending; } public run(accessor: ServicesAccessor, editor: ICommonCodeEditor): void { if (!SortLinesCommand.canRun(editor.getModel(), editor.getSelection(), this.descending)) { return; } var command = new SortLinesCommand(editor.getSelection(), this.descending); editor.pushUndoStop(); editor.executeCommands(this.id, [command]); editor.pushUndoStop(); } } @editorAction class SortLinesAscendingAction extends AbstractSortLinesAction { constructor() { super(false, { id: 'editor.action.sortLinesAscending', label: nls.localize('lines.sortAscending', "Sort Lines Ascending"), alias: 'Sort Lines Ascending', precondition: EditorContextKeys.writable }); } } @editorAction class SortLinesDescendingAction extends AbstractSortLinesAction { constructor() { super(true, { id: 'editor.action.sortLinesDescending', label: nls.localize('lines.sortDescending', "Sort Lines Descending"), alias: 'Sort Lines Descending', precondition: EditorContextKeys.writable }); } } @editorAction export class TrimTrailingWhitespaceAction extends EditorAction { public static ID = 'editor.action.trimTrailingWhitespace'; constructor() { super({ id: TrimTrailingWhitespaceAction.ID, label: nls.localize('lines.trimTrailingWhitespace', "Trim Trailing Whitespace"), alias: 'Trim Trailing Whitespace', precondition: EditorContextKeys.writable, kbOpts: { kbExpr: EditorContextKeys.textFocus, primary: KeyChord(KeyMod.CtrlCmd | KeyCode.KEY_K, KeyMod.CtrlCmd | KeyCode.KEY_X) } }); } public run(accessor: ServicesAccessor, editor: ICommonCodeEditor, args: any): void { var cursors: Position[]; if (args.reason === 'auto-save') { cursors = editor.getSelections().map(s => new Position(s.positionLineNumber, s.positionColumn)); } var command = new TrimTrailingWhitespaceCommand(editor.getSelection(), cursors); editor.pushUndoStop(); editor.executeCommands(this.id, [command]); editor.pushUndoStop(); } } // delete lines interface IDeleteLinesOperation { startLineNumber: number; endLineNumber: number; positionColumn: number; } abstract class AbstractRemoveLinesAction extends EditorAction { _getLinesToRemove(editor: ICommonCodeEditor): IDeleteLinesOperation[] { // Construct delete operations var operations: IDeleteLinesOperation[] = editor.getSelections().map((s) => { var endLineNumber = s.endLineNumber; if (s.startLineNumber < s.endLineNumber && s.endColumn === 1) { endLineNumber -= 1; } return { startLineNumber: s.startLineNumber, endLineNumber: endLineNumber, positionColumn: s.positionColumn }; }); // Sort delete operations operations.sort((a, b) => { return a.startLineNumber - b.startLineNumber; }); // Merge delete operations on consecutive lines var mergedOperations: IDeleteLinesOperation[] = []; var previousOperation = operations[0]; for (var i = 1; i < operations.length; i++) { if (previousOperation.endLineNumber + 1 === operations[i].startLineNumber) { // Merge current operations into the previous one previousOperation.endLineNumber = operations[i].endLineNumber; } else { // Push previous operation mergedOperations.push(previousOperation); previousOperation = operations[i]; } } // Push the last operation mergedOperations.push(previousOperation); return mergedOperations; } } @editorAction class DeleteLinesAction extends AbstractRemoveLinesAction { constructor() { super({ id: 'editor.action.deleteLines', label: nls.localize('lines.delete', "Delete Line"), alias: 'Delete Line', precondition: EditorContextKeys.writable, kbOpts: { kbExpr: EditorContextKeys.textFocus, primary: KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.KEY_K } }); } public run(accessor: ServicesAccessor, editor: ICommonCodeEditor): void { var ops = this._getLinesToRemove(editor); // Finally, construct the delete lines commands var commands: ICommand[] = ops.map((op) => { return new DeleteLinesCommand(op.startLineNumber, op.endLineNumber, op.positionColumn); }); editor.pushUndoStop(); editor.executeCommands(this.id, commands); editor.pushUndoStop(); } } @editorAction export class IndentLinesAction extends EditorAction { constructor() { super({ id: 'editor.action.indentLines', label: nls.localize('lines.indent', "Indent Line"), alias: 'Indent Line', precondition: EditorContextKeys.writable, kbOpts: { kbExpr: EditorContextKeys.textFocus, primary: KeyMod.CtrlCmd | KeyCode.US_CLOSE_SQUARE_BRACKET } }); } public run(accessor: ServicesAccessor, editor: ICommonCodeEditor): void { editor.pushUndoStop(); editor.executeCommands(this.id, TypeOperations.indent(editor._getCursorConfiguration(), editor.getModel(), editor.getSelections())); editor.pushUndoStop(); } } @editorAction class OutdentLinesAction extends EditorAction { constructor() { super({ id: 'editor.action.outdentLines', label: nls.localize('lines.outdent', "Outdent Line"), alias: 'Outdent Line', precondition: EditorContextKeys.writable, kbOpts: { kbExpr: EditorContextKeys.textFocus, primary: KeyMod.CtrlCmd | KeyCode.US_OPEN_SQUARE_BRACKET } }); } public run(accessor: ServicesAccessor, editor: ICommonCodeEditor): void { CoreEditingCommands.Outdent.runEditorCommand(null, editor, null); } } @editorAction export class InsertLineBeforeAction extends EditorAction { constructor() { super({ id: 'editor.action.insertLineBefore', label: nls.localize('lines.insertBefore', "Insert Line Above"), alias: 'Insert Line Above', precondition: EditorContextKeys.writable, kbOpts: { kbExpr: EditorContextKeys.textFocus, primary: KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.Enter } }); } public run(accessor: ServicesAccessor, editor: ICommonCodeEditor): void { editor.pushUndoStop(); editor.executeCommands(this.id, TypeOperations.lineInsertBefore(editor._getCursorConfiguration(), editor.getModel(), editor.getSelections())); } } @editorAction export class InsertLineAfterAction extends EditorAction { constructor() { super({ id: 'editor.action.insertLineAfter', label: nls.localize('lines.insertAfter', "Insert Line Below"), alias: 'Insert Line Below', precondition: EditorContextKeys.writable, kbOpts: { kbExpr: EditorContextKeys.textFocus, primary: KeyMod.CtrlCmd | KeyCode.Enter } }); } public run(accessor: ServicesAccessor, editor: ICommonCodeEditor): void { editor.pushUndoStop(); editor.executeCommands(this.id, TypeOperations.lineInsertAfter(editor._getCursorConfiguration(), editor.getModel(), editor.getSelections())); } } export abstract class AbstractDeleteAllToBoundaryAction extends EditorAction { public run(accessor: ServicesAccessor, editor: ICommonCodeEditor): void { const primaryCursor = editor.getSelection(); let rangesToDelete = this._getRangesToDelete(editor); // merge overlapping selections let effectiveRanges: Range[] = []; for (let i = 0, count = rangesToDelete.length - 1; i < count; i++) { let range = rangesToDelete[i]; let nextRange = rangesToDelete[i + 1]; if (Range.intersectRanges(range, nextRange) === null) { effectiveRanges.push(range); } else { rangesToDelete[i + 1] = Range.plusRange(range, nextRange); } } effectiveRanges.push(rangesToDelete[rangesToDelete.length - 1]); let endCursorState = this._getEndCursorState(primaryCursor, effectiveRanges); let edits: IIdentifiedSingleEditOperation[] = effectiveRanges.map(range => { endCursorState.push(new Selection(range.startLineNumber, range.startColumn, range.startLineNumber, range.startColumn)); return EditOperation.replace(range, ''); }); editor.executeEdits(this.id, edits, endCursorState); } /** * Compute the cursor state after the edit operations were applied. */ protected abstract _getEndCursorState(primaryCursor: Range, rangesToDelete: Range[]): Selection[]; protected abstract _getRangesToDelete(editor: ICommonCodeEditor): Range[]; } @editorAction export class DeleteAllLeftAction extends AbstractDeleteAllToBoundaryAction { constructor() { super({ id: 'deleteAllLeft', label: nls.localize('lines.deleteAllLeft', "Delete All Left"), alias: 'Delete All Left', precondition: EditorContextKeys.writable, kbOpts: { kbExpr: EditorContextKeys.textFocus, primary: null, mac: { primary: KeyMod.CtrlCmd | KeyCode.Backspace } } }); } _getEndCursorState(primaryCursor: Range, rangesToDelete: Range[]): Selection[] { let endPrimaryCursor: Selection; let endCursorState: Selection[] = []; for (let i = 0, len = rangesToDelete.length; i < len; i++) { let range = rangesToDelete[i]; let endCursor = new Selection(rangesToDelete[i].startLineNumber, rangesToDelete[i].startColumn, rangesToDelete[i].startLineNumber, rangesToDelete[i].startColumn); if (range.intersectRanges(primaryCursor)) { endPrimaryCursor = endCursor; } else { endCursorState.push(endCursor); } } if (endPrimaryCursor) { endCursorState.unshift(endPrimaryCursor); } return endCursorState; } _getRangesToDelete(editor: ICommonCodeEditor): Range[] { let rangesToDelete: Range[] = editor.getSelections(); rangesToDelete.sort(Range.compareRangesUsingStarts); rangesToDelete = rangesToDelete.map(selection => { if (selection.isEmpty()) { return new Range(selection.startLineNumber, 1, selection.startLineNumber, selection.startColumn); } else { return selection; } }); return rangesToDelete; } } @editorAction export class DeleteAllRightAction extends AbstractDeleteAllToBoundaryAction { constructor() { super({ id: 'deleteAllRight', label: nls.localize('lines.deleteAllRight', "Delete All Right"), alias: 'Delete All Right', precondition: EditorContextKeys.writable, kbOpts: { kbExpr: EditorContextKeys.textFocus, primary: null, mac: { primary: KeyMod.WinCtrl | KeyCode.KEY_K, secondary: [KeyMod.CtrlCmd | KeyCode.Delete] } } }); } _getEndCursorState(primaryCursor: Range, rangesToDelete: Range[]): Selection[] { let endPrimaryCursor: Selection; let endCursorState: Selection[] = []; for (let i = 0, len = rangesToDelete.length, offset = 0; i < len; i++) { let range = rangesToDelete[i]; let endCursor = new Selection(range.startLineNumber - offset, range.startColumn, range.startLineNumber - offset, range.startColumn); if (range.intersectRanges(primaryCursor)) { endPrimaryCursor = endCursor; } else { endCursorState.push(endCursor); } } if (endPrimaryCursor) { endCursorState.unshift(endPrimaryCursor); } return endCursorState; } _getRangesToDelete(editor: ICommonCodeEditor): Range[] { let model = editor.getModel(); let rangesToDelete: Range[] = editor.getSelections().map((sel) => { if (sel.isEmpty()) { const maxColumn = model.getLineMaxColumn(sel.startLineNumber); if (sel.startColumn === maxColumn) { return new Range(sel.startLineNumber, sel.startColumn, sel.startLineNumber + 1, 1); } else { return new Range(sel.startLineNumber, sel.startColumn, sel.startLineNumber, maxColumn); } } return sel; }); rangesToDelete.sort(Range.compareRangesUsingStarts); return rangesToDelete; } } @editorAction export class JoinLinesAction extends EditorAction { constructor() { super({ id: 'editor.action.joinLines', label: nls.localize('lines.joinLines', "Join Lines"), alias: 'Join Lines', precondition: EditorContextKeys.writable, kbOpts: { kbExpr: EditorContextKeys.textFocus, primary: 0, mac: { primary: KeyMod.WinCtrl | KeyCode.KEY_J } } }); } public run(accessor: ServicesAccessor, editor: ICommonCodeEditor): void { let selections = editor.getSelections(); let primaryCursor = editor.getSelection(); selections.sort(Range.compareRangesUsingStarts); let reducedSelections: Selection[] = []; let lastSelection = selections.reduce((previousValue, currentValue) => { if (previousValue.isEmpty()) { if (previousValue.endLineNumber === currentValue.startLineNumber) { if (primaryCursor.equalsSelection(previousValue)) { primaryCursor = currentValue; } return currentValue; } if (currentValue.startLineNumber > previousValue.endLineNumber + 1) { reducedSelections.push(previousValue); return currentValue; } else { return new Selection(previousValue.startLineNumber, previousValue.startColumn, currentValue.endLineNumber, currentValue.endColumn); } } else { if (currentValue.startLineNumber > previousValue.endLineNumber) { reducedSelections.push(previousValue); return currentValue; } else { return new Selection(previousValue.startLineNumber, previousValue.startColumn, currentValue.endLineNumber, currentValue.endColumn); } } }); reducedSelections.push(lastSelection); let model = editor.getModel(); let edits = []; let endCursorState = []; let endPrimaryCursor = primaryCursor; let lineOffset = 0; for (let i = 0, len = reducedSelections.length; i < len; i++) { let selection = reducedSelections[i]; let startLineNumber = selection.startLineNumber; let startColumn = 1; let endLineNumber: number, endColumn: number, columnDeltaOffset: number; let selectionEndPositionOffset = model.getLineContent(selection.endLineNumber).length - selection.endColumn; if (selection.isEmpty() || selection.startLineNumber === selection.endLineNumber) { let position = selection.getStartPosition(); if (position.lineNumber < model.getLineCount()) { endLineNumber = startLineNumber + 1; endColumn = model.getLineMaxColumn(endLineNumber); } else { endLineNumber = position.lineNumber; endColumn = model.getLineMaxColumn(position.lineNumber); } } else { endLineNumber = selection.endLineNumber; endColumn = model.getLineMaxColumn(endLineNumber); } let trimmedLinesContent = model.getLineContent(startLineNumber); for (let i = startLineNumber + 1; i <= endLineNumber; i++) { let lineText = model.getLineContent(i); let firstNonWhitespaceIdx = model.getLineFirstNonWhitespaceColumn(i); if (firstNonWhitespaceIdx >= 1) { let insertSpace = true; if (trimmedLinesContent === '') { insertSpace = false; } if (insertSpace && (trimmedLinesContent.charAt(trimmedLinesContent.length - 1) === ' ' || trimmedLinesContent.charAt(trimmedLinesContent.length - 1) === '\t')) { insertSpace = false; trimmedLinesContent = trimmedLinesContent.replace(/[\s\uFEFF\xA0]+$/g, ' '); } let lineTextWithoutIndent = lineText.substr(firstNonWhitespaceIdx - 1); trimmedLinesContent += (insertSpace ? ' ' : '') + lineTextWithoutIndent; if (insertSpace) { columnDeltaOffset = lineTextWithoutIndent.length + 1; } else { columnDeltaOffset = lineTextWithoutIndent.length; } } else { columnDeltaOffset = 0; } } let deleteSelection = new Range(startLineNumber, startColumn, endLineNumber, endColumn); if (!deleteSelection.isEmpty()) { let resultSelection: Selection; if (selection.isEmpty()) { edits.push(EditOperation.replace(deleteSelection, trimmedLinesContent)); resultSelection = new Selection(deleteSelection.startLineNumber - lineOffset, trimmedLinesContent.length - columnDeltaOffset + 1, startLineNumber - lineOffset, trimmedLinesContent.length - columnDeltaOffset + 1); } else { if (selection.startLineNumber === selection.endLineNumber) { edits.push(EditOperation.replace(deleteSelection, trimmedLinesContent)); resultSelection = new Selection(selection.startLineNumber - lineOffset, selection.startColumn, selection.endLineNumber - lineOffset, selection.endColumn); } else { edits.push(EditOperation.replace(deleteSelection, trimmedLinesContent)); resultSelection = new Selection(selection.startLineNumber - lineOffset, selection.startColumn, selection.startLineNumber - lineOffset, trimmedLinesContent.length - selectionEndPositionOffset); } } if (Range.intersectRanges(deleteSelection, primaryCursor) !== null) { endPrimaryCursor = resultSelection; } else { endCursorState.push(resultSelection); } } lineOffset += deleteSelection.endLineNumber - deleteSelection.startLineNumber; } endCursorState.unshift(endPrimaryCursor); editor.executeEdits(this.id, edits, endCursorState); } } @editorAction export class TransposeAction extends EditorAction { constructor() { super({ id: 'editor.action.transpose', label: nls.localize('editor.transpose', "Transpose characters around the cursor"), alias: 'Transpose characters around the cursor', precondition: EditorContextKeys.writable }); } public run(accessor: ServicesAccessor, editor: ICommonCodeEditor): void { let selections = editor.getSelections(); let model = editor.getModel(); let commands: ICommand[] = []; for (let i = 0, len = selections.length; i < len; i++) { let selection = selections[i]; if (!selection.isEmpty()) { continue; } let cursor = selection.getStartPosition(); let maxColumn = model.getLineMaxColumn(cursor.lineNumber); if (cursor.column >= maxColumn) { if (cursor.lineNumber === model.getLineCount()) { continue; } // The cursor is at the end of current line and current line is not empty // then we transpose the character before the cursor and the line break if there is any following line. let deleteSelection = new Range(cursor.lineNumber, Math.max(1, cursor.column - 1), cursor.lineNumber + 1, 1); let chars = model.getValueInRange(deleteSelection).split('').reverse().join(''); commands.push(new ReplaceCommand(new Selection(cursor.lineNumber, Math.max(1, cursor.column - 1), cursor.lineNumber + 1, 1), chars)); } else { let deleteSelection = new Range(cursor.lineNumber, Math.max(1, cursor.column - 1), cursor.lineNumber, cursor.column + 1); let chars = model.getValueInRange(deleteSelection).split('').reverse().join(''); commands.push(new ReplaceCommandThatPreservesSelection(deleteSelection, chars, new Selection(cursor.lineNumber, cursor.column + 1, cursor.lineNumber, cursor.column + 1))); } } editor.pushUndoStop(); editor.executeCommands(this.id, commands); editor.pushUndoStop(); } } export abstract class AbstractCaseAction extends EditorAction { public run(accessor: ServicesAccessor, editor: ICommonCodeEditor): void { let selections = editor.getSelections(); let model = editor.getModel(); let commands: ICommand[] = []; for (let i = 0, len = selections.length; i < len; i++) { let selection = selections[i]; if (selection.isEmpty()) { let cursor = selection.getStartPosition(); let word = model.getWordAtPosition(cursor); if (!word) { continue; } let wordRange = new Range(cursor.lineNumber, word.startColumn, cursor.lineNumber, word.endColumn); let text = model.getValueInRange(wordRange); commands.push(new ReplaceCommandThatPreservesSelection(wordRange, this._modifyText(text), new Selection(cursor.lineNumber, cursor.column, cursor.lineNumber, cursor.column))); } else { let text = model.getValueInRange(selection); commands.push(new ReplaceCommandThatPreservesSelection(selection, this._modifyText(text), selection)); } } editor.pushUndoStop(); editor.executeCommands(this.id, commands); editor.pushUndoStop(); } protected abstract _modifyText(text: string): string; } @editorAction export class UpperCaseAction extends AbstractCaseAction { constructor() { super({ id: 'editor.action.transformToUppercase', label: nls.localize('editor.transformToUppercase', "Transform to Uppercase"), alias: 'Transform to Uppercase', precondition: EditorContextKeys.writable }); } protected _modifyText(text: string): string { return text.toLocaleUpperCase(); } } @editorAction export class LowerCaseAction extends AbstractCaseAction { constructor() { super({ id: 'editor.action.transformToLowercase', label: nls.localize('editor.transformToLowercase', "Transform to Lowercase"), alias: 'Transform to Lowercase', precondition: EditorContextKeys.writable }); } protected _modifyText(text: string): string { return text.toLocaleLowerCase(); } }
src/vs/editor/contrib/linesOperations/common/linesOperations.ts
1
https://github.com/microsoft/vscode/commit/5d3dfe86cd6ac769a66f5473da3ab63c2a6918bf
[ 0.09061658382415771, 0.0025238259695470333, 0.0001642530842218548, 0.00017083677812479436, 0.0127944964915514 ]
{ "id": 3, "code_window": [ "import { withEditorModel } from 'vs/editor/test/common/editorTestUtils';\n", "\n", "function assertTrimTrailingWhitespaceCommand(text: string[], expected: IIdentifiedSingleEditOperation[]): void {\n", "\treturn withEditorModel(text, (model) => {\n", "\t\tvar op = new TrimTrailingWhitespaceCommand(new Selection(1, 1, 1, 1));\n", "\t\tvar actual = getEditOperation(model, op);\n", "\t\tassert.deepEqual(actual, expected);\n", "\t});\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\tvar op = new TrimTrailingWhitespaceCommand(new Selection(1, 1, 1, 1), []);\n" ], "file_path": "src/vs/editor/test/common/commands/trimTrailingWhitespaceCommand.test.ts", "type": "replace", "edit_start_line_idx": 16 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ // Do not edit this file. It is machine generated. { "tasksAriaLabel": "ビルド タスクの名前を入力してください", "noTasksMatching": "一致するタスクがありません", "noTasksFound": "ビルド タスクが見つかりません" }
i18n/jpn/src/vs/workbench/parts/tasks/browser/buildQuickOpen.i18n.json
0
https://github.com/microsoft/vscode/commit/5d3dfe86cd6ac769a66f5473da3ab63c2a6918bf
[ 0.00017412990564480424, 0.00017273800040129572, 0.0001713460951577872, 0.00017273800040129572, 0.0000013919052435085177 ]
{ "id": 3, "code_window": [ "import { withEditorModel } from 'vs/editor/test/common/editorTestUtils';\n", "\n", "function assertTrimTrailingWhitespaceCommand(text: string[], expected: IIdentifiedSingleEditOperation[]): void {\n", "\treturn withEditorModel(text, (model) => {\n", "\t\tvar op = new TrimTrailingWhitespaceCommand(new Selection(1, 1, 1, 1));\n", "\t\tvar actual = getEditOperation(model, op);\n", "\t\tassert.deepEqual(actual, expected);\n", "\t});\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\tvar op = new TrimTrailingWhitespaceCommand(new Selection(1, 1, 1, 1), []);\n" ], "file_path": "src/vs/editor/test/common/commands/trimTrailingWhitespaceCommand.test.ts", "type": "replace", "edit_start_line_idx": 16 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ // Do not edit this file. It is machine generated. { "first.chord": "Se presionó ({0}). Esperando la siguiente tecla...", "missing.chord": "La combinación de teclas ({0}, {1}) no es ningún comando." }
i18n/esn/src/vs/platform/keybinding/common/abstractKeybindingService.i18n.json
0
https://github.com/microsoft/vscode/commit/5d3dfe86cd6ac769a66f5473da3ab63c2a6918bf
[ 0.00017432695312891155, 0.00017432695312891155, 0.00017432695312891155, 0.00017432695312891155, 0 ]
{ "id": 3, "code_window": [ "import { withEditorModel } from 'vs/editor/test/common/editorTestUtils';\n", "\n", "function assertTrimTrailingWhitespaceCommand(text: string[], expected: IIdentifiedSingleEditOperation[]): void {\n", "\treturn withEditorModel(text, (model) => {\n", "\t\tvar op = new TrimTrailingWhitespaceCommand(new Selection(1, 1, 1, 1));\n", "\t\tvar actual = getEditOperation(model, op);\n", "\t\tassert.deepEqual(actual, expected);\n", "\t});\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "\t\tvar op = new TrimTrailingWhitespaceCommand(new Selection(1, 1, 1, 1), []);\n" ], "file_path": "src/vs/editor/test/common/commands/trimTrailingWhitespaceCommand.test.ts", "type": "replace", "edit_start_line_idx": 16 }
<svg xmlns="http://www.w3.org/2000/svg" width="13" height="13" viewBox="-295.5 390.5 13 13"><path fill="#FFF" d="M-289 390.5c-3.6 0-6.5 2.9-6.5 6.5s2.9 6.5 6.5 6.5 6.5-2.9 6.5-6.5-2.9-6.5-6.5-6.5zm.9 11.1h-1.9v-6.5h1.9v6.5zm0-7.4h-1.9v-1.9h1.9v1.9z"/></svg>
src/vs/workbench/parts/tasks/electron-browser/media/status-info.svg
0
https://github.com/microsoft/vscode/commit/5d3dfe86cd6ac769a66f5473da3ab63c2a6918bf
[ 0.00017225493502337486, 0.00017225493502337486, 0.00017225493502337486, 0.00017225493502337486, 0 ]
{ "id": 0, "code_window": [ " display: 'grid',\n", " gap: theme.spacing(3),\n", " gridTemplateColumns: 'repeat(auto-fill, minmax(300px, 1fr))',\n", " gridAutoRows: '130px',\n", " padding: theme.spacing(2, 0),\n", " }),\n", "});" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " gridAutoRows: '138px',\n" ], "file_path": "public/app/core/components/AppChrome/NavLandingPage.tsx", "type": "replace", "edit_start_line_idx": 53 }
import { css } from '@emotion/css'; import React from 'react'; import { GrafanaTheme2 } from '@grafana/data'; import { Card, useStyles2 } from '@grafana/ui'; interface Props { description?: string; text: string; url: string; } export function NavLandingPageCard({ description, text, url }: Props) { const styles = useStyles2(getStyles); return ( <Card className={styles.card} href={url}> <Card.Heading>{text}</Card.Heading> <Card.Description>{description}</Card.Description> </Card> ); } const getStyles = (theme: GrafanaTheme2) => ({ card: css({ marginBottom: 0, gridTemplateRows: '1fr 0 2fr', }), });
public/app/core/components/AppChrome/NavLandingPageCard.tsx
1
https://github.com/grafana/grafana/commit/6b53f927b27a3f266d1d208980ad3fdcfcb557b1
[ 0.0016422464977949858, 0.0006629212875850499, 0.000170731742400676, 0.00017578563711140305, 0.0006924905464984477 ]
{ "id": 0, "code_window": [ " display: 'grid',\n", " gap: theme.spacing(3),\n", " gridTemplateColumns: 'repeat(auto-fill, minmax(300px, 1fr))',\n", " gridAutoRows: '130px',\n", " padding: theme.spacing(2, 0),\n", " }),\n", "});" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " gridAutoRows: '138px',\n" ], "file_path": "public/app/core/components/AppChrome/NavLandingPage.tsx", "type": "replace", "edit_start_line_idx": 53 }
import { css } from '@emotion/css'; import { Map } from 'ol'; import { Coordinate } from 'ol/coordinate'; import { transform } from 'ol/proj'; import React, { PureComponent } from 'react'; import tinycolor from 'tinycolor2'; import { GrafanaTheme2 } from '@grafana/data'; import { selectors } from '@grafana/e2e-selectors/src'; import { stylesFactory } from '@grafana/ui'; import { config } from 'app/core/config'; interface Props { map: Map; } interface State { zoom?: number; center: Coordinate; } export class DebugOverlay extends PureComponent<Props, State> { style = getStyles(config.theme2); constructor(props: Props) { super(props); this.state = { zoom: 0, center: [0, 0] }; } updateViewState = () => { const view = this.props.map.getView(); this.setState({ zoom: view.getZoom(), center: transform(view.getCenter()!, view.getProjection(), 'EPSG:4326'), }); }; componentDidMount() { this.props.map.on('moveend', this.updateViewState); this.updateViewState(); } render() { const { zoom, center } = this.state; return ( <div className={this.style.infoWrap} aria-label={selectors.components.DebugOverlay.wrapper}> <table> <tbody> <tr> <th>Zoom:</th> <td>{zoom?.toFixed(1)}</td> </tr> <tr> <th>Center:&nbsp;</th> <td> {center[0].toFixed(5)}, {center[1].toFixed(5)} </td> </tr> </tbody> </table> </div> ); } } const getStyles = stylesFactory((theme: GrafanaTheme2) => ({ infoWrap: css` color: ${theme.colors.text.primary}; background: ${tinycolor(theme.components.panel.background).setAlpha(0.7).toString()}; border-radius: 2px; padding: 8px; `, }));
public/app/plugins/panel/geomap/components/DebugOverlay.tsx
0
https://github.com/grafana/grafana/commit/6b53f927b27a3f266d1d208980ad3fdcfcb557b1
[ 0.0004685560124926269, 0.00021523151372093707, 0.00017022796964738518, 0.00017529152682982385, 0.00009649815183365718 ]
{ "id": 0, "code_window": [ " display: 'grid',\n", " gap: theme.spacing(3),\n", " gridTemplateColumns: 'repeat(auto-fill, minmax(300px, 1fr))',\n", " gridAutoRows: '130px',\n", " padding: theme.spacing(2, 0),\n", " }),\n", "});" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " gridAutoRows: '138px',\n" ], "file_path": "public/app/core/components/AppChrome/NavLandingPage.tsx", "type": "replace", "edit_start_line_idx": 53 }
import { render, screen } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import React from 'react'; import { CustomHeadersSettings, Props } from './CustomHeadersSettings'; const setup = (propOverrides?: object) => { const onChange = jest.fn(); const props: Props = { dataSourceConfig: { id: 4, uid: 'x', orgId: 1, name: 'gdev-influxdb', type: 'influxdb', typeName: 'Influxdb', typeLogoUrl: '', access: 'direct', url: 'http://localhost:8086', user: 'grafana', database: 'site', basicAuth: false, basicAuthUser: '', withCredentials: false, isDefault: false, jsonData: { timeInterval: '15s', httpMode: 'GET', keepCookies: ['cookie1', 'cookie2'], }, secureJsonData: { password: true, }, secureJsonFields: {}, readOnly: false, }, onChange, ...propOverrides, }; render(<CustomHeadersSettings {...props} />); return { onChange }; }; function assertRowCount(configuredInputCount: number, passwordInputCount: number) { const inputs = screen.queryAllByPlaceholderText('X-Custom-Header'); const passwordInputs = screen.queryAllByPlaceholderText('Header Value'); const configuredInputs = screen.queryAllByDisplayValue('configured'); expect(inputs.length).toBe(passwordInputs.length + configuredInputs.length); expect(passwordInputs).toHaveLength(passwordInputCount); expect(configuredInputs).toHaveLength(configuredInputCount); } describe('Render', () => { it('should add a new header', async () => { setup(); const b = screen.getByRole('button', { name: 'Add header' }); expect(b).toBeInTheDocument(); assertRowCount(0, 0); await userEvent.click(b); assertRowCount(0, 1); }); it('add header button should not submit the form', () => { setup(); const b = screen.getByRole('button', { name: 'Add header' }); expect(b).toBeInTheDocument(); expect(b.getAttribute('type')).toBe('button'); }); it('should remove a header', async () => { const { onChange } = setup({ dataSourceConfig: { jsonData: { httpHeaderName1: 'X-Custom-Header', }, secureJsonFields: { httpHeaderValue1: true, }, }, }); const b = screen.getByRole('button', { name: 'Remove header' }); expect(b).toBeInTheDocument(); assertRowCount(1, 0); await userEvent.click(b); assertRowCount(0, 0); expect(onChange).toHaveBeenCalledTimes(1); expect(onChange.mock.calls[0][0].jsonData).toStrictEqual({}); }); it('when removing a just-created header, it should clean up secureJsonData', async () => { const { onChange } = setup({ dataSourceConfig: { jsonData: { httpHeaderName1: 'name1', }, secureJsonData: { httpHeaderValue1: 'value1', }, }, }); // we remove the row const removeButton = screen.getByRole('button', { name: 'Remove header' }); expect(removeButton).toBeInTheDocument(); await userEvent.click(removeButton); assertRowCount(0, 0); expect(onChange).toHaveBeenCalled(); // and we verify the onChange-data const lastCall = onChange.mock.calls[onChange.mock.calls.length - 1]; expect(lastCall[0].jsonData).not.toHaveProperty('httpHeaderName1'); expect(lastCall[0].secureJsonData).not.toHaveProperty('httpHeaderValue1'); }); it('should reset a header', async () => { setup({ dataSourceConfig: { jsonData: { httpHeaderName1: 'X-Custom-Header', }, secureJsonFields: { httpHeaderValue1: true, }, }, }); const b = screen.getByRole('button', { name: 'Reset' }); expect(b).toBeInTheDocument(); assertRowCount(1, 0); await userEvent.click(b); assertRowCount(0, 1); }); });
packages/grafana-ui/src/components/DataSourceSettings/CustomHeadersSettings.test.tsx
0
https://github.com/grafana/grafana/commit/6b53f927b27a3f266d1d208980ad3fdcfcb557b1
[ 0.0001785763306543231, 0.00017203330935444683, 0.000165100849699229, 0.0001734486868372187, 0.000004462366177904187 ]
{ "id": 0, "code_window": [ " display: 'grid',\n", " gap: theme.spacing(3),\n", " gridTemplateColumns: 'repeat(auto-fill, minmax(300px, 1fr))',\n", " gridAutoRows: '130px',\n", " padding: theme.spacing(2, 0),\n", " }),\n", "});" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " gridAutoRows: '138px',\n" ], "file_path": "public/app/core/components/AppChrome/NavLandingPage.tsx", "type": "replace", "edit_start_line_idx": 53 }
import { fireEvent, render, screen, waitFor } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import React from 'react'; import { Provider } from 'react-redux'; import { locationService } from '@grafana/runtime'; import { backendSrv } from 'app/core/services/backend_srv'; import { configureStore } from '../../store/configureStore'; import { PlaylistEditPage } from './PlaylistEditPage'; import { Playlist } from './types'; jest.mock('@grafana/runtime', () => ({ ...jest.requireActual('@grafana/runtime'), getBackendSrv: () => backendSrv, })); jest.mock('app/core/components/TagFilter/TagFilter', () => ({ TagFilter: () => { return <>mocked-tag-filter</>; }, })); async function getTestContext({ name, interval, items, uid }: Partial<Playlist> = {}) { jest.clearAllMocks(); const store = configureStore(); const playlist = { name, items, interval, uid } as unknown as Playlist; const queryParams = {}; const route: any = {}; const match: any = { params: { uid: 'foo' } }; const location: any = {}; const history: any = {}; const getMock = jest.spyOn(backendSrv, 'get'); const putMock = jest.spyOn(backendSrv, 'put'); getMock.mockResolvedValue({ name: 'Test Playlist', interval: '5s', items: [{ title: 'First item', type: 'dashboard_by_uid', order: 1, value: '1' }], uid: 'foo', }); const { rerender } = render( <Provider store={store}> <PlaylistEditPage queryParams={queryParams} route={route} match={match} location={location} history={history} /> </Provider> ); await waitFor(() => expect(getMock).toHaveBeenCalledTimes(1)); return { playlist, rerender, putMock }; } describe('PlaylistEditPage', () => { describe('when mounted', () => { it('then it should load playlist and header should be correct', async () => { await getTestContext(); expect(screen.getByRole('heading', { name: /edit playlist/i })).toBeInTheDocument(); expect(screen.getByRole('textbox', { name: /playlist name/i })).toHaveValue('Test Playlist'); expect(screen.getByRole('textbox', { name: /playlist interval/i })).toHaveValue('5s'); expect(screen.getAllByRole('row')).toHaveLength(1); }); }); describe('when submitted', () => { it('then correct api should be called', async () => { const { putMock } = await getTestContext(); expect(locationService.getLocation().pathname).toEqual('/'); await userEvent.clear(screen.getByRole('textbox', { name: /playlist name/i })); await userEvent.type(screen.getByRole('textbox', { name: /playlist name/i }), 'A Name'); await userEvent.clear(screen.getByRole('textbox', { name: /playlist interval/i })); await userEvent.type(screen.getByRole('textbox', { name: /playlist interval/i }), '10s'); fireEvent.submit(screen.getByRole('button', { name: /save/i })); await waitFor(() => expect(putMock).toHaveBeenCalledTimes(1)); expect(putMock).toHaveBeenCalledWith('/api/playlists/foo', { name: 'A Name', interval: '10s', items: [{ title: 'First item', type: 'dashboard_by_uid', order: 1, value: '1' }], }); expect(locationService.getLocation().pathname).toEqual('/playlists'); }); }); });
public/app/features/playlist/PlaylistEditPage.test.tsx
0
https://github.com/grafana/grafana/commit/6b53f927b27a3f266d1d208980ad3fdcfcb557b1
[ 0.0001770018134266138, 0.00017433593166060746, 0.00017290739924646914, 0.00017405289690941572, 0.000001258742599929974 ]
{ "id": 1, "code_window": [ " return (\n", " <Card className={styles.card} href={url}>\n", " <Card.Heading>{text}</Card.Heading>\n", " <Card.Description>{description}</Card.Description>\n", " </Card>\n", " );\n", "}\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " <Card.Description className={styles.description}>{description}</Card.Description>\n" ], "file_path": "public/app/core/components/AppChrome/NavLandingPageCard.tsx", "type": "replace", "edit_start_line_idx": 17 }
import { css } from '@emotion/css'; import React from 'react'; import { GrafanaTheme2 } from '@grafana/data'; import { useStyles2 } from '@grafana/ui'; import { Page } from 'app/core/components/Page/Page'; import { useNavModel } from 'app/core/hooks/useNavModel'; import { getNavTitle, getNavSubTitle } from '../NavBar/navBarItem-translations'; import { NavLandingPageCard } from './NavLandingPageCard'; interface Props { navId: string; } export function NavLandingPage({ navId }: Props) { const { node } = useNavModel(navId); const styles = useStyles2(getStyles); const children = node.children?.filter((child) => !child.hideFromTabs); return ( <Page navId={node.id}> <Page.Contents> <div className={styles.content}> {children && children.length > 0 && ( <section className={styles.grid}> {children?.map((child) => ( <NavLandingPageCard key={child.id} description={getNavSubTitle(child.id) ?? child.subTitle} text={getNavTitle(child.id) ?? child.text} url={child.url ?? ''} /> ))} </section> )} </div> </Page.Contents> </Page> ); } const getStyles = (theme: GrafanaTheme2) => ({ content: css({ display: 'flex', flexDirection: 'column', gap: theme.spacing(2), }), grid: css({ display: 'grid', gap: theme.spacing(3), gridTemplateColumns: 'repeat(auto-fill, minmax(300px, 1fr))', gridAutoRows: '130px', padding: theme.spacing(2, 0), }), });
public/app/core/components/AppChrome/NavLandingPage.tsx
1
https://github.com/grafana/grafana/commit/6b53f927b27a3f266d1d208980ad3fdcfcb557b1
[ 0.0005723558715544641, 0.0002478893438819796, 0.00015914268442429602, 0.0001782120525604114, 0.00014678825391456485 ]
{ "id": 1, "code_window": [ " return (\n", " <Card className={styles.card} href={url}>\n", " <Card.Heading>{text}</Card.Heading>\n", " <Card.Description>{description}</Card.Description>\n", " </Card>\n", " );\n", "}\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " <Card.Description className={styles.description}>{description}</Card.Description>\n" ], "file_path": "public/app/core/components/AppChrome/NavLandingPageCard.tsx", "type": "replace", "edit_start_line_idx": 17 }
--- aliases: - ../unified-alerting/alerting-rules/edit-cortex-loki-namespace-group/ - ../unified-alerting/alerting-rules/edit-mimir-loki-namespace-group/ description: Edit Grafana Mimir or Loki rule groups and namespaces keywords: - grafana - alerting - guide - group - namespace - grafana mimir - loki title: Grafana Mimir or Loki rule groups and namespaces weight: 405 --- # Grafana Mimir or Loki rule groups and namespaces A namespace contains one or more groups. The rules within a group are run sequentially at a regular interval. The default interval is one (1) minute. You can rename Grafana Mimir or Loki rule namespaces and groups, and edit group evaluation intervals. ![Group list](/static/img/docs/alerting/unified/rule-list-edit-mimir-loki-icon-8-2.png 'Rule group list screenshot') {{< figure src="/static/img/docs/alerting/unified/rule-list-edit-mimir-loki-icon-8-2.png" max-width="550px" caption="Alert details" >}} ## Rename a namespace To rename a namespace: 1. In the Grafana menu, click the **Alerting** (bell) icon to open the Alerting page listing existing alerts. 1. Find a Grafana Mimir or Loki managed rule with the group that belongs to the namespace you want to edit. 1. Click the **Edit** (pen) icon. 1. Enter a new name in the **Namespace** field, then click **Save changes**. A new namespace is created and all groups are copied into this namespace from the old one. The old namespace is deleted. ## Rename rule group or change the rule group evaluation interval The rules within a group are run sequentially at a regular interval, the default interval is one (1) minute. You can modify this interval using the following instructions. 1. In the Grafana menu, click the **Alerting** (bell) icon to open the Alerting page listing existing alerts. 1. Find a Grafana Mimir or Loki managed rule with the group you want to edit. 1. Click **Edit** (pen) icon. 1. Modify the **Rule group** and **Rule group evaluation interval** information as necessary. 1. Click **Save changes**. When you rename the group, a new group with all the rules from the old group is created. The old group is deleted. ![Group edit modal](/static/img/docs/alerting/unified/rule-list-mimir-loki-edit-ns-group-8-2.png 'Rule group edit modal screenshot')
docs/sources/alerting/alerting-rules/edit-mimir-loki-namespace-group.md
0
https://github.com/grafana/grafana/commit/6b53f927b27a3f266d1d208980ad3fdcfcb557b1
[ 0.00017314513388555497, 0.0001681027642916888, 0.00016343432071153075, 0.00016722868895158172, 0.0000031976155696611386 ]
{ "id": 1, "code_window": [ " return (\n", " <Card className={styles.card} href={url}>\n", " <Card.Heading>{text}</Card.Heading>\n", " <Card.Description>{description}</Card.Description>\n", " </Card>\n", " );\n", "}\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " <Card.Description className={styles.description}>{description}</Card.Description>\n" ], "file_path": "public/app/core/components/AppChrome/NavLandingPageCard.tsx", "type": "replace", "edit_start_line_idx": 17 }
package definitions import ( "time" "github.com/grafana/grafana/pkg/services/ngalert/models" "github.com/prometheus/common/model" ) // swagger:route GET /api/v1/provisioning/alert-rules provisioning stable RouteGetAlertRules // // Get all the alert rules. // // Responses: // 200: ProvisionedAlertRules // swagger:route GET /api/v1/provisioning/alert-rules/{UID} provisioning stable RouteGetAlertRule // // Get a specific alert rule by UID. // // Responses: // 200: ProvisionedAlertRule // 404: description: Not found. // swagger:route POST /api/v1/provisioning/alert-rules provisioning stable RoutePostAlertRule // // Create a new alert rule. // // Consumes: // - application/json // // Responses: // 201: ProvisionedAlertRule // 400: ValidationError // swagger:route PUT /api/v1/provisioning/alert-rules/{UID} provisioning stable RoutePutAlertRule // // Update an existing alert rule. // // Consumes: // - application/json // // Responses: // 200: ProvisionedAlertRule // 400: ValidationError // swagger:route DELETE /api/v1/provisioning/alert-rules/{UID} provisioning stable RouteDeleteAlertRule // // Delete a specific alert rule by UID. // // Responses: // 204: description: The alert rule was deleted successfully. // swagger:parameters RouteGetAlertRule RoutePutAlertRule RouteDeleteAlertRule type AlertRuleUIDReference struct { // Alert rule UID // in:path UID string } // swagger:parameters RoutePostAlertRule RoutePutAlertRule type AlertRulePayload struct { // in:body Body ProvisionedAlertRule } // swagger:parameters RoutePostAlertRule RoutePutAlertRule type AlertRuleHeaders struct { // in:header XDisableProvenance string `json:"X-Disable-Provenance"` } // swagger:model type ProvisionedAlertRules []ProvisionedAlertRule type ProvisionedAlertRule struct { ID int64 `json:"id"` UID string `json:"uid"` // required: true OrgID int64 `json:"orgID"` // required: true // example: project_x FolderUID string `json:"folderUID"` // required: true // minLength: 1 // maxLength: 190 // example: eval_group_1 RuleGroup string `json:"ruleGroup"` // required: true // minLength: 1 // maxLength: 190 // example: Always firing Title string `json:"title"` // required: true // example: A Condition string `json:"condition"` // required: true // example: [{"refId":"A","queryType":"","relativeTimeRange":{"from":0,"to":0},"datasourceUid":"-100","model":{"conditions":[{"evaluator":{"params":[0,0],"type":"gt"},"operator":{"type":"and"},"query":{"params":[]},"reducer":{"params":[],"type":"avg"},"type":"query"}],"datasource":{"type":"__expr__","uid":"__expr__"},"expression":"1 == 1","hide":false,"intervalMs":1000,"maxDataPoints":43200,"refId":"A","type":"math"}}] Data []models.AlertQuery `json:"data"` // readonly: true Updated time.Time `json:"updated,omitempty"` // required: true NoDataState models.NoDataState `json:"noDataState"` // required: true ExecErrState models.ExecutionErrorState `json:"execErrState"` // required: true For model.Duration `json:"for"` // example: {"runbook_url": "https://supercoolrunbook.com/page/13"} Annotations map[string]string `json:"annotations,omitempty"` // example: {"team": "sre-team-1"} Labels map[string]string `json:"labels,omitempty"` // readonly: true Provenance models.Provenance `json:"provenance,omitempty"` } func (a *ProvisionedAlertRule) UpstreamModel() (models.AlertRule, error) { return models.AlertRule{ ID: a.ID, UID: a.UID, OrgID: a.OrgID, NamespaceUID: a.FolderUID, RuleGroup: a.RuleGroup, Title: a.Title, Condition: a.Condition, Data: a.Data, Updated: a.Updated, NoDataState: a.NoDataState, ExecErrState: a.ExecErrState, For: time.Duration(a.For), Annotations: a.Annotations, Labels: a.Labels, }, nil } func NewAlertRule(rule models.AlertRule, provenance models.Provenance) ProvisionedAlertRule { return ProvisionedAlertRule{ ID: rule.ID, UID: rule.UID, OrgID: rule.OrgID, FolderUID: rule.NamespaceUID, RuleGroup: rule.RuleGroup, Title: rule.Title, For: model.Duration(rule.For), Condition: rule.Condition, Data: rule.Data, Updated: rule.Updated, NoDataState: rule.NoDataState, ExecErrState: rule.ExecErrState, Annotations: rule.Annotations, Labels: rule.Labels, Provenance: provenance, } } func NewAlertRules(rules []*models.AlertRule) ProvisionedAlertRules { result := make([]ProvisionedAlertRule, 0, len(rules)) for _, r := range rules { result = append(result, NewAlertRule(*r, models.ProvenanceNone)) } return result } // swagger:route GET /api/v1/provisioning/folder/{FolderUID}/rule-groups/{Group} provisioning stable RouteGetAlertRuleGroup // // Get a rule group. // // Responses: // 200: AlertRuleGroup // 404: description: Not found. // swagger:route PUT /api/v1/provisioning/folder/{FolderUID}/rule-groups/{Group} provisioning stable RoutePutAlertRuleGroup // // Update the interval of a rule group. // // Consumes: // - application/json // // Responses: // 200: AlertRuleGroup // 400: ValidationError // swagger:parameters RouteGetAlertRuleGroup RoutePutAlertRuleGroup type FolderUIDPathParam struct { // in:path FolderUID string `json:"FolderUID"` } // swagger:parameters RouteGetAlertRuleGroup RoutePutAlertRuleGroup type RuleGroupPathParam struct { // in:path Group string `json:"Group"` } // swagger:parameters RoutePutAlertRuleGroup type AlertRuleGroupPayload struct { // in:body Body AlertRuleGroup } // swagger:model type AlertRuleGroupMetadata struct { Interval int64 `json:"interval"` } // swagger:model type AlertRuleGroup struct { Title string `json:"title"` FolderUID string `json:"folderUid"` Interval int64 `json:"interval"` Rules []ProvisionedAlertRule `json:"rules"` } func (a *AlertRuleGroup) ToModel() (models.AlertRuleGroup, error) { ruleGroup := models.AlertRuleGroup{ Title: a.Title, FolderUID: a.FolderUID, Interval: a.Interval, } for i := range a.Rules { converted, err := a.Rules[i].UpstreamModel() if err != nil { return models.AlertRuleGroup{}, err } ruleGroup.Rules = append(ruleGroup.Rules, converted) } return ruleGroup, nil } func NewAlertRuleGroupFromModel(d models.AlertRuleGroup) AlertRuleGroup { rules := make([]ProvisionedAlertRule, 0, len(d.Rules)) for i := range d.Rules { rules = append(rules, NewAlertRule(d.Rules[i], d.Provenance)) } return AlertRuleGroup{ Title: d.Title, FolderUID: d.FolderUID, Interval: d.Interval, Rules: rules, } }
pkg/services/ngalert/api/tooling/definitions/provisioning_alert_rules.go
0
https://github.com/grafana/grafana/commit/6b53f927b27a3f266d1d208980ad3fdcfcb557b1
[ 0.0001805948413675651, 0.00017292689881287515, 0.0001671736827120185, 0.00017320425831712782, 0.000003865051894536009 ]
{ "id": 1, "code_window": [ " return (\n", " <Card className={styles.card} href={url}>\n", " <Card.Heading>{text}</Card.Heading>\n", " <Card.Description>{description}</Card.Description>\n", " </Card>\n", " );\n", "}\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " <Card.Description className={styles.description}>{description}</Card.Description>\n" ], "file_path": "public/app/core/components/AppChrome/NavLandingPageCard.tsx", "type": "replace", "edit_start_line_idx": 17 }
--- aliases: - ../features/datasources/parca/ description: Continuous profiling for analysis of CPU and memory usage, down to the line number and throughout time. Saving infrastructure cost, improving performance, and increasing reliability. keywords: - parca - guide - profiling title: Parca weight: 1110 --- # Parca data source > **Note:** This feature is behind the `flameGraph` feature toggle. > You can enable feature toggles through configuration file or environment variables. See configuration [docs]({{< relref "../setup-grafana/configure-grafana/#feature_toggles" >}}) for details. > Grafana Cloud users can access this feature by [opening a support ticket in the Cloud Portal](https://grafana.com/profile/org#support). Grafana ships with built-in support for Parca, a continuous profiling OSS database for analysis of CPU and memory usage, down to the line number and throughout time. Add it as a data source, and you are ready to query your profiles in [Explore]({{< relref "../explore" >}}). ## Configure the Parca data source To access Parca settings, click the **Configuration** (gear) icon, then click **Data Sources** > **Parca**. | Name | Description | | ------------ | ------------------------------------------------------------------ | | `Name` | A name to specify the data source in panels, queries, and Explore. | | `Default` | The default data source will be pre-selected for new panels. | | `URL` | The URL of the Tempo instance, e.g., `http://localhost:4100` | | `Basic Auth` | Enable basic authentication to the Tempo data source. | | `User` | User name for basic authentication. | | `Password` | Password for basic authentication. | ## Querying ### Query Editor ![Query editor](/static/img/docs/parca/query-editor.png 'Query editor') Query editor gives you access to a profile type selector, a label selector, and collapsible options. ![Profile selector](/static/img/docs/parca/select-profile.png 'Profile selector') Select a profile type from the drop-down menu. While the label selector can be left empty to query all profiles without filtering by labels, the profile type must be selected for the query to be valid. Grafana does not show any data if the profile type isn’t selected when a query is run. ![Labels selector](/static/img/docs/parca/labels-selector.png 'Labels selector') Use the labels selector input to filter by labels. Parca uses similar syntax to Prometheus to filter labels. Refer to [Parca documentation](https://www.parca.dev/docs) for available operators and syntax. ![Options section](/static/img/docs/parca/options-section.png 'Options section') Select a query type to return the profile data which can be shown in the [Flame Graph]({{< relref "../panels-visualizations/visualizations/flame-graph" >}}), metric data visualized in a graph, or both. You can only select both options in a dashboard, because panels allow only one visualization. ### Profiles query results Profiles can be visualized in a flame graph. See the [Flame Graph documentation]({{< relref "../panels-visualizations/visualizations/flame-graph" >}}) to learn about the visualization and its features. ![Flame graph](/static/img/docs/parca/flame-graph.png 'Flame graph') Parca returns profiles aggregated over a selected time range, and the absolute values in the flame graph grow as the time range gets bigger while keeping the relative values meaningful. You can zoom in on the time range to get a higher granularity profile up to the point of a single Parca scrape interval. ### Metrics query results Metrics results represent the aggregated value, over time, of the selected profile type. Parca returns ungrouped data with a series for each label combination. ![Metrics graph](/static/img/docs/parca/metric-graph.png 'Metrics graph') This allows you to quickly see any spikes in the value of the scraped profiles and zoom in to a particular time range. ## Provision the Parca data source You can modify the Grafana configuration files to provision the Parca data source. To learn more, and to view the available provisioning settings, see [provisioning documentation]({{< relref "../administration/provisioning/#datasources" >}}). Here is an example config: ```yaml apiVersion: 1 datasources: - name: Parca type: parca url: http://localhost:3100 ```
docs/sources/datasources/parca.md
0
https://github.com/grafana/grafana/commit/6b53f927b27a3f266d1d208980ad3fdcfcb557b1
[ 0.00017987597675528377, 0.00016908116231206805, 0.00016405072528868914, 0.0001692684891168028, 0.000004339890438131988 ]
{ "id": 2, "code_window": [ " card: css({\n", " marginBottom: 0,\n", " gridTemplateRows: '1fr 0 2fr',\n", " }),\n", "});" ], "labels": [ "keep", "keep", "keep", "add", "keep" ], "after_edit": [ " // Limit descriptions to 3 lines max before ellipsing\n", " // Some plugin descriptions can be very long\n", " description: css({\n", " WebkitLineClamp: 3,\n", " WebkitBoxOrient: 'vertical',\n", " display: '-webkit-box',\n", " overflow: 'hidden',\n", " }),\n" ], "file_path": "public/app/core/components/AppChrome/NavLandingPageCard.tsx", "type": "add", "edit_start_line_idx": 27 }
import { css } from '@emotion/css'; import React from 'react'; import { GrafanaTheme2 } from '@grafana/data'; import { Card, useStyles2 } from '@grafana/ui'; interface Props { description?: string; text: string; url: string; } export function NavLandingPageCard({ description, text, url }: Props) { const styles = useStyles2(getStyles); return ( <Card className={styles.card} href={url}> <Card.Heading>{text}</Card.Heading> <Card.Description>{description}</Card.Description> </Card> ); } const getStyles = (theme: GrafanaTheme2) => ({ card: css({ marginBottom: 0, gridTemplateRows: '1fr 0 2fr', }), });
public/app/core/components/AppChrome/NavLandingPageCard.tsx
1
https://github.com/grafana/grafana/commit/6b53f927b27a3f266d1d208980ad3fdcfcb557b1
[ 0.9966837763786316, 0.33275213837623596, 0.00030460863490588963, 0.0012680153595283628, 0.469470739364624 ]
{ "id": 2, "code_window": [ " card: css({\n", " marginBottom: 0,\n", " gridTemplateRows: '1fr 0 2fr',\n", " }),\n", "});" ], "labels": [ "keep", "keep", "keep", "add", "keep" ], "after_edit": [ " // Limit descriptions to 3 lines max before ellipsing\n", " // Some plugin descriptions can be very long\n", " description: css({\n", " WebkitLineClamp: 3,\n", " WebkitBoxOrient: 'vertical',\n", " display: '-webkit-box',\n", " overflow: 'hidden',\n", " }),\n" ], "file_path": "public/app/core/components/AppChrome/NavLandingPageCard.tsx", "type": "add", "edit_start_line_idx": 27 }
@grafana = grafana ### # create AM configuration POST http://admin:admin@localhost:3000/api/alertmanager/{{grafana}}/config/api/v1/alerts content-type: application/json < ./post-user-config.json ### # get latest AM configuration GET http://admin:admin@localhost:3000/api/alertmanager/{{grafana}}/config/api/v1/alerts content-type: application/json ### # delete AM configuration DELETE http://admin:admin@localhost:3000/api/alertmanager/{{grafana}}/config/api/v1/alerts ### # create AM alerts POST http://admin:admin@localhost:3000/api/alertmanager/{{grafana}}/api/v2/alerts content-type: application/json ### # get AM alerts GET http://admin:admin@localhost:3000/api/alertmanager/{{grafana}}/api/v2/alerts ### # get AM status GET http://admin:admin@localhost:3000/api/alertmanager/{{grafana}}/api/v2/status ### # get silences - no silences GET http://admin:admin@localhost:3000/api/alertmanager/{{grafana}}/api/v2/silences?Filter=foo="bar"&Filter=bar="foo" ### # create silence POST http://admin:admin@localhost:3000/api/alertmanager/{{grafana}}/api/v2/silences content-type: application/json { "comment": "string", "createdBy": "string", "endsAt": "2023-03-31T14:17:04.419Z", "matchers": [ { "isRegex": true, "name": "string", "value": "string" } ], "startsAt": "2021-03-31T13:17:04.419Z" } ### # update silence - does not exist POST http://admin:admin@localhost:3000/api/alertmanager/{{grafana}}/api/v2/silences content-type: application/json { "id": "something", "comment": "string", "createdBy": "string", "endsAt": "2023-03-31T14:17:04.419Z", "matchers": [ { "isRegex": true, "name": "string", "value": "string" } ], "startsAt": "2021-03-31T13:17:04.419Z" } ### # create silence - bad paylaad - start time must be before end time POST http://admin:admin@localhost:3000/api/alertmanager/{{grafana}}/api/v2/silences content-type: application/json { "comment": "string", "createdBy": "string", "endsAt": "2019-03-31T14:17:04.419Z", "matchers": [ { "isRegex": true, "name": "string", "value": "string" } ], "startsAt": "2021-03-31T13:17:04.419Z" } ### # get silences # @name getSilences GET http://admin:admin@localhost:3000/api/alertmanager/{{grafana}}/api/v2/silences ### @silenceID = {{getSilences.response.body.$.[0].id}} ### # get silence GET http://admin:admin@localhost:3000/api/alertmanager/{{grafana}}/api/v2/silence/{{silenceID}} ### # get silence - unknown GET http://admin:admin@localhost:3000/api/alertmanager/{{grafana}}/api/v2/silence/unknown ### # delete silence DELETE http://admin:admin@localhost:3000/api/alertmanager/{{grafana}}/api/v2/silence/{{silenceID}} ### # delete silence - unknown DELETE http://admin:admin@localhost:3000/api/alertmanager/{{grafana}}/api/v2/silence/unknown
pkg/services/ngalert/api/test-data/am-grafana-recipient.http
0
https://github.com/grafana/grafana/commit/6b53f927b27a3f266d1d208980ad3fdcfcb557b1
[ 0.00017523621500004083, 0.00017271477554459125, 0.00016991938173305243, 0.0001729298965074122, 0.0000016551823591726134 ]
{ "id": 2, "code_window": [ " card: css({\n", " marginBottom: 0,\n", " gridTemplateRows: '1fr 0 2fr',\n", " }),\n", "});" ], "labels": [ "keep", "keep", "keep", "add", "keep" ], "after_edit": [ " // Limit descriptions to 3 lines max before ellipsing\n", " // Some plugin descriptions can be very long\n", " description: css({\n", " WebkitLineClamp: 3,\n", " WebkitBoxOrient: 'vertical',\n", " display: '-webkit-box',\n", " overflow: 'hidden',\n", " }),\n" ], "file_path": "public/app/core/components/AppChrome/NavLandingPageCard.tsx", "type": "add", "edit_start_line_idx": 27 }
import { SelectableValue } from '@grafana/data'; import { CloudWatchMetricsQuery, MetricQueryType, MetricEditorMode } from '../types'; import { CloudWatchDatasource } from './../datasource'; export const toOption = (value: string) => ({ label: value, value }); export const appendTemplateVariables = (datasource: CloudWatchDatasource, values: SelectableValue[]) => [ ...values, { label: 'Template Variables', options: datasource.getVariables().map(toOption) }, ]; export const filterMetricsQuery = (query: CloudWatchMetricsQuery): boolean => { const { region, metricQueryType, metricEditorMode, expression, metricName, namespace, sqlExpression, statistic } = query; if (!region) { return false; } if (metricQueryType === MetricQueryType.Search && metricEditorMode === MetricEditorMode.Builder) { return !!namespace && !!metricName && !!statistic; } else if (metricQueryType === MetricQueryType.Search && metricEditorMode === MetricEditorMode.Code) { return !!expression; } else if (metricQueryType === MetricQueryType.Query) { // still TBD how to validate the visual query builder for SQL return !!sqlExpression; } return false; };
public/app/plugins/datasource/cloudwatch/utils/utils.ts
0
https://github.com/grafana/grafana/commit/6b53f927b27a3f266d1d208980ad3fdcfcb557b1
[ 0.00017978990217670798, 0.000174020417034626, 0.0001685914903646335, 0.00017385015962645411, 0.0000041430912460782565 ]
{ "id": 2, "code_window": [ " card: css({\n", " marginBottom: 0,\n", " gridTemplateRows: '1fr 0 2fr',\n", " }),\n", "});" ], "labels": [ "keep", "keep", "keep", "add", "keep" ], "after_edit": [ " // Limit descriptions to 3 lines max before ellipsing\n", " // Some plugin descriptions can be very long\n", " description: css({\n", " WebkitLineClamp: 3,\n", " WebkitBoxOrient: 'vertical',\n", " display: '-webkit-box',\n", " overflow: 'hidden',\n", " }),\n" ], "file_path": "public/app/core/components/AppChrome/NavLandingPageCard.tsx", "type": "add", "edit_start_line_idx": 27 }
import { FileDropzone, DropzoneFile, FileDropzoneProps, FileDropzoneDefaultChildren } from './FileDropzone'; import { FileListItem, FileListItemProps } from './FileListItem'; export { FileDropzone, type FileDropzoneProps, type DropzoneFile, FileListItem, type FileListItemProps, FileDropzoneDefaultChildren, };
packages/grafana-ui/src/components/FileDropzone/index.ts
0
https://github.com/grafana/grafana/commit/6b53f927b27a3f266d1d208980ad3fdcfcb557b1
[ 0.00017986910825129598, 0.00017728580860421062, 0.00017470250895712525, 0.00017728580860421062, 0.0000025832996470853686 ]
{ "id": 0, "code_window": [ " });\n", "\n", " await waitForNextUpdate();\n", "\n", " expect(spy).toBeCalledTimes(1);\n", " expect(spy).toBeCalledWith('/', { params: { q: 'something', limit: 10, page: 1 } });\n", " });\n", "\n", " test('does fetch search results with a different limit', async () => {\n", " const { result, waitForNextUpdate } = await setup(undefined, {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " expect(spy).toBeCalledWith('/', { params: { _q: 'something', limit: 10, page: 1 } });\n" ], "file_path": "packages/core/admin/admin/src/content-manager/hooks/useRelation/tests/useRelation.test.js", "type": "replace", "edit_start_line_idx": 226 }
import React from 'react'; import { QueryClientProvider, QueryClient } from 'react-query'; import { renderHook, act } from '@testing-library/react-hooks'; import { axiosInstance } from '../../../../core/utils'; import { useRelation } from '../useRelation'; jest.mock('../../../../core/utils', () => ({ ...jest.requireActual('../../../../core/utils'), axiosInstance: { get: jest .fn() .mockResolvedValue({ data: { values: [], pagination: { page: 1, pageCount: 10 } } }), }, })); const client = new QueryClient({ defaultOptions: { queries: { retry: false, }, }, }); // eslint-disable-next-line react/prop-types const ComponentFixture = ({ children }) => ( <QueryClientProvider client={client}>{children}</QueryClientProvider> ); function setup(name = 'test', args) { return new Promise((resolve) => { act(() => { resolve( renderHook( () => useRelation(name, { relation: { endpoint: '/', pageParams: { limit: 10, ...(args?.relation?.pageParams ?? {}), }, ...(args?.relation ?? {}), }, search: { endpoint: '/', pageParams: { limit: 10, ...(args?.search?.pageParams ?? {}), }, ...(args?.search ?? {}), }, }), { wrapper: ComponentFixture } ) ); }); }); } describe('useRelation', () => { afterEach(() => { jest.clearAllMocks(); }); test('fetch relations', async () => { const { result, waitForNextUpdate } = await setup(undefined); await waitForNextUpdate(); expect(result.current.relations.isSuccess).toBe(true); expect(axiosInstance.get).toBeCalledTimes(1); expect(axiosInstance.get).toBeCalledWith('/', { params: { limit: 10, page: 1, }, }); }); test('calls onLoad callback', async () => { const spy = jest.fn(); const FIXTURE_DATA = { values: [1, 2], pagination: { page: 1, pageCount: 3, }, }; axiosInstance.get = jest.fn().mockResolvedValue({ data: FIXTURE_DATA, }); const { waitForNextUpdate } = await setup(undefined, { relation: { onLoad: spy, }, }); await waitForNextUpdate(); expect(spy).toBeCalledTimes(1); expect(spy).toBeCalledWith(FIXTURE_DATA); }); test('fetch relations with different limit', async () => { const { waitForNextUpdate } = await setup(undefined, { relation: { pageParams: { limit: 5 } }, }); await waitForNextUpdate(); expect(axiosInstance.get).toBeCalledWith(expect.any(String), { params: { limit: 5, page: expect.any(Number), }, }); }); test('doesn not fetch relations if a relation endpoint was not passed', async () => { await setup(undefined, { relation: { endpoint: undefined } }); expect(axiosInstance.get).not.toBeCalled(); }); test('fetch relations', async () => { const { result, waitForNextUpdate } = await setup(); await waitForNextUpdate(); expect(result.current.relations.isSuccess).toBe(true); expect(axiosInstance.get).toBeCalledTimes(1); expect(axiosInstance.get).toBeCalledWith('/', { params: { limit: 10, page: 1, }, }); }); test('fetch relations next page, if there is one', async () => { axiosInstance.get = jest.fn().mockResolvedValue({ data: { values: [], pagination: { page: 1, pageCount: 3, }, }, }); const { result, waitForNextUpdate } = await setup(undefined); await waitForNextUpdate(); act(() => { result.current.relations.fetchNextPage(); }); await waitForNextUpdate(); expect(axiosInstance.get).toBeCalledTimes(2); expect(axiosInstance.get).toHaveBeenNthCalledWith(1, expect.any(String), { params: { limit: expect.any(Number), page: 1, }, }); expect(axiosInstance.get).toHaveBeenNthCalledWith(2, expect.any(String), { params: { limit: expect.any(Number), page: 2, }, }); }); test("does not fetch relations next page, if there isn't one", async () => { axiosInstance.get = jest.fn().mockResolvedValue({ data: { values: [], pagination: { page: 1, pageCount: 1, }, }, }); const { result, waitForNextUpdate } = await setup(undefined); await waitForNextUpdate(); act(() => { result.current.relations.fetchNextPage(); }); await waitForNextUpdate(); expect(axiosInstance.get).toBeCalledTimes(1); }); test('does not fetch search by default', async () => { const { result, waitForNextUpdate } = await setup(); await waitForNextUpdate(); expect(result.current.search.isLoading).toBe(false); }); test('does fetch search results once a term was provided', async () => { const { result, waitForNextUpdate } = await setup(); await waitForNextUpdate(); const spy = jest .fn() .mockResolvedValue({ data: { values: [], pagination: { page: 1, pageCount: 2 } } }); axiosInstance.get = spy; act(() => { result.current.searchFor('something'); }); await waitForNextUpdate(); expect(spy).toBeCalledTimes(1); expect(spy).toBeCalledWith('/', { params: { q: 'something', limit: 10, page: 1 } }); }); test('does fetch search results with a different limit', async () => { const { result, waitForNextUpdate } = await setup(undefined, { search: { pageParams: { limit: 5 } }, }); await waitForNextUpdate(); const spy = jest .fn() .mockResolvedValue({ data: { values: [], pagination: { page: 1, pageCount: 2 } } }); axiosInstance.get = spy; act(() => { result.current.searchFor('something'); }); await waitForNextUpdate(); expect(spy).toBeCalledTimes(1); expect(spy).toBeCalledWith(expect.any(String), { params: { q: 'something', limit: 5, page: expect.any(Number), }, }); }); test('fetch search next page, if there is one', async () => { const { result, waitForNextUpdate } = await setup(undefined); const spy = jest .fn() .mockResolvedValue({ data: { values: [], pagination: { page: 1, pageCount: 2 } } }); axiosInstance.get = spy; act(() => { result.current.searchFor('something'); }); await waitForNextUpdate(); act(() => { result.current.search.fetchNextPage(); }); await waitForNextUpdate(); expect(spy).toBeCalledTimes(2); expect(spy).toHaveBeenNthCalledWith(1, expect.any(String), { params: { q: 'something', limit: expect.any(Number), page: 1, }, }); expect(spy).toHaveBeenNthCalledWith(2, expect.any(String), { params: { q: 'something', limit: expect.any(Number), page: 2, }, }); }); test("doesn not fetch search next page, if there isn't one", async () => { const { result, waitForNextUpdate } = await setup(undefined); const spy = jest .fn() .mockResolvedValue({ data: { values: [], pagination: { page: 1, pageCount: 1 } } }); axiosInstance.get = spy; act(() => { result.current.searchFor('something'); }); await waitForNextUpdate(); act(() => { result.current.search.fetchNextPage(); }); await waitForNextUpdate(); expect(spy).toBeCalledTimes(1); }); });
packages/core/admin/admin/src/content-manager/hooks/useRelation/tests/useRelation.test.js
1
https://github.com/strapi/strapi/commit/389a582e38a0c4369b818ec7071a049bb77b0681
[ 0.9975111484527588, 0.2458394318819046, 0.00016521282668691128, 0.011509591713547707, 0.3885742127895355 ]
{ "id": 0, "code_window": [ " });\n", "\n", " await waitForNextUpdate();\n", "\n", " expect(spy).toBeCalledTimes(1);\n", " expect(spy).toBeCalledWith('/', { params: { q: 'something', limit: 10, page: 1 } });\n", " });\n", "\n", " test('does fetch search results with a different limit', async () => {\n", " const { result, waitForNextUpdate } = await setup(undefined, {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " expect(spy).toBeCalledWith('/', { params: { _q: 'something', limit: 10, page: 1 } });\n" ], "file_path": "packages/core/admin/admin/src/content-manager/hooks/useRelation/tests/useRelation.test.js", "type": "replace", "edit_start_line_idx": 226 }
examples/kitchensink-ts/public/uploads/.gitkeep
0
https://github.com/strapi/strapi/commit/389a582e38a0c4369b818ec7071a049bb77b0681
[ 0.00017015007324516773, 0.00017015007324516773, 0.00017015007324516773, 0.00017015007324516773, 0 ]
{ "id": 0, "code_window": [ " });\n", "\n", " await waitForNextUpdate();\n", "\n", " expect(spy).toBeCalledTimes(1);\n", " expect(spy).toBeCalledWith('/', { params: { q: 'something', limit: 10, page: 1 } });\n", " });\n", "\n", " test('does fetch search results with a different limit', async () => {\n", " const { result, waitForNextUpdate } = await setup(undefined, {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " expect(spy).toBeCalledWith('/', { params: { _q: 'something', limit: 10, page: 1 } });\n" ], "file_path": "packages/core/admin/admin/src/content-manager/hooks/useRelation/tests/useRelation.test.js", "type": "replace", "edit_start_line_idx": 226 }
const setHexOpacity = (hex, alpha) => `${hex}${Math.floor(alpha * 255) .toString(16) .padStart(2, 0)}`; export default setHexOpacity;
packages/core/helper-plugin/lib/src/utils/setHexOpacity/index.js
0
https://github.com/strapi/strapi/commit/389a582e38a0c4369b818ec7071a049bb77b0681
[ 0.00017561441927682608, 0.00017561441927682608, 0.00017561441927682608, 0.00017561441927682608, 0 ]
{ "id": 0, "code_window": [ " });\n", "\n", " await waitForNextUpdate();\n", "\n", " expect(spy).toBeCalledTimes(1);\n", " expect(spy).toBeCalledWith('/', { params: { q: 'something', limit: 10, page: 1 } });\n", " });\n", "\n", " test('does fetch search results with a different limit', async () => {\n", " const { result, waitForNextUpdate } = await setup(undefined, {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " expect(spy).toBeCalledWith('/', { params: { _q: 'something', limit: 10, page: 1 } });\n" ], "file_path": "packages/core/admin/admin/src/content-manager/hooks/useRelation/tests/useRelation.test.js", "type": "replace", "edit_start_line_idx": 226 }
import produce from 'immer'; import set from 'lodash/set'; import get from 'lodash/get'; import cloneDeep from 'lodash/cloneDeep'; import { arrayMoveItem } from '../../utils'; import { formatLayout, getDefaultInputSize, getFieldSize, setFieldSize } from './utils/layout'; const initialState = { fieldForm: {}, componentLayouts: {}, metaToEdit: '', initialData: {}, metaForm: {}, modifiedData: {}, }; const reducer = (state = initialState, action) => // eslint-disable-next-line consistent-return produce(state, (draftState) => { const layoutPathEdit = ['modifiedData', 'layouts', 'edit']; switch (action.type) { case 'MOVE_ROW': { const editFieldLayoutValue = get(state, layoutPathEdit, []); const { fromIndex, toIndex } = action; set(draftState, layoutPathEdit, arrayMoveItem(editFieldLayoutValue, fromIndex, toIndex)); break; } case 'ON_ADD_FIELD': { const newState = cloneDeep(state); const size = getDefaultInputSize( get(newState, ['modifiedData', 'attributes', action.name, 'type'], '') ); const listSize = get(newState, layoutPathEdit, []).length; const actualRowContentPath = [...layoutPathEdit, listSize - 1, 'rowContent']; const rowContentToSet = get(newState, actualRowContentPath, []); let newList = get(newState, layoutPathEdit, []); if (Array.isArray(rowContentToSet)) { set( newList, [listSize > 0 ? listSize - 1 : 0, 'rowContent'], [...rowContentToSet, { name: action.name, size }] ); } else { set( newList, [listSize > 0 ? listSize - 1 : 0, 'rowContent'], [{ name: action.name, size }] ); } const formattedList = formatLayout(newList); set(draftState, layoutPathEdit, formattedList); break; } case 'ON_CHANGE': { set(draftState, ['modifiedData', ...action.keys], action.value); break; } case 'ON_CHANGE_META': { set(draftState, ['metaForm', 'metadata', ...action.keys], action.value); break; } case 'ON_CHANGE_SIZE': { set(draftState, ['metaForm', 'size'], action.value); break; } case 'ON_RESET': { draftState.modifiedData = state.initialData; break; } case 'REMOVE_FIELD': { const row = get(state, [...layoutPathEdit, action.rowIndex, 'rowContent'], []); let newState = cloneDeep(state); if (row.length === 1 || (row.length === 2 && get(row, [1, 'name'], '') === '_TEMP_')) { const currentRowFieldList = get(state, layoutPathEdit, []); set( newState, layoutPathEdit, currentRowFieldList.filter((_, index) => action.rowIndex !== index) ); } else { set( newState, [...layoutPathEdit, action.rowIndex, 'rowContent'], row.filter((_, index) => index !== action.fieldIndex) ); } const updatedList = formatLayout(get(newState, layoutPathEdit, [])); set(draftState, layoutPathEdit, updatedList); break; } case 'REORDER_DIFF_ROW': { const actualRowContent = get( state, [...layoutPathEdit, action.dragRowIndex, 'rowContent'], [] ); const targetRowContent = get( state, [...layoutPathEdit, action.hoverRowIndex, 'rowContent'], [] ); const itemToInsert = get( state, [...layoutPathEdit, action.dragRowIndex, 'rowContent', action.dragIndex], {} ); const rowContent = [...targetRowContent, itemToInsert]; let newState = cloneDeep(state); set( newState, [...layoutPathEdit, action.dragRowIndex, 'rowContent'], actualRowContent.filter((_, index) => action.dragIndex !== index) ); set( newState, [...layoutPathEdit, action.hoverRowIndex, 'rowContent'], arrayMoveItem(rowContent, rowContent.length - 1, action.hoverIndex) ); const updatedList = formatLayout(get(newState, layoutPathEdit, [])); set(draftState, layoutPathEdit, updatedList); break; } case 'REORDER_ROW': { const newState = cloneDeep(state); const rowContent = get( newState, [...layoutPathEdit, action.dragRowIndex, 'rowContent'], [] ); set( newState, [...layoutPathEdit, action.dragRowIndex, 'rowContent'], arrayMoveItem(rowContent, action.dragIndex, action.hoverIndex) ); const updatedList = formatLayout(get(newState, layoutPathEdit, [])); set(draftState, layoutPathEdit, updatedList); break; } case 'SET_FIELD_TO_EDIT': { draftState.metaToEdit = action.name; draftState.metaForm = { metadata: get(state, ['modifiedData', 'metadatas', action.name, 'edit'], {}), size: getFieldSize(action.name, state.modifiedData?.layouts?.edit) ?? getDefaultInputSize(), }; break; } case 'SUBMIT_META_FORM': { set( draftState, ['modifiedData', 'metadatas', state.metaToEdit, 'edit'], state.metaForm.metadata ); const layoutsCopy = cloneDeep(get(state, layoutPathEdit, [])); const nextLayoutValue = setFieldSize(state.metaToEdit, state.metaForm.size, layoutsCopy); if (nextLayoutValue.length > 0) { set(draftState, layoutPathEdit, formatLayout(nextLayoutValue)); } break; } case 'SUBMIT_SUCCEEDED': { draftState.initialData = state.modifiedData; break; } case 'UNSET_FIELD_TO_EDIT': { draftState.metaToEdit = ''; draftState.metaForm = {}; break; } default: return draftState; } }); export default reducer; export { initialState };
packages/core/admin/admin/src/content-manager/pages/EditSettingsView/reducer.js
0
https://github.com/strapi/strapi/commit/389a582e38a0c4369b818ec7071a049bb77b0681
[ 0.00017986705643124878, 0.00017526255396660417, 0.00017275431309826672, 0.00017513331840746105, 0.0000018161111938752583 ]
{ "id": 1, "code_window": [ " expect(spy).toBeCalledTimes(1);\n", " expect(spy).toBeCalledWith(expect.any(String), {\n", " params: {\n", " q: 'something',\n", " limit: 5,\n", " page: expect.any(Number),\n", " },\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " _q: 'something',\n" ], "file_path": "packages/core/admin/admin/src/content-manager/hooks/useRelation/tests/useRelation.test.js", "type": "replace", "edit_start_line_idx": 250 }
import { useState } from 'react'; import { useInfiniteQuery } from 'react-query'; import { axiosInstance } from '../../../core/utils'; export const useRelation = (cacheKey, { relation, search }) => { const [searchParams, setSearchParams] = useState({}); const fetchRelations = async ({ pageParam = 1 }) => { try { const { data } = await axiosInstance.get(relation?.endpoint, { params: { ...(relation.pageParams ?? {}), page: pageParam, }, }); if (relation?.onLoad) { relation.onLoad(data); } return data; } catch (err) { return null; } }; const fetchSearch = async ({ pageParam = 1 }) => { const { data } = await axiosInstance.get(search.endpoint, { params: { ...(search.pageParams ?? {}), ...searchParams, page: pageParam, }, }); return data; }; const relationsRes = useInfiniteQuery(['relation', cacheKey], fetchRelations, { enabled: !!relation?.endpoint, getNextPageParam(lastPage) { if (lastPage.pagination.page >= lastPage.pagination.pageCount) { return undefined; } // eslint-disable-next-line consistent-return return lastPage.pagination.page + 1; }, }); const searchRes = useInfiniteQuery( ['relation', cacheKey, 'search', JSON.stringify(searchParams)], fetchSearch, { enabled: Object.keys(searchParams).length > 0, getNextPageParam(lastPage) { if (lastPage.pagination.page >= lastPage.pagination.pageCount) { return undefined; } // eslint-disable-next-line consistent-return return lastPage.pagination.page + 1; }, } ); const searchFor = (term, options = {}) => { searchRes.remove(); setSearchParams({ ...options, q: encodeURIComponent(term), }); }; return { relations: relationsRes, search: searchRes, searchFor }; };
packages/core/admin/admin/src/content-manager/hooks/useRelation/useRelation.js
1
https://github.com/strapi/strapi/commit/389a582e38a0c4369b818ec7071a049bb77b0681
[ 0.0003298711380921304, 0.00018965385970659554, 0.00016563761164434254, 0.00017012844909913838, 0.00005305036756908521 ]
{ "id": 1, "code_window": [ " expect(spy).toBeCalledTimes(1);\n", " expect(spy).toBeCalledWith(expect.any(String), {\n", " params: {\n", " q: 'something',\n", " limit: 5,\n", " page: expect.any(Number),\n", " },\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " _q: 'something',\n" ], "file_path": "packages/core/admin/admin/src/content-manager/hooks/useRelation/tests/useRelation.test.js", "type": "replace", "edit_start_line_idx": 250 }
'use strict'; const loadFiles = require('./load-files'); const findPackagePath = require('./package-path'); module.exports = { loadFiles, findPackagePath, };
packages/core/strapi/lib/load/index.js
0
https://github.com/strapi/strapi/commit/389a582e38a0c4369b818ec7071a049bb77b0681
[ 0.00017780548660084605, 0.00017780548660084605, 0.00017780548660084605, 0.00017780548660084605, 0 ]
{ "id": 1, "code_window": [ " expect(spy).toBeCalledTimes(1);\n", " expect(spy).toBeCalledWith(expect.any(String), {\n", " params: {\n", " q: 'something',\n", " limit: 5,\n", " page: expect.any(Number),\n", " },\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " _q: 'something',\n" ], "file_path": "packages/core/admin/admin/src/content-manager/hooks/useRelation/tests/useRelation.test.js", "type": "replace", "edit_start_line_idx": 250 }
import styled from 'styled-components'; const Container = styled.div` padding: 18px 30px 66px 30px; `; export default Container;
packages/core/admin/admin/src/content-manager/components/Container/index.js
0
https://github.com/strapi/strapi/commit/389a582e38a0c4369b818ec7071a049bb77b0681
[ 0.0001789622474461794, 0.0001789622474461794, 0.0001789622474461794, 0.0001789622474461794, 0 ]
{ "id": 1, "code_window": [ " expect(spy).toBeCalledTimes(1);\n", " expect(spy).toBeCalledWith(expect.any(String), {\n", " params: {\n", " q: 'something',\n", " limit: 5,\n", " page: expect.any(Number),\n", " },\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " _q: 'something',\n" ], "file_path": "packages/core/admin/admin/src/content-manager/hooks/useRelation/tests/useRelation.test.js", "type": "replace", "edit_start_line_idx": 250 }
import { useEffect, useState } from 'react'; /** * For more details about this hook see: * https://www.30secondsofcode.org/react/s/use-navigator-on-line */ const useNavigatorOnLine = () => { const onlineStatus = typeof navigator !== 'undefined' && typeof navigator.onLine === 'boolean' ? navigator.onLine : true; const [isOnline, setIsOnline] = useState(onlineStatus); const setOnline = () => setIsOnline(true); const setOffline = () => setIsOnline(false); useEffect(() => { window.addEventListener('online', setOnline); window.addEventListener('offline', setOffline); return () => { window.removeEventListener('online', setOnline); window.removeEventListener('offline', setOffline); }; }, []); return isOnline; }; export default useNavigatorOnLine;
packages/core/admin/admin/src/hooks/useNavigatorOnLine/index.js
0
https://github.com/strapi/strapi/commit/389a582e38a0c4369b818ec7071a049bb77b0681
[ 0.00017468634177930653, 0.0001730258227325976, 0.00016973671154119074, 0.00017384011880494654, 0.000002001233042392414 ]
{ "id": 2, "code_window": [ "\n", " expect(spy).toBeCalledTimes(2);\n", " expect(spy).toHaveBeenNthCalledWith(1, expect.any(String), {\n", " params: {\n", " q: 'something',\n", " limit: expect.any(Number),\n", " page: 1,\n", " },\n", " });\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " _q: 'something',\n" ], "file_path": "packages/core/admin/admin/src/content-manager/hooks/useRelation/tests/useRelation.test.js", "type": "replace", "edit_start_line_idx": 280 }
import React from 'react'; import { QueryClientProvider, QueryClient } from 'react-query'; import { renderHook, act } from '@testing-library/react-hooks'; import { axiosInstance } from '../../../../core/utils'; import { useRelation } from '../useRelation'; jest.mock('../../../../core/utils', () => ({ ...jest.requireActual('../../../../core/utils'), axiosInstance: { get: jest .fn() .mockResolvedValue({ data: { values: [], pagination: { page: 1, pageCount: 10 } } }), }, })); const client = new QueryClient({ defaultOptions: { queries: { retry: false, }, }, }); // eslint-disable-next-line react/prop-types const ComponentFixture = ({ children }) => ( <QueryClientProvider client={client}>{children}</QueryClientProvider> ); function setup(name = 'test', args) { return new Promise((resolve) => { act(() => { resolve( renderHook( () => useRelation(name, { relation: { endpoint: '/', pageParams: { limit: 10, ...(args?.relation?.pageParams ?? {}), }, ...(args?.relation ?? {}), }, search: { endpoint: '/', pageParams: { limit: 10, ...(args?.search?.pageParams ?? {}), }, ...(args?.search ?? {}), }, }), { wrapper: ComponentFixture } ) ); }); }); } describe('useRelation', () => { afterEach(() => { jest.clearAllMocks(); }); test('fetch relations', async () => { const { result, waitForNextUpdate } = await setup(undefined); await waitForNextUpdate(); expect(result.current.relations.isSuccess).toBe(true); expect(axiosInstance.get).toBeCalledTimes(1); expect(axiosInstance.get).toBeCalledWith('/', { params: { limit: 10, page: 1, }, }); }); test('calls onLoad callback', async () => { const spy = jest.fn(); const FIXTURE_DATA = { values: [1, 2], pagination: { page: 1, pageCount: 3, }, }; axiosInstance.get = jest.fn().mockResolvedValue({ data: FIXTURE_DATA, }); const { waitForNextUpdate } = await setup(undefined, { relation: { onLoad: spy, }, }); await waitForNextUpdate(); expect(spy).toBeCalledTimes(1); expect(spy).toBeCalledWith(FIXTURE_DATA); }); test('fetch relations with different limit', async () => { const { waitForNextUpdate } = await setup(undefined, { relation: { pageParams: { limit: 5 } }, }); await waitForNextUpdate(); expect(axiosInstance.get).toBeCalledWith(expect.any(String), { params: { limit: 5, page: expect.any(Number), }, }); }); test('doesn not fetch relations if a relation endpoint was not passed', async () => { await setup(undefined, { relation: { endpoint: undefined } }); expect(axiosInstance.get).not.toBeCalled(); }); test('fetch relations', async () => { const { result, waitForNextUpdate } = await setup(); await waitForNextUpdate(); expect(result.current.relations.isSuccess).toBe(true); expect(axiosInstance.get).toBeCalledTimes(1); expect(axiosInstance.get).toBeCalledWith('/', { params: { limit: 10, page: 1, }, }); }); test('fetch relations next page, if there is one', async () => { axiosInstance.get = jest.fn().mockResolvedValue({ data: { values: [], pagination: { page: 1, pageCount: 3, }, }, }); const { result, waitForNextUpdate } = await setup(undefined); await waitForNextUpdate(); act(() => { result.current.relations.fetchNextPage(); }); await waitForNextUpdate(); expect(axiosInstance.get).toBeCalledTimes(2); expect(axiosInstance.get).toHaveBeenNthCalledWith(1, expect.any(String), { params: { limit: expect.any(Number), page: 1, }, }); expect(axiosInstance.get).toHaveBeenNthCalledWith(2, expect.any(String), { params: { limit: expect.any(Number), page: 2, }, }); }); test("does not fetch relations next page, if there isn't one", async () => { axiosInstance.get = jest.fn().mockResolvedValue({ data: { values: [], pagination: { page: 1, pageCount: 1, }, }, }); const { result, waitForNextUpdate } = await setup(undefined); await waitForNextUpdate(); act(() => { result.current.relations.fetchNextPage(); }); await waitForNextUpdate(); expect(axiosInstance.get).toBeCalledTimes(1); }); test('does not fetch search by default', async () => { const { result, waitForNextUpdate } = await setup(); await waitForNextUpdate(); expect(result.current.search.isLoading).toBe(false); }); test('does fetch search results once a term was provided', async () => { const { result, waitForNextUpdate } = await setup(); await waitForNextUpdate(); const spy = jest .fn() .mockResolvedValue({ data: { values: [], pagination: { page: 1, pageCount: 2 } } }); axiosInstance.get = spy; act(() => { result.current.searchFor('something'); }); await waitForNextUpdate(); expect(spy).toBeCalledTimes(1); expect(spy).toBeCalledWith('/', { params: { q: 'something', limit: 10, page: 1 } }); }); test('does fetch search results with a different limit', async () => { const { result, waitForNextUpdate } = await setup(undefined, { search: { pageParams: { limit: 5 } }, }); await waitForNextUpdate(); const spy = jest .fn() .mockResolvedValue({ data: { values: [], pagination: { page: 1, pageCount: 2 } } }); axiosInstance.get = spy; act(() => { result.current.searchFor('something'); }); await waitForNextUpdate(); expect(spy).toBeCalledTimes(1); expect(spy).toBeCalledWith(expect.any(String), { params: { q: 'something', limit: 5, page: expect.any(Number), }, }); }); test('fetch search next page, if there is one', async () => { const { result, waitForNextUpdate } = await setup(undefined); const spy = jest .fn() .mockResolvedValue({ data: { values: [], pagination: { page: 1, pageCount: 2 } } }); axiosInstance.get = spy; act(() => { result.current.searchFor('something'); }); await waitForNextUpdate(); act(() => { result.current.search.fetchNextPage(); }); await waitForNextUpdate(); expect(spy).toBeCalledTimes(2); expect(spy).toHaveBeenNthCalledWith(1, expect.any(String), { params: { q: 'something', limit: expect.any(Number), page: 1, }, }); expect(spy).toHaveBeenNthCalledWith(2, expect.any(String), { params: { q: 'something', limit: expect.any(Number), page: 2, }, }); }); test("doesn not fetch search next page, if there isn't one", async () => { const { result, waitForNextUpdate } = await setup(undefined); const spy = jest .fn() .mockResolvedValue({ data: { values: [], pagination: { page: 1, pageCount: 1 } } }); axiosInstance.get = spy; act(() => { result.current.searchFor('something'); }); await waitForNextUpdate(); act(() => { result.current.search.fetchNextPage(); }); await waitForNextUpdate(); expect(spy).toBeCalledTimes(1); }); });
packages/core/admin/admin/src/content-manager/hooks/useRelation/tests/useRelation.test.js
1
https://github.com/strapi/strapi/commit/389a582e38a0c4369b818ec7071a049bb77b0681
[ 0.6412022113800049, 0.02054261416196823, 0.0001656390231801197, 0.00018882800941355526, 0.11147569119930267 ]
{ "id": 2, "code_window": [ "\n", " expect(spy).toBeCalledTimes(2);\n", " expect(spy).toHaveBeenNthCalledWith(1, expect.any(String), {\n", " params: {\n", " q: 'something',\n", " limit: expect.any(Number),\n", " page: 1,\n", " },\n", " });\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " _q: 'something',\n" ], "file_path": "packages/core/admin/admin/src/content-manager/hooks/useRelation/tests/useRelation.test.js", "type": "replace", "edit_start_line_idx": 280 }
'use strict'; module.exports = ({ nexus, strapi }) => { const { nonNull } = nexus; return { type: 'UsersPermissionsDeleteRolePayload', args: { id: nonNull('ID'), }, description: 'Delete an existing role', async resolve(parent, args, context) { const { koaContext } = context; koaContext.params = { role: args.id }; await strapi.plugin('users-permissions').controller('role').deleteRole(koaContext); return { ok: true }; }, }; };
packages/plugins/users-permissions/server/graphql/mutations/crud/role/delete-role.js
0
https://github.com/strapi/strapi/commit/389a582e38a0c4369b818ec7071a049bb77b0681
[ 0.00017649891378823668, 0.00017154875968117267, 0.00016892619896680117, 0.00016922120994422585, 0.0000035023485907004215 ]
{ "id": 2, "code_window": [ "\n", " expect(spy).toBeCalledTimes(2);\n", " expect(spy).toHaveBeenNthCalledWith(1, expect.any(String), {\n", " params: {\n", " q: 'something',\n", " limit: expect.any(Number),\n", " page: 1,\n", " },\n", " });\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " _q: 'something',\n" ], "file_path": "packages/core/admin/admin/src/content-manager/hooks/useRelation/tests/useRelation.test.js", "type": "replace", "edit_start_line_idx": 280 }
import { fixtures } from '@strapi/admin-test-utils/lib'; import addCommonFieldsToInitialDataMiddleware from '../addCommonFieldsToInitialDataMiddleware'; jest.mock('@strapi/helper-plugin', () => ({ request: () => ({ nonLocalizedFields: { common: 'test' }, localizations: ['test'], }), formatContentTypeData: (data) => data, contentManagementUtilRemoveFieldsFromData: (data) => data, })); describe('i18n | middlewares | addCommonFieldsToInitialDataMiddleware', () => { let getState; const dispatch = jest.fn(); beforeEach(() => { const store = { ...fixtures.store.state, 'content-manager_editViewCrudReducer': { contentTypeDataStructure: { name: 'test', common: 'common default value' }, }, 'content-manager_editViewLayoutManager': { currentLayout: { components: {}, contentType: { uid: 'article', attributes: { name: { type: 'string' }, common: { type: 'string' }, }, }, }, }, }; getState = () => store; }); it('should forward the action when the type is undefined', () => { const action = { test: true, type: undefined }; const next = jest.fn(); const middleware = addCommonFieldsToInitialDataMiddleware()({ getState, dispatch }); middleware(next)(action); expect(next).toBeCalledWith(action); }); it('should forward the action when the rawQuery is empty', () => { const action = { type: 'ContentManager/CrudReducer/INIT_FORM', rawQuery: '' }; const next = jest.fn(); const middleware = addCommonFieldsToInitialDataMiddleware()({ getState, dispatch }); middleware(next)(action); expect(next).toBeCalledWith(action); }); it('should forward the action when the relatedEntityId is not defined', () => { const action = { type: 'ContentManager/CrudReducer/INIT_FORM', rawQuery: '?plugins[i18n][locale]=en', }; const next = jest.fn(); const middleware = addCommonFieldsToInitialDataMiddleware()({ getState, dispatch }); middleware(next)(action); expect(next).toBeCalledWith(action); }); it('should makes a request to retrieve the common field when the relatedEntityId is defined', async () => { const action = { type: 'ContentManager/CrudReducer/INIT_FORM', rawQuery: '?plugins[i18n][relatedEntityId]=1', }; const next = jest.fn((x) => x); const middleware = addCommonFieldsToInitialDataMiddleware()({ getState, dispatch }); const nextAction = await middleware(next)(action); expect(dispatch).toHaveBeenCalledWith({ type: 'ContentManager/CrudReducer/GET_DATA' }); expect(nextAction).toEqual({ type: 'ContentManager/CrudReducer/INIT_FORM', rawQuery: '?plugins[i18n][relatedEntityId]=1', data: { name: 'test', localizations: ['test'], common: 'test', }, }); }); });
packages/plugins/i18n/admin/src/middlewares/tests/addCommonFieldsToInitialDataMiddleware.test.js
0
https://github.com/strapi/strapi/commit/389a582e38a0c4369b818ec7071a049bb77b0681
[ 0.00017377844778820872, 0.0001711684453766793, 0.00016868524835444987, 0.00017139731789939106, 0.0000015274483757821145 ]
{ "id": 2, "code_window": [ "\n", " expect(spy).toBeCalledTimes(2);\n", " expect(spy).toHaveBeenNthCalledWith(1, expect.any(String), {\n", " params: {\n", " q: 'something',\n", " limit: expect.any(Number),\n", " page: 1,\n", " },\n", " });\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " _q: 'something',\n" ], "file_path": "packages/core/admin/admin/src/content-manager/hooks/useRelation/tests/useRelation.test.js", "type": "replace", "edit_start_line_idx": 280 }
import { testData } from '../../testUtils'; import removePasswordFieldsFromData from '../removePasswordFieldsFromData'; describe('CONTENT MANAGER | utils', () => { describe('removePasswordFieldsFromData', () => { it('should return an empty object', () => { const { components, contentType } = testData; expect(removePasswordFieldsFromData({}, contentType, components)).toEqual({}); }); it('should return the initial data if there is no password field', () => { const { components, contentType } = testData; expect(removePasswordFieldsFromData({ name: 'test' }, contentType, components)).toEqual({ name: 'test', }); }); it('should remove the password field for a simple data structure', () => { const { components, contentType } = testData; const data = { name: 'test', password: 'password' }; const expected = { name: 'test' }; expect(removePasswordFieldsFromData(data, contentType, components)).toEqual(expected); }); it('should remove all password fields', () => { const { components, contentType, modifiedData, expectedModifiedData } = testData; expect(removePasswordFieldsFromData(modifiedData, contentType, components)).toEqual( expectedModifiedData ); }); }); });
packages/core/admin/admin/src/content-manager/utils/tests/removePasswordFieldsFromData.test.js
0
https://github.com/strapi/strapi/commit/389a582e38a0c4369b818ec7071a049bb77b0681
[ 0.0001769976079231128, 0.00017393242160324007, 0.00017156531976070255, 0.00017358337936457247, 0.000001974339511434664 ]
{ "id": 3, "code_window": [ " page: 1,\n", " },\n", " });\n", " expect(spy).toHaveBeenNthCalledWith(2, expect.any(String), {\n", " params: {\n", " q: 'something',\n", " limit: expect.any(Number),\n", " page: 2,\n", " },\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " _q: 'something',\n" ], "file_path": "packages/core/admin/admin/src/content-manager/hooks/useRelation/tests/useRelation.test.js", "type": "replace", "edit_start_line_idx": 287 }
import React from 'react'; import { QueryClientProvider, QueryClient } from 'react-query'; import { renderHook, act } from '@testing-library/react-hooks'; import { axiosInstance } from '../../../../core/utils'; import { useRelation } from '../useRelation'; jest.mock('../../../../core/utils', () => ({ ...jest.requireActual('../../../../core/utils'), axiosInstance: { get: jest .fn() .mockResolvedValue({ data: { values: [], pagination: { page: 1, pageCount: 10 } } }), }, })); const client = new QueryClient({ defaultOptions: { queries: { retry: false, }, }, }); // eslint-disable-next-line react/prop-types const ComponentFixture = ({ children }) => ( <QueryClientProvider client={client}>{children}</QueryClientProvider> ); function setup(name = 'test', args) { return new Promise((resolve) => { act(() => { resolve( renderHook( () => useRelation(name, { relation: { endpoint: '/', pageParams: { limit: 10, ...(args?.relation?.pageParams ?? {}), }, ...(args?.relation ?? {}), }, search: { endpoint: '/', pageParams: { limit: 10, ...(args?.search?.pageParams ?? {}), }, ...(args?.search ?? {}), }, }), { wrapper: ComponentFixture } ) ); }); }); } describe('useRelation', () => { afterEach(() => { jest.clearAllMocks(); }); test('fetch relations', async () => { const { result, waitForNextUpdate } = await setup(undefined); await waitForNextUpdate(); expect(result.current.relations.isSuccess).toBe(true); expect(axiosInstance.get).toBeCalledTimes(1); expect(axiosInstance.get).toBeCalledWith('/', { params: { limit: 10, page: 1, }, }); }); test('calls onLoad callback', async () => { const spy = jest.fn(); const FIXTURE_DATA = { values: [1, 2], pagination: { page: 1, pageCount: 3, }, }; axiosInstance.get = jest.fn().mockResolvedValue({ data: FIXTURE_DATA, }); const { waitForNextUpdate } = await setup(undefined, { relation: { onLoad: spy, }, }); await waitForNextUpdate(); expect(spy).toBeCalledTimes(1); expect(spy).toBeCalledWith(FIXTURE_DATA); }); test('fetch relations with different limit', async () => { const { waitForNextUpdate } = await setup(undefined, { relation: { pageParams: { limit: 5 } }, }); await waitForNextUpdate(); expect(axiosInstance.get).toBeCalledWith(expect.any(String), { params: { limit: 5, page: expect.any(Number), }, }); }); test('doesn not fetch relations if a relation endpoint was not passed', async () => { await setup(undefined, { relation: { endpoint: undefined } }); expect(axiosInstance.get).not.toBeCalled(); }); test('fetch relations', async () => { const { result, waitForNextUpdate } = await setup(); await waitForNextUpdate(); expect(result.current.relations.isSuccess).toBe(true); expect(axiosInstance.get).toBeCalledTimes(1); expect(axiosInstance.get).toBeCalledWith('/', { params: { limit: 10, page: 1, }, }); }); test('fetch relations next page, if there is one', async () => { axiosInstance.get = jest.fn().mockResolvedValue({ data: { values: [], pagination: { page: 1, pageCount: 3, }, }, }); const { result, waitForNextUpdate } = await setup(undefined); await waitForNextUpdate(); act(() => { result.current.relations.fetchNextPage(); }); await waitForNextUpdate(); expect(axiosInstance.get).toBeCalledTimes(2); expect(axiosInstance.get).toHaveBeenNthCalledWith(1, expect.any(String), { params: { limit: expect.any(Number), page: 1, }, }); expect(axiosInstance.get).toHaveBeenNthCalledWith(2, expect.any(String), { params: { limit: expect.any(Number), page: 2, }, }); }); test("does not fetch relations next page, if there isn't one", async () => { axiosInstance.get = jest.fn().mockResolvedValue({ data: { values: [], pagination: { page: 1, pageCount: 1, }, }, }); const { result, waitForNextUpdate } = await setup(undefined); await waitForNextUpdate(); act(() => { result.current.relations.fetchNextPage(); }); await waitForNextUpdate(); expect(axiosInstance.get).toBeCalledTimes(1); }); test('does not fetch search by default', async () => { const { result, waitForNextUpdate } = await setup(); await waitForNextUpdate(); expect(result.current.search.isLoading).toBe(false); }); test('does fetch search results once a term was provided', async () => { const { result, waitForNextUpdate } = await setup(); await waitForNextUpdate(); const spy = jest .fn() .mockResolvedValue({ data: { values: [], pagination: { page: 1, pageCount: 2 } } }); axiosInstance.get = spy; act(() => { result.current.searchFor('something'); }); await waitForNextUpdate(); expect(spy).toBeCalledTimes(1); expect(spy).toBeCalledWith('/', { params: { q: 'something', limit: 10, page: 1 } }); }); test('does fetch search results with a different limit', async () => { const { result, waitForNextUpdate } = await setup(undefined, { search: { pageParams: { limit: 5 } }, }); await waitForNextUpdate(); const spy = jest .fn() .mockResolvedValue({ data: { values: [], pagination: { page: 1, pageCount: 2 } } }); axiosInstance.get = spy; act(() => { result.current.searchFor('something'); }); await waitForNextUpdate(); expect(spy).toBeCalledTimes(1); expect(spy).toBeCalledWith(expect.any(String), { params: { q: 'something', limit: 5, page: expect.any(Number), }, }); }); test('fetch search next page, if there is one', async () => { const { result, waitForNextUpdate } = await setup(undefined); const spy = jest .fn() .mockResolvedValue({ data: { values: [], pagination: { page: 1, pageCount: 2 } } }); axiosInstance.get = spy; act(() => { result.current.searchFor('something'); }); await waitForNextUpdate(); act(() => { result.current.search.fetchNextPage(); }); await waitForNextUpdate(); expect(spy).toBeCalledTimes(2); expect(spy).toHaveBeenNthCalledWith(1, expect.any(String), { params: { q: 'something', limit: expect.any(Number), page: 1, }, }); expect(spy).toHaveBeenNthCalledWith(2, expect.any(String), { params: { q: 'something', limit: expect.any(Number), page: 2, }, }); }); test("doesn not fetch search next page, if there isn't one", async () => { const { result, waitForNextUpdate } = await setup(undefined); const spy = jest .fn() .mockResolvedValue({ data: { values: [], pagination: { page: 1, pageCount: 1 } } }); axiosInstance.get = spy; act(() => { result.current.searchFor('something'); }); await waitForNextUpdate(); act(() => { result.current.search.fetchNextPage(); }); await waitForNextUpdate(); expect(spy).toBeCalledTimes(1); }); });
packages/core/admin/admin/src/content-manager/hooks/useRelation/tests/useRelation.test.js
1
https://github.com/strapi/strapi/commit/389a582e38a0c4369b818ec7071a049bb77b0681
[ 0.9971469044685364, 0.03185506910085678, 0.00016584036347921938, 0.00017966226732823998, 0.1733749657869339 ]
{ "id": 3, "code_window": [ " page: 1,\n", " },\n", " });\n", " expect(spy).toHaveBeenNthCalledWith(2, expect.any(String), {\n", " params: {\n", " q: 'something',\n", " limit: expect.any(Number),\n", " page: 2,\n", " },\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " _q: 'something',\n" ], "file_path": "packages/core/admin/admin/src/content-manager/hooks/useRelation/tests/useRelation.test.js", "type": "replace", "edit_start_line_idx": 287 }
import reducers, { initialState } from '../reducers'; import { RESOLVE_LOCALES, ADD_LOCALE, DELETE_LOCALE, UPDATE_LOCALE } from '../constants'; describe('i18n reducer', () => { it('resolves the initial state when the action is not known', () => { const action = { type: 'UNKNWON_ACTION', }; const actual = reducers.i18n_locales(initialState, action); const expected = initialState; expect(actual).toEqual(expected); }); it('resolves a list of locales when triggering RESOLVE_LOCALES', () => { const action = { type: RESOLVE_LOCALES, locales: [{ id: 1, displayName: 'French', isDefault: false }], }; const actual = reducers.i18n_locales(initialState, action); const expected = { isLoading: false, locales: [ { displayName: 'French', id: 1, isDefault: false, }, ], }; expect(actual).toEqual(expected); }); it('adds a locale when triggering ADD_LOCALE', () => { const action = { type: ADD_LOCALE, newLocale: { id: 1, displayName: 'French', isDefault: false }, }; const actual = reducers.i18n_locales(initialState, action); const expected = { isLoading: true, locales: [ { displayName: 'French', id: 1, isDefault: false, }, ], }; expect(actual).toEqual(expected); }); it('adds a locale when triggering ADD_LOCALE and set it to default', () => { const action = { type: ADD_LOCALE, newLocale: { id: 1, displayName: 'French', isDefault: true }, }; const locales = [ { displayName: 'English', id: 2, isDefault: true, }, ]; const actual = reducers.i18n_locales({ ...initialState, locales }, action); const expected = { isLoading: true, locales: [ { displayName: 'English', id: 2, isDefault: false, }, { displayName: 'French', id: 1, isDefault: true, }, ], }; expect(actual).toEqual(expected); }); it('removes a locale when triggering DELETE_LOCALE ', () => { const action = { type: DELETE_LOCALE, id: 2, }; const locales = [ { displayName: 'French', id: 1, isDefault: true, }, { displayName: 'English', id: 2, isDefault: false, }, ]; const actual = reducers.i18n_locales({ ...initialState, locales }, action); const expected = { isLoading: true, locales: [ { displayName: 'French', id: 1, isDefault: true, }, ], }; expect(actual).toEqual(expected); }); it('updates a locale when triggering UPDATE_LOCALE', () => { const action = { type: UPDATE_LOCALE, editedLocale: { id: 1, displayName: 'Frenchie', isDefault: false }, }; const locales = [ { displayName: 'English', id: 2, isDefault: true, }, { displayName: 'French', id: 1, isDefault: false, }, ]; const actual = reducers.i18n_locales({ ...initialState, locales }, action); const expected = { isLoading: true, locales: [ { displayName: 'English', id: 2, isDefault: true, }, { displayName: 'Frenchie', id: 1, isDefault: false, }, ], }; expect(actual).toEqual(expected); }); it('updates a locale when triggering UPDATE_LOCALE and set it to default', () => { const action = { type: UPDATE_LOCALE, editedLocale: { id: 1, displayName: 'Frenchie', isDefault: true }, }; const locales = [ { displayName: 'English', id: 2, isDefault: true, }, { displayName: 'French', id: 1, isDefault: false, }, ]; const actual = reducers.i18n_locales({ ...initialState, locales }, action); const expected = { isLoading: true, locales: [ { displayName: 'English', id: 2, isDefault: false, }, { displayName: 'Frenchie', id: 1, isDefault: true, }, ], }; expect(actual).toEqual(expected); }); });
packages/plugins/i18n/admin/src/hooks/tests/reducers.test.js
0
https://github.com/strapi/strapi/commit/389a582e38a0c4369b818ec7071a049bb77b0681
[ 0.00019336299737915397, 0.00017053235205821693, 0.00016277923714369535, 0.00017084409773815423, 0.000006358832251862623 ]
{ "id": 3, "code_window": [ " page: 1,\n", " },\n", " });\n", " expect(spy).toHaveBeenNthCalledWith(2, expect.any(String), {\n", " params: {\n", " q: 'something',\n", " limit: expect.any(Number),\n", " page: 2,\n", " },\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " _q: 'something',\n" ], "file_path": "packages/core/admin/admin/src/content-manager/hooks/useRelation/tests/useRelation.test.js", "type": "replace", "edit_start_line_idx": 287 }
# From https://github.com/Danimoth/gitattributes/blob/master/Web.gitattributes # Handle line endings automatically for files detected as text # and leave all files detected as binary untouched. * text=auto # # The above will handle all files NOT found below # # ## These files are text and should be normalized (Convert crlf => lf) # # source code *.php text *.css text *.sass text *.scss text *.less text *.styl text *.js text eol=lf *.coffee text *.json text *.htm text *.html text *.xml text *.svg text *.txt text *.ini text *.inc text *.pl text *.rb text *.py text *.scm text *.sql text *.sh text *.bat text # templates *.ejs text *.hbt text *.jade text *.haml text *.hbs text *.dot text *.tmpl text *.phtml text # server config .htaccess text # git config .gitattributes text .gitignore text .gitconfig text # code analysis config .jshintrc text .jscsrc text .jshintignore text .csslintrc text # misc config *.yaml text *.yml text .editorconfig text # build config *.npmignore text *.bowerrc text # Heroku Procfile text .slugignore text # Documentation *.md text LICENSE text AUTHORS text # ## These files are binary and should be left untouched # # (binary is a macro for -text -diff) *.png binary *.jpg binary *.jpeg binary *.gif binary *.ico binary *.mov binary *.mp4 binary *.mp3 binary *.flv binary *.fla binary *.swf binary *.gz binary *.zip binary *.7z binary *.ttf binary *.eot binary *.woff binary *.pyc binary *.pdf binary
.gitattributes
0
https://github.com/strapi/strapi/commit/389a582e38a0c4369b818ec7071a049bb77b0681
[ 0.0001765492488630116, 0.00017363560618832707, 0.00016902608331292868, 0.00017419501091353595, 0.000002065328089884133 ]
{ "id": 3, "code_window": [ " page: 1,\n", " },\n", " });\n", " expect(spy).toHaveBeenNthCalledWith(2, expect.any(String), {\n", " params: {\n", " q: 'something',\n", " limit: expect.any(Number),\n", " page: 2,\n", " },\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " _q: 'something',\n" ], "file_path": "packages/core/admin/admin/src/content-manager/hooks/useRelation/tests/useRelation.test.js", "type": "replace", "edit_start_line_idx": 287 }
'use strict'; const _ = require('lodash'); const slugify = require('@sindresorhus/slugify'); module.exports = ({ strapi }) => ({ async generateUIDField({ contentTypeUID, field, data }) { const contentType = strapi.contentTypes[contentTypeUID]; const { attributes } = contentType; const { targetField, default: defaultValue, options } = attributes[field]; const targetValue = _.get(data, targetField); if (!_.isEmpty(targetValue)) { return this.findUniqueUID({ contentTypeUID, field, value: slugify(targetValue, options), }); } return this.findUniqueUID({ contentTypeUID, field, value: slugify(defaultValue || contentType.modelName, options), }); }, async findUniqueUID({ contentTypeUID, field, value }) { const query = strapi.db.query(contentTypeUID); const possibleColisions = await query .findMany({ where: { [field]: { $contains: value } }, }) .then((results) => results.map((result) => result[field])); if (possibleColisions.length === 0) { return value; } let i = 1; let tmpUId = `${value}-${i}`; while (possibleColisions.includes(tmpUId)) { i += 1; tmpUId = `${value}-${i}`; } return tmpUId; }, async checkUIDAvailability({ contentTypeUID, field, value }) { const query = strapi.db.query(contentTypeUID); const count = await query.count({ where: { [field]: value }, }); if (count > 0) return false; return true; }, });
packages/core/content-manager/server/services/uid.js
0
https://github.com/strapi/strapi/commit/389a582e38a0c4369b818ec7071a049bb77b0681
[ 0.0001757459103828296, 0.00017317272431682795, 0.00017103464051615447, 0.00017291233234573156, 0.0000016484550542372745 ]
{ "id": 4, "code_window": [ " searchRes.remove();\n", " setSearchParams({\n", " ...options,\n", " q: encodeURIComponent(term),\n", " });\n", " };\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " _q: encodeURIComponent(term),\n" ], "file_path": "packages/core/admin/admin/src/content-manager/hooks/useRelation/useRelation.js", "type": "replace", "edit_start_line_idx": 71 }
import React from 'react'; import { QueryClientProvider, QueryClient } from 'react-query'; import { renderHook, act } from '@testing-library/react-hooks'; import { axiosInstance } from '../../../../core/utils'; import { useRelation } from '../useRelation'; jest.mock('../../../../core/utils', () => ({ ...jest.requireActual('../../../../core/utils'), axiosInstance: { get: jest .fn() .mockResolvedValue({ data: { values: [], pagination: { page: 1, pageCount: 10 } } }), }, })); const client = new QueryClient({ defaultOptions: { queries: { retry: false, }, }, }); // eslint-disable-next-line react/prop-types const ComponentFixture = ({ children }) => ( <QueryClientProvider client={client}>{children}</QueryClientProvider> ); function setup(name = 'test', args) { return new Promise((resolve) => { act(() => { resolve( renderHook( () => useRelation(name, { relation: { endpoint: '/', pageParams: { limit: 10, ...(args?.relation?.pageParams ?? {}), }, ...(args?.relation ?? {}), }, search: { endpoint: '/', pageParams: { limit: 10, ...(args?.search?.pageParams ?? {}), }, ...(args?.search ?? {}), }, }), { wrapper: ComponentFixture } ) ); }); }); } describe('useRelation', () => { afterEach(() => { jest.clearAllMocks(); }); test('fetch relations', async () => { const { result, waitForNextUpdate } = await setup(undefined); await waitForNextUpdate(); expect(result.current.relations.isSuccess).toBe(true); expect(axiosInstance.get).toBeCalledTimes(1); expect(axiosInstance.get).toBeCalledWith('/', { params: { limit: 10, page: 1, }, }); }); test('calls onLoad callback', async () => { const spy = jest.fn(); const FIXTURE_DATA = { values: [1, 2], pagination: { page: 1, pageCount: 3, }, }; axiosInstance.get = jest.fn().mockResolvedValue({ data: FIXTURE_DATA, }); const { waitForNextUpdate } = await setup(undefined, { relation: { onLoad: spy, }, }); await waitForNextUpdate(); expect(spy).toBeCalledTimes(1); expect(spy).toBeCalledWith(FIXTURE_DATA); }); test('fetch relations with different limit', async () => { const { waitForNextUpdate } = await setup(undefined, { relation: { pageParams: { limit: 5 } }, }); await waitForNextUpdate(); expect(axiosInstance.get).toBeCalledWith(expect.any(String), { params: { limit: 5, page: expect.any(Number), }, }); }); test('doesn not fetch relations if a relation endpoint was not passed', async () => { await setup(undefined, { relation: { endpoint: undefined } }); expect(axiosInstance.get).not.toBeCalled(); }); test('fetch relations', async () => { const { result, waitForNextUpdate } = await setup(); await waitForNextUpdate(); expect(result.current.relations.isSuccess).toBe(true); expect(axiosInstance.get).toBeCalledTimes(1); expect(axiosInstance.get).toBeCalledWith('/', { params: { limit: 10, page: 1, }, }); }); test('fetch relations next page, if there is one', async () => { axiosInstance.get = jest.fn().mockResolvedValue({ data: { values: [], pagination: { page: 1, pageCount: 3, }, }, }); const { result, waitForNextUpdate } = await setup(undefined); await waitForNextUpdate(); act(() => { result.current.relations.fetchNextPage(); }); await waitForNextUpdate(); expect(axiosInstance.get).toBeCalledTimes(2); expect(axiosInstance.get).toHaveBeenNthCalledWith(1, expect.any(String), { params: { limit: expect.any(Number), page: 1, }, }); expect(axiosInstance.get).toHaveBeenNthCalledWith(2, expect.any(String), { params: { limit: expect.any(Number), page: 2, }, }); }); test("does not fetch relations next page, if there isn't one", async () => { axiosInstance.get = jest.fn().mockResolvedValue({ data: { values: [], pagination: { page: 1, pageCount: 1, }, }, }); const { result, waitForNextUpdate } = await setup(undefined); await waitForNextUpdate(); act(() => { result.current.relations.fetchNextPage(); }); await waitForNextUpdate(); expect(axiosInstance.get).toBeCalledTimes(1); }); test('does not fetch search by default', async () => { const { result, waitForNextUpdate } = await setup(); await waitForNextUpdate(); expect(result.current.search.isLoading).toBe(false); }); test('does fetch search results once a term was provided', async () => { const { result, waitForNextUpdate } = await setup(); await waitForNextUpdate(); const spy = jest .fn() .mockResolvedValue({ data: { values: [], pagination: { page: 1, pageCount: 2 } } }); axiosInstance.get = spy; act(() => { result.current.searchFor('something'); }); await waitForNextUpdate(); expect(spy).toBeCalledTimes(1); expect(spy).toBeCalledWith('/', { params: { q: 'something', limit: 10, page: 1 } }); }); test('does fetch search results with a different limit', async () => { const { result, waitForNextUpdate } = await setup(undefined, { search: { pageParams: { limit: 5 } }, }); await waitForNextUpdate(); const spy = jest .fn() .mockResolvedValue({ data: { values: [], pagination: { page: 1, pageCount: 2 } } }); axiosInstance.get = spy; act(() => { result.current.searchFor('something'); }); await waitForNextUpdate(); expect(spy).toBeCalledTimes(1); expect(spy).toBeCalledWith(expect.any(String), { params: { q: 'something', limit: 5, page: expect.any(Number), }, }); }); test('fetch search next page, if there is one', async () => { const { result, waitForNextUpdate } = await setup(undefined); const spy = jest .fn() .mockResolvedValue({ data: { values: [], pagination: { page: 1, pageCount: 2 } } }); axiosInstance.get = spy; act(() => { result.current.searchFor('something'); }); await waitForNextUpdate(); act(() => { result.current.search.fetchNextPage(); }); await waitForNextUpdate(); expect(spy).toBeCalledTimes(2); expect(spy).toHaveBeenNthCalledWith(1, expect.any(String), { params: { q: 'something', limit: expect.any(Number), page: 1, }, }); expect(spy).toHaveBeenNthCalledWith(2, expect.any(String), { params: { q: 'something', limit: expect.any(Number), page: 2, }, }); }); test("doesn not fetch search next page, if there isn't one", async () => { const { result, waitForNextUpdate } = await setup(undefined); const spy = jest .fn() .mockResolvedValue({ data: { values: [], pagination: { page: 1, pageCount: 1 } } }); axiosInstance.get = spy; act(() => { result.current.searchFor('something'); }); await waitForNextUpdate(); act(() => { result.current.search.fetchNextPage(); }); await waitForNextUpdate(); expect(spy).toBeCalledTimes(1); }); });
packages/core/admin/admin/src/content-manager/hooks/useRelation/tests/useRelation.test.js
1
https://github.com/strapi/strapi/commit/389a582e38a0c4369b818ec7071a049bb77b0681
[ 0.00017710126121528447, 0.00017237680731341243, 0.00016549536667298526, 0.00017377795302309096, 0.00000343386113854649 ]
{ "id": 4, "code_window": [ " searchRes.remove();\n", " setSearchParams({\n", " ...options,\n", " q: encodeURIComponent(term),\n", " });\n", " };\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " _q: encodeURIComponent(term),\n" ], "file_path": "packages/core/admin/admin/src/content-manager/hooks/useRelation/useRelation.js", "type": "replace", "edit_start_line_idx": 71 }
import React from 'react'; import { CheckPagePermissions } from '@strapi/helper-plugin'; import adminPermissions from '../../../../../permissions'; import EditView from '../EditView'; const ProtectedApiTokenCreateView = () => { return ( <CheckPagePermissions permissions={adminPermissions.settings['api-tokens'].update}> <EditView /> </CheckPagePermissions> ); }; export default ProtectedApiTokenCreateView;
packages/core/admin/admin/src/pages/SettingsPage/pages/ApiTokens/ProtectedEditView/index.js
0
https://github.com/strapi/strapi/commit/389a582e38a0c4369b818ec7071a049bb77b0681
[ 0.00017428092542104423, 0.00017380867211613804, 0.00017333641881123185, 0.00017380867211613804, 4.7225330490618944e-7 ]
{ "id": 4, "code_window": [ " searchRes.remove();\n", " setSearchParams({\n", " ...options,\n", " q: encodeURIComponent(term),\n", " });\n", " };\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " _q: encodeURIComponent(term),\n" ], "file_path": "packages/core/admin/admin/src/content-manager/hooks/useRelation/useRelation.js", "type": "replace", "edit_start_line_idx": 71 }
import React, { useCallback, useState } from 'react'; import matchSorter from 'match-sorter'; import { SettingsPageTitle, useQuery, useTracking, useFocusWhenNavigate, } from '@strapi/helper-plugin'; import Plus from '@strapi/icons/Plus'; import Trash from '@strapi/icons/Trash'; import Pencil from '@strapi/icons/Pencil'; import Duplicate from '@strapi/icons/Duplicate'; import { Button } from '@strapi/design-system/Button'; import { ContentLayout, HeaderLayout } from '@strapi/design-system/Layout'; import { Table, Tbody, Th, Thead, Tr, TFooter } from '@strapi/design-system/Table'; import { Typography } from '@strapi/design-system/Typography'; import { Main } from '@strapi/design-system/Main'; import { VisuallyHidden } from '@strapi/design-system/VisuallyHidden'; import { useIntl } from 'react-intl'; import { useHistory } from 'react-router-dom'; import RoleRow from './components/RoleRow'; import EmptyRole from './components/EmptyRole'; import UpgradePlanModal from '../../../../../components/UpgradePlanModal'; import { useRolesList } from '../../../../../hooks'; const useSortedRoles = () => { const { roles, isLoading } = useRolesList(); const query = useQuery(); const _q = decodeURIComponent(query.get('_q') || ''); const sortedRoles = matchSorter(roles, _q, { keys: ['name', 'description'] }); return { isLoading, sortedRoles }; }; const useRoleActions = () => { const { formatMessage } = useIntl(); const [isModalOpen, setIsModalOpen] = useState(false); const { trackUsage } = useTracking(); const { push } = useHistory(); const handleGoTo = useCallback( (id) => { push(`/settings/roles/${id}`); }, [push] ); const handleToggle = useCallback(() => { setIsModalOpen((prev) => !prev); }, []); const handleToggleModalForCreatingRole = useCallback(() => { trackUsage('didShowRBACUpgradeModal'); setIsModalOpen(true); }, [trackUsage]); const getIcons = useCallback( (role) => [ { onClick: handleToggle, label: formatMessage({ id: 'app.utils.duplicate', defaultMessage: 'Duplicate' }), icon: <Duplicate />, }, { onClick: () => handleGoTo(role.id), label: formatMessage({ id: 'app.utils.edit', defaultMessage: 'Edit' }), icon: <Pencil />, }, { onClick: handleToggle, label: formatMessage({ id: 'global.delete', defaultMessage: 'Delete' }), icon: <Trash />, }, ], [formatMessage, handleToggle, handleGoTo] ); return { isModalOpen, handleToggleModalForCreatingRole, handleToggle, getIcons, }; }; const RoleListPage = () => { const { formatMessage } = useIntl(); useFocusWhenNavigate(); const { sortedRoles, isLoading } = useSortedRoles(); const { isModalOpen, handleToggle, handleToggleModalForCreatingRole, getIcons } = useRoleActions(); const rowCount = sortedRoles.length + 1; const colCount = 5; // ! TODO - Add the search input return ( <Main> <SettingsPageTitle name="Roles" /> <HeaderLayout primaryAction={ <Button onClick={handleToggleModalForCreatingRole} startIcon={<Plus />} size="S"> {formatMessage({ id: 'Settings.roles.list.button.add', defaultMessage: 'Add new role', })} </Button> } title={formatMessage({ id: 'global.roles', defaultMessage: 'roles', })} subtitle={formatMessage({ id: 'Settings.roles.list.description', defaultMessage: 'List of roles', })} /> <ContentLayout> <Table colCount={colCount} rowCount={rowCount} footer={ <TFooter onClick={handleToggleModalForCreatingRole} icon={<Plus />}> {formatMessage({ id: 'Settings.roles.list.button.add', defaultMessage: 'Add new role', })} </TFooter> } > <Thead> <Tr> <Th> <Typography variant="sigma" textColor="neutral600"> {formatMessage({ id: 'global.name', defaultMessage: 'Name', })} </Typography> </Th> <Th> <Typography variant="sigma" textColor="neutral600"> {formatMessage({ id: 'global.description', defaultMessage: 'Description', })} </Typography> </Th> <Th> <Typography variant="sigma" textColor="neutral600"> {formatMessage({ id: 'global.users', defaultMessage: 'Users', })} </Typography> </Th> <Th> <VisuallyHidden> {formatMessage({ id: 'global.actions', defaultMessage: 'Actions', })} </VisuallyHidden> </Th> </Tr> </Thead> <Tbody> {sortedRoles?.map((role) => ( <RoleRow key={role.id} id={role.id} name={role.name} description={role.description} usersCount={role.usersCount} icons={getIcons(role)} /> ))} </Tbody> </Table> {!rowCount && !isLoading && <EmptyRole />} </ContentLayout> <UpgradePlanModal isOpen={isModalOpen} onClose={handleToggle} /> </Main> ); }; export default RoleListPage;
packages/core/admin/admin/src/pages/SettingsPage/pages/Roles/ListPage/index.js
0
https://github.com/strapi/strapi/commit/389a582e38a0c4369b818ec7071a049bb77b0681
[ 0.00017935311188921332, 0.0001716183905955404, 0.0001667042524786666, 0.00017170680803246796, 0.0000033357421216351213 ]
{ "id": 4, "code_window": [ " searchRes.remove();\n", " setSearchParams({\n", " ...options,\n", " q: encodeURIComponent(term),\n", " });\n", " };\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " _q: encodeURIComponent(term),\n" ], "file_path": "packages/core/admin/admin/src/content-manager/hooks/useRelation/useRelation.js", "type": "replace", "edit_start_line_idx": 71 }
# @strapi/provider-email-nodemailer ## Resources - [LICENSE](LICENSE) ## Links - [Strapi website](https://strapi.io/) - [Strapi documentation](https://docs.strapi.io) - [Strapi community on Discord](https://discord.strapi.io) - [Strapi news on Twitter](https://twitter.com/strapijs) ## Installation ```bash # using yarn yarn add @strapi/provider-email-nodemailer # using npm npm install @strapi/provider-email-nodemailer --save ``` ## Example **Path -** `config/plugins.js` ```js module.exports = ({ env }) => ({ // ... email: { config: { provider: 'nodemailer', providerOptions: { host: env('SMTP_HOST', 'smtp.example.com'), port: env('SMTP_PORT', 587), auth: { user: env('SMTP_USERNAME'), pass: env('SMTP_PASSWORD'), }, // ... any custom nodemailer options }, settings: { defaultFrom: '[email protected]', defaultReplyTo: '[email protected]', }, }, }, // ... }); ``` Check out the available options for nodemailer: https://nodemailer.com/about/ ### Development mode You can override the default configurations for specific environments. E.g. for `NODE_ENV=development` in **config/env/development/plugins.js**: ```js module.exports = ({ env }) => ({ email: { provider: 'nodemailer', providerOptions: { host: 'localhost', port: 1025, ignoreTLS: true, }, }, }); ``` The above setting is useful for local development with [maildev](https://github.com/maildev/maildev). ### Custom authentication mechanisms It is also possible to use custom authentication methods. Here is an example for a NTLM authentication: ```js const nodemailerNTLMAuth = require('nodemailer-ntlm-auth'); module.exports = ({ env }) => ({ email: { provider: 'nodemailer', providerOptions: { host: env('SMTP_HOST', 'smtp.example.com'), port: env('SMTP_PORT', 587), auth: { type: 'custom', method: 'NTLM', user: env('SMTP_USERNAME'), pass: env('SMTP_PASSWORD'), }, customAuth: { NTLM: nodemailerNTLMAuth, }, }, settings: { defaultFrom: '[email protected]', defaultReplyTo: '[email protected]', }, }, }); ``` ## Usage > :warning: The Shipper Email (or defaultfrom) may also need to be changed in the `Email Templates` tab on the admin panel for emails to send properly To send an email from anywhere inside Strapi: ```js await strapi .plugin('email') .service('email') .send({ to: '[email protected]', from: '[email protected]', subject: 'Hello world', text: 'Hello world', html: `<h4>Hello world</h4>`, }); ``` The following fields are supported: | Field | Description | | ----------- | ----------------------------------------------------------------- | | from | Email address of the sender | | to | Comma separated list or an array of recipients | | replyTo | Email address to which replies are sent | | cc | Comma separated list or an array of recipients | | bcc | Comma separated list or an array of recipients | | subject | Subject of the email | | text | Plaintext version of the message | | html | HTML version of the message | | attachments | Array of objects See: https://nodemailer.com/message/attachments/ | ## Troubleshooting Check your firewall to ensure that requests are allowed. If it doesn't work with ```js port: 465, secure: true ``` try using ```js port: 587, secure: false ``` to test if it works correctly.
packages/providers/email-nodemailer/README.md
0
https://github.com/strapi/strapi/commit/389a582e38a0c4369b818ec7071a049bb77b0681
[ 0.00017459476657677442, 0.0001700203283689916, 0.00016387483628932387, 0.00017069235036615282, 0.0000031577624213241506 ]
{ "id": 0, "code_window": [ " console.log('A new browser was registered');\n", "});\n", "\n", "//var runner = require('karma').runner; => cannot use this syntax otherwise runner is of type any\n", "karma.runner.run({port: 9876}, function(exitCode: number) {\n", " console.log('Karma has exited with ' + exitCode);\n", " process.exit(exitCode);\n", "});\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "server.on('run_complete', (browsers, results) => {\n", " results.disconnected = false;\n", " results.error = false;\n", " results.exitCode = 0;\n", " results.failed = 9;\n", " results.success = 10; \n", "});\n", "\n" ], "file_path": "karma/karma-tests.ts", "type": "add", "edit_start_line_idx": 45 }
// Type definitions for karma v0.13.9 // Project: https://github.com/karma-runner/karma // Definitions by: Tanguy Krotoff <https://github.com/tkrotoff> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// <reference path="../bluebird/bluebird.d.ts" /> /// <reference path="../node/node.d.ts" /> /// <reference path="../log4js/log4js.d.ts" /> declare module 'karma' { // See Karma public API https://karma-runner.github.io/0.13/dev/public-api.html import Promise = require('bluebird'); import https = require('https'); import log4js = require('log4js'); namespace karma { interface Karma { /** * `start` method is deprecated since 0.13. It will be removed in 0.14. * Please use * <code> * server = new Server(config, [done]) * server.start() * </code> * instead. */ server: DeprecatedServer; Server: Server; runner: Runner; launcher: Launcher; VERSION: string; } interface LauncherStatic { generateId(): string; //TODO: injector should be of type `di.Injector` new(emitter: NodeJS.EventEmitter, injector: any): Launcher; } interface Launcher { Launcher: LauncherStatic; //TODO: Can this return value ever be typified? launch(names: string[], protocol: string, hostname: string, port: number, urlRoot: string): any[]; kill(id: string, callback: Function): boolean; restart(id: string): boolean; killAll(callback: Function): void; areAllCaptured(): boolean; markCaptured(id: string): void; } interface DeprecatedServer { start(options?: any, callback?: ServerCallback): void; } interface Runner { run(options?: ConfigOptions|ConfigFile, callback?: ServerCallback): void; } interface Server extends NodeJS.EventEmitter { new(options?: ConfigOptions|ConfigFile, callback?: ServerCallback): Server; /** * Start the server */ start(): void; /** * Get properties from the injector * @param token */ get(token: string): any; /** * Force a refresh of the file list */ refreshFiles(): Promise<any>; ///** // * Backward-compatibility with karma-intellij bundled with WebStorm. // * Deprecated since version 0.13, to be removed in 0.14 // */ //static start(): void; } interface ServerCallback { (exitCode: number): void; } interface Config { set: (config: ConfigOptions) => void; LOG_DISABLE: string; LOG_ERROR: string; LOG_WARN: string; LOG_INFO: string; LOG_DEBUG: string; } interface ConfigFile { configFile: string; } interface ConfigOptions { /** * @description Enable or disable watching files and executing the tests whenever one of these files changes. * @default true */ autoWatch?: boolean; /** * @description When Karma is watching the files for changes, it tries to batch multiple changes into a single run * so that the test runner doesn't try to start and restart running tests more than it should. * The configuration setting tells Karma how long to wait (in milliseconds) after any changes have occurred * before starting the test process again. * @default 250 */ autoWatchBatchDelay?: number; /** * @default '' * @description The root path location that will be used to resolve all relative paths defined in <code>files</code> and <code>exclude</code>. * If the basePath configuration is a relative path then it will be resolved to * the <code>__dirname</code> of the configuration file. */ basePath?: string; /** * @default 2000 * @description How long does Karma wait for a browser to reconnect (in ms). * <p> * With a flaky connection it is pretty common that the browser disconnects, * but the actual test execution is still running without any problems. Karma does not treat a disconnection * as immediate failure and will wait <code>browserDisconnectTimeout</code> (ms). * If the browser reconnects during that time, everything is fine. * </p> */ browserDisconnectTimeout?: number; /** * @default 0 * @description The number of disconnections tolerated. * <p> * The <code>disconnectTolerance</code> value represents the maximum number of tries a browser will attempt * in the case of a disconnection. Usually any disconnection is considered a failure, * but this option allows you to define a tolerance level when there is a flaky network link between * the Karma server and the browsers. * </p> */ browserDisconnectTolerance?: number; /** * @default 10000 * @description How long will Karma wait for a message from a browser before disconnecting from it (in ms). * <p> * If, during test execution, Karma does not receive any message from a browser within * <code>browserNoActivityTimeout</code> (ms), it will disconnect from the browser * </p> */ browserNoActivityTimeout?: number; /** * @default [] * Possible Values: * <ul> * <li>Chrome (launcher comes installed with Karma)</li> * <li>ChromeCanary (launcher comes installed with Karma)</li> * <li>PhantomJS (launcher comes installed with Karma)</li> * <li>Firefox (launcher requires karma-firefox-launcher plugin)</li> * <li>Opera (launcher requires karma-opera-launcher plugin)</li> * <li>Internet Explorer (launcher requires karma-ie-launcher plugin)</li> * <li>Safari (launcher requires karma-safari-launcher plugin)</li> * </ul> * @description A list of browsers to launch and capture. When Karma starts up, it will also start up each browser * which is placed within this setting. Once Karma is shut down, it will shut down these browsers as well. * You can capture any browser manually by opening the browser and visiting the URL where * the Karma web server is listening (by default it is <code>http://localhost:9876/</code>). */ browsers?: string[]; /** * @default 60000 * @description Timeout for capturing a browser (in ms). * <p> * The <code>captureTimeout</code> value represents the maximum boot-up time allowed for a * browser to start and connect to Karma. If any browser does not get captured within the timeout, Karma * will kill it and try to launch it again and, after three attempts to capture it, Karma will give up. * </p> */ captureTimeout?: number; client?: ClientOptions; /** * @default true * @description Enable or disable colors in the output (reporters and logs). */ colors?: boolean; /** * @default [] * @description List of files/patterns to exclude from loaded files. */ exclude?: string[]; /** * @default [] * @description List of files/patterns to load in the browser. */ files?: (FilePattern|string)[]; /** * @default [] * @description List of test frameworks you want to use. Typically, you will set this to ['jasmine'], ['mocha'] or ['qunit']... * Please note just about all frameworks in Karma require an additional plugin/framework library to be installed (via NPM). */ frameworks?: string[]; /** * @default 'localhost' * @description Hostname to be used when capturing browsers. */ hostname?: string; /** * @default {} * @description Options object to be used by Node's https class. * Object description can be found in the * [NodeJS.org API docs](https://nodejs.org/api/tls.html#tls_tls_createserver_options_secureconnectionlistener) */ httpsServerOptions?: https.ServerOptions; /** * @default config.LOG_INFO * Possible values: * <ul> * <li>config.LOG_DISABLE</li> * <li>config.LOG_ERROR</li> * <li>config.LOG_WARN</li> * <li>config.LOG_INFO</li> * <li>config.LOG_DEBUG</li> * </ul> * @description Level of logging. */ logLevel?: string; /** * @default [{type: 'console'}] * @description A list of log appenders to be used. See the documentation for [log4js] for more information. */ loggers?: log4js.AppenderConfigBase[]; /** * @default ['karma-*'] * @description List of plugins to load. A plugin can be a string (in which case it will be required * by Karma) or an inlined plugin - Object. * By default, Karma loads all sibling NPM modules which have a name starting with karma-*. * Note: Just about all plugins in Karma require an additional library to be installed (via NPM). */ plugins?: any[]; /** * @default 9876 * @description The port where the web server will be listening. */ port?: number; /** * @default {'**\/*.coffee': 'coffee'} * @description A map of preprocessors to use. * * Preprocessors can be loaded through [plugins]. * * Note: Just about all preprocessors in Karma (other than CoffeeScript and some other defaults) * require an additional library to be installed (via NPM). * * Be aware that preprocessors may be transforming the files and file types that are available at run time. For instance, * if you are using the "coverage" preprocessor on your source files, if you then attempt to interactively debug * your tests, you'll discover that your expected source code is completely changed from what you expected. Because * of that, you'll want to engineer this so that your automated builds use the coverage entry in the "reporters" list, * but your interactive debugging does not. * */ preprocessors?: { [name: string]: string|string[] } /** * @default 'http:' * Possible Values: * <ul> * <li>http:</li> * <li>https:</li> * </ul> * @description Protocol used for running the Karma webserver. * Determines the use of the Node http or https class. * Note: Using <code>'https:'</code> requires you to specify <code>httpsServerOptions</code>. */ protocol?: string; /** * @default {} * @description A map of path-proxy pairs. */ proxies?: { [path: string]: string } /** * @default true * @description Whether or not Karma or any browsers should raise an error when an inavlid SSL certificate is found. */ proxyValidateSSL?: boolean; /** * @default 0 * @description Karma will report all the tests that are slower than given time limit (in ms). * This is disabled by default (since the default value is 0). */ reportSlowerThan?: number; /** * @default ['progress'] * Possible Values: * <ul> * <li>dots</li> * <li>progress</li> * </ul> * @description A list of reporters to use. * Additional reporters, such as growl, junit, teamcity or coverage can be loaded through plugins. * Note: Just about all additional reporters in Karma (other than progress) require an additional library to be installed (via NPM). */ reporters?: string[]; /** * @default false * @description Continuous Integration mode. * If true, Karma will start and capture all configured browsers, run tests and then exit with an exit code of 0 or 1 depending * on whether all tests passed or any tests failed. */ singleRun?: boolean; /** * @default ['polling', 'websocket'] * @description An array of allowed transport methods between the browser and testing server. This configuration setting * is handed off to [socket.io](http://socket.io/) (which manages the communication * between browsers and the testing server). */ transports?: string[]; /** * @default '/' * @description The base url, where Karma runs. * All of Karma's urls get prefixed with the urlRoot. This is helpful when using proxies, as * sometimes you might want to proxy a url that is already taken by Karma. */ urlRoot?: string; } interface ClientOptions { /** * @default undefined * @description When karma run is passed additional arguments on the command-line, they * are passed through to the test adapter as karma.config.args (an array of strings). * The client.args option allows you to set this value for actions other than run. * How this value is used is up to your test adapter - you should check your adapter's * documentation to see how (and if) it uses this value. */ args?: string[]; /** * @default true * @description Run the tests inside an iFrame or a new window * If true, Karma runs the tests inside an iFrame. If false, Karma runs the tests in a new window. Some tests may not run in an * iFrame and may need a new window to run. */ useIframe?: boolean; /** * @default true * @description Capture all console output and pipe it to the terminal. */ captureConsole?: boolean; } interface FilePattern { /** * The pattern to use for matching. This property is mandatory. */ pattern: string; /** * @default true * @description If <code>autoWatch</code> is true all files that have set watched to true will be watched * for changes. */ watched?: boolean; /** * @default true * @description Should the files be included in the browser using <script> tag? Use false if you want to * load them manually, eg. using Require.js. */ included?: boolean; /** * @default true * @description Should the files be served by Karma's webserver? */ served?: boolean; /** * @default false * @description Should the files be served from disk on each request by Karma's webserver? */ nocache?: boolean; } } var karma: karma.Karma; export = karma; }
karma/karma.d.ts
1
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/b13fb549b27f069cb40346a4a835dc7c229aba8b
[ 0.06591101735830307, 0.0022036959417164326, 0.0001632469502510503, 0.00021042248408775777, 0.010371544398367405 ]
{ "id": 0, "code_window": [ " console.log('A new browser was registered');\n", "});\n", "\n", "//var runner = require('karma').runner; => cannot use this syntax otherwise runner is of type any\n", "karma.runner.run({port: 9876}, function(exitCode: number) {\n", " console.log('Karma has exited with ' + exitCode);\n", " process.exit(exitCode);\n", "});\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "server.on('run_complete', (browsers, results) => {\n", " results.disconnected = false;\n", " results.error = false;\n", " results.exitCode = 0;\n", " results.failed = 9;\n", " results.success = 10; \n", "});\n", "\n" ], "file_path": "karma/karma-tests.ts", "type": "add", "edit_start_line_idx": 45 }
// Type definitions for should.js v8.1.1 // Project: https://github.com/shouldjs/should.js // Definitions by: Alex Varju <https://github.com/varju/>, Maxime LUCE <https://github.com/SomaticIT/> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped interface Object { should: ShouldAssertion; } interface ShouldAssertion { // basic grammar a: ShouldAssertion; an: ShouldAssertion; and: ShouldAssertion; be: ShouldAssertion; has: ShouldAssertion; have: ShouldAssertion; is: ShouldAssertion; it: ShouldAssertion; with: ShouldAssertion; which: ShouldAssertion; the: ShouldAssertion; of: ShouldAssertion; not: ShouldAssertion; // validators arguments(): ShouldAssertion; empty(): ShouldAssertion; ok(): ShouldAssertion; true(): ShouldAssertion; false(): ShouldAssertion; NaN(): ShouldAssertion; Infinity(): ShouldAssertion; Array(): ShouldAssertion; Object(): ShouldAssertion; String(): ShouldAssertion; Boolean(): ShouldAssertion; Number(): ShouldAssertion; Error(): ShouldAssertion; Function(): ShouldAssertion; Date(): ShouldAssertion; Class(): ShouldAssertion; generator(): ShouldAssertion; iterable(): ShouldAssertion; iterator(): ShouldAssertion; eql(expected: any, description?: string): ShouldAssertion; equal(expected: any, description?: string): ShouldAssertion; equalOneOf(...values: any[]): ShouldAssertion; within(start: number, finish: number, description?: string): ShouldAssertion; approximately(value: number, delta: number, description?: string): ShouldAssertion; type(expected: any, description?: string): ShouldAssertion; instanceof(constructor: Function, description?: string): ShouldAssertion; above(n: number, description?: string): ShouldAssertion; below(n: number, description?: string): ShouldAssertion; aboveOrEqual(n: number, description?: string): ShouldAssertion; greaterThanOrEqual(n: number, description?: string): ShouldAssertion; belowOrEqual(n: number, description?: string): ShouldAssertion; lessThanOrEqual(n: number, description?: string): ShouldAssertion; match(other: {}, description?: string): ShouldAssertion; match(other: (val: any) => any, description?: string): ShouldAssertion; match(regexp: RegExp, description?: string): ShouldAssertion; match(other: any, description?: string): ShouldAssertion; matchEach(other: {}, description?: string): ShouldAssertion; matchEach(other: (val: any) => any, description?: string): ShouldAssertion; matchEach(regexp: RegExp, description?: string): ShouldAssertion; matchEach(other: any, description?: string): ShouldAssertion; matchAny(other: {}, description?: string): ShouldAssertion; matchAny(other: (val: any) => any, description?: string): ShouldAssertion; matchAny(regexp: RegExp, description?: string): ShouldAssertion; matchAny(other: any, description?: string): ShouldAssertion; length(n: number, description?: string): ShouldAssertion; property(name: string, description?: string): ShouldAssertion; property(name: string, val: any, description?: string): ShouldAssertion; properties(names: string[]): ShouldAssertion; properties(name: string): ShouldAssertion; properties(descriptor: any): ShouldAssertion; properties(...properties: string[]): ShouldAssertion; propertyByPath(...properties: string[]): ShouldAssertion; propertyWithDescriptor(name: string, descriptor: PropertyDescriptor): ShouldAssertion; oneOf(...values: any[]): ShouldAssertion; ownProperty(name: string, description?: string): ShouldAssertion; containEql(obj: any): ShouldAssertion; containDeep(obj: any): ShouldAssertion; containDeepOrdered(obj: any): ShouldAssertion; keys(...allKeys: string[]): ShouldAssertion; keys(allKeys: string[]): ShouldAssertion; enumerable(property: string, value?: any): ShouldAssertion; enumerables(...properties: string[]): ShouldAssertion; startWith(expected: string, message?: any): ShouldAssertion; endWith(expected: string, message?: any): ShouldAssertion; throw(message?: any): ShouldAssertion; //http header(field: string, val?: string): ShouldAssertion; status(code: number): ShouldAssertion; json(): ShouldAssertion; html(): ShouldAssertion; //stubs alwaysCalledOn(thisTarget: any): ShouldAssertion; alwaysCalledWith(...arguments: any[]): ShouldAssertion; alwaysCalledWithExactly(...arguments: any[]): ShouldAssertion; alwaysCalledWithMatch(...arguments: any[]): ShouldAssertion; alwaysCalledWithNew(): ShouldAssertion; alwaysThrew(exception?: any): ShouldAssertion; callCount(count: number): ShouldAssertion; called(): ShouldAssertion; calledOn(thisTarget: any): ShouldAssertion; calledOnce(): ShouldAssertion; calledTwice(): ShouldAssertion; calledThrice(): ShouldAssertion; calledWith(...arguments: any[]): ShouldAssertion; calledWithExactly(...arguments: any[]): ShouldAssertion; calledWithMatch(...arguments: any[]): ShouldAssertion; calledWithNew(): ShouldAssertion; neverCalledWith(...arguments: any[]): ShouldAssertion; neverCalledWithMatch(...arguments: any[]): ShouldAssertion; threw(exception?: any): ShouldAssertion; // aliases True(): ShouldAssertion; False(): ShouldAssertion; Arguments(): ShouldAssertion; class(): ShouldAssertion; deepEqual(expected: any, description?: string): ShouldAssertion; exactly(expected: any, description?: string): ShouldAssertion; instanceOf(constructor: Function, description?: string): ShouldAssertion; throwError(message?: any): ShouldAssertion; lengthOf(n: number, description?: string): ShouldAssertion; key(key: string): ShouldAssertion; hasOwnProperty(name: string, description?: string): ShouldAssertion; greaterThan(n: number, description?: string): ShouldAssertion; lessThan(n: number, description?: string): ShouldAssertion; } interface ShouldInternal { // should.js's extras exist(actual: any, msg?: string): void; exists(actual: any, msg?: string): void; not: ShouldInternal; } interface Internal extends ShouldInternal { (obj: any): ShouldAssertion; // node.js's assert functions fail(actual: any, expected: any, message: string, operator: string): void; assert(value: any, message: string): void; ok(value: any, message?: string): void; equal(actual: any, expected: any, message?: string): void; notEqual(actual: any, expected: any, message?: string): void; deepEqual(actual: any, expected: any, message?: string): void; notDeepEqual(actual: any, expected: any, message?: string): void; strictEqual(actual: any, expected: any, message?: string): void; notStrictEqual(actual: any, expected: any, message?: string): void; throws(block: any, error?: any, message?: string): void; doesNotThrow(block: any, message?: string): void; ifError(value: any): void; inspect(value: any, obj: any): any; } declare var should: Internal; declare var Should: Internal; interface Window { Should: Internal; } declare module "should" { export = should; }
should/should.d.ts
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/b13fb549b27f069cb40346a4a835dc7c229aba8b
[ 0.0006032334640622139, 0.00019793141109403223, 0.0001649386395001784, 0.00017616167315281928, 0.00009840215352596715 ]
{ "id": 0, "code_window": [ " console.log('A new browser was registered');\n", "});\n", "\n", "//var runner = require('karma').runner; => cannot use this syntax otherwise runner is of type any\n", "karma.runner.run({port: 9876}, function(exitCode: number) {\n", " console.log('Karma has exited with ' + exitCode);\n", " process.exit(exitCode);\n", "});\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "server.on('run_complete', (browsers, results) => {\n", " results.disconnected = false;\n", " results.error = false;\n", " results.exitCode = 0;\n", " results.failed = 9;\n", " results.success = 10; \n", "});\n", "\n" ], "file_path": "karma/karma-tests.ts", "type": "add", "edit_start_line_idx": 45 }
// Type definitions for open 0.4.1 // Project: https://github.com/unclechu/node-deep-extend // Definitions by: rhysd <https://github.com/rhysd> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare module 'deep-extend' { /* * Recursive object extending. */ function deepExtend<T, U>(target: T, source: U): T & U; function deepExtend<T, U, V>(target: T, source1: U, source2: V): T & U & V; function deepExtend<T, U, V, W>(target: T, source1: U, source2: V, source3: W): T & U & V & W; function deepExtend(target: any, ...sources: any[]): any; export = deepExtend; }
deep-extend/deep-extend.d.ts
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/b13fb549b27f069cb40346a4a835dc7c229aba8b
[ 0.00017559599655214697, 0.00017126354214269668, 0.00016693108773324639, 0.00017126354214269668, 0.000004332454409450293 ]
{ "id": 0, "code_window": [ " console.log('A new browser was registered');\n", "});\n", "\n", "//var runner = require('karma').runner; => cannot use this syntax otherwise runner is of type any\n", "karma.runner.run({port: 9876}, function(exitCode: number) {\n", " console.log('Karma has exited with ' + exitCode);\n", " process.exit(exitCode);\n", "});\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "server.on('run_complete', (browsers, results) => {\n", " results.disconnected = false;\n", " results.error = false;\n", " results.exitCode = 0;\n", " results.failed = 9;\n", " results.success = 10; \n", "});\n", "\n" ], "file_path": "karma/karma-tests.ts", "type": "add", "edit_start_line_idx": 45 }
// Type definitions for easy-table // Project: https://github.com/eldargab/easy-table // Definitions by: Niklas Mollenhauer <https://github.com/nikeee> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare module "easy-table" { class EasyTable { /** * String to separate columns */ public separator: string; /** * Default printer */ public static string(value: any): string; /** * Create a printer which right aligns the content by padding with `ch` on the left * * @param {String} ch * @returns {Function} */ public static leftPadder<T>(ch: string): CellPrinter<T>; public static padLeft: CellPrinter<string>; /** * Create a printer which pads with `ch` on the right * * @param {String} ch * @returns {Function} */ public static rightPadder<T>(ch: string): CellPrinter<T>; // public static padRight: CellPrinter<string>; /** * Create a printer for numbers * * Will do right alignment and optionally fix the number of digits after decimal point * * @param {Number} [digits] - Number of digits for fixpoint notation * @returns {Function} */ public static number(digits?: number): CellPrinter<number>; public constructor(); /** * Push the current row to the table and start a new one * * @returns {Table} `this` */ public newRow(): EasyTable; /** * Write cell in the current row * * @param {String} col - Column name * @param {Any} val - Cell value * @param {Function} [printer] - Printer function to format the value * @returns {Table} `this` */ public cell<T>(col: string, val: T, printer?: CellPrinter<T>): EasyTable; /** * Get list of columns in printing order * * @returns {string[]} */ public columns(): string[]; /** * Format just rows, i.e. print the table without headers and totals * * @returns {String} String representaion of the table */ public print(): string; /** * Format the table * * @returns {String} */ public toString(): string; /** * Push delimeter row to the table (with each cell filled with dashs during printing) * * @param {String[]} [cols] * @returns {Table} `this` */ public pushDelimeter(cols?: string[]): EasyTable; /** * Compute all totals and yield the results to `cb` * * @param {Function} cb - Callback function with signature `(column, value, printer)` */ public forEachTotal<T>(cb: (column: string, value: T, printer: CellPrinter<T>) => void): void; /** * Format the table so that each row represents column and each column represents row * * @param {IPrintColumnOptions} [opts] * @returns {String} */ public printTransposed<T>(opts?: PrintColumnOptions<T>): string; /** * Sort the table * * @param {Function|string[]} [cmp] - Either compare function or a list of columns to sort on * @returns {Table} `this` */ public sort(cmp?: string[]): EasyTable; /** * Sort the table * * @param {Function|string[]} [cmp] - Either compare function or a list of columns to sort on * @returns {Table} `this` */ public sort<T>(cmp?: CompareFunction<T>): EasyTable; /** * Add a total for the column * * @param {String} col - column name * @param {Object} [opts] * @returns {Table} `this` */ public total<T>(col: string, opts?: TotalOptions<T>): EasyTable; /** * Predefined helpers for totals */ public static aggr: Aggregators; /** * Print the array or object * * @param {Array|Object} obj - Object to print * @param {Function|Object} [format] - Format options * @param {Function} [cb] - Table post processing and formating * @returns {String} */ public static print<T>(obj: T | T[], format?: FormatFunction<T> | FormatObject, cb?: TablePostProcessing): string; /** * Same as `Table.print()` but yields the result to `console.log()` */ public static log<T>(obj: T | T[], format?: FormatFunction<T> | FormatObject, cb?: TablePostProcessing): void; /** * Same as `.toString()` but yields the result to `console.log()` */ public log(): void; } type CellPrinter<T> = (val: T, width: number) => string; type CompareFunction<T> = (a: T, b: T) => number; type ReduceFunction<T> = (acc: T, val: T, idx: number, length: number) => T; type FormatFunction<T> = (obj: T, cell: (name: string, val: any) => void) => void; type TablePostProcessing = (result: EasyTable) => string; interface PrintColumnOptions<T> { /** * Column separation string */ separator?: string; /** * Printer to format column names */ namePrinter?: CellPrinter<T>; } interface Aggregators { /** * Create a printer which formats the value with `printer`, * adds the `prefix` to it and right aligns the whole thing * * @param {String} prefix * @param {Function} printer * @returns {printer} */ printer<T>(prefix: string, printer: CellPrinter<T>): CellPrinter<T>; /** * Sum reduction */ sum: any; /** * Average reduction */ avg: any; } interface TotalOptions<T> { /** * reduce(acc, val, idx, length) function to compute the total value */ reduce?: ReduceFunction<T>; /** * Printer to format the total cell */ printer?: CellPrinter<T>; /** * Initial value for reduction */ init?: T; } interface FormatObject { [key: string]: ColumnFormat<any>; } interface ColumnFormat<T> { name?: string; printer?: CellPrinter<T> } export = EasyTable; }
easy-table/easy-table.d.ts
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/b13fb549b27f069cb40346a4a835dc7c229aba8b
[ 0.0010756385745480657, 0.00021206795645412058, 0.0001639306137803942, 0.0001732823729980737, 0.00018414754595141858 ]
{ "id": 1, "code_window": [ " }\n", "\n", " interface LauncherStatic {\n", " generateId(): string;\n", " //TODO: injector should be of type `di.Injector`\n", " new(emitter: NodeJS.EventEmitter, injector: any): Launcher;\n", " }\n", "\n", " interface Launcher {\n", " Launcher: LauncherStatic;\n", " //TODO: Can this return value ever be typified?\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " new (emitter: NodeJS.EventEmitter, injector: any): Launcher;\n" ], "file_path": "karma/karma.d.ts", "type": "replace", "edit_start_line_idx": 36 }
// Type definitions for karma v0.13.9 // Project: https://github.com/karma-runner/karma // Definitions by: Tanguy Krotoff <https://github.com/tkrotoff> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// <reference path="../bluebird/bluebird.d.ts" /> /// <reference path="../node/node.d.ts" /> /// <reference path="../log4js/log4js.d.ts" /> declare module 'karma' { // See Karma public API https://karma-runner.github.io/0.13/dev/public-api.html import Promise = require('bluebird'); import https = require('https'); import log4js = require('log4js'); namespace karma { interface Karma { /** * `start` method is deprecated since 0.13. It will be removed in 0.14. * Please use * <code> * server = new Server(config, [done]) * server.start() * </code> * instead. */ server: DeprecatedServer; Server: Server; runner: Runner; launcher: Launcher; VERSION: string; } interface LauncherStatic { generateId(): string; //TODO: injector should be of type `di.Injector` new(emitter: NodeJS.EventEmitter, injector: any): Launcher; } interface Launcher { Launcher: LauncherStatic; //TODO: Can this return value ever be typified? launch(names: string[], protocol: string, hostname: string, port: number, urlRoot: string): any[]; kill(id: string, callback: Function): boolean; restart(id: string): boolean; killAll(callback: Function): void; areAllCaptured(): boolean; markCaptured(id: string): void; } interface DeprecatedServer { start(options?: any, callback?: ServerCallback): void; } interface Runner { run(options?: ConfigOptions|ConfigFile, callback?: ServerCallback): void; } interface Server extends NodeJS.EventEmitter { new(options?: ConfigOptions|ConfigFile, callback?: ServerCallback): Server; /** * Start the server */ start(): void; /** * Get properties from the injector * @param token */ get(token: string): any; /** * Force a refresh of the file list */ refreshFiles(): Promise<any>; ///** // * Backward-compatibility with karma-intellij bundled with WebStorm. // * Deprecated since version 0.13, to be removed in 0.14 // */ //static start(): void; } interface ServerCallback { (exitCode: number): void; } interface Config { set: (config: ConfigOptions) => void; LOG_DISABLE: string; LOG_ERROR: string; LOG_WARN: string; LOG_INFO: string; LOG_DEBUG: string; } interface ConfigFile { configFile: string; } interface ConfigOptions { /** * @description Enable or disable watching files and executing the tests whenever one of these files changes. * @default true */ autoWatch?: boolean; /** * @description When Karma is watching the files for changes, it tries to batch multiple changes into a single run * so that the test runner doesn't try to start and restart running tests more than it should. * The configuration setting tells Karma how long to wait (in milliseconds) after any changes have occurred * before starting the test process again. * @default 250 */ autoWatchBatchDelay?: number; /** * @default '' * @description The root path location that will be used to resolve all relative paths defined in <code>files</code> and <code>exclude</code>. * If the basePath configuration is a relative path then it will be resolved to * the <code>__dirname</code> of the configuration file. */ basePath?: string; /** * @default 2000 * @description How long does Karma wait for a browser to reconnect (in ms). * <p> * With a flaky connection it is pretty common that the browser disconnects, * but the actual test execution is still running without any problems. Karma does not treat a disconnection * as immediate failure and will wait <code>browserDisconnectTimeout</code> (ms). * If the browser reconnects during that time, everything is fine. * </p> */ browserDisconnectTimeout?: number; /** * @default 0 * @description The number of disconnections tolerated. * <p> * The <code>disconnectTolerance</code> value represents the maximum number of tries a browser will attempt * in the case of a disconnection. Usually any disconnection is considered a failure, * but this option allows you to define a tolerance level when there is a flaky network link between * the Karma server and the browsers. * </p> */ browserDisconnectTolerance?: number; /** * @default 10000 * @description How long will Karma wait for a message from a browser before disconnecting from it (in ms). * <p> * If, during test execution, Karma does not receive any message from a browser within * <code>browserNoActivityTimeout</code> (ms), it will disconnect from the browser * </p> */ browserNoActivityTimeout?: number; /** * @default [] * Possible Values: * <ul> * <li>Chrome (launcher comes installed with Karma)</li> * <li>ChromeCanary (launcher comes installed with Karma)</li> * <li>PhantomJS (launcher comes installed with Karma)</li> * <li>Firefox (launcher requires karma-firefox-launcher plugin)</li> * <li>Opera (launcher requires karma-opera-launcher plugin)</li> * <li>Internet Explorer (launcher requires karma-ie-launcher plugin)</li> * <li>Safari (launcher requires karma-safari-launcher plugin)</li> * </ul> * @description A list of browsers to launch and capture. When Karma starts up, it will also start up each browser * which is placed within this setting. Once Karma is shut down, it will shut down these browsers as well. * You can capture any browser manually by opening the browser and visiting the URL where * the Karma web server is listening (by default it is <code>http://localhost:9876/</code>). */ browsers?: string[]; /** * @default 60000 * @description Timeout for capturing a browser (in ms). * <p> * The <code>captureTimeout</code> value represents the maximum boot-up time allowed for a * browser to start and connect to Karma. If any browser does not get captured within the timeout, Karma * will kill it and try to launch it again and, after three attempts to capture it, Karma will give up. * </p> */ captureTimeout?: number; client?: ClientOptions; /** * @default true * @description Enable or disable colors in the output (reporters and logs). */ colors?: boolean; /** * @default [] * @description List of files/patterns to exclude from loaded files. */ exclude?: string[]; /** * @default [] * @description List of files/patterns to load in the browser. */ files?: (FilePattern|string)[]; /** * @default [] * @description List of test frameworks you want to use. Typically, you will set this to ['jasmine'], ['mocha'] or ['qunit']... * Please note just about all frameworks in Karma require an additional plugin/framework library to be installed (via NPM). */ frameworks?: string[]; /** * @default 'localhost' * @description Hostname to be used when capturing browsers. */ hostname?: string; /** * @default {} * @description Options object to be used by Node's https class. * Object description can be found in the * [NodeJS.org API docs](https://nodejs.org/api/tls.html#tls_tls_createserver_options_secureconnectionlistener) */ httpsServerOptions?: https.ServerOptions; /** * @default config.LOG_INFO * Possible values: * <ul> * <li>config.LOG_DISABLE</li> * <li>config.LOG_ERROR</li> * <li>config.LOG_WARN</li> * <li>config.LOG_INFO</li> * <li>config.LOG_DEBUG</li> * </ul> * @description Level of logging. */ logLevel?: string; /** * @default [{type: 'console'}] * @description A list of log appenders to be used. See the documentation for [log4js] for more information. */ loggers?: log4js.AppenderConfigBase[]; /** * @default ['karma-*'] * @description List of plugins to load. A plugin can be a string (in which case it will be required * by Karma) or an inlined plugin - Object. * By default, Karma loads all sibling NPM modules which have a name starting with karma-*. * Note: Just about all plugins in Karma require an additional library to be installed (via NPM). */ plugins?: any[]; /** * @default 9876 * @description The port where the web server will be listening. */ port?: number; /** * @default {'**\/*.coffee': 'coffee'} * @description A map of preprocessors to use. * * Preprocessors can be loaded through [plugins]. * * Note: Just about all preprocessors in Karma (other than CoffeeScript and some other defaults) * require an additional library to be installed (via NPM). * * Be aware that preprocessors may be transforming the files and file types that are available at run time. For instance, * if you are using the "coverage" preprocessor on your source files, if you then attempt to interactively debug * your tests, you'll discover that your expected source code is completely changed from what you expected. Because * of that, you'll want to engineer this so that your automated builds use the coverage entry in the "reporters" list, * but your interactive debugging does not. * */ preprocessors?: { [name: string]: string|string[] } /** * @default 'http:' * Possible Values: * <ul> * <li>http:</li> * <li>https:</li> * </ul> * @description Protocol used for running the Karma webserver. * Determines the use of the Node http or https class. * Note: Using <code>'https:'</code> requires you to specify <code>httpsServerOptions</code>. */ protocol?: string; /** * @default {} * @description A map of path-proxy pairs. */ proxies?: { [path: string]: string } /** * @default true * @description Whether or not Karma or any browsers should raise an error when an inavlid SSL certificate is found. */ proxyValidateSSL?: boolean; /** * @default 0 * @description Karma will report all the tests that are slower than given time limit (in ms). * This is disabled by default (since the default value is 0). */ reportSlowerThan?: number; /** * @default ['progress'] * Possible Values: * <ul> * <li>dots</li> * <li>progress</li> * </ul> * @description A list of reporters to use. * Additional reporters, such as growl, junit, teamcity or coverage can be loaded through plugins. * Note: Just about all additional reporters in Karma (other than progress) require an additional library to be installed (via NPM). */ reporters?: string[]; /** * @default false * @description Continuous Integration mode. * If true, Karma will start and capture all configured browsers, run tests and then exit with an exit code of 0 or 1 depending * on whether all tests passed or any tests failed. */ singleRun?: boolean; /** * @default ['polling', 'websocket'] * @description An array of allowed transport methods between the browser and testing server. This configuration setting * is handed off to [socket.io](http://socket.io/) (which manages the communication * between browsers and the testing server). */ transports?: string[]; /** * @default '/' * @description The base url, where Karma runs. * All of Karma's urls get prefixed with the urlRoot. This is helpful when using proxies, as * sometimes you might want to proxy a url that is already taken by Karma. */ urlRoot?: string; } interface ClientOptions { /** * @default undefined * @description When karma run is passed additional arguments on the command-line, they * are passed through to the test adapter as karma.config.args (an array of strings). * The client.args option allows you to set this value for actions other than run. * How this value is used is up to your test adapter - you should check your adapter's * documentation to see how (and if) it uses this value. */ args?: string[]; /** * @default true * @description Run the tests inside an iFrame or a new window * If true, Karma runs the tests inside an iFrame. If false, Karma runs the tests in a new window. Some tests may not run in an * iFrame and may need a new window to run. */ useIframe?: boolean; /** * @default true * @description Capture all console output and pipe it to the terminal. */ captureConsole?: boolean; } interface FilePattern { /** * The pattern to use for matching. This property is mandatory. */ pattern: string; /** * @default true * @description If <code>autoWatch</code> is true all files that have set watched to true will be watched * for changes. */ watched?: boolean; /** * @default true * @description Should the files be included in the browser using <script> tag? Use false if you want to * load them manually, eg. using Require.js. */ included?: boolean; /** * @default true * @description Should the files be served by Karma's webserver? */ served?: boolean; /** * @default false * @description Should the files be served from disk on each request by Karma's webserver? */ nocache?: boolean; } } var karma: karma.Karma; export = karma; }
karma/karma.d.ts
1
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/b13fb549b27f069cb40346a4a835dc7c229aba8b
[ 0.9991050362586975, 0.07692015171051025, 0.0001630252954782918, 0.0001698608830338344, 0.26579734683036804 ]
{ "id": 1, "code_window": [ " }\n", "\n", " interface LauncherStatic {\n", " generateId(): string;\n", " //TODO: injector should be of type `di.Injector`\n", " new(emitter: NodeJS.EventEmitter, injector: any): Launcher;\n", " }\n", "\n", " interface Launcher {\n", " Launcher: LauncherStatic;\n", " //TODO: Can this return value ever be typified?\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " new (emitter: NodeJS.EventEmitter, injector: any): Launcher;\n" ], "file_path": "karma/karma.d.ts", "type": "replace", "edit_start_line_idx": 36 }
/// <reference path="elm.d.ts" /> // Based on https://gist.github.com/evancz/8521339 interface Elm { Shanghai: ElmModule<ShanghaiPorts>; } interface ShanghaiPorts { coordinates: PortToElm<Array<number>>; incomingShip: PortToElm<Ship>; outgoingShip: PortToElm<string>; totalCapacity: PortFromElm<number>; } interface Ship { name: string; capacity: number; } // initialize the Shanghai component which keeps track of // shipping data in and out of the Port of Shanghai. var shanghai = Elm.worker(Elm.Shanghai, { coordinates: [0, 0], incomingShip: { name: "", capacity: 0 }, outgoingShip: "" }); function logger(x: any) { console.log(x) } shanghai.ports.totalCapacity.subscribe(logger); // send some ships to the port of Shanghai shanghai.ports.incomingShip.send({ name: "Mary Mærsk", capacity: 18270 }); shanghai.ports.incomingShip.send({ name: "Emma Mærsk", capacity: 15500 }); // have those ships leave the port of Shanghai shanghai.ports.outgoingShip.send("Mary Mærsk"); shanghai.ports.outgoingShip.send("Emma Mærsk");
elm/elm-tests.ts
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/b13fb549b27f069cb40346a4a835dc7c229aba8b
[ 0.00017225524061359465, 0.00016969474381767213, 0.00016599429363850504, 0.00017093632777687162, 0.000002301177801200538 ]
{ "id": 1, "code_window": [ " }\n", "\n", " interface LauncherStatic {\n", " generateId(): string;\n", " //TODO: injector should be of type `di.Injector`\n", " new(emitter: NodeJS.EventEmitter, injector: any): Launcher;\n", " }\n", "\n", " interface Launcher {\n", " Launcher: LauncherStatic;\n", " //TODO: Can this return value ever be typified?\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " new (emitter: NodeJS.EventEmitter, injector: any): Launcher;\n" ], "file_path": "karma/karma.d.ts", "type": "replace", "edit_start_line_idx": 36 }
// Type definitions for Firebase API 2.4.1 // Project: https://www.firebase.com/docs/javascript/firebase // Definitions by: Vincent Botone <https://github.com/vbortone/>, Shin1 Kashimura <https://github.com/in-async/>, Sebastien Dubois <https://github.com/dsebastien/>, Szymon Stasik <https://github.com/ciekawy/> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped interface FirebaseAuthResult { auth: any; expires: number; } interface FirebaseDataSnapshot { /** * Returns true if this DataSnapshot contains any data. * It is slightly more efficient than using snapshot.val() !== null. */ exists(): boolean; /** * Gets the JavaScript object representation of the DataSnapshot. */ val(): any; /** * Gets a DataSnapshot for the location at the specified relative path. */ child(childPath: string): FirebaseDataSnapshot; /** * Enumerates through the DataSnapshot’s children (in the default order). */ forEach(childAction: (childSnapshot: FirebaseDataSnapshot) => void): boolean; forEach(childAction: (childSnapshot: FirebaseDataSnapshot) => boolean): boolean; /** * Returns true if the specified child exists. */ hasChild(childPath: string): boolean; /** * Returns true if the DataSnapshot has any children. */ hasChildren(): boolean; /** * Gets the key name of the location that generated this DataSnapshot. */ key(): string; /** * @deprecated Use key() instead. * Gets the key name of the location that generated this DataSnapshot. */ name(): string; /** * Gets the number of children for this DataSnapshot. */ numChildren(): number; /** * Gets the Firebase reference for the location that generated this DataSnapshot. */ ref(): Firebase; /** * Gets the priority of the data in this DataSnapshot. * @returns {string, number, null} The priority, or null if no priority was set. */ getPriority(): any; // string or number /** * Exports the entire contents of the DataSnapshot as a JavaScript object. */ exportVal(): Object; } interface FirebaseOnDisconnect { /** * Ensures the data at this location is set to the specified value when the client is disconnected * (due to closing the browser, navigating to a new page, or network issues). */ set(value: any, onComplete: (error: any) => void): void; set(value: any): Promise<void>; /** * Ensures the data at this location is set to the specified value and priority when the client is disconnected * (due to closing the browser, navigating to a new page, or network issues). */ setWithPriority(value: any, priority: string|number, onComplete: (error: any) => void): void; setWithPriority(value: any, priority: string|number): Promise<void>; /** * Writes the enumerated children at this Firebase location when the client is disconnected * (due to closing the browser, navigating to a new page, or network issues). */ update(value: Object, onComplete: (error: any) => void): void; update(value: Object): Promise<void>; /** * Ensures the data at this location is deleted when the client is disconnected * (due to closing the browser, navigating to a new page, or network issues). */ remove(onComplete: (error: any) => void): void; remove(): Promise<void>; /** * Cancels all previously queued onDisconnect() set or update events for this location and all children. */ cancel(onComplete: (error: any) => void): void; cancel(): Promise<void>; } interface FirebaseQuery { /** * Listens for data changes at a particular location. */ on(eventType: string, callback: (dataSnapshot: FirebaseDataSnapshot, prevChildName?: string) => void, cancelCallback?: (error: any) => void, context?: Object): (dataSnapshot: FirebaseDataSnapshot, prevChildName?: string) => void; /** * Detaches a callback previously attached with on(). */ off(eventType?: string, callback?: (dataSnapshot: FirebaseDataSnapshot, prevChildName?: string) => void, context?: Object): void; /** * Listens for exactly one event of the specified event type, and then stops listening. */ once(eventType: string, successCallback: (dataSnapshot: FirebaseDataSnapshot) => void, context?: Object): void; once(eventType: string, successCallback: (dataSnapshot: FirebaseDataSnapshot) => void, failureCallback?: (error: any) => void, context?: Object): void; once(eventType: string): Promise<FirebaseDataSnapshot> /** * Generates a new Query object ordered by the specified child key. */ orderByChild(key: string): FirebaseQuery; /** * Generates a new Query object ordered by key name. */ orderByKey(): FirebaseQuery; /** * Generates a new Query object ordered by child values. */ orderByValue(): FirebaseQuery; /** * Generates a new Query object ordered by priority. */ orderByPriority(): FirebaseQuery; /** * @deprecated Use limitToFirst() and limitToLast() instead. * Generates a new Query object limited to the specified number of children. */ limit(limit: number): FirebaseQuery; /** * Creates a Query with the specified starting point. * The generated Query includes children which match the specified starting point. */ startAt(value: string, key?: string): FirebaseQuery; startAt(value: number, key?: string): FirebaseQuery; /** * Creates a Query with the specified ending point. * The generated Query includes children which match the specified ending point. */ endAt(value: string, key?: string): FirebaseQuery; endAt(value: number, key?: string): FirebaseQuery; /** * Creates a Query which includes children which match the specified value. */ equalTo(value: string|number|boolean, key?: string): FirebaseQuery; /** * Generates a new Query object limited to the first certain number of children. */ limitToFirst(limit: number): FirebaseQuery; /** * Generates a new Query object limited to the last certain number of children. */ limitToLast(limit: number): FirebaseQuery; /** * Gets a Firebase reference to the Query's location. */ ref(): Firebase; } interface Firebase extends FirebaseQuery { /** * @deprecated Use authWithCustomToken() instead. * Authenticates a Firebase client using the provided authentication token or Firebase Secret. */ auth(authToken: string, onComplete: (error: any, result: FirebaseAuthResult) => void, onCancel?:(error: any) => void): void; auth(authToken: string): Promise<FirebaseAuthResult>; /** * Authenticates a Firebase client using an authentication token or Firebase Secret. */ authWithCustomToken(autoToken: string, onComplete: (error: any, authData: FirebaseAuthData) => void, options?:Object): void; authWithCustomToken(autoToken: string, options?:Object): Promise<FirebaseAuthData>; /** * Authenticates a Firebase client using a new, temporary guest account. */ authAnonymously(onComplete: (error: any, authData: FirebaseAuthData) => void, options?: Object): void; authAnonymously(options?: Object): Promise<FirebaseAuthData>; /** * Authenticates a Firebase client using an email / password combination. */ authWithPassword(credentials: FirebaseCredentials, onComplete: (error: any, authData: FirebaseAuthData) => void, options?: Object): void; authWithPassword(credentials: FirebaseCredentials, options?: Object): Promise<FirebaseAuthData>; /** * Authenticates a Firebase client using a popup-based OAuth flow. */ authWithOAuthPopup(provider: string, onComplete:(error: any, authData: FirebaseAuthData) => void, options?: Object): void; authWithOAuthPopup(provider: string, options?: Object): Promise<FirebaseAuthData>; /** * Authenticates a Firebase client using a redirect-based OAuth flow. */ authWithOAuthRedirect(provider: string, onComplete: (error: any) => void, options?: Object): void; authWithOAuthRedirect(provider: string, options?: Object): Promise<void>; /** * Authenticates a Firebase client using OAuth access tokens or credentials. */ authWithOAuthToken(provider: string, credentials: string|Object, onComplete: (error: any, authData: FirebaseAuthData) => void, options?: Object): void; authWithOAuthToken(provider: string, credentials: string|Object, options?: Object): Promise<FirebaseAuthData>; /** * Synchronously access the current authentication state of the client. */ getAuth(): FirebaseAuthData; /** * Listen for changes to the client's authentication state. */ onAuth(onComplete: (authData: FirebaseAuthData) => void, context?: Object): void; /** * Detaches a callback previously attached with onAuth(). */ offAuth(onComplete: (authData: FirebaseAuthData) => void, context?: Object): void; /** * Unauthenticates a Firebase client. */ unauth(): void; /** * Gets a Firebase reference for the location at the specified relative path. */ child(childPath: string): Firebase; /** * Gets a Firebase reference to the parent location. */ parent(): Firebase; /** * Gets a Firebase reference to the root of the Firebase. */ root(): Firebase; /** * Returns the last token in a Firebase location. */ key(): string; /** * @deprecated Use key() instead. * Returns the last token in a Firebase location. */ name(): string; /** * Gets the absolute URL corresponding to this Firebase reference's location. */ toString(): string; /** * Writes data to this Firebase location. */ set(value: any, onComplete: (error: any) => void): void; set(value: any): Promise<void>; /** * Writes the enumerated children to this Firebase location. */ update(value: Object, onComplete: (error: any) => void): void; update(value: Object): Promise<void>; /** * Removes the data at this Firebase location. */ remove(onComplete: (error: any) => void): void; remove(): Promise<void>; /** * Generates a new child location using a unique name and returns a Firebase reference to it. * @returns {Firebase} A Firebase reference for the generated location. */ push(value?: any, onComplete?: (error: any) => void): FirebaseWithPromise<void>; /** * Writes data to this Firebase location. Like set() but also specifies the priority for that data. */ setWithPriority(value: any, priority: string|number, onComplete: (error: any) => void): void; setWithPriority(value: any, priority: string|number): Promise<void>; /** * Sets a priority for the data at this Firebase location. */ setPriority(priority: string|number, onComplete: (error: any) => void): void; setPriority(priority: string|number): Promise<void>; /** * Atomically modifies the data at this location. */ transaction(updateFunction: (currentData: any)=> any, onComplete?: (error: any, committed: boolean, snapshot: FirebaseDataSnapshot) => void, applyLocally?: boolean): void; /** * Creates a new user account using an email / password combination. */ createUser(credentials: FirebaseCredentials, onComplete: (error: any, userData: any) => void): void; /** * Updates the email associated with an email / password user account. */ changeEmail(credentials: FirebaseChangeEmailCredentials, onComplete: (error: any) => void): void; /** * Change the password of an existing user using an email / password combination. */ changePassword(credentials: FirebaseChangePasswordCredentials, onComplete: (error: any) => void): void; /** * Removes an existing user account using an email / password combination. */ removeUser(credentials: FirebaseCredentials, onComplete: (error: any) => void): void; /** * Sends a password-reset email to the owner of the account, containing a token that may be used to authenticate and change the user password. */ resetPassword(credentials: FirebaseResetPasswordCredentials, onComplete: (error: any) => void): void; onDisconnect(): FirebaseOnDisconnect; } interface FirebaseWithPromise<T> extends Firebase, Promise<T> {} interface FirebaseStatic { /** * Constructs a new Firebase reference from a full Firebase URL. */ new (firebaseURL: string): Firebase; /** * Manually disconnects the Firebase client from the server and disables automatic reconnection. */ goOffline(): void; /** * Manually reestablishes a connection to the Firebase server and enables automatic reconnection. */ goOnline(): void; ServerValue: { /** * A placeholder value for auto-populating the current timestamp * (time since the Unix epoch, in milliseconds) by the Firebase servers. */ TIMESTAMP: any; }; } declare var Firebase: FirebaseStatic; declare module 'firebase' { export = Firebase; } // Reference: https://www.firebase.com/docs/web/api/firebase/getauth.html interface FirebaseAuthData { uid: string; provider: string; token: string; expires: number; auth: Object; google?: FirebaseAuthDataGoogle; twitter?: FirebaseAuthDataTwitter; github?: FirebaseAuthDataGithub; facebook?: FirebaseAuthDataFacebook; password?: FirebaseAuthDataPassword; anonymous?: any; } interface FirebaseAuthDataPassword{ email: string; isTemporaryPassword: boolean; profileImageURL: string; } interface FirebaseAuthDataTwitter{ id: string; accessToken: string; accessTokenSecret: string; displayName: string; username: string; profileImageURL: string; cachedUserProfile: any; } interface FirebaseAuthDataGithub{ id: string; accessToken: string; displayName: string; email?: string; username: string; profileImageURL: string; cachedUserProfile: any; } interface FirebaseAuthDataFacebook{ id: string; accessToken: string; displayName: string; email?: string; profileImageURL: string; cachedUserProfile: any; } interface FirebaseAuthDataGoogle { accessToken: string; cachedUserProfile: FirebaseAuthDataGoogleCachedUserProfile; displayName: string; email?: string; id: string; profileImageURL: string; } interface FirebaseAuthDataGoogleCachedUserProfile { "family name"?: string; gender?: string; "given name"?: string; id?: string; link?: string; locale?: string; name?: string; picture?: string; } interface FirebaseCredentials { email: string; password: string; } interface FirebaseChangePasswordCredentials { email: string; oldPassword: string; newPassword: string; } interface FirebaseChangeEmailCredentials { oldEmail: string; newEmail: string; password: string; } interface FirebaseResetPasswordCredentials { email: string; }
firebase/firebase.d.ts
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/b13fb549b27f069cb40346a4a835dc7c229aba8b
[ 0.001371979247778654, 0.0002005121932597831, 0.00016068700642790645, 0.00017014710465446115, 0.00018352751794736832 ]
{ "id": 1, "code_window": [ " }\n", "\n", " interface LauncherStatic {\n", " generateId(): string;\n", " //TODO: injector should be of type `di.Injector`\n", " new(emitter: NodeJS.EventEmitter, injector: any): Launcher;\n", " }\n", "\n", " interface Launcher {\n", " Launcher: LauncherStatic;\n", " //TODO: Can this return value ever be typified?\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " new (emitter: NodeJS.EventEmitter, injector: any): Launcher;\n" ], "file_path": "karma/karma.d.ts", "type": "replace", "edit_start_line_idx": 36 }
// Type definitions for sanitize-filename v1.1.1 // Project: https://github.com/parshap/node-sanitize-filename // Definitions by: Wim Looman <https://github.com/Nemo157> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare module "sanitize-filename" { function sanitize(filename: string, options?: sanitize.Options): string; namespace sanitize { interface Options { replacement: string; } } export = sanitize; }
sanitize-filename/sanitize-filename.d.ts
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/b13fb549b27f069cb40346a4a835dc7c229aba8b
[ 0.00017006915004458278, 0.00016944260278251022, 0.00016881605552043766, 0.00016944260278251022, 6.265472620725632e-7 ]
{ "id": 2, "code_window": [ " }\n", "\n", " interface Runner {\n", " run(options?: ConfigOptions|ConfigFile, callback?: ServerCallback): void;\n", " }\n", "\n", " interface Server extends NodeJS.EventEmitter {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " run(options?: ConfigOptions | ConfigFile, callback?: ServerCallback): void;\n", " }\n", "\n", " interface TestResults {\n", " disconnected: boolean;\n", " error: boolean;\n", " exitCode: number;\n", " failed: number;\n", " success: number;\n" ], "file_path": "karma/karma.d.ts", "type": "replace", "edit_start_line_idx": 55 }
// Type definitions for karma v0.13.9 // Project: https://github.com/karma-runner/karma // Definitions by: Tanguy Krotoff <https://github.com/tkrotoff> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// <reference path="../bluebird/bluebird.d.ts" /> /// <reference path="../node/node.d.ts" /> /// <reference path="../log4js/log4js.d.ts" /> declare module 'karma' { // See Karma public API https://karma-runner.github.io/0.13/dev/public-api.html import Promise = require('bluebird'); import https = require('https'); import log4js = require('log4js'); namespace karma { interface Karma { /** * `start` method is deprecated since 0.13. It will be removed in 0.14. * Please use * <code> * server = new Server(config, [done]) * server.start() * </code> * instead. */ server: DeprecatedServer; Server: Server; runner: Runner; launcher: Launcher; VERSION: string; } interface LauncherStatic { generateId(): string; //TODO: injector should be of type `di.Injector` new(emitter: NodeJS.EventEmitter, injector: any): Launcher; } interface Launcher { Launcher: LauncherStatic; //TODO: Can this return value ever be typified? launch(names: string[], protocol: string, hostname: string, port: number, urlRoot: string): any[]; kill(id: string, callback: Function): boolean; restart(id: string): boolean; killAll(callback: Function): void; areAllCaptured(): boolean; markCaptured(id: string): void; } interface DeprecatedServer { start(options?: any, callback?: ServerCallback): void; } interface Runner { run(options?: ConfigOptions|ConfigFile, callback?: ServerCallback): void; } interface Server extends NodeJS.EventEmitter { new(options?: ConfigOptions|ConfigFile, callback?: ServerCallback): Server; /** * Start the server */ start(): void; /** * Get properties from the injector * @param token */ get(token: string): any; /** * Force a refresh of the file list */ refreshFiles(): Promise<any>; ///** // * Backward-compatibility with karma-intellij bundled with WebStorm. // * Deprecated since version 0.13, to be removed in 0.14 // */ //static start(): void; } interface ServerCallback { (exitCode: number): void; } interface Config { set: (config: ConfigOptions) => void; LOG_DISABLE: string; LOG_ERROR: string; LOG_WARN: string; LOG_INFO: string; LOG_DEBUG: string; } interface ConfigFile { configFile: string; } interface ConfigOptions { /** * @description Enable or disable watching files and executing the tests whenever one of these files changes. * @default true */ autoWatch?: boolean; /** * @description When Karma is watching the files for changes, it tries to batch multiple changes into a single run * so that the test runner doesn't try to start and restart running tests more than it should. * The configuration setting tells Karma how long to wait (in milliseconds) after any changes have occurred * before starting the test process again. * @default 250 */ autoWatchBatchDelay?: number; /** * @default '' * @description The root path location that will be used to resolve all relative paths defined in <code>files</code> and <code>exclude</code>. * If the basePath configuration is a relative path then it will be resolved to * the <code>__dirname</code> of the configuration file. */ basePath?: string; /** * @default 2000 * @description How long does Karma wait for a browser to reconnect (in ms). * <p> * With a flaky connection it is pretty common that the browser disconnects, * but the actual test execution is still running without any problems. Karma does not treat a disconnection * as immediate failure and will wait <code>browserDisconnectTimeout</code> (ms). * If the browser reconnects during that time, everything is fine. * </p> */ browserDisconnectTimeout?: number; /** * @default 0 * @description The number of disconnections tolerated. * <p> * The <code>disconnectTolerance</code> value represents the maximum number of tries a browser will attempt * in the case of a disconnection. Usually any disconnection is considered a failure, * but this option allows you to define a tolerance level when there is a flaky network link between * the Karma server and the browsers. * </p> */ browserDisconnectTolerance?: number; /** * @default 10000 * @description How long will Karma wait for a message from a browser before disconnecting from it (in ms). * <p> * If, during test execution, Karma does not receive any message from a browser within * <code>browserNoActivityTimeout</code> (ms), it will disconnect from the browser * </p> */ browserNoActivityTimeout?: number; /** * @default [] * Possible Values: * <ul> * <li>Chrome (launcher comes installed with Karma)</li> * <li>ChromeCanary (launcher comes installed with Karma)</li> * <li>PhantomJS (launcher comes installed with Karma)</li> * <li>Firefox (launcher requires karma-firefox-launcher plugin)</li> * <li>Opera (launcher requires karma-opera-launcher plugin)</li> * <li>Internet Explorer (launcher requires karma-ie-launcher plugin)</li> * <li>Safari (launcher requires karma-safari-launcher plugin)</li> * </ul> * @description A list of browsers to launch and capture. When Karma starts up, it will also start up each browser * which is placed within this setting. Once Karma is shut down, it will shut down these browsers as well. * You can capture any browser manually by opening the browser and visiting the URL where * the Karma web server is listening (by default it is <code>http://localhost:9876/</code>). */ browsers?: string[]; /** * @default 60000 * @description Timeout for capturing a browser (in ms). * <p> * The <code>captureTimeout</code> value represents the maximum boot-up time allowed for a * browser to start and connect to Karma. If any browser does not get captured within the timeout, Karma * will kill it and try to launch it again and, after three attempts to capture it, Karma will give up. * </p> */ captureTimeout?: number; client?: ClientOptions; /** * @default true * @description Enable or disable colors in the output (reporters and logs). */ colors?: boolean; /** * @default [] * @description List of files/patterns to exclude from loaded files. */ exclude?: string[]; /** * @default [] * @description List of files/patterns to load in the browser. */ files?: (FilePattern|string)[]; /** * @default [] * @description List of test frameworks you want to use. Typically, you will set this to ['jasmine'], ['mocha'] or ['qunit']... * Please note just about all frameworks in Karma require an additional plugin/framework library to be installed (via NPM). */ frameworks?: string[]; /** * @default 'localhost' * @description Hostname to be used when capturing browsers. */ hostname?: string; /** * @default {} * @description Options object to be used by Node's https class. * Object description can be found in the * [NodeJS.org API docs](https://nodejs.org/api/tls.html#tls_tls_createserver_options_secureconnectionlistener) */ httpsServerOptions?: https.ServerOptions; /** * @default config.LOG_INFO * Possible values: * <ul> * <li>config.LOG_DISABLE</li> * <li>config.LOG_ERROR</li> * <li>config.LOG_WARN</li> * <li>config.LOG_INFO</li> * <li>config.LOG_DEBUG</li> * </ul> * @description Level of logging. */ logLevel?: string; /** * @default [{type: 'console'}] * @description A list of log appenders to be used. See the documentation for [log4js] for more information. */ loggers?: log4js.AppenderConfigBase[]; /** * @default ['karma-*'] * @description List of plugins to load. A plugin can be a string (in which case it will be required * by Karma) or an inlined plugin - Object. * By default, Karma loads all sibling NPM modules which have a name starting with karma-*. * Note: Just about all plugins in Karma require an additional library to be installed (via NPM). */ plugins?: any[]; /** * @default 9876 * @description The port where the web server will be listening. */ port?: number; /** * @default {'**\/*.coffee': 'coffee'} * @description A map of preprocessors to use. * * Preprocessors can be loaded through [plugins]. * * Note: Just about all preprocessors in Karma (other than CoffeeScript and some other defaults) * require an additional library to be installed (via NPM). * * Be aware that preprocessors may be transforming the files and file types that are available at run time. For instance, * if you are using the "coverage" preprocessor on your source files, if you then attempt to interactively debug * your tests, you'll discover that your expected source code is completely changed from what you expected. Because * of that, you'll want to engineer this so that your automated builds use the coverage entry in the "reporters" list, * but your interactive debugging does not. * */ preprocessors?: { [name: string]: string|string[] } /** * @default 'http:' * Possible Values: * <ul> * <li>http:</li> * <li>https:</li> * </ul> * @description Protocol used for running the Karma webserver. * Determines the use of the Node http or https class. * Note: Using <code>'https:'</code> requires you to specify <code>httpsServerOptions</code>. */ protocol?: string; /** * @default {} * @description A map of path-proxy pairs. */ proxies?: { [path: string]: string } /** * @default true * @description Whether or not Karma or any browsers should raise an error when an inavlid SSL certificate is found. */ proxyValidateSSL?: boolean; /** * @default 0 * @description Karma will report all the tests that are slower than given time limit (in ms). * This is disabled by default (since the default value is 0). */ reportSlowerThan?: number; /** * @default ['progress'] * Possible Values: * <ul> * <li>dots</li> * <li>progress</li> * </ul> * @description A list of reporters to use. * Additional reporters, such as growl, junit, teamcity or coverage can be loaded through plugins. * Note: Just about all additional reporters in Karma (other than progress) require an additional library to be installed (via NPM). */ reporters?: string[]; /** * @default false * @description Continuous Integration mode. * If true, Karma will start and capture all configured browsers, run tests and then exit with an exit code of 0 or 1 depending * on whether all tests passed or any tests failed. */ singleRun?: boolean; /** * @default ['polling', 'websocket'] * @description An array of allowed transport methods between the browser and testing server. This configuration setting * is handed off to [socket.io](http://socket.io/) (which manages the communication * between browsers and the testing server). */ transports?: string[]; /** * @default '/' * @description The base url, where Karma runs. * All of Karma's urls get prefixed with the urlRoot. This is helpful when using proxies, as * sometimes you might want to proxy a url that is already taken by Karma. */ urlRoot?: string; } interface ClientOptions { /** * @default undefined * @description When karma run is passed additional arguments on the command-line, they * are passed through to the test adapter as karma.config.args (an array of strings). * The client.args option allows you to set this value for actions other than run. * How this value is used is up to your test adapter - you should check your adapter's * documentation to see how (and if) it uses this value. */ args?: string[]; /** * @default true * @description Run the tests inside an iFrame or a new window * If true, Karma runs the tests inside an iFrame. If false, Karma runs the tests in a new window. Some tests may not run in an * iFrame and may need a new window to run. */ useIframe?: boolean; /** * @default true * @description Capture all console output and pipe it to the terminal. */ captureConsole?: boolean; } interface FilePattern { /** * The pattern to use for matching. This property is mandatory. */ pattern: string; /** * @default true * @description If <code>autoWatch</code> is true all files that have set watched to true will be watched * for changes. */ watched?: boolean; /** * @default true * @description Should the files be included in the browser using <script> tag? Use false if you want to * load them manually, eg. using Require.js. */ included?: boolean; /** * @default true * @description Should the files be served by Karma's webserver? */ served?: boolean; /** * @default false * @description Should the files be served from disk on each request by Karma's webserver? */ nocache?: boolean; } } var karma: karma.Karma; export = karma; }
karma/karma.d.ts
1
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/b13fb549b27f069cb40346a4a835dc7c229aba8b
[ 0.9986529350280762, 0.05235954374074936, 0.00016264471923932433, 0.0001734088291414082, 0.2196779102087021 ]
{ "id": 2, "code_window": [ " }\n", "\n", " interface Runner {\n", " run(options?: ConfigOptions|ConfigFile, callback?: ServerCallback): void;\n", " }\n", "\n", " interface Server extends NodeJS.EventEmitter {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " run(options?: ConfigOptions | ConfigFile, callback?: ServerCallback): void;\n", " }\n", "\n", " interface TestResults {\n", " disconnected: boolean;\n", " error: boolean;\n", " exitCode: number;\n", " failed: number;\n", " success: number;\n" ], "file_path": "karma/karma.d.ts", "type": "replace", "edit_start_line_idx": 55 }
/// <reference path="gruntjs.d.ts" /> // Official code sample from // http://gruntjs.com/getting-started#an-example-gruntfile interface MyTaskData { repeat: number; } interface MyOptions { sourceRoot: string; } // exports should work same as module.exports exports = (grunt: IGrunt) => { // Project configuration. grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), uglify: { options: { banner: '/*! <%= pkg.name %> <%= grunt.template.today("yyyy-mm-dd") %> */\n' }, build: { src: 'src/<%= pkg.name %>.js', dest: 'build/<%= pkg.name %>.min.js' } } }); // Load the plugin that provides the "uglify" task. grunt.loadNpmTasks('grunt-contrib-uglify'); // Default task(s). grunt.registerTask('default', ['uglify']); grunt.registerMultiTask('mytask', "short description", function() { var currenttask: grunt.task.IMultiTask<MyTaskData> = this; var options = currenttask.options<MyOptions>({ sourceRoot: "default" }); var valid = false; valid = valid && options.sourceRoot === "default"; valid = valid && currenttask.data.repeat > 0; var done = this.async(); done(); }); grunt.registerMultiTask('task-1', "", function() { var done = this.async(); done(new Error('nope')); }); grunt.registerMultiTask('task-2', "", function() { var done = this.async(); done(false); }); // util methods var testOneArg = (a: number) => a * 2; var asyncedOneArg = grunt.util.callbackify(testOneArg); asyncedOneArg(1, (result: number) => { console.log(result); }); var testTwoArgs = (a: number, b: string) => "it works with " + a + " " + b; var asyncedTwoArgs = grunt.util.callbackify(testTwoArgs); asyncedTwoArgs(2, "values", (result: string) => { console.log(result); }); // tests for module grunt.file var expandedFilesConfig: grunt.file.IExpandedFilesConfig = { expand: true, cwd: 'src', src: ['**/*.ts'], dest: 'build', ext: '.js', flatten: false }; var fileMaps = grunt.file.expandMapping([''], '', expandedFilesConfig); fileMaps.length; fileMaps[0].src.length; fileMaps[0].dest; }; // Official grunt task template from // https://github.com/gruntjs/grunt-init-gruntplugin/blob/master/root/tasks/name.js exports.exports = function(grunt: IGrunt) { // Please see the Grunt documentation for more information regarding task // creation: http://gruntjs.com/creating-tasks grunt.registerMultiTask('taskName', 'task description', function() { // Merge task-specific and/or target-specific options with these defaults. var options = this.options({ punctuation: '.', separator: ', ' }); // Iterate over all specified file groups. this.files.forEach(function(f: grunt.file.IFilesConfig) { // Concat specified files. var src = f.src.filter(function(filepath: string) { // Warn on and remove invalid source files (if nonull was set). if (!grunt.file.exists(filepath)) { grunt.log.warn('Source file "' + filepath + '" not found.'); return false; } else { return true; } }).map(function(filepath) { // Read file source. return grunt.file.read(filepath); }).join(grunt.util.normalizelf(options.separator)); // Handle options. src += options.punctuation; // Write the destination file. grunt.file.write(f.dest, src); // Print a success message. grunt.log.writeln('File "' + f.dest + '" created.'); }); }); };
gruntjs/gruntjs-tests.ts
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/b13fb549b27f069cb40346a4a835dc7c229aba8b
[ 0.00023433036403730512, 0.00018070924852509052, 0.00016452818817924708, 0.00017257074068766087, 0.00002275971564813517 ]
{ "id": 2, "code_window": [ " }\n", "\n", " interface Runner {\n", " run(options?: ConfigOptions|ConfigFile, callback?: ServerCallback): void;\n", " }\n", "\n", " interface Server extends NodeJS.EventEmitter {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " run(options?: ConfigOptions | ConfigFile, callback?: ServerCallback): void;\n", " }\n", "\n", " interface TestResults {\n", " disconnected: boolean;\n", " error: boolean;\n", " exitCode: number;\n", " failed: number;\n", " success: number;\n" ], "file_path": "karma/karma.d.ts", "type": "replace", "edit_start_line_idx": 55 }
/// <reference path="./redux-saga.d.ts" /> import sagaMiddleware, { storeIO, runSaga, Saga, SagaCancellationException, takeEvery, takeLatest, isCancelError } from 'redux-saga' import { take, put, race, call, apply, fork, select, cancel, } from 'redux-saga/effects' import {applyMiddleware, createStore} from 'redux'; declare const delay: (ms: number) => Promise<any>; declare const fetchApi: (url: string) => Promise<any>; namespace GettingStarted { const incrementAsync:Saga = function* incrementAsync() { while(true) { // wait for each INCREMENT_ASYNC action const nextAction = yield take('INCREMENT_ASYNC') // delay is a sample function // return a Promise that resolves after (ms) milliseconds yield delay(1000) // dispatch INCREMENT_COUNTER yield put( {type: 'INCREMENT_COUNTER'} ) } } const createStoreWithSaga = applyMiddleware( // ..., sagaMiddleware(incrementAsync) )(createStore) export default function configureStore(initialState) { return createStoreWithSaga((state: any) => state, initialState) } } namespace EffectCombinators { const fetchPostsWithTimeout:Saga = function* fetchPostsWithTimeout() { while( yield take('FETCH_POSTS') ) { // starts a race between 2 effects const {posts, timeout} = yield race({ posts : call([this, fetchApi], '/posts'), timeout : call(delay, 1000) }) if(posts) put( {type: 'RECEIVE_POSTS', posts} ) else put( {type: 'TIMEOUT_ERROR'} ) } } } namespace SequencingSagasViaYield { function showScore(score) { return { type: 'SHOW_SCORE', score } } function* playLevelOne(getState) { yield 1 } function* playLevelTwo(getState) { yield 2 } function* playLevelThree(getState) { yield 3 } const game: Saga = function* game(getState) { const score1 = yield* playLevelOne(getState) yield put(showScore(score1)) const score2 = yield* playLevelTwo(getState) yield put(showScore(score2)) const score3 = yield* playLevelThree(getState) yield put(showScore(score3)) } } namespace ComposingSagas { function* fetchProducts() { yield put( {type: 'REQUEST_PRODUCTS'} ) const products = yield call(fetchApi, '/products') yield put( {type: 'RECEIVE_PRODUCTS', products } ) } function* watchFetch() { while ( yield take('FETCH_PRODUCTS') ) { yield call(fetchProducts) // waits for the fetchProducts task to // terminate } } } namespace NonBlockingCallsWithForkJoin { function* fetchPosts() { yield put( {type: 'REQUEST_POSTS'} ) const posts = yield call(fetchApi, '/posts') yield put( {type: 'RECEIVE_POSTS', posts} ) } function* watchFetch() { while ( yield take('FETCH_POSTS') ) { yield fork(fetchPosts) // non blocking call } } } namespace TaskCancellation { declare const someApi: () => any; function* bgSync() { try { while(true) { yield put({type: 'REQUEST_START'}) const result = yield apply(this, someApi) yield put({type: 'REQUEST_SUCCESS', result}) yield call(delay, 5000) } } catch(error) { if(error instanceof SagaCancellationException && isCancelError(error)) yield put({type: 'REQUEST_FAILURE', message: 'Sync cancelled!'}) } } function* main() { while( yield take('START_BACKGROUND_SYNC') ) { // starts the task in the background const bgSyncTask = yield fork(bgSync) // wait for the user stop action yield take('STOP_BACKGROUND_SYNC') // user clicked stop. cancel the background task // this will throw a SagaCancellationException into the forked bgSync // task yield cancel(bgSyncTask) } } } namespace DynamicallyStartingSagasWithRunSaga { const store = createStore((state: any, action: any) => state); function* serverSaga(getState) { yield getState() } runSaga( serverSaga(store.getState), storeIO(store) ) } namespace DynamicallyStartingSagasWithMiddleware { function* startupSaga() { } function* dynamicSaga() { } sagaMiddleware(startupSaga).run(dynamicSaga) } namespace TestHelpers { function* watchAndLog(getState) { yield* takeEvery('*', function* logger(action) { console.log('action', action) }) } function* fetchUser(action) { } function* watchLastFetchUser() { yield* takeLatest('USER_REQUESTED', fetchUser) } } namespace AccessCurrentState { export const getCart = state => state.cart; function* checkout() { const cart = yield select(getCart) } }
redux-saga/redux-saga-tests.ts
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/b13fb549b27f069cb40346a4a835dc7c229aba8b
[ 0.060687534511089325, 0.002931529190391302, 0.0001672192884143442, 0.00017099545220844448, 0.012603468261659145 ]
{ "id": 2, "code_window": [ " }\n", "\n", " interface Runner {\n", " run(options?: ConfigOptions|ConfigFile, callback?: ServerCallback): void;\n", " }\n", "\n", " interface Server extends NodeJS.EventEmitter {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " run(options?: ConfigOptions | ConfigFile, callback?: ServerCallback): void;\n", " }\n", "\n", " interface TestResults {\n", " disconnected: boolean;\n", " error: boolean;\n", " exitCode: number;\n", " failed: number;\n", " success: number;\n" ], "file_path": "karma/karma.d.ts", "type": "replace", "edit_start_line_idx": 55 }
vimeo/froogaloop.d.ts.tscparams
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/b13fb549b27f069cb40346a4a835dc7c229aba8b
[ 0.00017303851200267673, 0.00017303851200267673, 0.00017303851200267673, 0.00017303851200267673, 0 ]
{ "id": 3, "code_window": [ " }\n", "\n", " interface Server extends NodeJS.EventEmitter {\n", " new(options?: ConfigOptions|ConfigFile, callback?: ServerCallback): Server;\n", " /**\n", " * Start the server\n", " */\n", " start(): void;\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " new (options?: ConfigOptions | ConfigFile, callback?: ServerCallback): Server;\n" ], "file_path": "karma/karma.d.ts", "type": "replace", "edit_start_line_idx": 59 }
/// <reference path="karma.d.ts" /> /// <reference path="../gulp/gulp.d.ts" /> import gulp = require('gulp'); import karma = require('karma'); function runKarma(singleRun: boolean): void { // MEMO: `start` method is deprecated since 0.13. It will be removed in 0.14. karma.server.start({ configFile: __dirname + '/karma.conf.js', singleRun: singleRun }); } gulp.task('test:unit:karma', ['build:test:unit'], () => runKarma(true)); karma.server.start({port: 9876}, (exitCode: number) => { console.log('Karma has exited with ' + exitCode); process.exit(exitCode); }); karma.runner.run({port: 9876}, (exitCode: number) => { console.log('Karma has exited with ' + exitCode); process.exit(exitCode); }); //var Server = require('karma').Server; => cannot use this syntax otherwise Server is of type any var server = new karma.Server({logLevel: 'debug', port: 9876}, function(exitCode: number) { console.log('Karma has exited with ' + exitCode); process.exit(exitCode); }); server.start(); server.refreshFiles(); server.on('browser_register', function (browser: any) { console.log('A new browser was registered'); }); //var runner = require('karma').runner; => cannot use this syntax otherwise runner is of type any karma.runner.run({port: 9876}, function(exitCode: number) { console.log('Karma has exited with ' + exitCode); process.exit(exitCode); }); // var captured: boolean = karma.launcher.areAllCaptured(); // Example of configuration file karma.conf.ts, see http://karma-runner.github.io/0.13/config/configuration-file.html module.exports = function(config: karma.Config) { config.set({ logLevel: config.LOG_DEBUG, basePath: '..', urlRoot: '/base/', frameworks: ['jasmine'], files: [ 'file1.js', 'file2.js', 'file3.js', { pattern: '**/*.html', included: false } ], reporters: [ 'progress', 'coverage' ], preprocessors: { 'app.js': ['coverage'] }, port: 9876, autoWatch: true, browsers: [ 'Chrome', 'Firefox' ], singleRun: true }); };
karma/karma-tests.ts
1
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/b13fb549b27f069cb40346a4a835dc7c229aba8b
[ 0.9945456981658936, 0.2980811893939972, 0.00017001562810037285, 0.00017324878717772663, 0.45506390929222107 ]
{ "id": 3, "code_window": [ " }\n", "\n", " interface Server extends NodeJS.EventEmitter {\n", " new(options?: ConfigOptions|ConfigFile, callback?: ServerCallback): Server;\n", " /**\n", " * Start the server\n", " */\n", " start(): void;\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " new (options?: ConfigOptions | ConfigFile, callback?: ServerCallback): Server;\n" ], "file_path": "karma/karma.d.ts", "type": "replace", "edit_start_line_idx": 59 }
/// <reference path='../mocha/mocha.d.ts' /> /// <reference path='expectations.d.ts' /> // transplant from https://github.com/spmason/expectations/blob/695c25bd35bb1751533a8082a5aa378e3e1b381f/test/expect.tests.js var root = this; describe('expect', ()=> { describe('toEqual', ()=> { it('can expect true to be true', ()=> { expect(true).toEqual(true); }); it('can expect false not to be true', ()=> { try { expect(false).toEqual(true); } catch (err) { if (err.message !== 'expected false to equal true') { throw new Error('Expected error message is not correct: ' + err.message); } } }); it('can expect an object to be a different but equivalent object', ()=> { expect({abc: 123}).toEqual({abc: 123}); }); it('Ignores undefined values when comparing objects', ()=> { expect({abc: 123, def: undefined}).toEqual({abc: 123}); }); it('equates undefined values and null', ()=> { expect(undefined).toEqual(null); }); it('Can expect a more complex object to equal another complex object', ()=> { var obj1 = {"name": "someData", array: [1, 2, 3, {c: "hello"}], val2: 'ing', val1: 'test'}; var obj2 = {"name": "someData", array: [1, 2, 3, {c: "hello"}], val1: 'test', val2: 'ing'}; expect(obj1).toEqual(obj2); }); it('Can expect undefined to equal an object correctly', ()=> { try { expect(undefined).toEqual('Not undefined'); } catch (err) { if (err.message !== 'expected undefined to equal "Not undefined"') { throw new Error('Expected error message is not correct: ' + err.message); } } }); }); describe('toNotEqual', ()=> { it('can expect true to be false', ()=> { expect(true).toNotEqual(false); }); it('can expect true not to be true', ()=> { try { expect(true).toNotEqual(true); } catch (err) { if (err.message !== 'expected true not to equal true') { throw new Error('Expected error message is not correct: ' + err.message); } } }); }); describe('toBe', ()=> { var obj1 = {'abc': 123}; var obj2 = {'abc': 123}; it('can expect an object to be the same object', ()=> { expect(obj1).toBe(obj1); }); it('does not expect an object to be a different', ()=> { try { expect(obj1).toBe(obj2); } catch (err) { if (err.message !== 'expected {"abc": 123} to equal {"abc": 123}') { throw new Error('Expected error message is not correct: ' + err.message); } } }); }); describe('toMatch', ()=> { it('can expect string toMatch', ()=> { expect('abc').toMatch(/a/); }); it('can expect string to not match', ()=> { try { expect('abc').toMatch(/d/); } catch (err) { if (err.message !== 'expected "abc" to match /d/') { throw new Error('Expected error message is not correct: ' + err.message); } } }); }); describe('toBeTruthy', ()=> { it('can expect toBeTruthy when truthy', ()=> { expect('abc').toBeTruthy(); }); it('can expect toBeTruthy when falsey', ()=> { try { expect('').toBeTruthy(); } catch (err) { if (err.message !== 'expected "" to be truthy') { throw new Error('Expected error message is not correct: ' + err.message); } } }); }); describe('toContain', ()=> { it('can expect array of numbers to contain number (passing)', ()=> { expect([1, 2, 3, 4]).toContain(2); }); it('can expect array of numbers to contain number (failing)', ()=> { try { expect([1, 2, 3, 4]).toContain(5); } catch (err) { if (err.message !== 'expected [1, 2, 3, 4] to contain 5') { throw new Error('Expected error message is not correct: ' + err.message); } } }); it('can expect array of objects to contain object (passing)', ()=> { expect([ {a: 1}, {a: 2}, {a: 3}, {a: 4} ]).toContain({a: 2}); }); it('can expect array of objects to contain object (failing)', ()=> { try { expect([ {a: 1}, {a: 2}, {a: 3}, {a: 4} ]).toContain({a: 5}); } catch (err) { if (err.message !== 'expected [{"a": 1}, {"a": 2}, {"a": 3}, {"a": 4}] to contain {"a": 5}') { throw new Error('Expected error message is not correct: ' + err.message); } } }); }); describe('toBeFalsy', ()=> { it('can expect toBeFalsy when falsey', ()=> { expect('').toBeFalsy(); }); it('can expect toBeFalsy when truthy', ()=> { try { expect('abc').toBeFalsy(); } catch (err) { if (err.message !== 'expected "abc" to be falsey') { throw new Error('Expected error message is not correct: ' + err.message); } } }); }); describe('toBeGreaterThan', ()=> { it('can expect 1 toBeGreaterThan 0', ()=> { expect(1).toBeGreaterThan(0); }); it('can expect 0 toBeGreaterThan 1 throws', ()=> { try { expect(0).toBeGreaterThan(1); } catch (err) { if (err.message !== 'expected 0 to be greater than 1') { throw new Error('Expected error message is not correct: ' + err.message); } } }); }); describe('toBeLessThan', ()=> { it('can expect 0 toBeLessThan 1', ()=> { expect(0).toBeLessThan(1); }); it('can expect 1 toBeLessThan 0 throws', ()=> { try { expect(1).toBeLessThan(0); } catch (err) { if (err.message !== 'expected 1 to be less than 0') { throw new Error('Expected error message is not correct: ' + err.message); } } }); }); describe('toBeDefined', ()=> { it('can expect values toBeDefined', ()=> { expect({}).toBeDefined(); }); it('throws when expects undefined values toBeDefined', ()=> { try { expect(undefined).toBeDefined(); } catch (err) { if (err.message !== 'expected undefined to be defined') { throw new Error('Expected error message is not correct: ' + err.message); } } }); }); describe('toBeUndefined', ()=> { it('can expect undefined values toBeUndefined', ()=> { expect(undefined).toBeUndefined(); }); it('throws when expects defined values toBeUndefined', ()=> { try { expect({}).toBeUndefined(); } catch (err) { if (err.message !== 'expected {} to be undefined') { throw new Error('Expected error message is not correct: ' + err.message); } } }); }); describe('toThrow', ()=> { it('can expect functions to throw', ()=> { expect(()=> { throw new Error(''); }).toThrow(); }); it('throws when function does not throw', ()=> { var error:Error; try { expect(()=> { // All OK }).toThrow(); } catch (err) { error = err; } if (error === undefined) { throw new Error('Expected error was not thrown'); } if (error.message !== 'expected function (){} to throw an exception') { throw new Error('Expected error message is not correct: ' + error.message); } }); it('throws when toThrow is called on a non-function', ()=> { var error:Error; try { expect('bob').toThrow(); } catch (err) { error = err; } if (error === undefined) { throw new Error('Expected error was not thrown'); } if (error.message !== 'expected "bob" to be a function') { throw new Error('Expected error message is not correct: ' + error.message); } }); }); describe('toBeNull', ()=> { it('can expect values toBeNull', ()=> { expect(null).toBeNull(); }); it('throws when expects non-null values toBeNull', ()=> { try { expect('abc').toBeDefined(); } catch (err) { if (err.message !== 'expected "abc" to be null') { throw new Error('Expected error message is not correct: ' + err.message); } } }); }); describe('not', ()=> { it('negates equal', ()=> { expect(false).not.toEqual(true); }); }); describe('messages', ()=> { it('can generate correct message for objects', ()=> { try { expect({}).not.toBeDefined(); } catch (err) { if (err.message !== 'expected {} not to be defined') { throw new Error('Expected error message is not correct: ' + err.message); } } }); it('can generate correct message for arrays', ()=> { try { expect([]).not.toBeDefined(); } catch (err) { if (err.message !== 'expected [] not to be defined') { throw new Error('Expected error message is not correct: ' + err.message); } } }); it('can generate correct message for arrays of values', ()=> { try { expect([1, {abc: 'def'}]).not.toBeDefined(); } catch (err) { if (err.message !== 'expected [1, {"abc": "def"}] not to be defined') { throw new Error('Expected error message is not correct: ' + err.message); } } }); it('can generate correct message for nested arrays of values', ()=> { try { expect([1, [2]]).not.toBeDefined(); } catch (err) { if (err.message !== 'expected [1, [2]] not to be defined') { throw new Error('Expected error message is not correct: ' + err.message); } } }); it('can generate correct message for Function with custom toString()', ()=> { function Obj() { } Obj.prototype.toString = ()=> { return "testing"; }; try { expect(new (<any>Obj)()).not.toBeDefined(); } catch (err) { if (err.message !== 'expected [testing] not to be defined') { throw new Error('Expected error message is not correct: ' + err.message); } } }); it('can generate correct message for Errors', ()=> { try { expect(new Error('text')).not.toBeDefined(); } catch (err) { if (err.message !== 'expected [Error: text] not to be defined') { throw new Error('Expected error message is not correct: ' + err.message); } } }); it('can generate correct message for objects with circular references', ()=> { try { var obj:any = {abc: 'def'}; obj.obj = obj; expect(obj).not.toBeDefined(); } catch (err) { if (err.message !== 'expected {"abc": "def", "obj": {"abc": "def", "obj": [Circular]}} not to be defined') { throw new Error('Expected error message is not correct: ' + err.message); } } }); it('can generate correct message for deep objects', ()=> { var nested:any = {}, obj = { a: { b: { c: { d: nested } } } }; nested.e = obj; try { expect(obj).not.toBeDefined(); } catch (err) { if (err.message !== 'expected {"a": {"b": {"c": {"d": {"e": [object Object]}}}}} not to be defined') { throw new Error('Expected error message is not correct: ' + err.message); } } }); it('can generate correct message for deep objects with arrays', ()=> { var nested:any = {}, obj = { a: { b: { c: { d: nested } } } }; nested.e = [obj]; try { expect(obj).not.toBeDefined(); } catch (err) { if (err.message !== 'expected {"a": {"b": {"c": {"d": {"e": [[object Object]]}}}}} not to be defined') { throw new Error('Expected error message is not correct: ' + err.message); } } }); it('can generate correct message for objects with undefined values', ()=> { try { expect({a: 1, b: undefined}).toEqual({a: 1}); } catch (err) { if (err.message !== 'expected {"a": 1, "b": undefined} to equal {"a": 1}') { throw new Error('Expected error message is not correct: ' + err.message); } } }); it('can generate correct message for anonymous functions', ()=> { try { expect(()=> { }).not.toBeDefined(); } catch (err) { if (err.message !== 'expected function (){} not to be defined') { throw new Error('Expected error message is not correct: ' + err.message); } } }); it('can generate correct message for named functions', ()=> { try { expect(function name() { }).not.toBeDefined(); } catch (err) { if (err.message !== 'expected function name(){} not to be defined') { throw new Error('Expected error message is not correct: ' + err.message); } } }); it('can generate correct message for Dates', ()=> { try { expect(new Date(2012, 0, 1)).not.toBeDefined(); } catch (err) { if (err.message !== 'expected [Date Sun, 01 Jan 2012 00:00:00 GMT] not to be defined') { throw new Error('Expected error message is not correct: ' + err.message); } } }); if (root.document) { it('can generate correct message for DOM elements', ()=> { var el = root.document.createElement('div'); try { expect(el).toBeUndefined(); } catch (err) { if (err.message !== 'expected <div /> to be undefined') { throw new Error('Expected error message is not correct: ' + err.message); } } }); } }); describe('extensibility', ()=> { it('allows you to add your own assertions', ()=> { expect.addAssertion('toBeFoo', ()=> { if (this.value === 'foo') { return this.pass(); } this.fail('to be "foo"'); }); (<any>expect('foo')).toBeFoo(); }); }); });
expectations/expectations-tests.ts
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/b13fb549b27f069cb40346a4a835dc7c229aba8b
[ 0.00017745977675076574, 0.0001709852513158694, 0.00016702264838386327, 0.0001709883363218978, 0.0000024721696263441117 ]
{ "id": 3, "code_window": [ " }\n", "\n", " interface Server extends NodeJS.EventEmitter {\n", " new(options?: ConfigOptions|ConfigFile, callback?: ServerCallback): Server;\n", " /**\n", " * Start the server\n", " */\n", " start(): void;\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " new (options?: ConfigOptions | ConfigFile, callback?: ServerCallback): Server;\n" ], "file_path": "karma/karma.d.ts", "type": "replace", "edit_start_line_idx": 59 }
// Type definitions for Keypress v2.0.3 // Project: https://github.com/dmauro/Keypress/ // Definitions by: Roger Chen <https://github.com/rcchen> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // A keyboard input capturing utility in which any key can be a modifier key. declare namespace Keypress { interface ListenerDefaults { keys: string; prevent_default: boolean; prevent_repeat: boolean; is_unordered: boolean; is_counting: boolean; is_exclusive: boolean; is_solitary: boolean; is_sequence: boolean; } interface Combo { keys: string; on_keydown: (event?: KeyboardEvent, count?: number) => any; on_keyup: (event?: KeyboardEvent) => any; on_release: (event?: KeyboardEvent) => any; this: Element; prevent_default: boolean; prevent_repeat: boolean; is_unordered: boolean; is_counting: boolean; is_exclusive: boolean; is_sequence: boolean; is_solitary: boolean; } interface Listener { new(element: Element, defaults: ListenerDefaults): Listener; new(element: Element): Listener; new(): Listener; simple_combo(keys: string, on_keydown_callback: (event?: KeyboardEvent, count?: number) => any): void; counting_combo(keys: string, on_count_callback: (event?: KeyboardEvent, count?: number) => any): void; sequence_combo(keys: string, callback: (event?: KeyboardEvent, count?: number) => any): void; register_combo(combo: Combo): void; unregister_combo(combo: Combo): void; unregister_combo(keys: string): void; register_many(combos: Combo[]): void; unregister_many(combos: Combo[]): void; unregister_many(keys: string[]): void; get_registered_combos(): Combo[]; reset(): void; listen(): void; stop_listening(): void; } interface Keypress { Listener: Listener; } } interface Window { keypress: Keypress.Keypress; }
keypress/keypress.d.ts
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/b13fb549b27f069cb40346a4a835dc7c229aba8b
[ 0.0003368923789821565, 0.00020533896167762578, 0.00016899338515941054, 0.0001746568741509691, 0.00005645861165248789 ]
{ "id": 3, "code_window": [ " }\n", "\n", " interface Server extends NodeJS.EventEmitter {\n", " new(options?: ConfigOptions|ConfigFile, callback?: ServerCallback): Server;\n", " /**\n", " * Start the server\n", " */\n", " start(): void;\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " new (options?: ConfigOptions | ConfigFile, callback?: ServerCallback): Server;\n" ], "file_path": "karma/karma.d.ts", "type": "replace", "edit_start_line_idx": 59 }
// Type definitions for Hammer.js 1.1.3 // Project: http://eightmedia.github.com/hammer.js/ // Definitions by: Boris Yankov <https://github.com/borisyankov/>, Drew Noakes <https://drewnoakes.com> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// <reference path="../jquery/jquery.d.ts"/> declare var Hammer: HammerStatic; interface HammerStatic { (element: any, options?: HammerOptions): HammerInstance; VERSION: number; HAS_POINTEREVENTS: boolean; HAS_TOUCHEVENTS: boolean; UPDATE_VELOCITY_INTERVAL: number; POINTER_MOUSE: HammerPointerType; POINTER_TOUCH: HammerPointerType; POINTER_PEN: HammerPointerType; DIRECTION_UP: HammerDirectionType; DIRECTION_DOWN: HammerDirectionType; DIRECTION_LEFT: HammerDirectionType; DIRECTION_RIGH: HammerDirectionType; EVENT_START: HammerTouchEventState; EVENT_MOVE: HammerTouchEventState; EVENT_END: HammerTouchEventState; plugins: any; gestures: any; READY: boolean; } declare class HammerInstance { constructor(element: any, options?: HammerOptions); on(gesture: string, handler: (event: HammerEvent) => void): HammerInstance; off(gesture: string, handler: (event: HammerEvent) => void): HammerInstance; enable(toggle: boolean): HammerInstance; // You shouldn't normally use this internal method. Only use it when you know what you're doing! You can read the sourcecode for information about how to use this. trigger(gesture: string, eventData: HammerGestureEventData): HammerInstance; } // Gesture Options : https://github.com/EightMedia/hammer.js/wiki/Getting-Started#gesture-options interface HammerOptions { behavior?: { contentZooming?: string; tapHighlightColor?: string; touchAction?: string; touchCallout?: string; userDrag?: string; userSelect?: string; }; doubleTapDistance?: number; doubleTapInterval?: number; drag?: boolean; dragBlockHorizontal?: boolean; dragBlockVertical?: boolean; dragDistanceCorrection?: boolean; dragLockMinDistance?: number; dragLockToAxis?: boolean; dragMaxTouches?: number; dragMinDistance?: number; gesture?: boolean; hold?: boolean; holdThreshold?: number; holdTimeout?: number; preventDefault?: boolean; preventMouse?: boolean; release?: boolean; showTouches?: boolean; swipe?: boolean; swipeMaxTouches?: number; swipeMinTouches?: number; swipeVelocityX?: number; swipeVelocityY?: number; tap?: boolean; tapAlways?: boolean; tapMaxDistance?: number; tapMaxTime?: number; touch?: boolean; transform?: boolean; transformMinRotation?: number; transformMinScale?: number; } interface HammerGestureEventData { timestamp: number; target: HTMLElement; touches: HammerPoint[]; pointerType: HammerPointerType; center: HammerPoint; deltaTime: number; deltaX: number; deltaY: number; velocityX: number; velocityY: number; angle: number; interimAngle: number; direction: HammerDirectionType; interimDirection: HammerDirectionType; distance: number; scale: number; rotation: number; eventType: HammerTouchEventState; srcEvent: any; startEvent: any; stopPropagation(): void; preventDefault(): void; stopDetect(): void; } interface HammerPoint { clientX: number; clientY: number; pageX: number; pageY: number; } interface HammerEvent { type: string; gesture: HammerGestureEventData; stopPropagation(): void; preventDefault(): void; } declare enum HammerPointerType { } declare enum HammerDirectionType { } declare enum HammerTouchEventState { } interface JQuery { hammer(options?: HammerOptions): JQuery; }
hammerjs/hammerjs-1.1.3.d.ts
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/b13fb549b27f069cb40346a4a835dc7c229aba8b
[ 0.0003853236557915807, 0.00019278291438240558, 0.0001664103037910536, 0.0001725004694890231, 0.00005663746196660213 ]
{ "id": 4, "code_window": [ " * Force a refresh of the file list\n", " */\n", " refreshFiles(): Promise<any>;\n", "\n", " ///**\n", " // * Backward-compatibility with karma-intellij bundled with WebStorm.\n", " // * Deprecated since version 0.13, to be removed in 0.14\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " on(event: string, listener: Function): this;\n", " \n", " /**\n", " * Listen to the 'run_complete' event.\n", " */\n", " on(event: 'run_complete', listener: (browsers: any, results: TestResults ) => void): this;\n", "\n" ], "file_path": "karma/karma.d.ts", "type": "add", "edit_start_line_idx": 74 }
// Type definitions for karma v0.13.9 // Project: https://github.com/karma-runner/karma // Definitions by: Tanguy Krotoff <https://github.com/tkrotoff> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// <reference path="../bluebird/bluebird.d.ts" /> /// <reference path="../node/node.d.ts" /> /// <reference path="../log4js/log4js.d.ts" /> declare module 'karma' { // See Karma public API https://karma-runner.github.io/0.13/dev/public-api.html import Promise = require('bluebird'); import https = require('https'); import log4js = require('log4js'); namespace karma { interface Karma { /** * `start` method is deprecated since 0.13. It will be removed in 0.14. * Please use * <code> * server = new Server(config, [done]) * server.start() * </code> * instead. */ server: DeprecatedServer; Server: Server; runner: Runner; launcher: Launcher; VERSION: string; } interface LauncherStatic { generateId(): string; //TODO: injector should be of type `di.Injector` new(emitter: NodeJS.EventEmitter, injector: any): Launcher; } interface Launcher { Launcher: LauncherStatic; //TODO: Can this return value ever be typified? launch(names: string[], protocol: string, hostname: string, port: number, urlRoot: string): any[]; kill(id: string, callback: Function): boolean; restart(id: string): boolean; killAll(callback: Function): void; areAllCaptured(): boolean; markCaptured(id: string): void; } interface DeprecatedServer { start(options?: any, callback?: ServerCallback): void; } interface Runner { run(options?: ConfigOptions|ConfigFile, callback?: ServerCallback): void; } interface Server extends NodeJS.EventEmitter { new(options?: ConfigOptions|ConfigFile, callback?: ServerCallback): Server; /** * Start the server */ start(): void; /** * Get properties from the injector * @param token */ get(token: string): any; /** * Force a refresh of the file list */ refreshFiles(): Promise<any>; ///** // * Backward-compatibility with karma-intellij bundled with WebStorm. // * Deprecated since version 0.13, to be removed in 0.14 // */ //static start(): void; } interface ServerCallback { (exitCode: number): void; } interface Config { set: (config: ConfigOptions) => void; LOG_DISABLE: string; LOG_ERROR: string; LOG_WARN: string; LOG_INFO: string; LOG_DEBUG: string; } interface ConfigFile { configFile: string; } interface ConfigOptions { /** * @description Enable or disable watching files and executing the tests whenever one of these files changes. * @default true */ autoWatch?: boolean; /** * @description When Karma is watching the files for changes, it tries to batch multiple changes into a single run * so that the test runner doesn't try to start and restart running tests more than it should. * The configuration setting tells Karma how long to wait (in milliseconds) after any changes have occurred * before starting the test process again. * @default 250 */ autoWatchBatchDelay?: number; /** * @default '' * @description The root path location that will be used to resolve all relative paths defined in <code>files</code> and <code>exclude</code>. * If the basePath configuration is a relative path then it will be resolved to * the <code>__dirname</code> of the configuration file. */ basePath?: string; /** * @default 2000 * @description How long does Karma wait for a browser to reconnect (in ms). * <p> * With a flaky connection it is pretty common that the browser disconnects, * but the actual test execution is still running without any problems. Karma does not treat a disconnection * as immediate failure and will wait <code>browserDisconnectTimeout</code> (ms). * If the browser reconnects during that time, everything is fine. * </p> */ browserDisconnectTimeout?: number; /** * @default 0 * @description The number of disconnections tolerated. * <p> * The <code>disconnectTolerance</code> value represents the maximum number of tries a browser will attempt * in the case of a disconnection. Usually any disconnection is considered a failure, * but this option allows you to define a tolerance level when there is a flaky network link between * the Karma server and the browsers. * </p> */ browserDisconnectTolerance?: number; /** * @default 10000 * @description How long will Karma wait for a message from a browser before disconnecting from it (in ms). * <p> * If, during test execution, Karma does not receive any message from a browser within * <code>browserNoActivityTimeout</code> (ms), it will disconnect from the browser * </p> */ browserNoActivityTimeout?: number; /** * @default [] * Possible Values: * <ul> * <li>Chrome (launcher comes installed with Karma)</li> * <li>ChromeCanary (launcher comes installed with Karma)</li> * <li>PhantomJS (launcher comes installed with Karma)</li> * <li>Firefox (launcher requires karma-firefox-launcher plugin)</li> * <li>Opera (launcher requires karma-opera-launcher plugin)</li> * <li>Internet Explorer (launcher requires karma-ie-launcher plugin)</li> * <li>Safari (launcher requires karma-safari-launcher plugin)</li> * </ul> * @description A list of browsers to launch and capture. When Karma starts up, it will also start up each browser * which is placed within this setting. Once Karma is shut down, it will shut down these browsers as well. * You can capture any browser manually by opening the browser and visiting the URL where * the Karma web server is listening (by default it is <code>http://localhost:9876/</code>). */ browsers?: string[]; /** * @default 60000 * @description Timeout for capturing a browser (in ms). * <p> * The <code>captureTimeout</code> value represents the maximum boot-up time allowed for a * browser to start and connect to Karma. If any browser does not get captured within the timeout, Karma * will kill it and try to launch it again and, after three attempts to capture it, Karma will give up. * </p> */ captureTimeout?: number; client?: ClientOptions; /** * @default true * @description Enable or disable colors in the output (reporters and logs). */ colors?: boolean; /** * @default [] * @description List of files/patterns to exclude from loaded files. */ exclude?: string[]; /** * @default [] * @description List of files/patterns to load in the browser. */ files?: (FilePattern|string)[]; /** * @default [] * @description List of test frameworks you want to use. Typically, you will set this to ['jasmine'], ['mocha'] or ['qunit']... * Please note just about all frameworks in Karma require an additional plugin/framework library to be installed (via NPM). */ frameworks?: string[]; /** * @default 'localhost' * @description Hostname to be used when capturing browsers. */ hostname?: string; /** * @default {} * @description Options object to be used by Node's https class. * Object description can be found in the * [NodeJS.org API docs](https://nodejs.org/api/tls.html#tls_tls_createserver_options_secureconnectionlistener) */ httpsServerOptions?: https.ServerOptions; /** * @default config.LOG_INFO * Possible values: * <ul> * <li>config.LOG_DISABLE</li> * <li>config.LOG_ERROR</li> * <li>config.LOG_WARN</li> * <li>config.LOG_INFO</li> * <li>config.LOG_DEBUG</li> * </ul> * @description Level of logging. */ logLevel?: string; /** * @default [{type: 'console'}] * @description A list of log appenders to be used. See the documentation for [log4js] for more information. */ loggers?: log4js.AppenderConfigBase[]; /** * @default ['karma-*'] * @description List of plugins to load. A plugin can be a string (in which case it will be required * by Karma) or an inlined plugin - Object. * By default, Karma loads all sibling NPM modules which have a name starting with karma-*. * Note: Just about all plugins in Karma require an additional library to be installed (via NPM). */ plugins?: any[]; /** * @default 9876 * @description The port where the web server will be listening. */ port?: number; /** * @default {'**\/*.coffee': 'coffee'} * @description A map of preprocessors to use. * * Preprocessors can be loaded through [plugins]. * * Note: Just about all preprocessors in Karma (other than CoffeeScript and some other defaults) * require an additional library to be installed (via NPM). * * Be aware that preprocessors may be transforming the files and file types that are available at run time. For instance, * if you are using the "coverage" preprocessor on your source files, if you then attempt to interactively debug * your tests, you'll discover that your expected source code is completely changed from what you expected. Because * of that, you'll want to engineer this so that your automated builds use the coverage entry in the "reporters" list, * but your interactive debugging does not. * */ preprocessors?: { [name: string]: string|string[] } /** * @default 'http:' * Possible Values: * <ul> * <li>http:</li> * <li>https:</li> * </ul> * @description Protocol used for running the Karma webserver. * Determines the use of the Node http or https class. * Note: Using <code>'https:'</code> requires you to specify <code>httpsServerOptions</code>. */ protocol?: string; /** * @default {} * @description A map of path-proxy pairs. */ proxies?: { [path: string]: string } /** * @default true * @description Whether or not Karma or any browsers should raise an error when an inavlid SSL certificate is found. */ proxyValidateSSL?: boolean; /** * @default 0 * @description Karma will report all the tests that are slower than given time limit (in ms). * This is disabled by default (since the default value is 0). */ reportSlowerThan?: number; /** * @default ['progress'] * Possible Values: * <ul> * <li>dots</li> * <li>progress</li> * </ul> * @description A list of reporters to use. * Additional reporters, such as growl, junit, teamcity or coverage can be loaded through plugins. * Note: Just about all additional reporters in Karma (other than progress) require an additional library to be installed (via NPM). */ reporters?: string[]; /** * @default false * @description Continuous Integration mode. * If true, Karma will start and capture all configured browsers, run tests and then exit with an exit code of 0 or 1 depending * on whether all tests passed or any tests failed. */ singleRun?: boolean; /** * @default ['polling', 'websocket'] * @description An array of allowed transport methods between the browser and testing server. This configuration setting * is handed off to [socket.io](http://socket.io/) (which manages the communication * between browsers and the testing server). */ transports?: string[]; /** * @default '/' * @description The base url, where Karma runs. * All of Karma's urls get prefixed with the urlRoot. This is helpful when using proxies, as * sometimes you might want to proxy a url that is already taken by Karma. */ urlRoot?: string; } interface ClientOptions { /** * @default undefined * @description When karma run is passed additional arguments on the command-line, they * are passed through to the test adapter as karma.config.args (an array of strings). * The client.args option allows you to set this value for actions other than run. * How this value is used is up to your test adapter - you should check your adapter's * documentation to see how (and if) it uses this value. */ args?: string[]; /** * @default true * @description Run the tests inside an iFrame or a new window * If true, Karma runs the tests inside an iFrame. If false, Karma runs the tests in a new window. Some tests may not run in an * iFrame and may need a new window to run. */ useIframe?: boolean; /** * @default true * @description Capture all console output and pipe it to the terminal. */ captureConsole?: boolean; } interface FilePattern { /** * The pattern to use for matching. This property is mandatory. */ pattern: string; /** * @default true * @description If <code>autoWatch</code> is true all files that have set watched to true will be watched * for changes. */ watched?: boolean; /** * @default true * @description Should the files be included in the browser using <script> tag? Use false if you want to * load them manually, eg. using Require.js. */ included?: boolean; /** * @default true * @description Should the files be served by Karma's webserver? */ served?: boolean; /** * @default false * @description Should the files be served from disk on each request by Karma's webserver? */ nocache?: boolean; } } var karma: karma.Karma; export = karma; }
karma/karma.d.ts
1
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/b13fb549b27f069cb40346a4a835dc7c229aba8b
[ 0.9975900650024414, 0.025907525792717934, 0.00016107820556499064, 0.00019389916269574314, 0.1576291024684906 ]
{ "id": 4, "code_window": [ " * Force a refresh of the file list\n", " */\n", " refreshFiles(): Promise<any>;\n", "\n", " ///**\n", " // * Backward-compatibility with karma-intellij bundled with WebStorm.\n", " // * Deprecated since version 0.13, to be removed in 0.14\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " on(event: string, listener: Function): this;\n", " \n", " /**\n", " * Listen to the 'run_complete' event.\n", " */\n", " on(event: 'run_complete', listener: (browsers: any, results: TestResults ) => void): this;\n", "\n" ], "file_path": "karma/karma.d.ts", "type": "add", "edit_start_line_idx": 74 }
/// <reference path="sequelize-2.0.0.d.ts" /> import Sequelize = require('sequelize'); var opts: Sequelize.Options; var defOpts: Sequelize.DefineOptions = { indexes: [{ fields: [""], type: "", method: "" }] }; var attrOpts: Sequelize.AttributeOptions; var defIndexOpts: Sequelize.DefineIndexOptions; var indexOpts: Sequelize.IndexOptions; var dropOpts: Sequelize.DropOptions; var transOpts: Sequelize.TransactionOptions; var syncOpts: Sequelize.SyncOptions; var assocOpts: Sequelize.AssociationOptions; var schemaOpts: Sequelize.SchemaOptions; var findOpts: Sequelize.FindOptions; var findCrOpts: Sequelize.FindOrCreateOptions; var queryOpts: Sequelize.QueryOptions; var buildOpts: Sequelize.BuildOptions; var copyOpts: Sequelize.CopyOptions; var bulkCrOpts: Sequelize.BulkCreateOptions; var destroyOpts: Sequelize.DestroyOptions; var destroyInstOpts: Sequelize.DestroyInstanceOptions; var updateOpts: Sequelize.UpdateOptions; var saveOpts: Sequelize.SaveOptions; var valOpts: Sequelize.ValidateOptions; var incrOpts: Sequelize.IncrementOptions; var promiseMe: Sequelize.Promise; var emitMe: Sequelize.EventEmitter; var sequelize = new Sequelize("", ""); sequelize = new Sequelize("", opts); sequelize = new Sequelize("", "", ""); sequelize = new Sequelize("", "", opts); sequelize = new Sequelize("", "", "", opts); interface modelPojo { name: string; } interface modelInst extends Sequelize.Instance<modelInst, modelPojo>, modelPojo { }; var myModelInst: modelInst; var myModelPojo: modelPojo; sequelize.define<modelInst, modelPojo>("MyTable", attrOpts, defOpts); var model: Sequelize.Model<modelInst, modelPojo> = sequelize.model<modelInst, modelPojo>("MyTable"); model = sequelize.import<modelInst, modelPojo>(""); emitMe = sequelize.authenticate(); sequelize.cast({}, ""); sequelize.col("myCol"); sequelize.models.MyTable; emitMe = sequelize.drop(dropOpts); emitMe = sequelize.createSchema("schema"); emitMe = sequelize.dropAllSchemas(); emitMe = sequelize.dropSchema("dbo"); emitMe = sequelize.fn("upper", sequelize.col("username")); sequelize.literal(""); sequelize.literal(1234); sequelize.and("", 1234); sequelize.or("", 123); sequelize.where("", ""); sequelize.where("", sequelize.and("", "")); promiseMe= sequelize.transaction(transOpts); promiseMe = sequelize.transaction(transOpts, function (t:Sequelize.Transaction): boolean { return true; }); emitMe = sequelize.query<modelInst, modelPojo>("", model).complete(function (err, result) { }); emitMe = sequelize.query(""); var dialect: string = sequelize.getDialect(); emitMe = sequelize.showAllSchemas(); emitMe = sequelize.sync(syncOpts); model.addHook("", "", function () { }); model.addHook("", function () { }); model.beforeValidate("", function () { }); model.afterValidate("", function () { }); model.beforeCreate("", function () { }); model.afterCreate("", function () { }); model.beforeDestroy("", function () { }); model.afterDestroy("", function () { }); model.beforeUpdate("", function () { }); model.afterUpdate("", function () { }); model.beforeBulkCreate("", function () { }); model.afterBulkCreate("", function () { }); model.beforeBulkDestroy("", function () { }); model.afterBulkDestroy("", function () { }); model.beforeBulkUpdate("", function () { }); model.afterBulkUpdate("", function () { }); model.hasOne<modelInst, modelPojo>(model); model.hasOne<modelInst, modelPojo>(model, assocOpts); model.belongsTo<modelInst, modelPojo>(model); model.belongsTo<modelInst, modelPojo>(model, assocOpts); model.hasMany<modelInst, modelPojo>(model); model.hasMany<modelInst, modelPojo>(model, assocOpts); model.belongsToMany<modelInst, modelPojo>(model); model.belongsToMany<modelInst, modelPojo>(model, assocOpts); promiseMe = model.sync(); promiseMe = model.drop(dropOpts); model.schema("", schemaOpts); model.getTableName(); model = model.scope({}); model = model.scope(""); model = model.scope([]); model = model.scope(null); model.find().then(function () { }, function () { }); model.find().then(function () { }); model.find().then(null, function () { }); model.find().then(function (result: modelInst) { }); model.find().then<modelInst>(function (result: modelInst): Sequelize.PromiseT<modelInst> { return model.find(1); }); model.find().then<modelInst, any>(function (result: modelInst): Sequelize.PromiseT<modelInst> { return model.find(1); }, function (): Sequelize.PromiseT<any> { return model.find(1); }); model.find().catch(function () { }); model.find().catch(function (result: modelInst) { }); model.find().catch(function (result: modelInst): Sequelize.Promise { return model.find(1); }); model.find().spread(function () { }, function () { }); model.find().spread(function () { }); model.find().spread(null, function () { }); model.find().spread(function (result: modelInst) { }); model.find().spread(function (result1: modelInst, result2: any) { }); model.find().spread(null, function (result1: any, result2: boolean) { }); model.find().spread(function (result: modelInst): Sequelize.Promise { return model.find(1); }); model.find().spread<modelInst>(function (result: modelInst): Sequelize.PromiseT<modelInst> { return model.find(1); }); model.find().spread<modelInst>(function (result: modelInst) { }, function (): Sequelize.PromiseT<modelInst> { return model.find(1); }); model.find().spread<modelInst, any>(function (result: modelInst): Sequelize.PromiseT<modelInst> { return model.find(1); }, function (): Sequelize.PromiseT<any> { return model.find(1); }); promiseMe = model.findAll(findOpts, queryOpts); promiseMe = model.findAll(findOpts); promiseMe = model.findAll(); promiseMe = model.find(findOpts, queryOpts); promiseMe = model.find(findOpts); promiseMe = model.find(1, queryOpts); promiseMe = model.find(1); promiseMe = model.find(); promiseMe = model.aggregate<number>("", "", findOpts); promiseMe = model.count(); promiseMe = model.count(findOpts); promiseMe = model.findAndCountAll(findOpts, queryOpts); promiseMe = model.findAndCountAll(findOpts); promiseMe = model.findAndCountAll(); promiseMe = model.max<number>("", findOpts); promiseMe = model.max<number>(""); promiseMe = model.min<number>("", findOpts); promiseMe = model.min<number>(""); promiseMe = model.sum("", findOpts); promiseMe = model.sum(""); myModelInst = model.build(myModelPojo, buildOpts); myModelInst = model.build(myModelPojo); promiseMe = model.create(myModelPojo, copyOpts); promiseMe = model.create(myModelPojo); promiseMe = model.findOrInitialize({}, myModelPojo, queryOpts); promiseMe = model.findOrInitialize({}, myModelPojo); promiseMe = model.findOrInitialize({}); promiseMe = model.findOrCreate({}, myModelPojo, findCrOpts); promiseMe = model.findOrCreate({}, myModelPojo); promiseMe = model.findOrCreate({}); promiseMe = model.bulkCreate([myModelPojo], bulkCrOpts); promiseMe = model.bulkCreate([myModelPojo]); promiseMe = model.destroy({}, destroyOpts); promiseMe = model.destroy({}); promiseMe = model.destroy(); promiseMe = model.update(myModelPojo, {}, updateOpts); promiseMe = model.update(myModelPojo, {}); promiseMe = model.describe(); model.dataset; //var isDefined: boolean = sequelize.isDefined(""); model.find().spread(function (arg1: string, arg2: number) { return model.find(); }); var isBool: boolean; var strArr: Array<string>; isBool = myModelInst.isNewRecord; model = myModelInst.Model; sequelize = myModelInst.sequelize; isBool = myModelInst.isDeleted; myModelPojo = myModelInst.values; isBool = myModelInst.isDirty; myModelPojo = myModelInst.primaryKeyValues; myModelInst.getDataValue(""); myModelInst.setDataValue("", ""); myModelInst.setDataValue("", 123); myModelInst.get(""); myModelInst.set("", ""); myModelInst.set("", 123); isBool = myModelInst.changed(""); strArr = myModelInst.changed(); myModelInst.previous(""); promiseMe = myModelInst.save(["", ""], saveOpts); promiseMe = myModelInst.save(["", ""]); promiseMe = myModelInst.reload(); promiseMe = myModelInst.reload(findOpts); promiseMe = myModelInst.validate(valOpts); promiseMe = myModelInst.validate(); promiseMe = myModelInst.updateAttributes(myModelPojo, saveOpts); promiseMe = myModelInst.destroy(destroyInstOpts); promiseMe = myModelInst.destroy(); promiseMe = myModelInst.increment({}, incrOpts); promiseMe = myModelInst.increment({}); promiseMe = myModelInst.decrement({}, incrOpts); isBool = myModelInst.equal(myModelInst); isBool = myModelInst.equalsOneOf([myModelInst]); myModelPojo = myModelInst.toJSON(); // data types test var types:any = Sequelize.STRING; types = Sequelize.STRING(12); types = Sequelize.STRING(12, true); types = Sequelize.STRING.BINARY; types = Sequelize.STRING(12).BINARY; types = Sequelize.STRING.BINARY(12); types = Sequelize.STRING({length:12, binary:true}); types = Sequelize.STRING({length:12}).BINARY; types = Sequelize.CHAR; types = Sequelize.CHAR(12); types = Sequelize.CHAR(12, true); types = Sequelize.CHAR.BINARY; types = Sequelize.CHAR(12).BINARY; types = Sequelize.CHAR.BINARY(12); types = Sequelize.CHAR({length:12, binary:true}); types = Sequelize.CHAR({length:12}).BINARY; types = Sequelize.TEXT; types = Sequelize.TEXT('tiny'); types = Sequelize.TEXT({length:'tiny'}); types = Sequelize.NUMBER; var numberOptions = {length:12, zerofill:true, decimals:1, precision:1, scale:1, unsigned:true}; types = Sequelize.NUMBER(numberOptions); types = Sequelize.INTEGER; types = Sequelize.INTEGER.ZEROFILL; types = Sequelize.INTEGER.UNSIGNED; types = Sequelize.INTEGER.ZEROFILL.UNSIGNED; types = Sequelize.INTEGER.UNSIGNED.ZEROFILL; types = Sequelize.INTEGER(12); types = Sequelize.INTEGER(12).ZEROFILL; types = Sequelize.INTEGER(12).UNSIGNED; types = Sequelize.INTEGER(12).ZEROFILL.UNSIGNED; types = Sequelize.INTEGER(12).UNSIGNED.ZEROFILL; types = Sequelize.INTEGER(numberOptions); types = Sequelize.INTEGER(numberOptions).ZEROFILL; types = Sequelize.INTEGER(numberOptions).UNSIGNED; types = Sequelize.INTEGER(numberOptions).ZEROFILL.UNSIGNED; types = Sequelize.INTEGER(numberOptions).UNSIGNED.ZEROFILL; types = Sequelize.BIGINT; types = Sequelize.BIGINT.ZEROFILL; types = Sequelize.BIGINT.UNSIGNED; types = Sequelize.BIGINT.ZEROFILL.UNSIGNED; types = Sequelize.BIGINT.UNSIGNED.ZEROFILL; types = Sequelize.BIGINT(12); types = Sequelize.BIGINT(12).ZEROFILL; types = Sequelize.BIGINT(12).UNSIGNED; types = Sequelize.BIGINT(12).ZEROFILL.UNSIGNED; types = Sequelize.BIGINT(12).UNSIGNED.ZEROFILL; types = Sequelize.BIGINT(numberOptions); types = Sequelize.BIGINT(numberOptions).ZEROFILL; types = Sequelize.BIGINT(numberOptions).UNSIGNED; types = Sequelize.BIGINT(numberOptions).ZEROFILL.UNSIGNED; types = Sequelize.BIGINT(numberOptions).UNSIGNED.ZEROFILL; types = Sequelize.FLOAT; types = Sequelize.FLOAT.ZEROFILL; types = Sequelize.FLOAT.UNSIGNED; types = Sequelize.FLOAT.ZEROFILL.UNSIGNED; types = Sequelize.FLOAT.UNSIGNED.ZEROFILL; types = Sequelize.FLOAT(12); types = Sequelize.FLOAT(12).ZEROFILL; types = Sequelize.FLOAT(12).UNSIGNED; types = Sequelize.FLOAT(12).ZEROFILL.UNSIGNED; types = Sequelize.FLOAT(12).UNSIGNED.ZEROFILL; types = Sequelize.FLOAT(12,12); types = Sequelize.FLOAT(12,12).ZEROFILL; types = Sequelize.FLOAT(12,12).UNSIGNED; types = Sequelize.FLOAT(12,12).ZEROFILL.UNSIGNED; types = Sequelize.FLOAT(12,12).UNSIGNED.ZEROFILL; types = Sequelize.FLOAT(numberOptions); types = Sequelize.FLOAT(numberOptions).ZEROFILL; types = Sequelize.FLOAT(numberOptions).UNSIGNED; types = Sequelize.FLOAT(numberOptions).ZEROFILL.UNSIGNED; types = Sequelize.FLOAT(numberOptions).UNSIGNED.ZEROFILL; types = Sequelize.DOUBLE; types = Sequelize.DOUBLE.ZEROFILL; types = Sequelize.DOUBLE.UNSIGNED; types = Sequelize.DOUBLE.ZEROFILL.UNSIGNED; types = Sequelize.DOUBLE.UNSIGNED.ZEROFILL; types = Sequelize.DOUBLE(12); types = Sequelize.DOUBLE(12).ZEROFILL; types = Sequelize.DOUBLE(12).UNSIGNED; types = Sequelize.DOUBLE(12).ZEROFILL.UNSIGNED; types = Sequelize.DOUBLE(12).UNSIGNED.ZEROFILL; types = Sequelize.DOUBLE(12,12); types = Sequelize.DOUBLE(12,12).ZEROFILL; types = Sequelize.DOUBLE(12,12).UNSIGNED; types = Sequelize.DOUBLE(12,12).ZEROFILL.UNSIGNED; types = Sequelize.DOUBLE(12,12).UNSIGNED.ZEROFILL; types = Sequelize.DOUBLE(numberOptions); types = Sequelize.DOUBLE(numberOptions).ZEROFILL; types = Sequelize.DOUBLE(numberOptions).UNSIGNED; types = Sequelize.DOUBLE(numberOptions).ZEROFILL.UNSIGNED; types = Sequelize.DOUBLE(numberOptions).UNSIGNED.ZEROFILL; types = Sequelize.TIME; types = Sequelize.DATE; types = Sequelize.DATEONLY; types = Sequelize.BOOLEAN; types = Sequelize.NOW; types = Sequelize.BLOB; types = Sequelize.BLOB('tiny'); types = Sequelize.BLOB({length:'tiny'}); types = Sequelize.DECIMAL; types = Sequelize.DECIMAL.ZEROFILL; types = Sequelize.DECIMAL.UNSIGNED; types = Sequelize.DECIMAL.ZEROFILL.UNSIGNED; types = Sequelize.DECIMAL.UNSIGNED.ZEROFILL; types = Sequelize.DECIMAL(12,12); types = Sequelize.DECIMAL(12,12).ZEROFILL; types = Sequelize.DECIMAL(12,12).UNSIGNED; types = Sequelize.DECIMAL(12,12).ZEROFILL.UNSIGNED; types = Sequelize.DECIMAL(12,12).UNSIGNED.ZEROFILL; types = Sequelize.DECIMAL(numberOptions); types = Sequelize.DECIMAL(numberOptions).ZEROFILL; types = Sequelize.DECIMAL(numberOptions).UNSIGNED; types = Sequelize.DECIMAL(numberOptions).ZEROFILL.UNSIGNED; types = Sequelize.DECIMAL(numberOptions).UNSIGNED.ZEROFILL; types = Sequelize.NUMERIC; types = Sequelize.NUMERIC.ZEROFILL; types = Sequelize.NUMERIC.UNSIGNED; types = Sequelize.NUMERIC.ZEROFILL.UNSIGNED; types = Sequelize.NUMERIC.UNSIGNED.ZEROFILL; types = Sequelize.NUMERIC(12,12); types = Sequelize.NUMERIC(12,12).ZEROFILL; types = Sequelize.NUMERIC(12,12).UNSIGNED; types = Sequelize.NUMERIC(12,12).ZEROFILL.UNSIGNED; types = Sequelize.NUMERIC(12,12).UNSIGNED.ZEROFILL; types = Sequelize.NUMERIC(numberOptions); types = Sequelize.NUMERIC(numberOptions).ZEROFILL; types = Sequelize.NUMERIC(numberOptions).UNSIGNED; types = Sequelize.NUMERIC(numberOptions).ZEROFILL.UNSIGNED; types = Sequelize.NUMERIC(numberOptions).UNSIGNED.ZEROFILL; types = Sequelize.UUID; types = Sequelize.UUIDV1; types = Sequelize.UUIDV4; types = Sequelize.HSTORE; types = Sequelize.JSON; types = Sequelize.JSONB; types = Sequelize.VIRTUAL; types = Sequelize.ARRAY(Sequelize.INTEGER(12)); types = Sequelize.ARRAY({type: Sequelize.BLOB}); var obj = {}; var isbool:boolean = types.is(obj, obj); types = Sequelize.NONE; types = Sequelize.ENUM("one", "two", 'three'); types = Sequelize.RANGE(Sequelize.INTEGER(12)); types = Sequelize.RANGE({subtype: Sequelize.BLOB}); types = Sequelize.REAL; types = Sequelize.REAL.ZEROFILL; types = Sequelize.REAL.UNSIGNED; types = Sequelize.REAL.ZEROFILL.UNSIGNED; types = Sequelize.REAL.UNSIGNED.ZEROFILL; types = Sequelize.REAL(12,12); types = Sequelize.REAL(12,12).ZEROFILL; types = Sequelize.REAL(12,12).UNSIGNED; types = Sequelize.REAL(12,12).ZEROFILL.UNSIGNED; types = Sequelize.REAL(12,12).UNSIGNED.ZEROFILL; types = Sequelize.REAL(numberOptions); types = Sequelize.REAL(numberOptions).ZEROFILL; types = Sequelize.REAL(numberOptions).UNSIGNED; types = Sequelize.REAL(numberOptions).ZEROFILL.UNSIGNED; types = Sequelize.REAL(numberOptions).UNSIGNED.ZEROFILL; types = Sequelize.DOUBLE; types = Sequelize.DOUBLE.ZEROFILL; types = Sequelize.DOUBLE.UNSIGNED; types = Sequelize.DOUBLE.ZEROFILL.UNSIGNED; types = Sequelize.DOUBLE.UNSIGNED.ZEROFILL; types = Sequelize.DOUBLE(12,12); types = Sequelize.DOUBLE(12,12).ZEROFILL; types = Sequelize.DOUBLE(12,12).UNSIGNED; types = Sequelize.DOUBLE(12,12).ZEROFILL.UNSIGNED; types = Sequelize.DOUBLE(12,12).UNSIGNED.ZEROFILL; types = Sequelize.DOUBLE(numberOptions); types = Sequelize.DOUBLE(numberOptions).ZEROFILL; types = Sequelize.DOUBLE(numberOptions).UNSIGNED; types = Sequelize.DOUBLE(numberOptions).ZEROFILL.UNSIGNED; types = Sequelize.DOUBLE(numberOptions).UNSIGNED.ZEROFILL; types = Sequelize["DOUBLE PRECISION"]; types = Sequelize["DOUBLE PRECISION"].ZEROFILL; types = Sequelize["DOUBLE PRECISION"].UNSIGNED; types = Sequelize["DOUBLE PRECISION"].ZEROFILL.UNSIGNED; types = Sequelize["DOUBLE PRECISION"].UNSIGNED.ZEROFILL; types = Sequelize["DOUBLE PRECISION"](12,12); types = Sequelize["DOUBLE PRECISION"](12,12).ZEROFILL; types = Sequelize["DOUBLE PRECISION"](12,12).UNSIGNED; types = Sequelize["DOUBLE PRECISION"](12,12).ZEROFILL.UNSIGNED; types = Sequelize["DOUBLE PRECISION"](12,12).UNSIGNED.ZEROFILL; types = Sequelize["DOUBLE PRECISION"](numberOptions); types = Sequelize["DOUBLE PRECISION"](numberOptions).ZEROFILL; types = Sequelize["DOUBLE PRECISION"](numberOptions).UNSIGNED; types = Sequelize["DOUBLE PRECISION"](numberOptions).ZEROFILL.UNSIGNED; types = Sequelize["DOUBLE PRECISION"](numberOptions).UNSIGNED.ZEROFILL;
sequelize/sequelize-tests-2.0.0.ts
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/b13fb549b27f069cb40346a4a835dc7c229aba8b
[ 0.0007903726655058563, 0.0001839401520555839, 0.00016254828369710594, 0.00017035624478012323, 0.00009361632692161947 ]
{ "id": 4, "code_window": [ " * Force a refresh of the file list\n", " */\n", " refreshFiles(): Promise<any>;\n", "\n", " ///**\n", " // * Backward-compatibility with karma-intellij bundled with WebStorm.\n", " // * Deprecated since version 0.13, to be removed in 0.14\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " on(event: string, listener: Function): this;\n", " \n", " /**\n", " * Listen to the 'run_complete' event.\n", " */\n", " on(event: 'run_complete', listener: (browsers: any, results: TestResults ) => void): this;\n", "\n" ], "file_path": "karma/karma.d.ts", "type": "add", "edit_start_line_idx": 74 }
// Type definitions for sqlite3 2.2.3 // Project: https://github.com/mapbox/node-sqlite3 // Definitions by: Nick Malaguti <https://github.com/nmalaguti/> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// <reference path="../node/node.d.ts" /> declare module "sqlite3" { import events = require("events"); export var OPEN_READONLY: number; export var OPEN_READWRITE: number; export var OPEN_CREATE: number; export var cached: { Database(filename: string, callback?: (err: Error) => void): Database; Database(filename: string, mode?: number, callback?: (err: Error) => void): Database; }; export interface RunResult { lastID: number; changes: number; } export class Statement { public bind(callback?: (err: Error) => void): Statement; public bind(...params: any[]): Statement; public reset(callback?: (err: Error) => void): Statement; public finalize(callback?: (err: Error) => void): Statement; public run(callback?: (err: Error) => void): Statement; public run(...params: any[]): Statement; public get(callback?: (err: Error, row: any) => void): Statement; public get(...params: any[]): Statement; public all(callback?: (err: Error, rows: any[]) => void): Statement; public all(...params: any[]): Statement; public each(callback?: (err: Error, row: any) => void, complete?: (err: Error, count: number) => void): Statement; public each(...params: any[]): Statement; } export class Database extends events.EventEmitter { constructor(filename: string, callback?: (err: Error) => void); constructor(filename: string, mode?: number, callback?: (err: Error) => void); public close(callback?: (err: Error) => void): void; public run(sql: string, callback?: (err: Error) => void): Database; public run(sql: string, ...params: any[]): Database; public get(sql: string, callback?: (err: Error, row: any) => void): Database; public get(sql: string, ...params: any[]): Database; public all(sql: string, callback?: (err: Error, rows: any[]) => void): Database; public all(sql: string, ...params: any[]): Database; public each(sql: string, callback?: (err: Error, row: any) => void, complete?: (err: Error, count: number) => void): Database; public each(sql: string, ...params: any[]): Database; public exec(sql: string, callback?: (err: Error) => void): Database; public prepare(sql: string, callback?: (err: Error) => void): Statement; public prepare(sql: string, ...params: any[]): Statement; public serialize(callback?: () => void): void; public parallelize(callback?: () => void): void; public on(event: "trace", listener: (sql: string) => void): this; public on(event: "profile", listener: (sql: string, time: number) => void): this; public on(event: "error", listener: (err: Error) => void): this; public on(event: "open", listener: () => void): this; public on(event: "close", listener: () => void): this; public on(event: string, listener: Function): this; } function verbose(): void; }
sqlite3/sqlite3.d.ts
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/b13fb549b27f069cb40346a4a835dc7c229aba8b
[ 0.00017259920423384756, 0.00016865211364347488, 0.00016579988005105406, 0.00016873831918928772, 0.0000018995924619957805 ]
{ "id": 4, "code_window": [ " * Force a refresh of the file list\n", " */\n", " refreshFiles(): Promise<any>;\n", "\n", " ///**\n", " // * Backward-compatibility with karma-intellij bundled with WebStorm.\n", " // * Deprecated since version 0.13, to be removed in 0.14\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " on(event: string, listener: Function): this;\n", " \n", " /**\n", " * Listen to the 'run_complete' event.\n", " */\n", " on(event: 'run_complete', listener: (browsers: any, results: TestResults ) => void): this;\n", "\n" ], "file_path": "karma/karma.d.ts", "type": "add", "edit_start_line_idx": 74 }
// Type definitions for express-validator 2.9.0 // Project: https://github.com/ctavan/express-validator // Definitions by: Nathan Ridley <https://github.com/axefrog/>, Jonathan Häberle <http://dreampulse.de> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// <reference path="../express/express.d.ts" /> // Add RequestValidation Interface on to Express's Request Interface. declare namespace Express { interface Request extends ExpressValidator.RequestValidation {} } // External express-validator module. declare module "express-validator" { import express = require('express'); /** * * @middlewareOptions see: https://github.com/ctavan/express-validator#middleware-options */ function ExpressValidator(middlewareOptions?:any):express.RequestHandler; export = ExpressValidator; } // Internal Module. declare namespace ExpressValidator { export interface ValidationError { msg: string; param: string; } interface ValidatorFunction { (item: string, message: string): Validator; } interface SanitizerFunction { (item: string): Sanitizer; } interface Dictionary<T> { [key: string]: T; } export interface RequestValidation { assert: ValidatorFunction; check: ValidatorFunction; checkBody: ValidatorFunction; checkFiles: ValidatorFunction; checkHeader: ValidatorFunction; checkParams: ValidatorFunction; checkQuery: ValidatorFunction; validate: ValidatorFunction; filter: SanitizerFunction; sanitize: SanitizerFunction; onValidationError(errback: (msg: string) => void): void; validationErrors(mapped?: boolean): Dictionary<any> | any[]; } export interface Validator { /** * Alias for regex() */ is(): Validator; /** * Alias for notRegex() */ not(): Validator; isEmail(): Validator; /** * Accepts http, https, ftp */ isUrl(): Validator; /** * Combines isIPv4 and isIPv6 */ isIP(): Validator; isIPv4(): Validator; isIPv6(): Validator; isMACAddress(): Validator; isAlpha(): Validator; isAlphanumeric(): Validator; isNumeric(): Validator; isHexadecimal(): Validator; /** * Accepts valid hexcolors with or without # prefix */ isHexColor(): Validator; /** * isNumeric accepts zero padded numbers, e.g. '001', isInt doesn't */ isInt(): Validator; isLowercase(): Validator; isUppercase(): Validator; isDecimal(): Validator; /** * Alias for isDecimal */ isFloat(): Validator; /** * Check if length is 0 */ notNull(): Validator; isNull(): Validator; /** * Not just whitespace (input.trim().length !== 0) */ notEmpty(): Validator; equals(equals:any): Validator; contains(str:string): Validator; notContains(str:string): Validator; /** * Usage: regex(/[a-z]/i) or regex('[a-z]','i') */ regex(pattern:string, modifiers:string): Validator; notRegex(pattern:string, modifiers:string): Validator; /** * max is optional */ len(min:number, max?:number): Validator; /** * Version can be 3, 4 or 5 or empty, see http://en.wikipedia.org/wiki/Universally_unique_identifier */ isUUID(version:number): Validator; /** * Alias for isUUID(3) */ isUUIDv3(): Validator; /** * Alias for isUUID(4) */ isUUIDv4(): Validator; /** * Alias for isUUID(5) */ isUUIDv5(): Validator; /** * Uses Date.parse() - regex is probably a better choice */ isDate(): Validator; /** * Argument is optional and defaults to today. Comparison is non-inclusive */ isAfter(date:Date): Validator; /** * Argument is optional and defaults to today. Comparison is non-inclusive */ isBefore(date:Date): Validator; isIn(options:string): Validator; isIn(options:string[]): Validator; notIn(options:string): Validator; notIn(options:string[]): Validator; max(val:string): Validator; min(val:string): Validator; /** * Will work against Visa, MasterCard, American Express, Discover, Diners Club, and JCB card numbering formats */ isCreditCard(): Validator; /** * Check an input only when the input exists */ optional(): Validator; } interface Sanitizer { /** * Trim optional `chars`, default is to trim whitespace (\r\n\t ) */ trim(...chars:string[]): Sanitizer; ltrim(...chars:string[]): Sanitizer; rtrim(...chars:string[]): Sanitizer; ifNull(replace:any): Sanitizer; toFloat(): Sanitizer; toInt(): Sanitizer; /** * True unless str = '0', 'false', or str.length == 0 */ toBoolean(): Sanitizer; /** * False unless str = '1' or 'true' */ toBooleanStrict(): Sanitizer; /** * Decode HTML entities */ /** * Convert the input string to a date, or null if the input is not a date. */ toDate(): Sanitizer; entityDecode(): Sanitizer; entityEncode(): Sanitizer; /** * Escape &, <, >, and " */ escape(): Sanitizer; /** * Remove common XSS attack vectors from user-supplied HTML */ xss(): Sanitizer; /** * Remove common XSS attack vectors from images */ xss(fromImages:boolean): Sanitizer; } }
express-validator/express-validator.d.ts
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/b13fb549b27f069cb40346a4a835dc7c229aba8b
[ 0.00029857183108106256, 0.00017483584815636277, 0.00016248399333562702, 0.00016608944861218333, 0.000028676067813648842 ]
{ "id": 5, "code_window": [ " * @default []\n", " * @description List of files/patterns to load in the browser.\n", " */\n", " files?: (FilePattern|string)[];\n", " /**\n", " * @default []\n", " * @description List of test frameworks you want to use. Typically, you will set this to ['jasmine'], ['mocha'] or ['qunit']...\n", " * Please note just about all frameworks in Karma require an additional plugin/framework library to be installed (via NPM).\n", " */\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " files?: (FilePattern | string)[];\n" ], "file_path": "karma/karma.d.ts", "type": "replace", "edit_start_line_idx": 193 }
// Type definitions for karma v0.13.9 // Project: https://github.com/karma-runner/karma // Definitions by: Tanguy Krotoff <https://github.com/tkrotoff> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// <reference path="../bluebird/bluebird.d.ts" /> /// <reference path="../node/node.d.ts" /> /// <reference path="../log4js/log4js.d.ts" /> declare module 'karma' { // See Karma public API https://karma-runner.github.io/0.13/dev/public-api.html import Promise = require('bluebird'); import https = require('https'); import log4js = require('log4js'); namespace karma { interface Karma { /** * `start` method is deprecated since 0.13. It will be removed in 0.14. * Please use * <code> * server = new Server(config, [done]) * server.start() * </code> * instead. */ server: DeprecatedServer; Server: Server; runner: Runner; launcher: Launcher; VERSION: string; } interface LauncherStatic { generateId(): string; //TODO: injector should be of type `di.Injector` new(emitter: NodeJS.EventEmitter, injector: any): Launcher; } interface Launcher { Launcher: LauncherStatic; //TODO: Can this return value ever be typified? launch(names: string[], protocol: string, hostname: string, port: number, urlRoot: string): any[]; kill(id: string, callback: Function): boolean; restart(id: string): boolean; killAll(callback: Function): void; areAllCaptured(): boolean; markCaptured(id: string): void; } interface DeprecatedServer { start(options?: any, callback?: ServerCallback): void; } interface Runner { run(options?: ConfigOptions|ConfigFile, callback?: ServerCallback): void; } interface Server extends NodeJS.EventEmitter { new(options?: ConfigOptions|ConfigFile, callback?: ServerCallback): Server; /** * Start the server */ start(): void; /** * Get properties from the injector * @param token */ get(token: string): any; /** * Force a refresh of the file list */ refreshFiles(): Promise<any>; ///** // * Backward-compatibility with karma-intellij bundled with WebStorm. // * Deprecated since version 0.13, to be removed in 0.14 // */ //static start(): void; } interface ServerCallback { (exitCode: number): void; } interface Config { set: (config: ConfigOptions) => void; LOG_DISABLE: string; LOG_ERROR: string; LOG_WARN: string; LOG_INFO: string; LOG_DEBUG: string; } interface ConfigFile { configFile: string; } interface ConfigOptions { /** * @description Enable or disable watching files and executing the tests whenever one of these files changes. * @default true */ autoWatch?: boolean; /** * @description When Karma is watching the files for changes, it tries to batch multiple changes into a single run * so that the test runner doesn't try to start and restart running tests more than it should. * The configuration setting tells Karma how long to wait (in milliseconds) after any changes have occurred * before starting the test process again. * @default 250 */ autoWatchBatchDelay?: number; /** * @default '' * @description The root path location that will be used to resolve all relative paths defined in <code>files</code> and <code>exclude</code>. * If the basePath configuration is a relative path then it will be resolved to * the <code>__dirname</code> of the configuration file. */ basePath?: string; /** * @default 2000 * @description How long does Karma wait for a browser to reconnect (in ms). * <p> * With a flaky connection it is pretty common that the browser disconnects, * but the actual test execution is still running without any problems. Karma does not treat a disconnection * as immediate failure and will wait <code>browserDisconnectTimeout</code> (ms). * If the browser reconnects during that time, everything is fine. * </p> */ browserDisconnectTimeout?: number; /** * @default 0 * @description The number of disconnections tolerated. * <p> * The <code>disconnectTolerance</code> value represents the maximum number of tries a browser will attempt * in the case of a disconnection. Usually any disconnection is considered a failure, * but this option allows you to define a tolerance level when there is a flaky network link between * the Karma server and the browsers. * </p> */ browserDisconnectTolerance?: number; /** * @default 10000 * @description How long will Karma wait for a message from a browser before disconnecting from it (in ms). * <p> * If, during test execution, Karma does not receive any message from a browser within * <code>browserNoActivityTimeout</code> (ms), it will disconnect from the browser * </p> */ browserNoActivityTimeout?: number; /** * @default [] * Possible Values: * <ul> * <li>Chrome (launcher comes installed with Karma)</li> * <li>ChromeCanary (launcher comes installed with Karma)</li> * <li>PhantomJS (launcher comes installed with Karma)</li> * <li>Firefox (launcher requires karma-firefox-launcher plugin)</li> * <li>Opera (launcher requires karma-opera-launcher plugin)</li> * <li>Internet Explorer (launcher requires karma-ie-launcher plugin)</li> * <li>Safari (launcher requires karma-safari-launcher plugin)</li> * </ul> * @description A list of browsers to launch and capture. When Karma starts up, it will also start up each browser * which is placed within this setting. Once Karma is shut down, it will shut down these browsers as well. * You can capture any browser manually by opening the browser and visiting the URL where * the Karma web server is listening (by default it is <code>http://localhost:9876/</code>). */ browsers?: string[]; /** * @default 60000 * @description Timeout for capturing a browser (in ms). * <p> * The <code>captureTimeout</code> value represents the maximum boot-up time allowed for a * browser to start and connect to Karma. If any browser does not get captured within the timeout, Karma * will kill it and try to launch it again and, after three attempts to capture it, Karma will give up. * </p> */ captureTimeout?: number; client?: ClientOptions; /** * @default true * @description Enable or disable colors in the output (reporters and logs). */ colors?: boolean; /** * @default [] * @description List of files/patterns to exclude from loaded files. */ exclude?: string[]; /** * @default [] * @description List of files/patterns to load in the browser. */ files?: (FilePattern|string)[]; /** * @default [] * @description List of test frameworks you want to use. Typically, you will set this to ['jasmine'], ['mocha'] or ['qunit']... * Please note just about all frameworks in Karma require an additional plugin/framework library to be installed (via NPM). */ frameworks?: string[]; /** * @default 'localhost' * @description Hostname to be used when capturing browsers. */ hostname?: string; /** * @default {} * @description Options object to be used by Node's https class. * Object description can be found in the * [NodeJS.org API docs](https://nodejs.org/api/tls.html#tls_tls_createserver_options_secureconnectionlistener) */ httpsServerOptions?: https.ServerOptions; /** * @default config.LOG_INFO * Possible values: * <ul> * <li>config.LOG_DISABLE</li> * <li>config.LOG_ERROR</li> * <li>config.LOG_WARN</li> * <li>config.LOG_INFO</li> * <li>config.LOG_DEBUG</li> * </ul> * @description Level of logging. */ logLevel?: string; /** * @default [{type: 'console'}] * @description A list of log appenders to be used. See the documentation for [log4js] for more information. */ loggers?: log4js.AppenderConfigBase[]; /** * @default ['karma-*'] * @description List of plugins to load. A plugin can be a string (in which case it will be required * by Karma) or an inlined plugin - Object. * By default, Karma loads all sibling NPM modules which have a name starting with karma-*. * Note: Just about all plugins in Karma require an additional library to be installed (via NPM). */ plugins?: any[]; /** * @default 9876 * @description The port where the web server will be listening. */ port?: number; /** * @default {'**\/*.coffee': 'coffee'} * @description A map of preprocessors to use. * * Preprocessors can be loaded through [plugins]. * * Note: Just about all preprocessors in Karma (other than CoffeeScript and some other defaults) * require an additional library to be installed (via NPM). * * Be aware that preprocessors may be transforming the files and file types that are available at run time. For instance, * if you are using the "coverage" preprocessor on your source files, if you then attempt to interactively debug * your tests, you'll discover that your expected source code is completely changed from what you expected. Because * of that, you'll want to engineer this so that your automated builds use the coverage entry in the "reporters" list, * but your interactive debugging does not. * */ preprocessors?: { [name: string]: string|string[] } /** * @default 'http:' * Possible Values: * <ul> * <li>http:</li> * <li>https:</li> * </ul> * @description Protocol used for running the Karma webserver. * Determines the use of the Node http or https class. * Note: Using <code>'https:'</code> requires you to specify <code>httpsServerOptions</code>. */ protocol?: string; /** * @default {} * @description A map of path-proxy pairs. */ proxies?: { [path: string]: string } /** * @default true * @description Whether or not Karma or any browsers should raise an error when an inavlid SSL certificate is found. */ proxyValidateSSL?: boolean; /** * @default 0 * @description Karma will report all the tests that are slower than given time limit (in ms). * This is disabled by default (since the default value is 0). */ reportSlowerThan?: number; /** * @default ['progress'] * Possible Values: * <ul> * <li>dots</li> * <li>progress</li> * </ul> * @description A list of reporters to use. * Additional reporters, such as growl, junit, teamcity or coverage can be loaded through plugins. * Note: Just about all additional reporters in Karma (other than progress) require an additional library to be installed (via NPM). */ reporters?: string[]; /** * @default false * @description Continuous Integration mode. * If true, Karma will start and capture all configured browsers, run tests and then exit with an exit code of 0 or 1 depending * on whether all tests passed or any tests failed. */ singleRun?: boolean; /** * @default ['polling', 'websocket'] * @description An array of allowed transport methods between the browser and testing server. This configuration setting * is handed off to [socket.io](http://socket.io/) (which manages the communication * between browsers and the testing server). */ transports?: string[]; /** * @default '/' * @description The base url, where Karma runs. * All of Karma's urls get prefixed with the urlRoot. This is helpful when using proxies, as * sometimes you might want to proxy a url that is already taken by Karma. */ urlRoot?: string; } interface ClientOptions { /** * @default undefined * @description When karma run is passed additional arguments on the command-line, they * are passed through to the test adapter as karma.config.args (an array of strings). * The client.args option allows you to set this value for actions other than run. * How this value is used is up to your test adapter - you should check your adapter's * documentation to see how (and if) it uses this value. */ args?: string[]; /** * @default true * @description Run the tests inside an iFrame or a new window * If true, Karma runs the tests inside an iFrame. If false, Karma runs the tests in a new window. Some tests may not run in an * iFrame and may need a new window to run. */ useIframe?: boolean; /** * @default true * @description Capture all console output and pipe it to the terminal. */ captureConsole?: boolean; } interface FilePattern { /** * The pattern to use for matching. This property is mandatory. */ pattern: string; /** * @default true * @description If <code>autoWatch</code> is true all files that have set watched to true will be watched * for changes. */ watched?: boolean; /** * @default true * @description Should the files be included in the browser using <script> tag? Use false if you want to * load them manually, eg. using Require.js. */ included?: boolean; /** * @default true * @description Should the files be served by Karma's webserver? */ served?: boolean; /** * @default false * @description Should the files be served from disk on each request by Karma's webserver? */ nocache?: boolean; } } var karma: karma.Karma; export = karma; }
karma/karma.d.ts
1
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/b13fb549b27f069cb40346a4a835dc7c229aba8b
[ 0.4909285604953766, 0.013071934692561626, 0.0001655742817092687, 0.0002467352896928787, 0.07752040028572083 ]
{ "id": 5, "code_window": [ " * @default []\n", " * @description List of files/patterns to load in the browser.\n", " */\n", " files?: (FilePattern|string)[];\n", " /**\n", " * @default []\n", " * @description List of test frameworks you want to use. Typically, you will set this to ['jasmine'], ['mocha'] or ['qunit']...\n", " * Please note just about all frameworks in Karma require an additional plugin/framework library to be installed (via NPM).\n", " */\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " files?: (FilePattern | string)[];\n" ], "file_path": "karma/karma.d.ts", "type": "replace", "edit_start_line_idx": 193 }
/// <reference path="../../yui/yui.d.ts" /> /// <reference path="../cryptojs.d.ts" /> YUI.add('enc-latin1-test', function (Y) { var C = CryptoJS; Y.Test.Runner.add(new Y.Test.Case({ name: 'Latin1', testStringify: function () { Y.Assert.areEqual('\x12\x34\x56\x78', C.enc.Latin1.stringify(C.lib.WordArray.create([0x12345678]))); }, testParse: function () { Y.Assert.areEqual(C.lib.WordArray.create([0x12345678]).toString(), C.enc.Latin1.parse('\x12\x34\x56\x78').toString()); } })); }, '$Rev$');
cryptojs/test/enc-latin1-tests.ts
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/b13fb549b27f069cb40346a4a835dc7c229aba8b
[ 0.00017294335702899843, 0.00017224566545337439, 0.00017154797387775034, 0.00017224566545337439, 6.976915756240487e-7 ]