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": 8,
"code_window": [
"\t}\n",
"\tadapters[name] = log\n",
"}\n",
"\n",
"type logMsg struct {\n",
"\tskip, level int\n",
"\tmsg string\n",
"}\n",
"\n",
"// Logger is default logger in beego application.\n",
"// it can contain several providers and log message into all providers.\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tskip int\n",
"\tlevel LogLevel\n",
"\tmsg string\n"
],
"file_path": "pkg/log/log.go",
"type": "replace",
"edit_start_line_idx": 134
} |
import {describe, beforeEach, it, sinon, expect} from 'test/lib/common';
import queryPart from '../query_part';
describe('InfluxQueryPart', () => {
describe('series with mesurement only', () => {
it('should handle nested function parts', () => {
var part = queryPart.create({
type: 'derivative',
params: ['10s'],
});
expect(part.text).to.be('derivative(10s)');
expect(part.render('mean(value)')).to.be('derivative(mean(value), 10s)');
});
it('should handle suffirx parts', () => {
var part = queryPart.create({
type: 'math',
params: ['/ 100'],
});
expect(part.text).to.be('math(/ 100)');
expect(part.render('mean(value)')).to.be('mean(value) / 100');
});
it('should handle alias parts', () => {
var part = queryPart.create({
type: 'alias',
params: ['test'],
});
expect(part.text).to.be('alias(test)');
expect(part.render('mean(value)')).to.be('mean(value) AS "test"');
});
});
});
| public/app/plugins/datasource/influxdb/specs/query_part_specs.ts | 0 | https://github.com/grafana/grafana/commit/bf943ddba38ced67da56f0cfd847760f41d31e61 | [
0.00017283964552916586,
0.00016971809964161366,
0.00016504091036040336,
0.00017123176075983793,
0.000003239269972254988
] |
{
"id": 8,
"code_window": [
"\t}\n",
"\tadapters[name] = log\n",
"}\n",
"\n",
"type logMsg struct {\n",
"\tskip, level int\n",
"\tmsg string\n",
"}\n",
"\n",
"// Logger is default logger in beego application.\n",
"// it can contain several providers and log message into all providers.\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tskip int\n",
"\tlevel LogLevel\n",
"\tmsg string\n"
],
"file_path": "pkg/log/log.go",
"type": "replace",
"edit_start_line_idx": 134
} | // Copyright 2011 The Snappy-Go Authors. All rights reserved.
// Modified for deflate by Klaus Post (c) 2015.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package flate
// We limit how far copy back-references can go, the same as the C++ code.
const maxOffset = 1 << 15
// emitLiteral writes a literal chunk and returns the number of bytes written.
func emitLiteral(dst *tokens, lit []byte) {
ol := dst.n
for i, v := range lit {
dst.tokens[i+ol] = token(v)
}
dst.n += len(lit)
}
// emitCopy writes a copy chunk and returns the number of bytes written.
func emitCopy(dst *tokens, offset, length int) {
dst.tokens[dst.n] = matchToken(uint32(length-3), uint32(offset-minOffsetSize))
dst.n++
}
// snappyEncode uses Snappy-like compression, but stores as Huffman
// blocks.
func snappyEncode(dst *tokens, src []byte) {
// Return early if src is short.
if len(src) <= 4 {
if len(src) != 0 {
emitLiteral(dst, src)
}
return
}
// Initialize the hash table. Its size ranges from 1<<8 to 1<<14 inclusive.
const maxTableSize = 1 << 14
shift, tableSize := uint(32-8), 1<<8
for tableSize < maxTableSize && tableSize < len(src) {
shift--
tableSize *= 2
}
var table [maxTableSize]int
var misses int
// Iterate over the source bytes.
var (
s int // The iterator position.
t int // The last position with the same hash as s.
lit int // The start position of any pending literal bytes.
)
for s+3 < len(src) {
// Update the hash table.
b0, b1, b2, b3 := src[s], src[s+1], src[s+2], src[s+3]
h := uint32(b0) | uint32(b1)<<8 | uint32(b2)<<16 | uint32(b3)<<24
p := &table[(h*0x1e35a7bd)>>shift]
// We need to to store values in [-1, inf) in table. To save
// some initialization time, (re)use the table's zero value
// and shift the values against this zero: add 1 on writes,
// subtract 1 on reads.
t, *p = *p-1, s+1
// If t is invalid or src[s:s+4] differs from src[t:t+4], accumulate a literal byte.
if t < 0 || s-t >= maxOffset || b0 != src[t] || b1 != src[t+1] || b2 != src[t+2] || b3 != src[t+3] {
misses++
// Skip 1 byte for 16 consecutive missed.
s += 1 + (misses >> 4)
continue
}
// Otherwise, we have a match. First, emit any pending literal bytes.
if lit != s {
emitLiteral(dst, src[lit:s])
}
// Extend the match to be as long as possible.
s0 := s
s1 := s + maxMatchLength
if s1 > len(src) {
s1 = len(src)
}
s, t = s+4, t+4
for s < s1 && src[s] == src[t] {
s++
t++
}
misses = 0
// Emit the copied bytes.
// inlined: emitCopy(dst, s-t, s-s0)
dst.tokens[dst.n] = matchToken(uint32(s-s0-3), uint32(s-t-minOffsetSize))
dst.n++
lit = s
}
// Emit any final pending literal bytes and return.
if lit != len(src) {
emitLiteral(dst, src[lit:])
}
}
| Godeps/_workspace/src/github.com/klauspost/compress/flate/snappy.go | 0 | https://github.com/grafana/grafana/commit/bf943ddba38ced67da56f0cfd847760f41d31e61 | [
0.00017404741083737463,
0.00017021840903908014,
0.0001673855003900826,
0.0001698216947261244,
0.000002021407453867141
] |
{
"id": 9,
"code_window": [
"type Logger struct {\n",
"\tadapter string\n",
"\tlock sync.Mutex\n",
"\tlevel int\n",
"\tmsg chan *logMsg\n",
"\toutputs map[string]LoggerInterface\n",
"\tquit chan bool\n",
"}\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tlevel LogLevel\n"
],
"file_path": "pkg/log/log.go",
"type": "replace",
"edit_start_line_idx": 143
} | // Copyright 2014 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package log
import (
"fmt"
"os"
"path/filepath"
"runtime"
"strings"
"sync"
)
var (
loggers []*Logger
)
func NewLogger(bufLen int64, mode, config string) {
logger := newLogger(bufLen)
isExist := false
for _, l := range loggers {
if l.adapter == mode {
isExist = true
l = logger
}
}
if !isExist {
loggers = append(loggers, logger)
}
if err := logger.SetLogger(mode, config); err != nil {
Fatal(1, "Fail to set logger(%s): %v", mode, err)
}
}
func Trace(format string, v ...interface{}) {
for _, logger := range loggers {
logger.Trace(format, v...)
}
}
func Debug(format string, v ...interface{}) {
for _, logger := range loggers {
logger.Debug(format, v...)
}
}
func Info(format string, v ...interface{}) {
for _, logger := range loggers {
logger.Info(format, v...)
}
}
func Warn(format string, v ...interface{}) {
for _, logger := range loggers {
logger.Warn(format, v...)
}
}
func Error(skip int, format string, v ...interface{}) {
for _, logger := range loggers {
logger.Error(skip, format, v...)
}
}
func Critical(skip int, format string, v ...interface{}) {
for _, logger := range loggers {
logger.Critical(skip, format, v...)
}
}
func Fatal(skip int, format string, v ...interface{}) {
Error(skip, format, v...)
for _, l := range loggers {
l.Close()
}
os.Exit(1)
}
func Close() {
for _, l := range loggers {
l.Close()
// delete the logger.
l = nil
}
// clear the loggers slice.
loggers = nil
}
// .___ __ _____
// | | _____/ |_ ____________/ ____\____ ____ ____
// | |/ \ __\/ __ \_ __ \ __\\__ \ _/ ___\/ __ \
// | | | \ | \ ___/| | \/| | / __ \\ \__\ ___/
// |___|___| /__| \___ >__| |__| (____ /\___ >___ >
// \/ \/ \/ \/ \/
type LogLevel int
const (
TRACE = iota
DEBUG
INFO
WARN
ERROR
CRITICAL
FATAL
)
// LoggerInterface represents behaviors of a logger provider.
type LoggerInterface interface {
Init(config string) error
WriteMsg(msg string, skip, level int) error
Destroy()
Flush()
}
type loggerType func() LoggerInterface
var adapters = make(map[string]loggerType)
// Register registers given logger provider to adapters.
func Register(name string, log loggerType) {
if log == nil {
panic("log: register provider is nil")
}
if _, dup := adapters[name]; dup {
panic("log: register called twice for provider \"" + name + "\"")
}
adapters[name] = log
}
type logMsg struct {
skip, level int
msg string
}
// Logger is default logger in beego application.
// it can contain several providers and log message into all providers.
type Logger struct {
adapter string
lock sync.Mutex
level int
msg chan *logMsg
outputs map[string]LoggerInterface
quit chan bool
}
// newLogger initializes and returns a new logger.
func newLogger(buffer int64) *Logger {
l := &Logger{
msg: make(chan *logMsg, buffer),
outputs: make(map[string]LoggerInterface),
quit: make(chan bool),
}
go l.StartLogger()
return l
}
// SetLogger sets new logger instanse with given logger adapter and config.
func (l *Logger) SetLogger(adapter string, config string) error {
l.lock.Lock()
defer l.lock.Unlock()
if log, ok := adapters[adapter]; ok {
lg := log()
if err := lg.Init(config); err != nil {
return err
}
l.outputs[adapter] = lg
l.adapter = adapter
} else {
panic("log: unknown adapter \"" + adapter + "\" (forgotten register?)")
}
return nil
}
// DelLogger removes a logger adapter instance.
func (l *Logger) DelLogger(adapter string) error {
l.lock.Lock()
defer l.lock.Unlock()
if lg, ok := l.outputs[adapter]; ok {
lg.Destroy()
delete(l.outputs, adapter)
} else {
panic("log: unknown adapter \"" + adapter + "\" (forgotten register?)")
}
return nil
}
func (l *Logger) writerMsg(skip, level int, msg string) error {
if l.level > level {
return nil
}
lm := &logMsg{
skip: skip,
level: level,
}
// Only error information needs locate position for debugging.
if lm.level >= ERROR {
pc, file, line, ok := runtime.Caller(skip)
if ok {
// Get caller function name.
fn := runtime.FuncForPC(pc)
var fnName string
if fn == nil {
fnName = "?()"
} else {
fnName = strings.TrimLeft(filepath.Ext(fn.Name()), ".") + "()"
}
lm.msg = fmt.Sprintf("[%s:%d %s] %s", filepath.Base(file), line, fnName, msg)
} else {
lm.msg = msg
}
} else {
lm.msg = msg
}
l.msg <- lm
return nil
}
// StartLogger starts logger chan reading.
func (l *Logger) StartLogger() {
for {
select {
case bm := <-l.msg:
for _, l := range l.outputs {
if err := l.WriteMsg(bm.msg, bm.skip, bm.level); err != nil {
fmt.Println("ERROR, unable to WriteMsg:", err)
}
}
case <-l.quit:
return
}
}
}
// Flush flushs all chan data.
func (l *Logger) Flush() {
for _, l := range l.outputs {
l.Flush()
}
}
// Close closes logger, flush all chan data and destroy all adapter instances.
func (l *Logger) Close() {
l.quit <- true
for {
if len(l.msg) > 0 {
bm := <-l.msg
for _, l := range l.outputs {
if err := l.WriteMsg(bm.msg, bm.skip, bm.level); err != nil {
fmt.Println("ERROR, unable to WriteMsg:", err)
}
}
} else {
break
}
}
for _, l := range l.outputs {
l.Flush()
l.Destroy()
}
}
func (l *Logger) Trace(format string, v ...interface{}) {
msg := fmt.Sprintf("[T] "+format, v...)
l.writerMsg(0, TRACE, msg)
}
func (l *Logger) Debug(format string, v ...interface{}) {
msg := fmt.Sprintf("[D] "+format, v...)
l.writerMsg(0, DEBUG, msg)
}
func (l *Logger) Info(format string, v ...interface{}) {
msg := fmt.Sprintf("[I] "+format, v...)
l.writerMsg(0, INFO, msg)
}
func (l *Logger) Warn(format string, v ...interface{}) {
msg := fmt.Sprintf("[W] "+format, v...)
l.writerMsg(0, WARN, msg)
}
func (l *Logger) Error(skip int, format string, v ...interface{}) {
msg := fmt.Sprintf("[E] "+format, v...)
l.writerMsg(skip, ERROR, msg)
}
func (l *Logger) Critical(skip int, format string, v ...interface{}) {
msg := fmt.Sprintf("[C] "+format, v...)
l.writerMsg(skip, CRITICAL, msg)
}
func (l *Logger) Fatal(skip int, format string, v ...interface{}) {
msg := fmt.Sprintf("[F] "+format, v...)
l.writerMsg(skip, FATAL, msg)
l.Close()
os.Exit(1)
}
| pkg/log/log.go | 1 | https://github.com/grafana/grafana/commit/bf943ddba38ced67da56f0cfd847760f41d31e61 | [
0.9889203906059265,
0.37773799896240234,
0.00017177862173411995,
0.06091661751270294,
0.42958536744117737
] |
{
"id": 9,
"code_window": [
"type Logger struct {\n",
"\tadapter string\n",
"\tlock sync.Mutex\n",
"\tlevel int\n",
"\tmsg chan *logMsg\n",
"\toutputs map[string]LoggerInterface\n",
"\tquit chan bool\n",
"}\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tlevel LogLevel\n"
],
"file_path": "pkg/log/log.go",
"type": "replace",
"edit_start_line_idx": 143
} | package queryutil
import (
"encoding/base64"
"fmt"
"net/url"
"reflect"
"sort"
"strconv"
"strings"
"time"
)
// Parse parses an object i and fills a url.Values object. The isEC2 flag
// indicates if this is the EC2 Query sub-protocol.
func Parse(body url.Values, i interface{}, isEC2 bool) error {
q := queryParser{isEC2: isEC2}
return q.parseValue(body, reflect.ValueOf(i), "", "")
}
func elemOf(value reflect.Value) reflect.Value {
for value.Kind() == reflect.Ptr {
value = value.Elem()
}
return value
}
type queryParser struct {
isEC2 bool
}
func (q *queryParser) parseValue(v url.Values, value reflect.Value, prefix string, tag reflect.StructTag) error {
value = elemOf(value)
// no need to handle zero values
if !value.IsValid() {
return nil
}
t := tag.Get("type")
if t == "" {
switch value.Kind() {
case reflect.Struct:
t = "structure"
case reflect.Slice:
t = "list"
case reflect.Map:
t = "map"
}
}
switch t {
case "structure":
return q.parseStruct(v, value, prefix)
case "list":
return q.parseList(v, value, prefix, tag)
case "map":
return q.parseMap(v, value, prefix, tag)
default:
return q.parseScalar(v, value, prefix, tag)
}
}
func (q *queryParser) parseStruct(v url.Values, value reflect.Value, prefix string) error {
if !value.IsValid() {
return nil
}
t := value.Type()
for i := 0; i < value.NumField(); i++ {
if c := t.Field(i).Name[0:1]; strings.ToLower(c) == c {
continue // ignore unexported fields
}
value := elemOf(value.Field(i))
field := t.Field(i)
var name string
if q.isEC2 {
name = field.Tag.Get("queryName")
}
if name == "" {
if field.Tag.Get("flattened") != "" && field.Tag.Get("locationNameList") != "" {
name = field.Tag.Get("locationNameList")
} else if locName := field.Tag.Get("locationName"); locName != "" {
name = locName
}
if name != "" && q.isEC2 {
name = strings.ToUpper(name[0:1]) + name[1:]
}
}
if name == "" {
name = field.Name
}
if prefix != "" {
name = prefix + "." + name
}
if err := q.parseValue(v, value, name, field.Tag); err != nil {
return err
}
}
return nil
}
func (q *queryParser) parseList(v url.Values, value reflect.Value, prefix string, tag reflect.StructTag) error {
// If it's empty, generate an empty value
if !value.IsNil() && value.Len() == 0 {
v.Set(prefix, "")
return nil
}
// check for unflattened list member
if !q.isEC2 && tag.Get("flattened") == "" {
prefix += ".member"
}
for i := 0; i < value.Len(); i++ {
slicePrefix := prefix
if slicePrefix == "" {
slicePrefix = strconv.Itoa(i + 1)
} else {
slicePrefix = slicePrefix + "." + strconv.Itoa(i+1)
}
if err := q.parseValue(v, value.Index(i), slicePrefix, ""); err != nil {
return err
}
}
return nil
}
func (q *queryParser) parseMap(v url.Values, value reflect.Value, prefix string, tag reflect.StructTag) error {
// If it's empty, generate an empty value
if !value.IsNil() && value.Len() == 0 {
v.Set(prefix, "")
return nil
}
// check for unflattened list member
if !q.isEC2 && tag.Get("flattened") == "" {
prefix += ".entry"
}
// sort keys for improved serialization consistency.
// this is not strictly necessary for protocol support.
mapKeyValues := value.MapKeys()
mapKeys := map[string]reflect.Value{}
mapKeyNames := make([]string, len(mapKeyValues))
for i, mapKey := range mapKeyValues {
name := mapKey.String()
mapKeys[name] = mapKey
mapKeyNames[i] = name
}
sort.Strings(mapKeyNames)
for i, mapKeyName := range mapKeyNames {
mapKey := mapKeys[mapKeyName]
mapValue := value.MapIndex(mapKey)
kname := tag.Get("locationNameKey")
if kname == "" {
kname = "key"
}
vname := tag.Get("locationNameValue")
if vname == "" {
vname = "value"
}
// serialize key
var keyName string
if prefix == "" {
keyName = strconv.Itoa(i+1) + "." + kname
} else {
keyName = prefix + "." + strconv.Itoa(i+1) + "." + kname
}
if err := q.parseValue(v, mapKey, keyName, ""); err != nil {
return err
}
// serialize value
var valueName string
if prefix == "" {
valueName = strconv.Itoa(i+1) + "." + vname
} else {
valueName = prefix + "." + strconv.Itoa(i+1) + "." + vname
}
if err := q.parseValue(v, mapValue, valueName, ""); err != nil {
return err
}
}
return nil
}
func (q *queryParser) parseScalar(v url.Values, r reflect.Value, name string, tag reflect.StructTag) error {
switch value := r.Interface().(type) {
case string:
v.Set(name, value)
case []byte:
if !r.IsNil() {
v.Set(name, base64.StdEncoding.EncodeToString(value))
}
case bool:
v.Set(name, strconv.FormatBool(value))
case int64:
v.Set(name, strconv.FormatInt(value, 10))
case int:
v.Set(name, strconv.Itoa(value))
case float64:
v.Set(name, strconv.FormatFloat(value, 'f', -1, 64))
case float32:
v.Set(name, strconv.FormatFloat(float64(value), 'f', -1, 32))
case time.Time:
const ISO8601UTC = "2006-01-02T15:04:05Z"
v.Set(name, value.UTC().Format(ISO8601UTC))
default:
return fmt.Errorf("unsupported value for param %s: %v (%s)", name, r.Interface(), r.Type().Name())
}
return nil
}
| Godeps/_workspace/src/github.com/aws/aws-sdk-go/internal/protocol/query/queryutil/queryutil.go | 0 | https://github.com/grafana/grafana/commit/bf943ddba38ced67da56f0cfd847760f41d31e61 | [
0.00020111074263695627,
0.00017682324687484652,
0.00016806456551421434,
0.0001737351849442348,
0.000009880876859824639
] |
{
"id": 9,
"code_window": [
"type Logger struct {\n",
"\tadapter string\n",
"\tlock sync.Mutex\n",
"\tlevel int\n",
"\tmsg chan *logMsg\n",
"\toutputs map[string]LoggerInterface\n",
"\tquit chan bool\n",
"}\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tlevel LogLevel\n"
],
"file_path": "pkg/log/log.go",
"type": "replace",
"edit_start_line_idx": 143
} | foo.nested.*.{a: a,b: b} | Godeps/_workspace/src/github.com/jmespath/go-jmespath/fuzz/corpus/expr-430 | 0 | https://github.com/grafana/grafana/commit/bf943ddba38ced67da56f0cfd847760f41d31e61 | [
0.0001701132714515552,
0.0001701132714515552,
0.0001701132714515552,
0.0001701132714515552,
0
] |
{
"id": 9,
"code_window": [
"type Logger struct {\n",
"\tadapter string\n",
"\tlock sync.Mutex\n",
"\tlevel int\n",
"\tmsg chan *logMsg\n",
"\toutputs map[string]LoggerInterface\n",
"\tquit chan bool\n",
"}\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tlevel LogLevel\n"
],
"file_path": "pkg/log/log.go",
"type": "replace",
"edit_start_line_idx": 143
} | /*!
* Bootstrap v2.3.2
*
* Copyright 2013 Twitter, Inc
* Licensed under the Apache License v2.0
* http://www.apache.org/licenses/LICENSE-2.0
*
* Designed and built with all the love in the world by @mdo and @fat.
*/
// Core variables and mixins
@import "variables.less"; // Modify this for custom colors, font-sizes, etc
@import "mixins.less";
// CSS Reset
@import "reset.less";
// Grid system and page structure
@import "scaffolding.less";
@import "grid.less";
@import "layouts.less";
// Base CSS
@import "type.less";
@import "forms.less";
@import "tables.less";
// Components: common
@import "dropdowns.less";
@import "component-animations.less";
@import "close.less";
// Components: Buttons & Alerts
@import "buttons.less";
@import "button-groups.less";
@import "alerts.less"; // Note: alerts share common CSS with buttons and thus have styles in buttons.less
// Components: Nav
@import "navs.less";
@import "navbar.less";
// Components: Popovers
@import "modals.less";
@import "tooltip.less";
@import "popovers.less";
// Components: Misc
@import "media.less";
@import "labels-badges.less";
// Utility classes
@import "utilities.less"; // Has to be last to override when necessary
| public/vendor/bootstrap/less/bootstrap.less | 0 | https://github.com/grafana/grafana/commit/bf943ddba38ced67da56f0cfd847760f41d31e61 | [
0.00017518879030831158,
0.0001730947260512039,
0.00017092557391151786,
0.00017314896103926003,
0.0000014063816706766374
] |
{
"id": 10,
"code_window": [
"\treturn nil\n",
"}\n",
"\n",
"func (l *Logger) writerMsg(skip, level int, msg string) error {\n",
"\tif l.level > level {\n",
"\t\treturn nil\n",
"\t}\n",
"\tlm := &logMsg{\n",
"\t\tskip: skip,\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"func (l *Logger) writerMsg(skip int, level LogLevel, msg string) error {\n"
],
"file_path": "pkg/log/log.go",
"type": "replace",
"edit_start_line_idx": 190
} | // Copyright 2014 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package log
import (
"encoding/json"
"fmt"
"log"
"os"
"runtime"
)
type Brush func(string) string
func NewBrush(color string) Brush {
pre := "\033["
reset := "\033[0m"
return func(text string) string {
return pre + color + "m" + text + reset
}
}
var (
Red = NewBrush("1;31")
Purple = NewBrush("1;35")
Yellow = NewBrush("1;33")
Green = NewBrush("1;32")
Blue = NewBrush("1;34")
Cyan = NewBrush("1;36")
colors = []Brush{
Cyan, // Trace cyan
Blue, // Debug blue
Green, // Info green
Yellow, // Warn yellow
Red, // Error red
Purple, // Critical purple
Red, // Fatal red
}
consoleWriter = &ConsoleWriter{lg: log.New(os.Stdout, "", 0),
Level: TRACE}
)
// ConsoleWriter implements LoggerInterface and writes messages to terminal.
type ConsoleWriter struct {
lg *log.Logger
Level int `json:"level"`
Formatting bool `json:"formatting"`
}
// create ConsoleWriter returning as LoggerInterface.
func NewConsole() LoggerInterface {
return &ConsoleWriter{
lg: log.New(os.Stderr, "", log.Ldate|log.Ltime),
Level: TRACE,
Formatting: true,
}
}
func (cw *ConsoleWriter) Init(config string) error {
return json.Unmarshal([]byte(config), cw)
}
func (cw *ConsoleWriter) WriteMsg(msg string, skip, level int) error {
if cw.Level > level {
return nil
}
if runtime.GOOS == "windows" || !cw.Formatting {
cw.lg.Println(msg)
} else {
cw.lg.Println(colors[level](msg))
}
return nil
}
func (_ *ConsoleWriter) Flush() {
}
func (_ *ConsoleWriter) Destroy() {
}
func printConsole(level int, msg string) {
consoleWriter.WriteMsg(msg, 0, level)
}
func printfConsole(level int, format string, v ...interface{}) {
consoleWriter.WriteMsg(fmt.Sprintf(format, v...), 0, level)
}
// ConsoleTrace prints to stdout using TRACE colors
func ConsoleTrace(s string) {
printConsole(TRACE, s)
}
// ConsoleTracef prints a formatted string to stdout using TRACE colors
func ConsoleTracef(format string, v ...interface{}) {
printfConsole(TRACE, format, v...)
}
// ConsoleDebug prints to stdout using DEBUG colors
func ConsoleDebug(s string) {
printConsole(DEBUG, s)
}
// ConsoleDebugf prints a formatted string to stdout using DEBUG colors
func ConsoleDebugf(format string, v ...interface{}) {
printfConsole(DEBUG, format, v...)
}
// ConsoleInfo prints to stdout using INFO colors
func ConsoleInfo(s string) {
printConsole(INFO, s)
}
// ConsoleInfof prints a formatted string to stdout using INFO colors
func ConsoleInfof(format string, v ...interface{}) {
printfConsole(INFO, format, v...)
}
// ConsoleWarn prints to stdout using WARN colors
func ConsoleWarn(s string) {
printConsole(WARN, s)
}
// ConsoleWarnf prints a formatted string to stdout using WARN colors
func ConsoleWarnf(format string, v ...interface{}) {
printfConsole(WARN, format, v...)
}
// ConsoleError prints to stdout using ERROR colors
func ConsoleError(s string) {
printConsole(ERROR, s)
}
// ConsoleErrorf prints a formatted string to stdout using ERROR colors
func ConsoleErrorf(format string, v ...interface{}) {
printfConsole(ERROR, format, v...)
}
// ConsoleFatal prints to stdout using FATAL colors
func ConsoleFatal(s string) {
printConsole(FATAL, s)
os.Exit(1)
}
// ConsoleFatalf prints a formatted string to stdout using FATAL colors
func ConsoleFatalf(format string, v ...interface{}) {
printfConsole(FATAL, format, v...)
os.Exit(1)
}
func init() {
Register("console", NewConsole)
}
| pkg/log/console.go | 1 | https://github.com/grafana/grafana/commit/bf943ddba38ced67da56f0cfd847760f41d31e61 | [
0.9485310912132263,
0.17948836088180542,
0.0001718595449347049,
0.0016393575351685286,
0.3658197224140167
] |
{
"id": 10,
"code_window": [
"\treturn nil\n",
"}\n",
"\n",
"func (l *Logger) writerMsg(skip, level int, msg string) error {\n",
"\tif l.level > level {\n",
"\t\treturn nil\n",
"\t}\n",
"\tlm := &logMsg{\n",
"\t\tskip: skip,\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"func (l *Logger) writerMsg(skip int, level LogLevel, msg string) error {\n"
],
"file_path": "pkg/log/log.go",
"type": "replace",
"edit_start_line_idx": 190
} | I_ | Godeps/_workspace/src/github.com/jmespath/go-jmespath/fuzz/corpus/expr-295 | 0 | https://github.com/grafana/grafana/commit/bf943ddba38ced67da56f0cfd847760f41d31e61 | [
0.00019649490423034877,
0.00019649490423034877,
0.00019649490423034877,
0.00019649490423034877,
0
] |
{
"id": 10,
"code_window": [
"\treturn nil\n",
"}\n",
"\n",
"func (l *Logger) writerMsg(skip, level int, msg string) error {\n",
"\tif l.level > level {\n",
"\t\treturn nil\n",
"\t}\n",
"\tlm := &logMsg{\n",
"\t\tskip: skip,\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"func (l *Logger) writerMsg(skip int, level LogLevel, msg string) error {\n"
],
"file_path": "pkg/log/log.go",
"type": "replace",
"edit_start_line_idx": 190
} | m_ | Godeps/_workspace/src/github.com/jmespath/go-jmespath/fuzz/corpus/expr-246 | 0 | https://github.com/grafana/grafana/commit/bf943ddba38ced67da56f0cfd847760f41d31e61 | [
0.0002693219284992665,
0.0002693219284992665,
0.0002693219284992665,
0.0002693219284992665,
0
] |
{
"id": 10,
"code_window": [
"\treturn nil\n",
"}\n",
"\n",
"func (l *Logger) writerMsg(skip, level int, msg string) error {\n",
"\tif l.level > level {\n",
"\t\treturn nil\n",
"\t}\n",
"\tlm := &logMsg{\n",
"\t\tskip: skip,\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"func (l *Logger) writerMsg(skip int, level LogLevel, msg string) error {\n"
],
"file_path": "pkg/log/log.go",
"type": "replace",
"edit_start_line_idx": 190
} | #! /usr/bin/env bash
version=2.6.0
wget https://grafanarel.s3.amazonaws.com/builds/grafana_${version}_amd64.deb
package_cloud push grafana/stable/debian/jessie grafana_${version}_amd64.deb
package_cloud push grafana/stable/debian/wheezy grafana_${version}_amd64.deb
package_cloud push grafana/testing/debian/jessie grafana_${version}_amd64.deb
package_cloud push grafana/testing/debian/wheezy grafana_${version}_amd64.deb
wget https://grafanarel.s3.amazonaws.com/builds/grafana-${version}-1.x86_64.rpm
package_cloud push grafana/testing/el/6 grafana-${version}-1.x86_64.rpm
package_cloud push grafana/testing/el/7 grafana-${version}-1.x86_64.rpm
package_cloud push grafana/stable/el/7 grafana-${version}-1.x86_64.rpm
package_cloud push grafana/stable/el/6 grafana-${version}-1.x86_64.rpm
| packaging/publish/publish.sh | 0 | https://github.com/grafana/grafana/commit/bf943ddba38ced67da56f0cfd847760f41d31e61 | [
0.00018273177556693554,
0.00017700095486361533,
0.00017127013416029513,
0.00017700095486361533,
0.000005730820703320205
] |
{
"id": 11,
"code_window": [
"\n",
"\tsw.syslog = w\n",
"\treturn nil\n",
"}\n",
"\n",
"func (sw *SyslogWriter) WriteMsg(msg string, skip, level int) error {\n",
"\tvar err error\n",
"\n",
"\tswitch level {\n",
"\tcase TRACE, DEBUG:\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"func (sw *SyslogWriter) WriteMsg(msg string, skip int, level LogLevel) error {\n"
],
"file_path": "pkg/log/syslog.go",
"type": "replace",
"edit_start_line_idx": 41
} | // Copyright 2014 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package log
import (
"encoding/json"
"fmt"
"log"
"os"
"runtime"
)
type Brush func(string) string
func NewBrush(color string) Brush {
pre := "\033["
reset := "\033[0m"
return func(text string) string {
return pre + color + "m" + text + reset
}
}
var (
Red = NewBrush("1;31")
Purple = NewBrush("1;35")
Yellow = NewBrush("1;33")
Green = NewBrush("1;32")
Blue = NewBrush("1;34")
Cyan = NewBrush("1;36")
colors = []Brush{
Cyan, // Trace cyan
Blue, // Debug blue
Green, // Info green
Yellow, // Warn yellow
Red, // Error red
Purple, // Critical purple
Red, // Fatal red
}
consoleWriter = &ConsoleWriter{lg: log.New(os.Stdout, "", 0),
Level: TRACE}
)
// ConsoleWriter implements LoggerInterface and writes messages to terminal.
type ConsoleWriter struct {
lg *log.Logger
Level int `json:"level"`
Formatting bool `json:"formatting"`
}
// create ConsoleWriter returning as LoggerInterface.
func NewConsole() LoggerInterface {
return &ConsoleWriter{
lg: log.New(os.Stderr, "", log.Ldate|log.Ltime),
Level: TRACE,
Formatting: true,
}
}
func (cw *ConsoleWriter) Init(config string) error {
return json.Unmarshal([]byte(config), cw)
}
func (cw *ConsoleWriter) WriteMsg(msg string, skip, level int) error {
if cw.Level > level {
return nil
}
if runtime.GOOS == "windows" || !cw.Formatting {
cw.lg.Println(msg)
} else {
cw.lg.Println(colors[level](msg))
}
return nil
}
func (_ *ConsoleWriter) Flush() {
}
func (_ *ConsoleWriter) Destroy() {
}
func printConsole(level int, msg string) {
consoleWriter.WriteMsg(msg, 0, level)
}
func printfConsole(level int, format string, v ...interface{}) {
consoleWriter.WriteMsg(fmt.Sprintf(format, v...), 0, level)
}
// ConsoleTrace prints to stdout using TRACE colors
func ConsoleTrace(s string) {
printConsole(TRACE, s)
}
// ConsoleTracef prints a formatted string to stdout using TRACE colors
func ConsoleTracef(format string, v ...interface{}) {
printfConsole(TRACE, format, v...)
}
// ConsoleDebug prints to stdout using DEBUG colors
func ConsoleDebug(s string) {
printConsole(DEBUG, s)
}
// ConsoleDebugf prints a formatted string to stdout using DEBUG colors
func ConsoleDebugf(format string, v ...interface{}) {
printfConsole(DEBUG, format, v...)
}
// ConsoleInfo prints to stdout using INFO colors
func ConsoleInfo(s string) {
printConsole(INFO, s)
}
// ConsoleInfof prints a formatted string to stdout using INFO colors
func ConsoleInfof(format string, v ...interface{}) {
printfConsole(INFO, format, v...)
}
// ConsoleWarn prints to stdout using WARN colors
func ConsoleWarn(s string) {
printConsole(WARN, s)
}
// ConsoleWarnf prints a formatted string to stdout using WARN colors
func ConsoleWarnf(format string, v ...interface{}) {
printfConsole(WARN, format, v...)
}
// ConsoleError prints to stdout using ERROR colors
func ConsoleError(s string) {
printConsole(ERROR, s)
}
// ConsoleErrorf prints a formatted string to stdout using ERROR colors
func ConsoleErrorf(format string, v ...interface{}) {
printfConsole(ERROR, format, v...)
}
// ConsoleFatal prints to stdout using FATAL colors
func ConsoleFatal(s string) {
printConsole(FATAL, s)
os.Exit(1)
}
// ConsoleFatalf prints a formatted string to stdout using FATAL colors
func ConsoleFatalf(format string, v ...interface{}) {
printfConsole(FATAL, format, v...)
os.Exit(1)
}
func init() {
Register("console", NewConsole)
}
| pkg/log/console.go | 1 | https://github.com/grafana/grafana/commit/bf943ddba38ced67da56f0cfd847760f41d31e61 | [
0.9940648674964905,
0.18918809294700623,
0.0001747136702761054,
0.003283258993178606,
0.3783208429813385
] |
{
"id": 11,
"code_window": [
"\n",
"\tsw.syslog = w\n",
"\treturn nil\n",
"}\n",
"\n",
"func (sw *SyslogWriter) WriteMsg(msg string, skip, level int) error {\n",
"\tvar err error\n",
"\n",
"\tswitch level {\n",
"\tcase TRACE, DEBUG:\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"func (sw *SyslogWriter) WriteMsg(msg string, skip int, level LogLevel) error {\n"
],
"file_path": "pkg/log/syslog.go",
"type": "replace",
"edit_start_line_idx": 41
} | "0" | Godeps/_workspace/src/github.com/jmespath/go-jmespath/fuzz/corpus/expr-311 | 0 | https://github.com/grafana/grafana/commit/bf943ddba38ced67da56f0cfd847760f41d31e61 | [
0.00021786823344882578,
0.00021786823344882578,
0.00021786823344882578,
0.00021786823344882578,
0
] |
{
"id": 11,
"code_window": [
"\n",
"\tsw.syslog = w\n",
"\treturn nil\n",
"}\n",
"\n",
"func (sw *SyslogWriter) WriteMsg(msg string, skip, level int) error {\n",
"\tvar err error\n",
"\n",
"\tswitch level {\n",
"\tcase TRACE, DEBUG:\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"func (sw *SyslogWriter) WriteMsg(msg string, skip int, level LogLevel) error {\n"
],
"file_path": "pkg/log/syslog.go",
"type": "replace",
"edit_start_line_idx": 41
} | module.exports = function(config) {
return {
options: {
encoding: 'utf8',
algorithm: 'md5',
length: 8,
},
cssDark: {
src: '<%= genDir %>/css/grafana.dark.min.css',
dest: '<%= genDir %>/css'
},
cssLight: {
src: '<%= genDir %>/css/grafana.light.min.css',
dest: '<%= genDir %>/css'
},
js: {
src: '<%= genDir %>/app/boot.js',
dest: '<%= genDir %>/app'
}
};
};
| tasks/options/filerev.js | 0 | https://github.com/grafana/grafana/commit/bf943ddba38ced67da56f0cfd847760f41d31e61 | [
0.00023320542823057622,
0.00019423459889367223,
0.00017334980657324195,
0.00017614856187719852,
0.000027580214009503834
] |
{
"id": 11,
"code_window": [
"\n",
"\tsw.syslog = w\n",
"\treturn nil\n",
"}\n",
"\n",
"func (sw *SyslogWriter) WriteMsg(msg string, skip, level int) error {\n",
"\tvar err error\n",
"\n",
"\tswitch level {\n",
"\tcase TRACE, DEBUG:\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"func (sw *SyslogWriter) WriteMsg(msg string, skip int, level LogLevel) error {\n"
],
"file_path": "pkg/log/syslog.go",
"type": "replace",
"edit_start_line_idx": 41
} | {
"id": null,
"title": "Home",
"originalTitle": "Home",
"tags": [],
"style": "dark",
"timezone": "browser",
"editable": true,
"hideControls": true,
"sharedCrosshair": false,
"rows": [
{
"collapse": false,
"editable": true,
"height": "100px",
"panels": [
{
"content": "<div class=\"text-center dashboard-header\">\nHome Dashboard\n</div>",
"editable": true,
"id": 1,
"mode": "html",
"span": 12,
"style": {},
"title": "",
"transparent": true,
"type": "text"
}
],
"title": "New row"
},
{
"collapse": false,
"editable": true,
"height": "510px",
"panels": [
{
"id": 2,
"limit": 10,
"mode": "starred",
"query": "",
"span": 6,
"tags": [],
"title": "Starred dashboards",
"type": "dashlist"
},
{
"id": 3,
"limit": 10,
"mode": "search",
"query": "",
"span": 6,
"tags": [],
"title": "Dashboards",
"type": "dashlist"
}
],
"title": "Row"
}
],
"time": {
"from": "now-6h",
"to": "now"
},
"timepicker": {
"enable": false,
"refresh_intervals": [
"5s",
"10s",
"30s",
"1m",
"5m",
"15m",
"30m",
"1h",
"2h",
"1d"
],
"time_options": [
"5m",
"15m",
"1h",
"6h",
"12h",
"24h",
"2d",
"7d",
"30d"
],
"type": "timepicker"
},
"templating": {
"list": []
},
"annotations": {
"list": []
},
"schemaVersion": 9,
"version": 5,
"links": []
}
| public/dashboards/home.json | 0 | https://github.com/grafana/grafana/commit/bf943ddba38ced67da56f0cfd847760f41d31e61 | [
0.0016404874622821808,
0.00030890374910086393,
0.0001700177526799962,
0.00017550945631228387,
0.0004211001214571297
] |
{
"id": 0,
"code_window": [
"\n",
" hoistVariables(\n",
" path,\n",
" (id, name, hasInit) => {\n",
" variableIds.push(id);\n",
" if (!hasInit) {\n",
" exportNames.push(name);\n",
" exportValues.push(scope.buildUndefinedNode());\n",
" }\n",
" },\n",
" null,\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" if (!hasInit && name in exportMap) {\n",
" for (const exported of exportMap[name]) {\n",
" exportNames.push(exported);\n",
" exportValues.push(scope.buildUndefinedNode());\n",
" }\n"
],
"file_path": "packages/babel-plugin-transform-modules-systemjs/src/index.js",
"type": "replace",
"edit_start_line_idx": 508
} | System.register([], function (_export, _context) {
"use strict";
var foo;
_export("foo", void 0);
return {
setters: [],
execute: function () {}
};
});
| packages/babel-plugin-transform-modules-systemjs/test/fixtures/systemjs/export-named-4/output.mjs | 1 | https://github.com/babel/babel/commit/62df8d2b793db1dc032b9b687e48caec186b1799 | [
0.00016944727394729853,
0.0001689647469902411,
0.0001684822200331837,
0.0001689647469902411,
4.825269570574164e-7
] |
{
"id": 0,
"code_window": [
"\n",
" hoistVariables(\n",
" path,\n",
" (id, name, hasInit) => {\n",
" variableIds.push(id);\n",
" if (!hasInit) {\n",
" exportNames.push(name);\n",
" exportValues.push(scope.buildUndefinedNode());\n",
" }\n",
" },\n",
" null,\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" if (!hasInit && name in exportMap) {\n",
" for (const exported of exportMap[name]) {\n",
" exportNames.push(exported);\n",
" exportValues.push(scope.buildUndefinedNode());\n",
" }\n"
],
"file_path": "packages/babel-plugin-transform-modules-systemjs/src/index.js",
"type": "replace",
"edit_start_line_idx": 508
} | function _skipFirstGeneratorNext(fn) { return function () { var it = fn.apply(this, arguments); it.next(); return it; }; }
function gen() {
return _gen.apply(this, arguments);
}
function _gen() {
_gen = _skipFirstGeneratorNext(function* () {
let _functionSent = yield;
return _functionSent;
});
return _gen.apply(this, arguments);
}
| packages/babel-plugin-proposal-function-sent/test/fixtures/generator-kinds/statement/output.js | 0 | https://github.com/babel/babel/commit/62df8d2b793db1dc032b9b687e48caec186b1799 | [
0.00016984193644020706,
0.00016958847118075937,
0.00016933500592131168,
0.00016958847118075937,
2.534652594476938e-7
] |
{
"id": 0,
"code_window": [
"\n",
" hoistVariables(\n",
" path,\n",
" (id, name, hasInit) => {\n",
" variableIds.push(id);\n",
" if (!hasInit) {\n",
" exportNames.push(name);\n",
" exportValues.push(scope.buildUndefinedNode());\n",
" }\n",
" },\n",
" null,\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" if (!hasInit && name in exportMap) {\n",
" for (const exported of exportMap[name]) {\n",
" exportNames.push(exported);\n",
" exportValues.push(scope.buildUndefinedNode());\n",
" }\n"
],
"file_path": "packages/babel-plugin-transform-modules-systemjs/src/index.js",
"type": "replace",
"edit_start_line_idx": 508
} | {
"plugins": [
[
"moduleAttributes",
{
"version": "may-2020"
}
]
],
"sourceType": "module"
}
| packages/babel-parser/test/fixtures/experimental/module-attributes/invalid-spread-element-import-call/options.json | 0 | https://github.com/babel/babel/commit/62df8d2b793db1dc032b9b687e48caec186b1799 | [
0.000169850216479972,
0.00016876362496986985,
0.00016767704801168293,
0.00016876362496986985,
0.0000010865842341445386
] |
{
"id": 0,
"code_window": [
"\n",
" hoistVariables(\n",
" path,\n",
" (id, name, hasInit) => {\n",
" variableIds.push(id);\n",
" if (!hasInit) {\n",
" exportNames.push(name);\n",
" exportValues.push(scope.buildUndefinedNode());\n",
" }\n",
" },\n",
" null,\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" if (!hasInit && name in exportMap) {\n",
" for (const exported of exportMap[name]) {\n",
" exportNames.push(exported);\n",
" exportValues.push(scope.buildUndefinedNode());\n",
" }\n"
],
"file_path": "packages/babel-plugin-transform-modules-systemjs/src/index.js",
"type": "replace",
"edit_start_line_idx": 508
} | const x = (n) => do {
switch (n) {
case 0:
'a';
case 1:
'b';
break;
default: 'd';
case 2:
'c';
case 3:
case 4:
}
}
expect(x(0)).toBe('b');
expect(x(1)).toBe('b');
expect(x(2)).toBe('c');
expect(x(3)).toBeUndefined();
expect(x(4)).toBeUndefined();
expect(x(5)).toBe('c'); | packages/babel-plugin-proposal-do-expressions/test/fixtures/do-expression-switch-case/fallthrough-last/exec.js | 0 | https://github.com/babel/babel/commit/62df8d2b793db1dc032b9b687e48caec186b1799 | [
0.000173118882230483,
0.00017044361447915435,
0.00016904428775887936,
0.00016916765889618546,
0.000001892373688860971
] |
{
"id": 1,
"code_window": [
" \"use strict\";\n",
"\n",
" var foo;\n",
"\n",
" _export(\"foo\", void 0);\n",
"\n",
" return {\n",
" setters: [],\n",
" execute: function () {}\n",
" };\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" _export(\"bar\", void 0);\n"
],
"file_path": "packages/babel-plugin-transform-modules-systemjs/test/fixtures/systemjs/export-named-3/output.mjs",
"type": "replace",
"edit_start_line_idx": 5
} | System.register([], function (_export, _context) {
"use strict";
var foo, bar;
_export({
foo: void 0,
bar: void 0
});
return {
setters: [],
execute: function () {}
};
});
| packages/babel-plugin-transform-modules-systemjs/test/fixtures/systemjs/export-named-5/output.mjs | 1 | https://github.com/babel/babel/commit/62df8d2b793db1dc032b9b687e48caec186b1799 | [
0.8992881178855896,
0.44992589950561523,
0.0005637019057758152,
0.44992589950561523,
0.44936221837997437
] |
{
"id": 1,
"code_window": [
" \"use strict\";\n",
"\n",
" var foo;\n",
"\n",
" _export(\"foo\", void 0);\n",
"\n",
" return {\n",
" setters: [],\n",
" execute: function () {}\n",
" };\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" _export(\"bar\", void 0);\n"
],
"file_path": "packages/babel-plugin-transform-modules-systemjs/test/fixtures/systemjs/export-named-3/output.mjs",
"type": "replace",
"edit_start_line_idx": 5
} | {
"type": "File",
"start":0,"end":14,"loc":{"start":{"line":1,"column":0},"end":{"line":1,"column":14}},
"program": {
"type": "Program",
"start":0,"end":14,"loc":{"start":{"line":1,"column":0},"end":{"line":1,"column":14}},
"sourceType": "module",
"interpreter": null,
"body": [
{
"type": "ExpressionStatement",
"start":0,"end":14,"loc":{"start":{"line":1,"column":0},"end":{"line":1,"column":14}},
"expression": {
"type": "CallExpression",
"start":0,"end":13,"loc":{"start":{"line":1,"column":0},"end":{"line":1,"column":13}},
"callee": {
"type": "Identifier",
"start":0,"end":1,"loc":{"start":{"line":1,"column":0},"end":{"line":1,"column":1},"identifierName":"f"},
"name": "f"
},
"arguments": [
{
"type": "BinaryExpression",
"start":2,"end":7,"loc":{"start":{"line":1,"column":2},"end":{"line":1,"column":7}},
"left": {
"type": "Identifier",
"start":2,"end":3,"loc":{"start":{"line":1,"column":2},"end":{"line":1,"column":3},"identifierName":"x"},
"name": "x"
},
"operator": "<",
"right": {
"type": "NumericLiteral",
"start":6,"end":7,"loc":{"start":{"line":1,"column":6},"end":{"line":1,"column":7}},
"extra": {
"rawValue": 0,
"raw": "0"
},
"value": 0
}
},
{
"type": "RegExpLiteral",
"start":9,"end":12,"loc":{"start":{"line":1,"column":9},"end":{"line":1,"column":12}},
"extra": {
"raw": "/a/"
},
"pattern": "a",
"flags": ""
}
]
}
}
],
"directives": []
}
} | packages/babel-parser/test/fixtures/typescript/cast/false-positive/output.json | 0 | https://github.com/babel/babel/commit/62df8d2b793db1dc032b9b687e48caec186b1799 | [
0.00017375244351569563,
0.00017147518519777805,
0.000169007878866978,
0.00017172511434182525,
0.000001696669187367661
] |
{
"id": 1,
"code_window": [
" \"use strict\";\n",
"\n",
" var foo;\n",
"\n",
" _export(\"foo\", void 0);\n",
"\n",
" return {\n",
" setters: [],\n",
" execute: function () {}\n",
" };\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" _export(\"bar\", void 0);\n"
],
"file_path": "packages/babel-plugin-transform-modules-systemjs/test/fixtures/systemjs/export-named-3/output.mjs",
"type": "replace",
"edit_start_line_idx": 5
} | {
"plugins": [
"external-helpers",
"transform-function-name",
"transform-classes",
"transform-spread",
"transform-block-scoping"
],
"throws": "Destructuring to a super field is not supported yet."
}
| packages/babel-plugin-transform-classes/test/fixtures/spec/super-destructuring-array-pattern/options.json | 0 | https://github.com/babel/babel/commit/62df8d2b793db1dc032b9b687e48caec186b1799 | [
0.00017627252964302897,
0.00017216798732988536,
0.00016806343046482652,
0.00017216798732988536,
0.000004104549589101225
] |
{
"id": 1,
"code_window": [
" \"use strict\";\n",
"\n",
" var foo;\n",
"\n",
" _export(\"foo\", void 0);\n",
"\n",
" return {\n",
" setters: [],\n",
" execute: function () {}\n",
" };\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" _export(\"bar\", void 0);\n"
],
"file_path": "packages/babel-plugin-transform-modules-systemjs/test/fixtures/systemjs/export-named-3/output.mjs",
"type": "replace",
"edit_start_line_idx": 5
} | var _privateField = babelHelpers.classPrivateFieldLooseKey("privateField");
var _privateFieldValue = babelHelpers.classPrivateFieldLooseKey("privateFieldValue");
class Cl {
constructor() {
Object.defineProperty(this, _privateFieldValue, {
get: void 0,
set: _set_privateFieldValue
});
Object.defineProperty(this, _privateField, {
writable: true,
value: 0
});
this.publicField = babelHelpers.classPrivateFieldLooseBase(this, _privateFieldValue)[_privateFieldValue];
}
}
var _set_privateFieldValue = function (newValue) {
babelHelpers.classPrivateFieldLooseBase(this, _privateField)[_privateField] = newValue;
};
| packages/babel-plugin-proposal-private-methods/test/fixtures/accessors-loose/get-only-setter/output.js | 0 | https://github.com/babel/babel/commit/62df8d2b793db1dc032b9b687e48caec186b1799 | [
0.00017835749895311892,
0.00017413869500160217,
0.00016807946667540818,
0.00017597914848010987,
0.000004393170002003899
] |
{
"id": 2,
"code_window": [
" \"use strict\";\n",
"\n",
" var foo;\n",
"\n",
" _export(\"foo\", void 0);\n",
"\n",
" return {\n",
" setters: [],\n",
" execute: function () {}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" _export(\"default\", void 0);\n"
],
"file_path": "packages/babel-plugin-transform-modules-systemjs/test/fixtures/systemjs/export-named-4/output.mjs",
"type": "replace",
"edit_start_line_idx": 5
} | System.register([], function (_export, _context) {
"use strict";
var foo;
_export("foo", void 0);
return {
setters: [],
execute: function () {}
};
});
| packages/babel-plugin-transform-modules-systemjs/test/fixtures/systemjs/export-named-3/output.mjs | 1 | https://github.com/babel/babel/commit/62df8d2b793db1dc032b9b687e48caec186b1799 | [
0.9981110095977783,
0.4991421699523926,
0.00017330783884972334,
0.4991421699523926,
0.49896883964538574
] |
{
"id": 2,
"code_window": [
" \"use strict\";\n",
"\n",
" var foo;\n",
"\n",
" _export(\"foo\", void 0);\n",
"\n",
" return {\n",
" setters: [],\n",
" execute: function () {}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" _export(\"default\", void 0);\n"
],
"file_path": "packages/babel-plugin-transform-modules-systemjs/test/fixtures/systemjs/export-named-4/output.mjs",
"type": "replace",
"edit_start_line_idx": 5
} | {
"type": "File",
"start":0,"end":32,"loc":{"start":{"line":1,"column":0},"end":{"line":2,"column":19}},
"program": {
"type": "Program",
"start":0,"end":32,"loc":{"start":{"line":1,"column":0},"end":{"line":2,"column":19}},
"sourceType": "script",
"interpreter": null,
"body": [
{
"type": "ExpressionStatement",
"start":0,"end":12,"loc":{"start":{"line":1,"column":0},"end":{"line":1,"column":12}},
"expression": {
"type": "JSXElement",
"start":0,"end":11,"loc":{"start":{"line":1,"column":0},"end":{"line":1,"column":11}},
"openingElement": {
"type": "JSXOpeningElement",
"start":0,"end":11,"loc":{"start":{"line":1,"column":0},"end":{"line":1,"column":11}},
"name": {
"type": "JSXNamespacedName",
"start":1,"end":8,"loc":{"start":{"line":1,"column":1},"end":{"line":1,"column":8}},
"namespace": {
"type": "JSXIdentifier",
"start":1,"end":4,"loc":{"start":{"line":1,"column":1},"end":{"line":1,"column":4}},
"name": "Foo"
},
"name": {
"type": "JSXIdentifier",
"start":5,"end":8,"loc":{"start":{"line":1,"column":5},"end":{"line":1,"column":8}},
"name": "Bar"
}
},
"attributes": [],
"selfClosing": true
},
"closingElement": null,
"children": []
}
},
{
"type": "ExpressionStatement",
"start":13,"end":32,"loc":{"start":{"line":2,"column":0},"end":{"line":2,"column":19}},
"expression": {
"type": "JSXElement",
"start":13,"end":32,"loc":{"start":{"line":2,"column":0},"end":{"line":2,"column":19}},
"openingElement": {
"type": "JSXOpeningElement",
"start":13,"end":22,"loc":{"start":{"line":2,"column":0},"end":{"line":2,"column":9}},
"name": {
"type": "JSXNamespacedName",
"start":14,"end":21,"loc":{"start":{"line":2,"column":1},"end":{"line":2,"column":8}},
"namespace": {
"type": "JSXIdentifier",
"start":14,"end":17,"loc":{"start":{"line":2,"column":1},"end":{"line":2,"column":4}},
"name": "Foo"
},
"name": {
"type": "JSXIdentifier",
"start":18,"end":21,"loc":{"start":{"line":2,"column":5},"end":{"line":2,"column":8}},
"name": "Bar"
}
},
"attributes": [],
"selfClosing": false
},
"closingElement": {
"type": "JSXClosingElement",
"start":22,"end":32,"loc":{"start":{"line":2,"column":9},"end":{"line":2,"column":19}},
"name": {
"type": "JSXNamespacedName",
"start":24,"end":31,"loc":{"start":{"line":2,"column":11},"end":{"line":2,"column":18}},
"namespace": {
"type": "JSXIdentifier",
"start":24,"end":27,"loc":{"start":{"line":2,"column":11},"end":{"line":2,"column":14}},
"name": "Foo"
},
"name": {
"type": "JSXIdentifier",
"start":28,"end":31,"loc":{"start":{"line":2,"column":15},"end":{"line":2,"column":18}},
"name": "Bar"
}
}
},
"children": []
}
}
],
"directives": []
}
} | packages/babel-parser/test/fixtures/jsx/basic/namespace-tag/output.json | 0 | https://github.com/babel/babel/commit/62df8d2b793db1dc032b9b687e48caec186b1799 | [
0.00017623507301323116,
0.00016975657490547746,
0.0001658961846260354,
0.00016961997607722878,
0.0000029929160518804565
] |
{
"id": 2,
"code_window": [
" \"use strict\";\n",
"\n",
" var foo;\n",
"\n",
" _export(\"foo\", void 0);\n",
"\n",
" return {\n",
" setters: [],\n",
" execute: function () {}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" _export(\"default\", void 0);\n"
],
"file_path": "packages/babel-plugin-transform-modules-systemjs/test/fixtures/systemjs/export-named-4/output.mjs",
"type": "replace",
"edit_start_line_idx": 5
} | class Cl %%BODY%% | packages/babel-parser/test/fixtures/placeholders/class/body_statement/input.js | 0 | https://github.com/babel/babel/commit/62df8d2b793db1dc032b9b687e48caec186b1799 | [
0.00016852430417202413,
0.00016852430417202413,
0.00016852430417202413,
0.00016852430417202413,
0
] |
{
"id": 2,
"code_window": [
" \"use strict\";\n",
"\n",
" var foo;\n",
"\n",
" _export(\"foo\", void 0);\n",
"\n",
" return {\n",
" setters: [],\n",
" execute: function () {}\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" _export(\"default\", void 0);\n"
],
"file_path": "packages/babel-plugin-transform-modules-systemjs/test/fixtures/systemjs/export-named-4/output.mjs",
"type": "replace",
"edit_start_line_idx": 5
} | "use strict";
class Base {
}
Object.defineProperty(Base.prototype, 'test', {
value: 1,
writable: true,
configurable: true,
});
class Obj extends Base {
set() {
return super.test = 3;
}
}
Object.defineProperty(Obj.prototype, 'test', {
value: 2,
writable: true,
configurable: true,
});
const obj = new Obj();
expect(obj.set()).toBe(3);
expect(Base.prototype.test).toBe(1);
expect(Obj.prototype.test).toBe(2);
expect(obj.test).toBe(3);
| packages/babel-plugin-transform-classes/test/fixtures/get-set-loose/set-semantics-data-defined-on-parent/exec.js | 0 | https://github.com/babel/babel/commit/62df8d2b793db1dc032b9b687e48caec186b1799 | [
0.00017392233712598681,
0.0001694297679932788,
0.0001666667521931231,
0.0001677002146607265,
0.00000320462117997522
] |
{
"id": 3,
"code_window": [
" \"use strict\";\n",
"\n",
" var foo, bar;\n",
"\n",
" _export({\n",
" foo: void 0,\n",
" bar: void 0\n",
" });\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" default: void 0,\n"
],
"file_path": "packages/babel-plugin-transform-modules-systemjs/test/fixtures/systemjs/export-named-5/output.mjs",
"type": "replace",
"edit_start_line_idx": 6
} | System.register([], function (_export, _context) {
"use strict";
var foo, bar;
_export({
foo: void 0,
bar: void 0
});
return {
setters: [],
execute: function () {}
};
});
| packages/babel-plugin-transform-modules-systemjs/test/fixtures/systemjs/export-named-5/output.mjs | 1 | https://github.com/babel/babel/commit/62df8d2b793db1dc032b9b687e48caec186b1799 | [
0.9978378415107727,
0.49900323152542114,
0.00016863956989254802,
0.49900323152542114,
0.4988345801830292
] |
{
"id": 3,
"code_window": [
" \"use strict\";\n",
"\n",
" var foo, bar;\n",
"\n",
" _export({\n",
" foo: void 0,\n",
" bar: void 0\n",
" });\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" default: void 0,\n"
],
"file_path": "packages/babel-plugin-transform-modules-systemjs/test/fixtures/systemjs/export-named-5/output.mjs",
"type": "replace",
"edit_start_line_idx": 6
} | {
"type": "File",
"start":0,"end":26,"loc":{"start":{"line":1,"column":0},"end":{"line":1,"column":26}},
"errors": [
"SyntaxError: Binding 'eval' in strict mode (1:15)"
],
"program": {
"type": "Program",
"start":0,"end":26,"loc":{"start":{"line":1,"column":0},"end":{"line":1,"column":26}},
"sourceType": "script",
"interpreter": null,
"body": [
{
"type": "ExpressionStatement",
"start":14,"end":26,"loc":{"start":{"line":1,"column":14},"end":{"line":1,"column":26}},
"expression": {
"type": "ArrowFunctionExpression",
"start":14,"end":26,"loc":{"start":{"line":1,"column":14},"end":{"line":1,"column":26}},
"id": null,
"generator": false,
"async": false,
"params": [
{
"type": "Identifier",
"start":15,"end":19,"loc":{"start":{"line":1,"column":15},"end":{"line":1,"column":19},"identifierName":"eval"},
"name": "eval"
}
],
"body": {
"type": "NumericLiteral",
"start":24,"end":26,"loc":{"start":{"line":1,"column":24},"end":{"line":1,"column":26}},
"extra": {
"rawValue": 42,
"raw": "42"
},
"value": 42
}
}
}
],
"directives": [
{
"type": "Directive",
"start":0,"end":13,"loc":{"start":{"line":1,"column":0},"end":{"line":1,"column":13}},
"value": {
"type": "DirectiveLiteral",
"start":0,"end":12,"loc":{"start":{"line":1,"column":0},"end":{"line":1,"column":12}},
"value": "use strict",
"extra": {
"raw": "\"use strict\"",
"rawValue": "use strict"
}
}
}
]
}
} | packages/babel-parser/test/fixtures/esprima/invalid-syntax/migrated_0100/output.json | 0 | https://github.com/babel/babel/commit/62df8d2b793db1dc032b9b687e48caec186b1799 | [
0.00022423842165153474,
0.00018408424512017518,
0.00016548162966500968,
0.00017117563402280211,
0.000021665518943336792
] |
{
"id": 3,
"code_window": [
" \"use strict\";\n",
"\n",
" var foo, bar;\n",
"\n",
" _export({\n",
" foo: void 0,\n",
" bar: void 0\n",
" });\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" default: void 0,\n"
],
"file_path": "packages/babel-plugin-transform-modules-systemjs/test/fixtures/systemjs/export-named-5/output.mjs",
"type": "replace",
"edit_start_line_idx": 6
} | var test = {
setInterval: function(fn, ms) {
setInterval(fn, ms);
}
};
| packages/babel-plugin-transform-function-name/test/fixtures/function-name/global/input.js | 0 | https://github.com/babel/babel/commit/62df8d2b793db1dc032b9b687e48caec186b1799 | [
0.00017073645722121,
0.00017073645722121,
0.00017073645722121,
0.00017073645722121,
0
] |
{
"id": 3,
"code_window": [
" \"use strict\";\n",
"\n",
" var foo, bar;\n",
"\n",
" _export({\n",
" foo: void 0,\n",
" bar: void 0\n",
" });\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" default: void 0,\n"
],
"file_path": "packages/babel-plugin-transform-modules-systemjs/test/fixtures/systemjs/export-named-5/output.mjs",
"type": "replace",
"edit_start_line_idx": 6
} | import { jsx as _jsx } from "react/jsx-runtime";
/*#__PURE__*/
_jsx("f:image", {
"n:attr": true
});
| packages/babel-plugin-transform-react-jsx/test/fixtures/nextReact/should-support-xml-namespaces-if-flag/output.mjs | 0 | https://github.com/babel/babel/commit/62df8d2b793db1dc032b9b687e48caec186b1799 | [
0.0001721907319733873,
0.0001721907319733873,
0.0001721907319733873,
0.0001721907319733873,
0
] |
{
"id": 4,
"code_window": [
" return _export(\"p\", p = isEven(n) ? n + 1 : n + 2);\n",
" }\n",
"\n",
" _export({\n",
" nextOdd: nextOdd,\n",
" a: void 0\n",
" });\n",
"\n",
" return {\n",
" setters: [function (_evens) {\n",
" isEven = _evens.isEven;\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" _export(\"nextOdd\", nextOdd);\n"
],
"file_path": "packages/babel-plugin-transform-modules-systemjs/test/fixtures/systemjs/hoist-function-exports/output.mjs",
"type": "replace",
"edit_start_line_idx": 9
} | System.register([], function (_export, _context) {
"use strict";
var foo, bar;
_export({
foo: void 0,
bar: void 0
});
return {
setters: [],
execute: function () {}
};
});
| packages/babel-plugin-transform-modules-systemjs/test/fixtures/systemjs/export-named-5/output.mjs | 1 | https://github.com/babel/babel/commit/62df8d2b793db1dc032b9b687e48caec186b1799 | [
0.0031033530831336975,
0.0016383460024371743,
0.0001733389071887359,
0.0016383460024371743,
0.0014650070806965232
] |
{
"id": 4,
"code_window": [
" return _export(\"p\", p = isEven(n) ? n + 1 : n + 2);\n",
" }\n",
"\n",
" _export({\n",
" nextOdd: nextOdd,\n",
" a: void 0\n",
" });\n",
"\n",
" return {\n",
" setters: [function (_evens) {\n",
" isEven = _evens.isEven;\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" _export(\"nextOdd\", nextOdd);\n"
],
"file_path": "packages/babel-plugin-transform-modules-systemjs/test/fixtures/systemjs/hoist-function-exports/output.mjs",
"type": "replace",
"edit_start_line_idx": 9
} | /*
*/] | packages/babel-parser/test/fixtures/core/uncategorised/445/input.js | 0 | https://github.com/babel/babel/commit/62df8d2b793db1dc032b9b687e48caec186b1799 | [
0.00017713772831484675,
0.00017713772831484675,
0.00017713772831484675,
0.00017713772831484675,
0
] |
{
"id": 4,
"code_window": [
" return _export(\"p\", p = isEven(n) ? n + 1 : n + 2);\n",
" }\n",
"\n",
" _export({\n",
" nextOdd: nextOdd,\n",
" a: void 0\n",
" });\n",
"\n",
" return {\n",
" setters: [function (_evens) {\n",
" isEven = _evens.isEven;\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" _export(\"nextOdd\", nextOdd);\n"
],
"file_path": "packages/babel-plugin-transform-modules-systemjs/test/fixtures/systemjs/hoist-function-exports/output.mjs",
"type": "replace",
"edit_start_line_idx": 9
} | import foo from "bar";
import { baz } from "fuz";
export const exp = foo + baz;
export * from "mod";
| packages/babel-plugin-transform-runtime/test/fixtures/runtime-corejs3/modules-loose/input.mjs | 0 | https://github.com/babel/babel/commit/62df8d2b793db1dc032b9b687e48caec186b1799 | [
0.0001728080096654594,
0.0001728080096654594,
0.0001728080096654594,
0.0001728080096654594,
0
] |
{
"id": 4,
"code_window": [
" return _export(\"p\", p = isEven(n) ? n + 1 : n + 2);\n",
" }\n",
"\n",
" _export({\n",
" nextOdd: nextOdd,\n",
" a: void 0\n",
" });\n",
"\n",
" return {\n",
" setters: [function (_evens) {\n",
" isEven = _evens.isEven;\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" _export(\"nextOdd\", nextOdd);\n"
],
"file_path": "packages/babel-plugin-transform-modules-systemjs/test/fixtures/systemjs/hoist-function-exports/output.mjs",
"type": "replace",
"edit_start_line_idx": 9
} | --arguments
| packages/babel-parser/test/fixtures/esprima/expression-unary/migrated_0005/input.js | 0 | https://github.com/babel/babel/commit/62df8d2b793db1dc032b9b687e48caec186b1799 | [
0.00017842503439169377,
0.00017842503439169377,
0.00017842503439169377,
0.00017842503439169377,
0
] |
{
"id": 1,
"code_window": [
" db.session\n",
" .query(models.Database)\n",
" .filter_by(id=db_id)\n",
" .one()\n",
" )\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
" .first()\n"
],
"file_path": "superset/views/core.py",
"type": "replace",
"edit_start_line_idx": 1000
} | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import React from 'react';
import PropTypes from 'prop-types';
import Select from 'react-virtualized-select';
import createFilterOptions from 'react-select-fast-filter-options';
import { ControlLabel, Label } from 'react-bootstrap';
import { t } from '@superset-ui/translation';
import { SupersetClient } from '@superset-ui/connection';
import AsyncSelect from './AsyncSelect';
import RefreshLabel from './RefreshLabel';
import './TableSelector.css';
const propTypes = {
dbId: PropTypes.number.isRequired,
schema: PropTypes.string,
onSchemaChange: PropTypes.func,
onDbChange: PropTypes.func,
getDbList: PropTypes.func,
onTableChange: PropTypes.func,
tableNameSticky: PropTypes.bool,
tableName: PropTypes.string,
database: PropTypes.object,
sqlLabMode: PropTypes.bool,
onChange: PropTypes.func,
clearable: PropTypes.bool,
handleError: PropTypes.func.isRequired,
};
const defaultProps = {
onDbChange: () => {},
onSchemaChange: () => {},
getDbList: () => {},
onTableChange: () => {},
onChange: () => {},
tableNameSticky: true,
sqlLabMode: true,
clearable: true,
};
export default class TableSelector extends React.PureComponent {
constructor(props) {
super(props);
this.state = {
schemaLoading: false,
schemaOptions: [],
tableLoading: false,
tableOptions: [],
dbId: props.dbId,
schema: props.schema,
tableName: props.tableName,
filterOptions: null,
};
this.changeSchema = this.changeSchema.bind(this);
this.changeTable = this.changeTable.bind(this);
this.dbMutator = this.dbMutator.bind(this);
this.getTableNamesBySubStr = this.getTableNamesBySubStr.bind(this);
this.onChange = this.onChange.bind(this);
this.onDatabaseChange = this.onDatabaseChange.bind(this);
}
componentDidMount() {
this.fetchSchemas(this.state.dbId);
this.fetchTables();
}
onDatabaseChange(db, force = false) {
const dbId = db ? db.id : null;
this.setState({ schemaOptions: [] });
this.props.onSchemaChange(null);
this.props.onDbChange(db);
this.fetchSchemas(dbId, force);
this.setState({ dbId, schema: null, tableOptions: [] }, this.onChange);
}
onChange() {
this.props.onChange({
dbId: this.state.dbId,
shema: this.state.schema,
tableName: this.state.tableName,
});
}
getTableNamesBySubStr(input) {
const { tableName } = this.state;
if (!this.props.dbId || !input) {
const options = this.addOptionIfMissing([], tableName);
return Promise.resolve({ options });
}
return SupersetClient.get({
endpoint: (
`/superset/tables/${this.props.dbId}/` +
`${this.props.schema}/${input}`),
}).then(({ json }) => ({ options: this.addOptionIfMissing(json.options, tableName) }));
}
dbMutator(data) {
this.props.getDbList(data.result);
if (data.result.length === 0) {
this.props.handleError(t("It seems you don't have access to any database"));
}
return data.result;
}
fetchTables(force, substr) {
// This can be large so it shouldn't be put in the Redux store
const forceRefresh = force || false;
const { dbId, schema } = this.props;
if (dbId && schema) {
this.setState(() => ({ tableLoading: true, tableOptions: [] }));
const endpoint = `/superset/tables/${dbId}/${schema}/${substr}/${forceRefresh}/`;
return SupersetClient.get({ endpoint })
.then(({ json }) => {
const filterOptions = createFilterOptions({ options: json.options });
this.setState(() => ({
filterOptions,
tableLoading: false,
tableOptions: json.options,
}));
})
.catch(() => {
this.setState(() => ({ tableLoading: false, tableOptions: [] }));
this.props.handleError(t('Error while fetching table list'));
});
}
this.setState(() => ({ tableLoading: false, tableOptions: [], filterOptions: null }));
return Promise.resolve();
}
fetchSchemas(dbId, force) {
const actualDbId = dbId || this.props.dbId;
const forceRefresh = force || false;
if (actualDbId) {
this.setState({ schemaLoading: true });
const endpoint = `/superset/schemas/${actualDbId}/${forceRefresh}/`;
return SupersetClient.get({ endpoint })
.then(({ json }) => {
const schemaOptions = json.schemas.map(s => ({ value: s, label: s }));
this.setState({ schemaOptions, schemaLoading: false });
})
.catch(() => {
this.setState({ schemaLoading: false, schemaOptions: [] });
this.props.handleError(t('Error while fetching schema list'));
});
}
return Promise.resolve();
}
changeTable(tableOpt) {
if (!tableOpt) {
this.setState({ tableName: '' });
return;
}
const namePieces = tableOpt.value.split('.');
let tableName = namePieces[0];
let schemaName = this.props.schema;
if (namePieces.length > 1) {
schemaName = namePieces[0];
tableName = namePieces[1];
}
if (this.props.tableNameSticky) {
this.setState({ tableName }, this.onChange);
}
this.props.onTableChange(tableName, schemaName);
}
changeSchema(schemaOpt) {
const schema = schemaOpt ? schemaOpt.value : null;
this.props.onSchemaChange(schema);
this.setState({ schema }, () => {
this.fetchTables();
this.onChange();
});
}
addOptionIfMissing(options, value) {
if (options.filter(o => o.value === this.state.tableName).length === 0 && value) {
return [...options, { value, label: value }];
}
return options;
}
renderDatabaseOption(db) {
return (
<span>
<Label bsStyle="default" className="m-r-5">{db.backend}</Label>
{db.database_name}
</span>);
}
renderSelectRow(select, refreshBtn) {
return (
<div className="section">
<span className="select">{select}</span>
<span className="refresh-col">{refreshBtn}</span>
</div>
);
}
renderDatabaseSelect() {
return this.renderSelectRow(
<AsyncSelect
dataEndpoint={
'/databaseasync/api/' +
'read?_flt_0_expose_in_sqllab=1&' +
'_oc_DatabaseAsync=database_name&' +
'_od_DatabaseAsync=asc'
}
onChange={this.onDatabaseChange}
onAsyncError={() => this.props.handleError(t('Error while fetching database list'))}
clearable={false}
value={this.state.dbId}
valueKey="id"
valueRenderer={db => (
<div>
<span className="text-muted m-r-5">{t('Database:')}</span>
{this.renderDatabaseOption(db)}
</div>
)}
optionRenderer={this.renderDatabaseOption}
mutator={this.dbMutator}
placeholder={t('Select a database')}
autoSelect
/>);
}
renderSchema() {
return this.renderSelectRow(
<Select
name="select-schema"
placeholder={t('Select a schema (%s)', this.state.schemaOptions.length)}
options={this.state.schemaOptions}
value={this.props.schema}
valueRenderer={o => (
<div>
<span className="text-muted">{t('Schema:')}</span> {o.label}
</div>
)}
isLoading={this.state.schemaLoading}
autosize={false}
onChange={this.changeSchema}
/>,
<RefreshLabel
onClick={() => this.onDatabaseChange({ id: this.props.dbId }, true)}
tooltipContent={t('Force refresh schema list')}
/>,
);
}
renderTable() {
let tableSelectPlaceholder;
let tableSelectDisabled = false;
if (this.props.database && this.props.database.allow_multi_schema_metadata_fetch) {
tableSelectPlaceholder = t('Type to search ...');
} else {
tableSelectPlaceholder = t('Select table ');
tableSelectDisabled = true;
}
const options = this.addOptionIfMissing(this.state.tableOptions, this.state.tableName);
const select = this.props.schema ? (
<Select
name="select-table"
ref="selectTable"
isLoading={this.state.tableLoading}
placeholder={t('Select table or type table name')}
autosize={false}
onChange={this.changeTable}
filterOptions={this.state.filterOptions}
options={options}
value={this.state.tableName}
/>) : (
<Select
async
name="async-select-table"
ref="selectTable"
placeholder={tableSelectPlaceholder}
disabled={tableSelectDisabled}
autosize={false}
onChange={this.changeTable}
value={this.state.tableName}
loadOptions={this.getTableNamesBySubStr}
/>);
return this.renderSelectRow(
select,
<RefreshLabel
onClick={() => this.changeSchema({ value: this.props.schema }, true)}
tooltipContent={t('Force refresh table list')}
/>);
}
renderSeeTableLabel() {
return (
<div className="section">
<ControlLabel>
{t('See table schema')}{' '}
<small>
({this.state.tableOptions.length}
{' '}{t('in')}{' '}
<i>
{this.props.schema}
</i>)
</small>
</ControlLabel>
</div>);
}
render() {
return (
<div className="TableSelector">
{this.renderDatabaseSelect()}
{this.renderSchema()}
<div className="divider" />
{this.props.sqlLabMode && this.renderSeeTableLabel()}
{this.renderTable()}
</div>
);
}
}
TableSelector.propTypes = propTypes;
TableSelector.defaultProps = defaultProps;
| superset/assets/src/components/TableSelector.jsx | 1 | https://github.com/apache/superset/commit/25ec00b3c6717a1800199b685ed160b38bc0ee17 | [
0.006546725053340197,
0.0006362603162415326,
0.00016544897516723722,
0.0001716736442176625,
0.001215823576785624
] |
{
"id": 1,
"code_window": [
" db.session\n",
" .query(models.Database)\n",
" .filter_by(id=db_id)\n",
" .one()\n",
" )\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
" .first()\n"
],
"file_path": "superset/views/core.py",
"type": "replace",
"edit_start_line_idx": 1000
} | #!/usr/bin/env bash
#
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
set -ex
# Create an admin user (you will be prompted to set username, first and last name before setting a password)
fabmanager create-admin --app superset
# Initialize the database
superset db upgrade
if [ "$SUPERSET_LOAD_EXAMPLES" = "yes" ]; then
# Load some data to play with
superset load_examples
fi
# Create default roles and permissions
superset init
| contrib/docker/docker-init.sh | 0 | https://github.com/apache/superset/commit/25ec00b3c6717a1800199b685ed160b38bc0ee17 | [
0.0002878614468500018,
0.00019890445400960743,
0.00016590979066677392,
0.00017092327470891178,
0.000051400362281128764
] |
{
"id": 1,
"code_window": [
" db.session\n",
" .query(models.Database)\n",
" .filter_by(id=db_id)\n",
" .one()\n",
" )\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
" .first()\n"
],
"file_path": "superset/views/core.py",
"type": "replace",
"edit_start_line_idx": 1000
} | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
"""empty message
Revision ID: 46ba6aaaac97
Revises: ('705732c70154', 'e3970889f38e')
Create Date: 2018-07-23 11:20:54.929246
"""
# revision identifiers, used by Alembic.
revision = '46ba6aaaac97'
down_revision = ('705732c70154', 'e3970889f38e')
from alembic import op
import sqlalchemy as sa
def upgrade():
pass
def downgrade():
pass
| superset/migrations/versions/46ba6aaaac97_.py | 0 | https://github.com/apache/superset/commit/25ec00b3c6717a1800199b685ed160b38bc0ee17 | [
0.00017199823923874646,
0.0001697691041044891,
0.00016646695439703763,
0.00017030563321895897,
0.0000020732579741888912
] |
{
"id": 1,
"code_window": [
" db.session\n",
" .query(models.Database)\n",
" .filter_by(id=db_id)\n",
" .one()\n",
" )\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
" .first()\n"
],
"file_path": "superset/views/core.py",
"type": "replace",
"edit_start_line_idx": 1000
} | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
.reactable-pagination td {
padding: 15px 0 0 0!important;
}
.reactable-pagination a:focus {
text-decoration: none;
color: #555555;
outline: 1;
}
.reactable-page-button,
.reactable-next-page,
.reactable-previous-page {
background: #fff;
border-radius: 2px;
border: 1px solid #b3b3b3;
color: #555555;
display: inline-block;
font-size: 12px;
line-height: 1.5;
margin-right: 5px;
padding: 5px 10px;
text-align: center;
text-decoration: none;
vertical-align: middle;
white-space: nowrap;
}
.reactable-current-page {
border: 1px solid #b3b3b3;
color: #555555;
font-weight: bold;
pointer-events: none;
opacity: 0.65;
}
.reactable-page-button:hover,
.reactable-next-page:hover,
.reactable-previous-page:hover {
background-color: #efefef;
border-color: #949494;
color: #555555;
text-decoration: none;
}
| superset/assets/stylesheets/reactable-pagination.css | 0 | https://github.com/apache/superset/commit/25ec00b3c6717a1800199b685ed160b38bc0ee17 | [
0.000171887906617485,
0.00016829912783578038,
0.00016517817857675254,
0.00016756424156483263,
0.0000026417912977194646
] |
{
"id": 0,
"code_window": [
"\n",
"export interface IConfigurationResolverService {\n",
"\treadonly _serviceBrand: undefined;\n",
"\n",
"\tresolve(folder: IWorkspaceFolder | undefined, value: string): string;\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep"
],
"after_edit": [
"\t/**\n",
"\t * @deprecated Use the async version of `resolve` instead.\n",
"\t */\n"
],
"file_path": "src/vs/workbench/services/configurationResolver/common/configurationResolver.ts",
"type": "add",
"edit_start_line_idx": 15
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { IStringDictionary } from 'vs/base/common/collections';
import { createDecorator } from 'vs/platform/instantiation/common/instantiation';
import { IWorkspaceFolder } from 'vs/platform/workspace/common/workspace';
import { ConfigurationTarget } from 'vs/platform/configuration/common/configuration';
export const IConfigurationResolverService = createDecorator<IConfigurationResolverService>('configurationResolverService');
export interface IConfigurationResolverService {
readonly _serviceBrand: undefined;
resolve(folder: IWorkspaceFolder | undefined, value: string): string;
resolve(folder: IWorkspaceFolder | undefined, value: string[]): string[];
resolve(folder: IWorkspaceFolder | undefined, value: IStringDictionary<string>): IStringDictionary<string>;
/**
* Recursively resolves all variables in the given config and returns a copy of it with substituted values.
* Command variables are only substituted if a "commandValueMapping" dictionary is given and if it contains an entry for the command.
*/
resolveAny(folder: IWorkspaceFolder | undefined, config: any, commandValueMapping?: IStringDictionary<string>): any;
/**
* Recursively resolves all variables (including commands and user input) in the given config and returns a copy of it with substituted values.
* If a "variables" dictionary (with names -> command ids) is given, command variables are first mapped through it before being resolved.
*
* @param section For example, 'tasks' or 'debug'. Used for resolving inputs.
* @param variables Aliases for commands.
*/
resolveWithInteractionReplace(folder: IWorkspaceFolder | undefined, config: any, section?: string, variables?: IStringDictionary<string>, target?: ConfigurationTarget): Promise<any>;
/**
* Similar to resolveWithInteractionReplace, except without the replace. Returns a map of variables and their resolution.
* Keys in the map will be of the format input:variableName or command:variableName.
*/
resolveWithInteraction(folder: IWorkspaceFolder | undefined, config: any, section?: string, variables?: IStringDictionary<string>, target?: ConfigurationTarget): Promise<Map<string, string> | undefined>;
/**
* Contributes a variable that can be resolved later. Consumers that use resolveAny, resolveWithInteraction,
* and resolveWithInteractionReplace will have contributed variables resolved.
*/
contributeVariable(variable: string, resolution: () => Promise<string | undefined>): void;
}
export interface PromptStringInputInfo {
id: string;
type: 'promptString';
description: string;
default?: string;
password?: boolean;
}
export interface PickStringInputInfo {
id: string;
type: 'pickString';
description: string;
options: (string | { value: string, label?: string })[];
default?: string;
}
export interface CommandInputInfo {
id: string;
type: 'command';
command: string;
args?: any;
}
export type ConfiguredInput = PromptStringInputInfo | PickStringInputInfo | CommandInputInfo;
| src/vs/workbench/services/configurationResolver/common/configurationResolver.ts | 1 | https://github.com/microsoft/vscode/commit/36ef468d4dd9a84203bdb2dba688ce395e4b4408 | [
0.998927652835846,
0.1268070489168167,
0.00016997155034914613,
0.0004361385654192418,
0.3296433985233307
] |
{
"id": 0,
"code_window": [
"\n",
"export interface IConfigurationResolverService {\n",
"\treadonly _serviceBrand: undefined;\n",
"\n",
"\tresolve(folder: IWorkspaceFolder | undefined, value: string): string;\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep"
],
"after_edit": [
"\t/**\n",
"\t * @deprecated Use the async version of `resolve` instead.\n",
"\t */\n"
],
"file_path": "src/vs/workbench/services/configurationResolver/common/configurationResolver.ts",
"type": "add",
"edit_start_line_idx": 15
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
export interface IPropertyData {
classification: 'SystemMetaData' | 'CallstackOrException' | 'CustomerContent' | 'PublicNonPersonalData' | 'EndUserPseudonymizedInformation';
purpose: 'PerformanceAndHealth' | 'FeatureInsight' | 'BusinessInsight';
endpoint?: string;
isMeasurement?: boolean;
}
export interface IGDPRProperty {
readonly [name: string]: IPropertyData | undefined | IGDPRProperty;
}
export type ClassifiedEvent<T extends IGDPRProperty> = {
[k in keyof T]: any
};
export type StrictPropertyChecker<TEvent, TClassifiedEvent, TError> = keyof TEvent extends keyof TClassifiedEvent ? keyof TClassifiedEvent extends keyof TEvent ? TEvent : TError : TError;
export type StrictPropertyCheckError = 'Type of classified event does not match event properties';
export type StrictPropertyCheck<T extends IGDPRProperty, E> = StrictPropertyChecker<E, ClassifiedEvent<T>, StrictPropertyCheckError>;
export type GDPRClassification<T> = { [_ in keyof T]: IPropertyData | IGDPRProperty | undefined };
| src/vs/platform/telemetry/common/gdprTypings.ts | 0 | https://github.com/microsoft/vscode/commit/36ef468d4dd9a84203bdb2dba688ce395e4b4408 | [
0.0004013920552097261,
0.0002494922955520451,
0.00016682734712958336,
0.00018025746976491064,
0.00010754919640021399
] |
{
"id": 0,
"code_window": [
"\n",
"export interface IConfigurationResolverService {\n",
"\treadonly _serviceBrand: undefined;\n",
"\n",
"\tresolve(folder: IWorkspaceFolder | undefined, value: string): string;\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep"
],
"after_edit": [
"\t/**\n",
"\t * @deprecated Use the async version of `resolve` instead.\n",
"\t */\n"
],
"file_path": "src/vs/workbench/services/configurationResolver/common/configurationResolver.ts",
"type": "add",
"edit_start_line_idx": 15
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { getErrorMessage, isPromiseCanceledError, canceled } from 'vs/base/common/errors';
import { StatisticType, IGalleryExtension, IExtensionGalleryService, IGalleryExtensionAsset, IQueryOptions, SortBy, SortOrder, IExtensionIdentifier, IReportedExtension, InstallOperation, ITranslation, IGalleryExtensionVersion, IGalleryExtensionAssets, isIExtensionIdentifier, DefaultIconPath } from 'vs/platform/extensionManagement/common/extensionManagement';
import { getGalleryExtensionId, getGalleryExtensionTelemetryData, adoptToGalleryExtensionId } from 'vs/platform/extensionManagement/common/extensionManagementUtil';
import { getOrDefault } from 'vs/base/common/objects';
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
import { IPager } from 'vs/base/common/paging';
import { IRequestService, asJson, asText, isSuccess } from 'vs/platform/request/common/request';
import { IRequestOptions, IRequestContext, IHeaders } from 'vs/base/parts/request/common/request';
import { isEngineValid } from 'vs/platform/extensions/common/extensionValidator';
import { IEnvironmentService } from 'vs/platform/environment/common/environment';
import { CancellationToken } from 'vs/base/common/cancellation';
import { ILogService } from 'vs/platform/log/common/log';
import { IExtensionManifest } from 'vs/platform/extensions/common/extensions';
import { IFileService } from 'vs/platform/files/common/files';
import { URI } from 'vs/base/common/uri';
import { IProductService } from 'vs/platform/product/common/productService';
import { IStorageService, StorageScope, StorageTarget } from 'vs/platform/storage/common/storage';
import { getServiceMachineId } from 'vs/platform/serviceMachineId/common/serviceMachineId';
import { optional } from 'vs/platform/instantiation/common/instantiation';
import { joinPath } from 'vs/base/common/resources';
interface IRawGalleryExtensionFile {
assetType: string;
source: string;
}
interface IRawGalleryExtensionProperty {
key: string;
value: string;
}
interface IRawGalleryExtensionVersion {
version: string;
lastUpdated: string;
assetUri: string;
fallbackAssetUri: string;
files: IRawGalleryExtensionFile[];
properties?: IRawGalleryExtensionProperty[];
}
interface IRawGalleryExtensionStatistics {
statisticName: string;
value: number;
}
interface IRawGalleryExtension {
extensionId: string;
extensionName: string;
displayName: string;
shortDescription: string;
publisher: { displayName: string, publisherId: string, publisherName: string; };
versions: IRawGalleryExtensionVersion[];
statistics: IRawGalleryExtensionStatistics[];
flags: string;
}
interface IRawGalleryQueryResult {
results: {
extensions: IRawGalleryExtension[];
resultMetadata: {
metadataType: string;
metadataItems: {
name: string;
count: number;
}[];
}[]
}[];
}
enum Flags {
None = 0x0,
IncludeVersions = 0x1,
IncludeFiles = 0x2,
IncludeCategoryAndTags = 0x4,
IncludeSharedAccounts = 0x8,
IncludeVersionProperties = 0x10,
ExcludeNonValidated = 0x20,
IncludeInstallationTargets = 0x40,
IncludeAssetUri = 0x80,
IncludeStatistics = 0x100,
IncludeLatestVersionOnly = 0x200,
Unpublished = 0x1000
}
function flagsToString(...flags: Flags[]): string {
return String(flags.reduce((r, f) => r | f, 0));
}
enum FilterType {
Tag = 1,
ExtensionId = 4,
Category = 5,
ExtensionName = 7,
Target = 8,
Featured = 9,
SearchText = 10,
ExcludeWithFlags = 12
}
const AssetType = {
Icon: 'Microsoft.VisualStudio.Services.Icons.Default',
Details: 'Microsoft.VisualStudio.Services.Content.Details',
Changelog: 'Microsoft.VisualStudio.Services.Content.Changelog',
Manifest: 'Microsoft.VisualStudio.Code.Manifest',
VSIX: 'Microsoft.VisualStudio.Services.VSIXPackage',
License: 'Microsoft.VisualStudio.Services.Content.License',
Repository: 'Microsoft.VisualStudio.Services.Links.Source'
};
const PropertyType = {
Dependency: 'Microsoft.VisualStudio.Code.ExtensionDependencies',
ExtensionPack: 'Microsoft.VisualStudio.Code.ExtensionPack',
Engine: 'Microsoft.VisualStudio.Code.Engine',
LocalizedLanguages: 'Microsoft.VisualStudio.Code.LocalizedLanguages',
WebExtension: 'Microsoft.VisualStudio.Code.WebExtension'
};
interface ICriterium {
filterType: FilterType;
value?: string;
}
const DefaultPageSize = 10;
interface IQueryState {
pageNumber: number;
pageSize: number;
sortBy: SortBy;
sortOrder: SortOrder;
flags: Flags;
criteria: ICriterium[];
assetTypes: string[];
}
const DefaultQueryState: IQueryState = {
pageNumber: 1,
pageSize: DefaultPageSize,
sortBy: SortBy.NoneOrRelevance,
sortOrder: SortOrder.Default,
flags: Flags.None,
criteria: [],
assetTypes: []
};
type GalleryServiceQueryClassification = {
filterTypes: { classification: 'SystemMetaData', purpose: 'FeatureInsight' };
sortBy: { classification: 'SystemMetaData', purpose: 'FeatureInsight' };
sortOrder: { classification: 'SystemMetaData', purpose: 'FeatureInsight' };
duration: { classification: 'SystemMetaData', purpose: 'PerformanceAndHealth', 'isMeasurement': true };
success: { classification: 'SystemMetaData', purpose: 'FeatureInsight' };
requestBodySize: { classification: 'SystemMetaData', purpose: 'FeatureInsight' };
responseBodySize?: { classification: 'SystemMetaData', purpose: 'FeatureInsight' };
statusCode?: { classification: 'SystemMetaData', purpose: 'FeatureInsight' };
errorCode?: { classification: 'SystemMetaData', purpose: 'FeatureInsight' };
count?: { classification: 'SystemMetaData', purpose: 'FeatureInsight' };
};
type QueryTelemetryData = {
filterTypes: string[];
sortBy: string;
sortOrder: string;
};
type GalleryServiceQueryEvent = QueryTelemetryData & {
duration: number;
success: boolean;
requestBodySize: string;
responseBodySize?: string;
statusCode?: string;
errorCode?: string;
count?: string;
};
class Query {
constructor(private state = DefaultQueryState) { }
get pageNumber(): number { return this.state.pageNumber; }
get pageSize(): number { return this.state.pageSize; }
get sortBy(): number { return this.state.sortBy; }
get sortOrder(): number { return this.state.sortOrder; }
get flags(): number { return this.state.flags; }
withPage(pageNumber: number, pageSize: number = this.state.pageSize): Query {
return new Query({ ...this.state, pageNumber, pageSize });
}
withFilter(filterType: FilterType, ...values: string[]): Query {
const criteria = [
...this.state.criteria,
...values.length ? values.map(value => ({ filterType, value })) : [{ filterType }]
];
return new Query({ ...this.state, criteria });
}
withSortBy(sortBy: SortBy): Query {
return new Query({ ...this.state, sortBy });
}
withSortOrder(sortOrder: SortOrder): Query {
return new Query({ ...this.state, sortOrder });
}
withFlags(...flags: Flags[]): Query {
return new Query({ ...this.state, flags: flags.reduce<number>((r, f) => r | f, 0) });
}
withAssetTypes(...assetTypes: string[]): Query {
return new Query({ ...this.state, assetTypes });
}
get raw(): any {
const { criteria, pageNumber, pageSize, sortBy, sortOrder, flags, assetTypes } = this.state;
const filters = [{ criteria, pageNumber, pageSize, sortBy, sortOrder }];
return { filters, assetTypes, flags };
}
get searchText(): string {
const criterium = this.state.criteria.filter(criterium => criterium.filterType === FilterType.SearchText)[0];
return criterium && criterium.value ? criterium.value : '';
}
get telemetryData(): QueryTelemetryData {
return {
filterTypes: this.state.criteria.map(criterium => String(criterium.filterType)),
sortBy: String(this.sortBy),
sortOrder: String(this.sortOrder)
};
}
}
function getStatistic(statistics: IRawGalleryExtensionStatistics[], name: string): number {
const result = (statistics || []).filter(s => s.statisticName === name)[0];
return result ? result.value : 0;
}
function getCoreTranslationAssets(version: IRawGalleryExtensionVersion): [string, IGalleryExtensionAsset][] {
const coreTranslationAssetPrefix = 'Microsoft.VisualStudio.Code.Translation.';
const result = version.files.filter(f => f.assetType.indexOf(coreTranslationAssetPrefix) === 0);
return result.reduce<[string, IGalleryExtensionAsset][]>((result, file) => {
const asset = getVersionAsset(version, file.assetType);
if (asset) {
result.push([file.assetType.substring(coreTranslationAssetPrefix.length), asset]);
}
return result;
}, []);
}
function getRepositoryAsset(version: IRawGalleryExtensionVersion): IGalleryExtensionAsset | null {
if (version.properties) {
const results = version.properties.filter(p => p.key === AssetType.Repository);
const gitRegExp = new RegExp('((git|ssh|http(s)?)|(git@[\w.]+))(:(//)?)([\w.@\:/\-~]+)(.git)(/)?');
const uri = results.filter(r => gitRegExp.test(r.value))[0];
return uri ? { uri: uri.value, fallbackUri: uri.value } : null;
}
return getVersionAsset(version, AssetType.Repository);
}
function getDownloadAsset(version: IRawGalleryExtensionVersion): IGalleryExtensionAsset {
return {
uri: `${version.fallbackAssetUri}/${AssetType.VSIX}?redirect=true`,
fallbackUri: `${version.fallbackAssetUri}/${AssetType.VSIX}`
};
}
function getIconAsset(version: IRawGalleryExtensionVersion): IGalleryExtensionAsset {
const asset = getVersionAsset(version, AssetType.Icon);
if (asset) {
return asset;
}
const uri = DefaultIconPath;
return { uri, fallbackUri: uri };
}
function getVersionAsset(version: IRawGalleryExtensionVersion, type: string): IGalleryExtensionAsset | null {
const result = version.files.filter(f => f.assetType === type)[0];
return result ? { uri: `${version.assetUri}/${type}`, fallbackUri: `${version.fallbackAssetUri}/${type}` } : null;
}
function getExtensions(version: IRawGalleryExtensionVersion, property: string): string[] {
const values = version.properties ? version.properties.filter(p => p.key === property) : [];
const value = values.length > 0 && values[0].value;
return value ? value.split(',').map(v => adoptToGalleryExtensionId(v)) : [];
}
function getEngine(version: IRawGalleryExtensionVersion): string {
const values = version.properties ? version.properties.filter(p => p.key === PropertyType.Engine) : [];
return (values.length > 0 && values[0].value) || '';
}
function getLocalizedLanguages(version: IRawGalleryExtensionVersion): string[] {
const values = version.properties ? version.properties.filter(p => p.key === PropertyType.LocalizedLanguages) : [];
const value = (values.length > 0 && values[0].value) || '';
return value ? value.split(',') : [];
}
function getIsPreview(flags: string): boolean {
return flags.indexOf('preview') !== -1;
}
function getIsWebExtension(version: IRawGalleryExtensionVersion): boolean {
const webExtensionProperty = version.properties ? version.properties.find(p => p.key === PropertyType.WebExtension) : undefined;
return !!webExtensionProperty && webExtensionProperty.value === 'true';
}
function getWebResource(version: IRawGalleryExtensionVersion): URI | undefined {
return version.files.some(f => f.assetType.startsWith('Microsoft.VisualStudio.Code.WebResources'))
? joinPath(URI.parse(version.assetUri), 'Microsoft.VisualStudio.Code.WebResources', 'extension')
: undefined;
}
function toExtension(galleryExtension: IRawGalleryExtension, version: IRawGalleryExtensionVersion, index: number, query: Query, querySource?: string): IGalleryExtension {
const assets = <IGalleryExtensionAssets>{
manifest: getVersionAsset(version, AssetType.Manifest),
readme: getVersionAsset(version, AssetType.Details),
changelog: getVersionAsset(version, AssetType.Changelog),
license: getVersionAsset(version, AssetType.License),
repository: getRepositoryAsset(version),
download: getDownloadAsset(version),
icon: getIconAsset(version),
coreTranslations: getCoreTranslationAssets(version)
};
return {
identifier: {
id: getGalleryExtensionId(galleryExtension.publisher.publisherName, galleryExtension.extensionName),
uuid: galleryExtension.extensionId
},
name: galleryExtension.extensionName,
version: version.version,
date: version.lastUpdated,
displayName: galleryExtension.displayName,
publisherId: galleryExtension.publisher.publisherId,
publisher: galleryExtension.publisher.publisherName,
publisherDisplayName: galleryExtension.publisher.displayName,
description: galleryExtension.shortDescription || '',
installCount: getStatistic(galleryExtension.statistics, 'install'),
rating: getStatistic(galleryExtension.statistics, 'averagerating'),
ratingCount: getStatistic(galleryExtension.statistics, 'ratingcount'),
assetUri: URI.parse(version.assetUri),
webResource: getWebResource(version),
assetTypes: version.files.map(({ assetType }) => assetType),
assets,
properties: {
dependencies: getExtensions(version, PropertyType.Dependency),
extensionPack: getExtensions(version, PropertyType.ExtensionPack),
engine: getEngine(version),
localizedLanguages: getLocalizedLanguages(version),
webExtension: getIsWebExtension(version)
},
/* __GDPR__FRAGMENT__
"GalleryExtensionTelemetryData2" : {
"index" : { "classification": "SystemMetaData", "purpose": "FeatureInsight", "isMeasurement": true },
"searchText": { "classification": "CustomerContent", "purpose": "FeatureInsight" },
"querySource": { "classification": "SystemMetaData", "purpose": "FeatureInsight" }
}
*/
telemetryData: {
index: ((query.pageNumber - 1) * query.pageSize) + index,
searchText: query.searchText,
querySource
},
preview: getIsPreview(galleryExtension.flags)
};
}
interface IRawExtensionsReport {
malicious: string[];
slow: string[];
}
export class ExtensionGalleryService implements IExtensionGalleryService {
declare readonly _serviceBrand: undefined;
private extensionsGalleryUrl: string | undefined;
private extensionsControlUrl: string | undefined;
private readonly commonHeadersPromise: Promise<{ [key: string]: string; }>;
constructor(
@IRequestService private readonly requestService: IRequestService,
@ILogService private readonly logService: ILogService,
@IEnvironmentService private readonly environmentService: IEnvironmentService,
@ITelemetryService private readonly telemetryService: ITelemetryService,
@IFileService private readonly fileService: IFileService,
@IProductService private readonly productService: IProductService,
@optional(IStorageService) storageService: IStorageService,
) {
const config = productService.extensionsGallery;
this.extensionsGalleryUrl = config && config.serviceUrl;
this.extensionsControlUrl = config && config.controlUrl;
this.commonHeadersPromise = resolveMarketplaceHeaders(productService.version, this.environmentService, this.fileService, storageService);
}
private api(path = ''): string {
return `${this.extensionsGalleryUrl}${path}`;
}
isEnabled(): boolean {
return !!this.extensionsGalleryUrl;
}
async getExtensions(names: string[], token: CancellationToken): Promise<IGalleryExtension[]> {
const result: IGalleryExtension[] = [];
let { total, firstPage: pageResult, getPage } = await this.query({ names, pageSize: names.length }, token);
result.push(...pageResult);
for (let pageIndex = 1; result.length < total; pageIndex++) {
pageResult = await getPage(pageIndex, token);
if (pageResult.length) {
result.push(...pageResult);
} else {
break;
}
}
return result;
}
async getCompatibleExtension(arg1: IExtensionIdentifier | IGalleryExtension, version?: string): Promise<IGalleryExtension | null> {
const extension = await this.getCompatibleExtensionByEngine(arg1, version);
if (extension?.properties.webExtension) {
return extension.webResource ? extension : null;
} else {
return extension;
}
}
private async getCompatibleExtensionByEngine(arg1: IExtensionIdentifier | IGalleryExtension, version?: string): Promise<IGalleryExtension | null> {
const extension: IGalleryExtension | null = isIExtensionIdentifier(arg1) ? null : arg1;
if (extension && extension.properties.engine && isEngineValid(extension.properties.engine, this.productService.version)) {
return extension;
}
const { id, uuid } = extension ? extension.identifier : <IExtensionIdentifier>arg1;
let query = new Query()
.withFlags(Flags.IncludeAssetUri, Flags.IncludeStatistics, Flags.IncludeFiles, Flags.IncludeVersionProperties)
.withPage(1, 1)
.withFilter(FilterType.Target, 'Microsoft.VisualStudio.Code');
if (uuid) {
query = query.withFilter(FilterType.ExtensionId, uuid);
} else {
query = query.withFilter(FilterType.ExtensionName, id);
}
const { galleryExtensions } = await this.queryGallery(query, CancellationToken.None);
const [rawExtension] = galleryExtensions;
if (!rawExtension || !rawExtension.versions.length) {
return null;
}
if (version) {
const versionAsset = rawExtension.versions.filter(v => v.version === version)[0];
if (versionAsset) {
const extension = toExtension(rawExtension, versionAsset, 0, query);
if (extension.properties.engine && isEngineValid(extension.properties.engine, this.productService.version)) {
return extension;
}
}
return null;
}
const rawVersion = await this.getLastValidExtensionVersion(rawExtension, rawExtension.versions);
if (rawVersion) {
return toExtension(rawExtension, rawVersion, 0, query);
}
return null;
}
query(token: CancellationToken): Promise<IPager<IGalleryExtension>>;
query(options: IQueryOptions, token: CancellationToken): Promise<IPager<IGalleryExtension>>;
async query(arg1: any, arg2?: any): Promise<IPager<IGalleryExtension>> {
const options: IQueryOptions = CancellationToken.isCancellationToken(arg1) ? {} : arg1;
const token: CancellationToken = CancellationToken.isCancellationToken(arg1) ? arg1 : arg2;
if (!this.isEnabled()) {
throw new Error('No extension gallery service configured.');
}
let text = options.text || '';
const pageSize = getOrDefault(options, o => o.pageSize, 50);
let query = new Query()
.withFlags(Flags.IncludeLatestVersionOnly, Flags.IncludeAssetUri, Flags.IncludeStatistics, Flags.IncludeFiles, Flags.IncludeVersionProperties)
.withPage(1, pageSize)
.withFilter(FilterType.Target, 'Microsoft.VisualStudio.Code');
if (text) {
// Use category filter instead of "category:themes"
text = text.replace(/\bcategory:("([^"]*)"|([^"]\S*))(\s+|\b|$)/g, (_, quotedCategory, category) => {
query = query.withFilter(FilterType.Category, category || quotedCategory);
return '';
});
// Use tag filter instead of "tag:debuggers"
text = text.replace(/\btag:("([^"]*)"|([^"]\S*))(\s+|\b|$)/g, (_, quotedTag, tag) => {
query = query.withFilter(FilterType.Tag, tag || quotedTag);
return '';
});
// Use featured filter
text = text.replace(/\bfeatured(\s+|\b|$)/g, () => {
query = query.withFilter(FilterType.Featured);
return '';
});
text = text.trim();
if (text) {
text = text.length < 200 ? text : text.substring(0, 200);
query = query.withFilter(FilterType.SearchText, text);
}
query = query.withSortBy(SortBy.NoneOrRelevance);
} else if (options.ids) {
query = query.withFilter(FilterType.ExtensionId, ...options.ids);
} else if (options.names) {
query = query.withFilter(FilterType.ExtensionName, ...options.names);
} else {
query = query.withSortBy(SortBy.InstallCount);
}
if (typeof options.sortBy === 'number') {
query = query.withSortBy(options.sortBy);
}
if (typeof options.sortOrder === 'number') {
query = query.withSortOrder(options.sortOrder);
}
const { galleryExtensions, total } = await this.queryGallery(query, token);
const extensions = galleryExtensions.map((e, index) => toExtension(e, e.versions[0], index, query, options.source));
const getPage = async (pageIndex: number, ct: CancellationToken) => {
if (ct.isCancellationRequested) {
throw canceled();
}
const nextPageQuery = query.withPage(pageIndex + 1);
const { galleryExtensions } = await this.queryGallery(nextPageQuery, ct);
return galleryExtensions.map((e, index) => toExtension(e, e.versions[0], index, nextPageQuery, options.source));
};
return { firstPage: extensions, total, pageSize: query.pageSize, getPage } as IPager<IGalleryExtension>;
}
private async queryGallery(query: Query, token: CancellationToken): Promise<{ galleryExtensions: IRawGalleryExtension[], total: number; }> {
if (!this.isEnabled()) {
throw new Error('No extension gallery service configured.');
}
// Always exclude non validated and unpublished extensions
query = query
.withFlags(query.flags, Flags.ExcludeNonValidated)
.withFilter(FilterType.ExcludeWithFlags, flagsToString(Flags.Unpublished));
const commonHeaders = await this.commonHeadersPromise;
const data = JSON.stringify(query.raw);
const headers = {
...commonHeaders,
'Content-Type': 'application/json',
'Accept': 'application/json;api-version=3.0-preview.1',
'Accept-Encoding': 'gzip',
'Content-Length': String(data.length)
};
const startTime = new Date().getTime();
let context: IRequestContext | undefined, error: any, total: number = 0;
try {
context = await this.requestService.request({
type: 'POST',
url: this.api('/extensionquery'),
data,
headers
}, token);
if (context.res.statusCode && context.res.statusCode >= 400 && context.res.statusCode < 500) {
return { galleryExtensions: [], total };
}
const result = await asJson<IRawGalleryQueryResult>(context);
if (result) {
const r = result.results[0];
const galleryExtensions = r.extensions;
const resultCount = r.resultMetadata && r.resultMetadata.filter(m => m.metadataType === 'ResultCount')[0];
total = resultCount && resultCount.metadataItems.filter(i => i.name === 'TotalCount')[0].count || 0;
return { galleryExtensions, total };
}
return { galleryExtensions: [], total };
} catch (e) {
error = e;
throw e;
} finally {
this.telemetryService.publicLog2<GalleryServiceQueryEvent, GalleryServiceQueryClassification>('galleryService:query', {
...query.telemetryData,
requestBodySize: String(data.length),
duration: new Date().getTime() - startTime,
success: !!context && isSuccess(context),
responseBodySize: context?.res.headers['Content-Length'],
statusCode: context ? String(context.res.statusCode) : undefined,
errorCode: error
? isPromiseCanceledError(error) ? 'canceled' : getErrorMessage(error).startsWith('XHR timeout') ? 'timeout' : 'failed'
: undefined,
count: String(total)
});
}
}
async reportStatistic(publisher: string, name: string, version: string, type: StatisticType): Promise<void> {
if (!this.isEnabled()) {
return undefined;
}
const commonHeaders = await this.commonHeadersPromise;
const headers = { ...commonHeaders, Accept: '*/*;api-version=4.0-preview.1' };
try {
await this.requestService.request({
type: 'POST',
url: this.api(`/publishers/${publisher}/extensions/${name}/${version}/stats?statType=${type}`),
headers
}, CancellationToken.None);
} catch (error) { /* Ignore */ }
}
async download(extension: IGalleryExtension, location: URI, operation: InstallOperation): Promise<void> {
this.logService.trace('ExtensionGalleryService#download', extension.identifier.id);
const data = getGalleryExtensionTelemetryData(extension);
const startTime = new Date().getTime();
/* __GDPR__
"galleryService:downloadVSIX" : {
"duration": { "classification": "SystemMetaData", "purpose": "PerformanceAndHealth", "isMeasurement": true },
"${include}": [
"${GalleryExtensionTelemetryData}"
]
}
*/
const log = (duration: number) => this.telemetryService.publicLog('galleryService:downloadVSIX', { ...data, duration });
const operationParam = operation === InstallOperation.Install ? 'install' : operation === InstallOperation.Update ? 'update' : '';
const downloadAsset = operationParam ? {
uri: `${extension.assets.download.uri}&${operationParam}=true`,
fallbackUri: `${extension.assets.download.fallbackUri}?${operationParam}=true`
} : extension.assets.download;
const context = await this.getAsset(downloadAsset);
await this.fileService.writeFile(location, context.stream);
log(new Date().getTime() - startTime);
}
async getReadme(extension: IGalleryExtension, token: CancellationToken): Promise<string> {
if (extension.assets.readme) {
const context = await this.getAsset(extension.assets.readme, {}, token);
const content = await asText(context);
return content || '';
}
return '';
}
async getManifest(extension: IGalleryExtension, token: CancellationToken): Promise<IExtensionManifest | null> {
if (extension.assets.manifest) {
const context = await this.getAsset(extension.assets.manifest, {}, token);
const text = await asText(context);
return text ? JSON.parse(text) : null;
}
return null;
}
async getCoreTranslation(extension: IGalleryExtension, languageId: string): Promise<ITranslation | null> {
const asset = extension.assets.coreTranslations.filter(t => t[0] === languageId.toUpperCase())[0];
if (asset) {
const context = await this.getAsset(asset[1]);
const text = await asText(context);
return text ? JSON.parse(text) : null;
}
return null;
}
async getChangelog(extension: IGalleryExtension, token: CancellationToken): Promise<string> {
if (extension.assets.changelog) {
const context = await this.getAsset(extension.assets.changelog, {}, token);
const content = await asText(context);
return content || '';
}
return '';
}
async getAllVersions(extension: IGalleryExtension, compatible: boolean): Promise<IGalleryExtensionVersion[]> {
let query = new Query()
.withFlags(Flags.IncludeVersions, Flags.IncludeFiles, Flags.IncludeVersionProperties)
.withPage(1, 1)
.withFilter(FilterType.Target, 'Microsoft.VisualStudio.Code');
if (extension.identifier.uuid) {
query = query.withFilter(FilterType.ExtensionId, extension.identifier.uuid);
} else {
query = query.withFilter(FilterType.ExtensionName, extension.identifier.id);
}
const result: IGalleryExtensionVersion[] = [];
const { galleryExtensions } = await this.queryGallery(query, CancellationToken.None);
if (galleryExtensions.length) {
if (compatible) {
await Promise.all(galleryExtensions[0].versions.map(async v => {
let engine: string | undefined;
try {
engine = await this.getEngine(v);
} catch (error) { /* Ignore error and skip version */ }
if (engine && isEngineValid(engine, this.productService.version)) {
result.push({ version: v!.version, date: v!.lastUpdated });
}
}));
} else {
result.push(...galleryExtensions[0].versions.map(v => ({ version: v.version, date: v.lastUpdated })));
}
}
return result;
}
private async getAsset(asset: IGalleryExtensionAsset, options: IRequestOptions = {}, token: CancellationToken = CancellationToken.None): Promise<IRequestContext> {
const commonHeaders = await this.commonHeadersPromise;
const baseOptions = { type: 'GET' };
const headers = { ...commonHeaders, ...(options.headers || {}) };
options = { ...options, ...baseOptions, headers };
const url = asset.uri;
const fallbackUrl = asset.fallbackUri;
const firstOptions = { ...options, url };
try {
const context = await this.requestService.request(firstOptions, token);
if (context.res.statusCode === 200) {
return context;
}
const message = await asText(context);
throw new Error(`Expected 200, got back ${context.res.statusCode} instead.\n\n${message}`);
} catch (err) {
if (isPromiseCanceledError(err)) {
throw err;
}
const message = getErrorMessage(err);
type GalleryServiceCDNFallbackClassification = {
url: { classification: 'SystemMetaData', purpose: 'FeatureInsight' };
message: { classification: 'SystemMetaData', purpose: 'FeatureInsight' };
};
type GalleryServiceCDNFallbackEvent = {
url: string;
message: string;
};
this.telemetryService.publicLog2<GalleryServiceCDNFallbackEvent, GalleryServiceCDNFallbackClassification>('galleryService:cdnFallback', { url, message });
const fallbackOptions = { ...options, url: fallbackUrl };
return this.requestService.request(fallbackOptions, token);
}
}
private async getLastValidExtensionVersion(extension: IRawGalleryExtension, versions: IRawGalleryExtensionVersion[]): Promise<IRawGalleryExtensionVersion | null> {
const version = this.getLastValidExtensionVersionFromProperties(extension, versions);
if (version) {
return version;
}
return this.getLastValidExtensionVersionRecursively(extension, versions);
}
private getLastValidExtensionVersionFromProperties(extension: IRawGalleryExtension, versions: IRawGalleryExtensionVersion[]): IRawGalleryExtensionVersion | null {
for (const version of versions) {
const engine = getEngine(version);
if (!engine) {
return null;
}
if (isEngineValid(engine, this.productService.version)) {
return version;
}
}
return null;
}
private async getEngine(version: IRawGalleryExtensionVersion): Promise<string> {
const engine = getEngine(version);
if (engine) {
return engine;
}
const manifestAsset = getVersionAsset(version, AssetType.Manifest);
if (!manifestAsset) {
throw new Error('Manifest was not found');
}
const headers = { 'Accept-Encoding': 'gzip' };
const context = await this.getAsset(manifestAsset, { headers });
const manifest = await asJson<IExtensionManifest>(context);
if (manifest) {
return manifest.engines.vscode;
}
throw new Error('Error while reading manifest');
}
private async getLastValidExtensionVersionRecursively(extension: IRawGalleryExtension, versions: IRawGalleryExtensionVersion[]): Promise<IRawGalleryExtensionVersion | null> {
if (!versions.length) {
return null;
}
const version = versions[0];
const engine = await this.getEngine(version);
if (!isEngineValid(engine, this.productService.version)) {
return this.getLastValidExtensionVersionRecursively(extension, versions.slice(1));
}
version.properties = version.properties || [];
version.properties.push({ key: PropertyType.Engine, value: engine });
return version;
}
async getExtensionsReport(): Promise<IReportedExtension[]> {
if (!this.isEnabled()) {
throw new Error('No extension gallery service configured.');
}
if (!this.extensionsControlUrl) {
return [];
}
const context = await this.requestService.request({ type: 'GET', url: this.extensionsControlUrl }, CancellationToken.None);
if (context.res.statusCode !== 200) {
throw new Error('Could not get extensions report.');
}
const result = await asJson<IRawExtensionsReport>(context);
const map = new Map<string, IReportedExtension>();
if (result) {
for (const id of result.malicious) {
const ext = map.get(id) || { id: { id }, malicious: true, slow: false };
ext.malicious = true;
map.set(id, ext);
}
}
return [...map.values()];
}
}
export async function resolveMarketplaceHeaders(version: string, environmentService: IEnvironmentService, fileService: IFileService, storageService: {
get: (key: string, scope: StorageScope) => string | undefined,
store: (key: string, value: string, scope: StorageScope, target: StorageTarget) => void
} | undefined): Promise<{ [key: string]: string; }> {
const headers: IHeaders = {
'X-Market-Client-Id': `VSCode ${version}`,
'User-Agent': `VSCode ${version}`
};
const uuid = await getServiceMachineId(environmentService, fileService, storageService);
headers['X-Market-User-Id'] = uuid;
return headers;
}
| src/vs/platform/extensionManagement/common/extensionGalleryService.ts | 0 | https://github.com/microsoft/vscode/commit/36ef468d4dd9a84203bdb2dba688ce395e4b4408 | [
0.7626363635063171,
0.009175701066851616,
0.0001652345818001777,
0.00017087130981963128,
0.0812578797340393
] |
{
"id": 0,
"code_window": [
"\n",
"export interface IConfigurationResolverService {\n",
"\treadonly _serviceBrand: undefined;\n",
"\n",
"\tresolve(folder: IWorkspaceFolder | undefined, value: string): string;\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep"
],
"after_edit": [
"\t/**\n",
"\t * @deprecated Use the async version of `resolve` instead.\n",
"\t */\n"
],
"file_path": "src/vs/workbench/services/configurationResolver/common/configurationResolver.ts",
"type": "add",
"edit_start_line_idx": 15
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { NotebookEditorWidget } from 'vs/workbench/contrib/notebook/browser/notebookEditorWidget';
import { IEditorGroup } from 'vs/workbench/services/editor/common/editorGroupsService';
import { createDecorator, ServicesAccessor } from 'vs/platform/instantiation/common/instantiation';
import { NotebookEditorInput } from 'vs/workbench/contrib/notebook/common/notebookEditorInput';
import { INotebookEditor } from 'vs/workbench/contrib/notebook/browser/notebookBrowser';
import { Event } from 'vs/base/common/event';
import { INotebookDecorationRenderOptions } from 'vs/workbench/contrib/notebook/common/notebookCommon';
export const INotebookEditorService = createDecorator<INotebookEditorService>('INotebookEditorWidgetService');
export interface IBorrowValue<T> {
readonly value: T | undefined;
}
export interface INotebookEditorService {
_serviceBrand: undefined;
retrieveWidget(accessor: ServicesAccessor, group: IEditorGroup, input: NotebookEditorInput): IBorrowValue<NotebookEditorWidget>;
onDidAddNotebookEditor: Event<INotebookEditor>;
onDidRemoveNotebookEditor: Event<INotebookEditor>;
addNotebookEditor(editor: INotebookEditor): void;
removeNotebookEditor(editor: INotebookEditor): void;
getNotebookEditor(editorId: string): INotebookEditor | undefined;
listNotebookEditors(): readonly INotebookEditor[];
registerEditorDecorationType(key: string, options: INotebookDecorationRenderOptions): void;
removeEditorDecorationType(key: string): void;
resolveEditorDecorationOptions(key: string): INotebookDecorationRenderOptions | undefined;
}
| src/vs/workbench/contrib/notebook/browser/notebookEditorService.ts | 0 | https://github.com/microsoft/vscode/commit/36ef468d4dd9a84203bdb2dba688ce395e4b4408 | [
0.0009998045861721039,
0.0005563171580433846,
0.00017003282846417278,
0.0005277156597003341,
0.00038649330963380635
] |
{
"id": 1,
"code_window": [
"\tresolve(folder: IWorkspaceFolder | undefined, value: string): string;\n",
"\tresolve(folder: IWorkspaceFolder | undefined, value: string[]): string[];\n"
],
"labels": [
"add",
"keep"
],
"after_edit": [
"\t/**\n",
"\t * @deprecated Use the async version of `resolve` instead.\n",
"\t */\n"
],
"file_path": "src/vs/workbench/services/configurationResolver/common/configurationResolver.ts",
"type": "add",
"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.
*--------------------------------------------------------------------------------------------*/
import { IStringDictionary } from 'vs/base/common/collections';
import { createDecorator } from 'vs/platform/instantiation/common/instantiation';
import { IWorkspaceFolder } from 'vs/platform/workspace/common/workspace';
import { ConfigurationTarget } from 'vs/platform/configuration/common/configuration';
export const IConfigurationResolverService = createDecorator<IConfigurationResolverService>('configurationResolverService');
export interface IConfigurationResolverService {
readonly _serviceBrand: undefined;
resolve(folder: IWorkspaceFolder | undefined, value: string): string;
resolve(folder: IWorkspaceFolder | undefined, value: string[]): string[];
resolve(folder: IWorkspaceFolder | undefined, value: IStringDictionary<string>): IStringDictionary<string>;
/**
* Recursively resolves all variables in the given config and returns a copy of it with substituted values.
* Command variables are only substituted if a "commandValueMapping" dictionary is given and if it contains an entry for the command.
*/
resolveAny(folder: IWorkspaceFolder | undefined, config: any, commandValueMapping?: IStringDictionary<string>): any;
/**
* Recursively resolves all variables (including commands and user input) in the given config and returns a copy of it with substituted values.
* If a "variables" dictionary (with names -> command ids) is given, command variables are first mapped through it before being resolved.
*
* @param section For example, 'tasks' or 'debug'. Used for resolving inputs.
* @param variables Aliases for commands.
*/
resolveWithInteractionReplace(folder: IWorkspaceFolder | undefined, config: any, section?: string, variables?: IStringDictionary<string>, target?: ConfigurationTarget): Promise<any>;
/**
* Similar to resolveWithInteractionReplace, except without the replace. Returns a map of variables and their resolution.
* Keys in the map will be of the format input:variableName or command:variableName.
*/
resolveWithInteraction(folder: IWorkspaceFolder | undefined, config: any, section?: string, variables?: IStringDictionary<string>, target?: ConfigurationTarget): Promise<Map<string, string> | undefined>;
/**
* Contributes a variable that can be resolved later. Consumers that use resolveAny, resolveWithInteraction,
* and resolveWithInteractionReplace will have contributed variables resolved.
*/
contributeVariable(variable: string, resolution: () => Promise<string | undefined>): void;
}
export interface PromptStringInputInfo {
id: string;
type: 'promptString';
description: string;
default?: string;
password?: boolean;
}
export interface PickStringInputInfo {
id: string;
type: 'pickString';
description: string;
options: (string | { value: string, label?: string })[];
default?: string;
}
export interface CommandInputInfo {
id: string;
type: 'command';
command: string;
args?: any;
}
export type ConfiguredInput = PromptStringInputInfo | PickStringInputInfo | CommandInputInfo;
| src/vs/workbench/services/configurationResolver/common/configurationResolver.ts | 1 | https://github.com/microsoft/vscode/commit/36ef468d4dd9a84203bdb2dba688ce395e4b4408 | [
0.9888463616371155,
0.191175177693367,
0.00017126866441685706,
0.0006083549233153462,
0.33690354228019714
] |
{
"id": 1,
"code_window": [
"\tresolve(folder: IWorkspaceFolder | undefined, value: string): string;\n",
"\tresolve(folder: IWorkspaceFolder | undefined, value: string[]): string[];\n"
],
"labels": [
"add",
"keep"
],
"after_edit": [
"\t/**\n",
"\t * @deprecated Use the async version of `resolve` instead.\n",
"\t */\n"
],
"file_path": "src/vs/workbench/services/configurationResolver/common/configurationResolver.ts",
"type": "add",
"edit_start_line_idx": 16
} | trigger:
branches:
include: ["main", "release/*"]
pr:
branches:
include: ["main", "release/*"]
steps:
- task: NodeTool@0
inputs:
versionSpec: "12.18.3"
- task: AzureKeyVault@1
displayName: "Azure Key Vault: Get Secrets"
inputs:
azureSubscription: "vscode-builds-subscription"
KeyVaultName: vscode
- script: |
set -e
cat << EOF > ~/.netrc
machine github.com
login vscode
password $(github-distro-mixin-password)
EOF
git config user.email "[email protected]"
git config user.name "VSCode"
git remote add distro "https://github.com/$VSCODE_MIXIN_REPO.git"
git fetch distro
# Push main branch into oss/main
git push distro origin/main:refs/heads/oss/main
# Push every release branch into oss/release
git for-each-ref --format="%(refname:short)" refs/remotes/origin/release/* | sed 's/^origin\/\(.*\)$/\0:refs\/heads\/oss\/\1/' | xargs git push distro
git merge $(node -p "require('./package.json').distro")
displayName: Sync & Merge Distro
| build/azure-pipelines/distro-build.yml | 0 | https://github.com/microsoft/vscode/commit/36ef468d4dd9a84203bdb2dba688ce395e4b4408 | [
0.00017728931561578065,
0.00017470969760324806,
0.0001702419394860044,
0.00017597580153960735,
0.0000025633898985688575
] |
{
"id": 1,
"code_window": [
"\tresolve(folder: IWorkspaceFolder | undefined, value: string): string;\n",
"\tresolve(folder: IWorkspaceFolder | undefined, value: string[]): string[];\n"
],
"labels": [
"add",
"keep"
],
"after_edit": [
"\t/**\n",
"\t * @deprecated Use the async version of `resolve` instead.\n",
"\t */\n"
],
"file_path": "src/vs/workbench/services/configurationResolver/common/configurationResolver.ts",
"type": "add",
"edit_start_line_idx": 16
} | test/**
cgmanifest.json
| extensions/lua/.vscodeignore | 0 | https://github.com/microsoft/vscode/commit/36ef468d4dd9a84203bdb2dba688ce395e4b4408 | [
0.00017912905605044216,
0.00017912905605044216,
0.00017912905605044216,
0.00017912905605044216,
0
] |
{
"id": 1,
"code_window": [
"\tresolve(folder: IWorkspaceFolder | undefined, value: string): string;\n",
"\tresolve(folder: IWorkspaceFolder | undefined, value: string[]): string[];\n"
],
"labels": [
"add",
"keep"
],
"after_edit": [
"\t/**\n",
"\t * @deprecated Use the async version of `resolve` instead.\n",
"\t */\n"
],
"file_path": "src/vs/workbench/services/configurationResolver/common/configurationResolver.ts",
"type": "add",
"edit_start_line_idx": 16
} | #!/usr/bin/env bash
#
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Deregister code from the alternatives system
update-alternatives --remove editor /usr/bin/@@NAME@@ | resources/linux/debian/prerm.template | 0 | https://github.com/microsoft/vscode/commit/36ef468d4dd9a84203bdb2dba688ce395e4b4408 | [
0.00017678120639175177,
0.00017678120639175177,
0.00017678120639175177,
0.00017678120639175177,
0
] |
{
"id": 2,
"code_window": [
"\tresolve(folder: IWorkspaceFolder | undefined, value: string[]): string[];\n",
"\tresolve(folder: IWorkspaceFolder | undefined, value: IStringDictionary<string>): IStringDictionary<string>;\n",
"\n",
"\t/**\n",
"\t * Recursively resolves all variables in the given config and returns a copy of it with substituted values.\n",
"\t * Command variables are only substituted if a \"commandValueMapping\" dictionary is given and if it contains an entry for the command.\n"
],
"labels": [
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t/**\n",
"\t * @deprecated Use the async version of `resolve` instead.\n",
"\t */\n"
],
"file_path": "src/vs/workbench/services/configurationResolver/common/configurationResolver.ts",
"type": "add",
"edit_start_line_idx": 17
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as paths from 'vs/base/common/path';
import * as process from 'vs/base/common/process';
import * as types from 'vs/base/common/types';
import * as objects from 'vs/base/common/objects';
import { IStringDictionary } from 'vs/base/common/collections';
import { IProcessEnvironment, isWindows, isMacintosh, isLinux } from 'vs/base/common/platform';
import { normalizeDriveLetter } from 'vs/base/common/labels';
import { localize } from 'vs/nls';
import { URI as uri } from 'vs/base/common/uri';
import { IConfigurationResolverService } from 'vs/workbench/services/configurationResolver/common/configurationResolver';
import { IWorkspaceFolder } from 'vs/platform/workspace/common/workspace';
import { ILabelService } from 'vs/platform/label/common/label';
export interface IVariableResolveContext {
getFolderUri(folderName: string): uri | undefined;
getWorkspaceFolderCount(): number;
getConfigurationValue(folderUri: uri | undefined, section: string): string | undefined;
getAppRoot(): string | undefined;
getExecPath(): string | undefined;
getFilePath(): string | undefined;
getWorkspaceFolderPathForFile?(): string | undefined;
getSelectedText(): string | undefined;
getLineNumber(): string | undefined;
}
export class AbstractVariableResolverService implements IConfigurationResolverService {
static readonly VARIABLE_LHS = '${';
static readonly VARIABLE_REGEXP = /\$\{(.*?)\}/g;
declare readonly _serviceBrand: undefined;
private _context: IVariableResolveContext;
private _labelService?: ILabelService;
private _envVariables?: IProcessEnvironment;
protected _contributedVariables: Map<string, () => Promise<string | undefined>> = new Map();
constructor(_context: IVariableResolveContext, _labelService?: ILabelService, _envVariables?: IProcessEnvironment) {
this._context = _context;
this._labelService = _labelService;
if (_envVariables) {
if (isWindows) {
// windows env variables are case insensitive
const ev: IProcessEnvironment = Object.create(null);
this._envVariables = ev;
Object.keys(_envVariables).forEach(key => {
ev[key.toLowerCase()] = _envVariables[key];
});
} else {
this._envVariables = _envVariables;
}
}
}
public resolve(root: IWorkspaceFolder | undefined, value: string): string;
public resolve(root: IWorkspaceFolder | undefined, value: string[]): string[];
public resolve(root: IWorkspaceFolder | undefined, value: IStringDictionary<string>): IStringDictionary<string>;
public resolve(root: IWorkspaceFolder | undefined, value: any): any {
return this.recursiveResolve(root ? root.uri : undefined, value);
}
public resolveAnyBase(workspaceFolder: IWorkspaceFolder | undefined, config: any, commandValueMapping?: IStringDictionary<string>, resolvedVariables?: Map<string, string>): any {
const result = objects.deepClone(config) as any;
// hoist platform specific attributes to top level
if (isWindows && result.windows) {
Object.keys(result.windows).forEach(key => result[key] = result.windows[key]);
} else if (isMacintosh && result.osx) {
Object.keys(result.osx).forEach(key => result[key] = result.osx[key]);
} else if (isLinux && result.linux) {
Object.keys(result.linux).forEach(key => result[key] = result.linux[key]);
}
// delete all platform specific sections
delete result.windows;
delete result.osx;
delete result.linux;
// substitute all variables recursively in string values
return this.recursiveResolve(workspaceFolder ? workspaceFolder.uri : undefined, result, commandValueMapping, resolvedVariables);
}
public resolveAny(workspaceFolder: IWorkspaceFolder | undefined, config: any, commandValueMapping?: IStringDictionary<string>): any {
return this.resolveAnyBase(workspaceFolder, config, commandValueMapping);
}
public resolveAnyMap(workspaceFolder: IWorkspaceFolder | undefined, config: any, commandValueMapping?: IStringDictionary<string>): { newConfig: any, resolvedVariables: Map<string, string> } {
const resolvedVariables = new Map<string, string>();
const newConfig = this.resolveAnyBase(workspaceFolder, config, commandValueMapping, resolvedVariables);
return { newConfig, resolvedVariables };
}
public resolveWithInteractionReplace(folder: IWorkspaceFolder | undefined, config: any, section?: string, variables?: IStringDictionary<string>): Promise<any> {
throw new Error('resolveWithInteractionReplace not implemented.');
}
public resolveWithInteraction(folder: IWorkspaceFolder | undefined, config: any, section?: string, variables?: IStringDictionary<string>): Promise<Map<string, string> | undefined> {
throw new Error('resolveWithInteraction not implemented.');
}
public contributeVariable(variable: string, resolution: () => Promise<string | undefined>): void {
if (this._contributedVariables.has(variable)) {
throw new Error('Variable ' + variable + ' is contributed twice.');
} else {
this._contributedVariables.set(variable, resolution);
}
}
private recursiveResolve(folderUri: uri | undefined, value: any, commandValueMapping?: IStringDictionary<string>, resolvedVariables?: Map<string, string>): any {
if (types.isString(value)) {
return this.resolveString(folderUri, value, commandValueMapping, resolvedVariables);
} else if (types.isArray(value)) {
return value.map(s => this.recursiveResolve(folderUri, s, commandValueMapping, resolvedVariables));
} else if (types.isObject(value)) {
let result: IStringDictionary<string | IStringDictionary<string> | string[]> = Object.create(null);
Object.keys(value).forEach(key => {
const replaced = this.resolveString(folderUri, key, commandValueMapping, resolvedVariables);
result[replaced] = this.recursiveResolve(folderUri, value[key], commandValueMapping, resolvedVariables);
});
return result;
}
return value;
}
private resolveString(folderUri: uri | undefined, value: string, commandValueMapping: IStringDictionary<string> | undefined, resolvedVariables?: Map<string, string>): string {
// loop through all variables occurrences in 'value'
const replaced = value.replace(AbstractVariableResolverService.VARIABLE_REGEXP, (match: string, variable: string) => {
// disallow attempted nesting, see #77289
if (variable.includes(AbstractVariableResolverService.VARIABLE_LHS)) {
return match;
}
let resolvedValue = this.evaluateSingleVariable(match, variable, folderUri, commandValueMapping);
if (resolvedVariables) {
resolvedVariables.set(variable, resolvedValue);
}
return resolvedValue;
});
return replaced;
}
private fsPath(displayUri: uri): string {
return this._labelService ? this._labelService.getUriLabel(displayUri, { noPrefix: true }) : displayUri.fsPath;
}
private evaluateSingleVariable(match: string, variable: string, folderUri: uri | undefined, commandValueMapping: IStringDictionary<string> | undefined): string {
// try to separate variable arguments from variable name
let argument: string | undefined;
const parts = variable.split(':');
if (parts.length > 1) {
variable = parts[0];
argument = parts[1];
}
// common error handling for all variables that require an open editor
const getFilePath = (): string => {
const filePath = this._context.getFilePath();
if (filePath) {
return filePath;
}
throw new Error(localize('canNotResolveFile', "Variable {0} can not be resolved. Please open an editor.", match));
};
// common error handling for all variables that require an open editor
const getFolderPathForFile = (): string => {
const filePath = getFilePath(); // throws error if no editor open
if (this._context.getWorkspaceFolderPathForFile) {
const folderPath = this._context.getWorkspaceFolderPathForFile();
if (folderPath) {
return folderPath;
}
}
throw new Error(localize('canNotResolveFolderForFile', "Variable {0}: can not find workspace folder of '{1}'.", match, paths.basename(filePath)));
};
// common error handling for all variables that require an open folder and accept a folder name argument
const getFolderUri = (): uri => {
if (argument) {
const folder = this._context.getFolderUri(argument);
if (folder) {
return folder;
}
throw new Error(localize('canNotFindFolder', "Variable {0} can not be resolved. No such folder '{1}'.", match, argument));
}
if (folderUri) {
return folderUri;
}
if (this._context.getWorkspaceFolderCount() > 1) {
throw new Error(localize('canNotResolveWorkspaceFolderMultiRoot', "Variable {0} can not be resolved in a multi folder workspace. Scope this variable using ':' and a workspace folder name.", match));
}
throw new Error(localize('canNotResolveWorkspaceFolder', "Variable {0} can not be resolved. Please open a folder.", match));
};
switch (variable) {
case 'env':
if (argument) {
if (this._envVariables) {
const env = this._envVariables[isWindows ? argument.toLowerCase() : argument];
if (types.isString(env)) {
return env;
}
}
// For `env` we should do the same as a normal shell does - evaluates undefined envs to an empty string #46436
return '';
}
throw new Error(localize('missingEnvVarName', "Variable {0} can not be resolved because no environment variable name is given.", match));
case 'config':
if (argument) {
const config = this._context.getConfigurationValue(folderUri, argument);
if (types.isUndefinedOrNull(config)) {
throw new Error(localize('configNotFound', "Variable {0} can not be resolved because setting '{1}' not found.", match, argument));
}
if (types.isObject(config)) {
throw new Error(localize('configNoString', "Variable {0} can not be resolved because '{1}' is a structured value.", match, argument));
}
return config;
}
throw new Error(localize('missingConfigName', "Variable {0} can not be resolved because no settings name is given.", match));
case 'command':
return this.resolveFromMap(match, argument, commandValueMapping, 'command');
case 'input':
return this.resolveFromMap(match, argument, commandValueMapping, 'input');
default: {
switch (variable) {
case 'workspaceRoot':
case 'workspaceFolder':
return normalizeDriveLetter(this.fsPath(getFolderUri()));
case 'cwd':
return ((folderUri || argument) ? normalizeDriveLetter(this.fsPath(getFolderUri())) : process.cwd());
case 'workspaceRootFolderName':
case 'workspaceFolderBasename':
return paths.basename(this.fsPath(getFolderUri()));
case 'lineNumber':
const lineNumber = this._context.getLineNumber();
if (lineNumber) {
return lineNumber;
}
throw new Error(localize('canNotResolveLineNumber', "Variable {0} can not be resolved. Make sure to have a line selected in the active editor.", match));
case 'selectedText':
const selectedText = this._context.getSelectedText();
if (selectedText) {
return selectedText;
}
throw new Error(localize('canNotResolveSelectedText', "Variable {0} can not be resolved. Make sure to have some text selected in the active editor.", match));
case 'file':
return getFilePath();
case 'fileWorkspaceFolder':
return getFolderPathForFile();
case 'relativeFile':
if (folderUri || argument) {
return paths.relative(this.fsPath(getFolderUri()), getFilePath());
}
return getFilePath();
case 'relativeFileDirname':
const dirname = paths.dirname(getFilePath());
if (folderUri || argument) {
const relative = paths.relative(this.fsPath(getFolderUri()), dirname);
return relative.length === 0 ? '.' : relative;
}
return dirname;
case 'fileDirname':
return paths.dirname(getFilePath());
case 'fileExtname':
return paths.extname(getFilePath());
case 'fileBasename':
return paths.basename(getFilePath());
case 'fileBasenameNoExtension':
const basename = paths.basename(getFilePath());
return (basename.slice(0, basename.length - paths.extname(basename).length));
case 'fileDirnameBasename':
return paths.basename(paths.dirname(getFilePath()));
case 'execPath':
const ep = this._context.getExecPath();
if (ep) {
return ep;
}
return match;
case 'execInstallFolder':
const ar = this._context.getAppRoot();
if (ar) {
return ar;
}
return match;
case 'pathSeparator':
return paths.sep;
default:
try {
const key = argument ? `${variable}:${argument}` : variable;
return this.resolveFromMap(match, key, commandValueMapping, undefined);
} catch (error) {
return match;
}
}
}
}
}
private resolveFromMap(match: string, argument: string | undefined, commandValueMapping: IStringDictionary<string> | undefined, prefix: string | undefined): string {
if (argument && commandValueMapping) {
const v = (prefix === undefined) ? commandValueMapping[argument] : commandValueMapping[prefix + ':' + argument];
if (typeof v === 'string') {
return v;
}
throw new Error(localize('noValueForCommand', "Variable {0} can not be resolved because the command has no value.", match));
}
return match;
}
}
| src/vs/workbench/services/configurationResolver/common/variableResolver.ts | 1 | https://github.com/microsoft/vscode/commit/36ef468d4dd9a84203bdb2dba688ce395e4b4408 | [
0.001969455275684595,
0.00041424858500249684,
0.00016698267427273095,
0.0002724383375607431,
0.0003554626018740237
] |
{
"id": 2,
"code_window": [
"\tresolve(folder: IWorkspaceFolder | undefined, value: string[]): string[];\n",
"\tresolve(folder: IWorkspaceFolder | undefined, value: IStringDictionary<string>): IStringDictionary<string>;\n",
"\n",
"\t/**\n",
"\t * Recursively resolves all variables in the given config and returns a copy of it with substituted values.\n",
"\t * Command variables are only substituted if a \"commandValueMapping\" dictionary is given and if it contains an entry for the command.\n"
],
"labels": [
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t/**\n",
"\t * @deprecated Use the async version of `resolve` instead.\n",
"\t */\n"
],
"file_path": "src/vs/workbench/services/configurationResolver/common/configurationResolver.ts",
"type": "add",
"edit_start_line_idx": 17
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { IBuiltinExtensionsScannerService, IScannedExtension, ExtensionType, IExtensionManifest } from 'vs/platform/extensions/common/extensions';
import { isWeb } from 'vs/base/common/platform';
import { IWorkbenchEnvironmentService } from 'vs/workbench/services/environment/common/environmentService';
import { IUriIdentityService } from 'vs/workbench/services/uriIdentity/common/uriIdentity';
import { registerSingleton } from 'vs/platform/instantiation/common/extensions';
import { URI } from 'vs/base/common/uri';
import { getGalleryExtensionId } from 'vs/platform/extensionManagement/common/extensionManagementUtil';
import { FileAccess } from 'vs/base/common/network';
interface IScannedBuiltinExtension {
extensionPath: string;
packageJSON: IExtensionManifest;
packageNLS?: any;
readmePath?: string;
changelogPath?: string;
}
export class BuiltinExtensionsScannerService implements IBuiltinExtensionsScannerService {
declare readonly _serviceBrand: undefined;
private readonly builtinExtensions: IScannedExtension[] = [];
constructor(
@IWorkbenchEnvironmentService environmentService: IWorkbenchEnvironmentService,
@IUriIdentityService uriIdentityService: IUriIdentityService,
) {
if (isWeb) {
const builtinExtensionsServiceUrl = this._getBuiltinExtensionsUrl(environmentService);
if (builtinExtensionsServiceUrl) {
let scannedBuiltinExtensions: IScannedBuiltinExtension[] = [];
if (environmentService.isBuilt) {
// Built time configuration (do NOT modify)
scannedBuiltinExtensions = [/*BUILD->INSERT_BUILTIN_EXTENSIONS*/];
} else {
// Find builtin extensions by checking for DOM
const builtinExtensionsElement = document.getElementById('vscode-workbench-builtin-extensions');
const builtinExtensionsElementAttribute = builtinExtensionsElement ? builtinExtensionsElement.getAttribute('data-settings') : undefined;
if (builtinExtensionsElementAttribute) {
try {
scannedBuiltinExtensions = JSON.parse(builtinExtensionsElementAttribute);
} catch (error) { /* ignore error*/ }
}
}
this.builtinExtensions = scannedBuiltinExtensions.map(e => ({
identifier: { id: getGalleryExtensionId(e.packageJSON.publisher, e.packageJSON.name) },
location: uriIdentityService.extUri.joinPath(builtinExtensionsServiceUrl!, e.extensionPath),
type: ExtensionType.System,
packageJSON: e.packageJSON,
packageNLS: e.packageNLS,
readmeUrl: e.readmePath ? uriIdentityService.extUri.joinPath(builtinExtensionsServiceUrl!, e.readmePath) : undefined,
changelogUrl: e.changelogPath ? uriIdentityService.extUri.joinPath(builtinExtensionsServiceUrl!, e.changelogPath) : undefined,
}));
}
}
}
private _getBuiltinExtensionsUrl(environmentService: IWorkbenchEnvironmentService): URI | undefined {
let enableBuiltinExtensions: boolean;
if (environmentService.options && typeof environmentService.options._enableBuiltinExtensions !== 'undefined') {
enableBuiltinExtensions = environmentService.options._enableBuiltinExtensions;
} else {
enableBuiltinExtensions = environmentService.remoteAuthority ? false : true;
}
if (enableBuiltinExtensions) {
return FileAccess.asBrowserUri('../../../../../../extensions', require);
}
return undefined;
}
async scanBuiltinExtensions(): Promise<IScannedExtension[]> {
if (isWeb) {
return this.builtinExtensions;
}
throw new Error('not supported');
}
}
registerSingleton(IBuiltinExtensionsScannerService, BuiltinExtensionsScannerService);
| src/vs/workbench/services/extensionManagement/browser/builtinExtensionsScannerService.ts | 0 | https://github.com/microsoft/vscode/commit/36ef468d4dd9a84203bdb2dba688ce395e4b4408 | [
0.00017601372383069247,
0.00016986523405648768,
0.00016647568554617465,
0.00016876793233677745,
0.0000028377739909046795
] |
{
"id": 2,
"code_window": [
"\tresolve(folder: IWorkspaceFolder | undefined, value: string[]): string[];\n",
"\tresolve(folder: IWorkspaceFolder | undefined, value: IStringDictionary<string>): IStringDictionary<string>;\n",
"\n",
"\t/**\n",
"\t * Recursively resolves all variables in the given config and returns a copy of it with substituted values.\n",
"\t * Command variables are only substituted if a \"commandValueMapping\" dictionary is given and if it contains an entry for the command.\n"
],
"labels": [
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t/**\n",
"\t * @deprecated Use the async version of `resolve` instead.\n",
"\t */\n"
],
"file_path": "src/vs/workbench/services/configurationResolver/common/configurationResolver.ts",
"type": "add",
"edit_start_line_idx": 17
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { ICodeEditor } from 'vs/editor/browser/editorBrowser';
import { TextEdit, WorkspaceEdit, WorkspaceEditMetadata, WorkspaceFileEdit, WorkspaceFileEditOptions, WorkspaceTextEdit } from 'vs/editor/common/modes';
import { createDecorator } from 'vs/platform/instantiation/common/instantiation';
import { IProgress, IProgressStep } from 'vs/platform/progress/common/progress';
import { IDisposable } from 'vs/base/common/lifecycle';
import { URI } from 'vs/base/common/uri';
import { isObject } from 'vs/base/common/types';
import { UndoRedoSource } from 'vs/platform/undoRedo/common/undoRedo';
import { CancellationToken } from 'vs/base/common/cancellation';
export const IBulkEditService = createDecorator<IBulkEditService>('IWorkspaceEditService');
function isWorkspaceFileEdit(thing: any): thing is WorkspaceFileEdit {
return isObject(thing) && (Boolean((<WorkspaceFileEdit>thing).newUri) || Boolean((<WorkspaceFileEdit>thing).oldUri));
}
function isWorkspaceTextEdit(thing: any): thing is WorkspaceTextEdit {
return isObject(thing) && URI.isUri((<WorkspaceTextEdit>thing).resource) && isObject((<WorkspaceTextEdit>thing).edit);
}
export class ResourceEdit {
protected constructor(readonly metadata?: WorkspaceEditMetadata) { }
static convert(edit: WorkspaceEdit): ResourceEdit[] {
return edit.edits.map(edit => {
if (isWorkspaceTextEdit(edit)) {
return new ResourceTextEdit(edit.resource, edit.edit, edit.modelVersionId, edit.metadata);
}
if (isWorkspaceFileEdit(edit)) {
return new ResourceFileEdit(edit.oldUri, edit.newUri, edit.options, edit.metadata);
}
throw new Error('Unsupported edit');
});
}
}
export class ResourceTextEdit extends ResourceEdit {
constructor(
readonly resource: URI,
readonly textEdit: TextEdit,
readonly versionId?: number,
readonly metadata?: WorkspaceEditMetadata
) {
super(metadata);
}
}
export class ResourceFileEdit extends ResourceEdit {
constructor(
readonly oldResource: URI | undefined,
readonly newResource: URI | undefined,
readonly options?: WorkspaceFileEditOptions,
readonly metadata?: WorkspaceEditMetadata
) {
super(metadata);
}
}
export interface IBulkEditOptions {
editor?: ICodeEditor;
progress?: IProgress<IProgressStep>;
token?: CancellationToken;
showPreview?: boolean;
label?: string;
quotableLabel?: string;
undoRedoSource?: UndoRedoSource;
undoRedoGroupId?: number;
confirmBeforeUndo?: boolean;
}
export interface IBulkEditResult {
ariaSummary: string;
}
export type IBulkEditPreviewHandler = (edits: ResourceEdit[], options?: IBulkEditOptions) => Promise<ResourceEdit[]>;
export interface IBulkEditService {
readonly _serviceBrand: undefined;
hasPreviewHandler(): boolean;
setPreviewHandler(handler: IBulkEditPreviewHandler): IDisposable;
apply(edit: ResourceEdit[], options?: IBulkEditOptions): Promise<IBulkEditResult>;
}
| src/vs/editor/browser/services/bulkEditService.ts | 0 | https://github.com/microsoft/vscode/commit/36ef468d4dd9a84203bdb2dba688ce395e4b4408 | [
0.00020254038099665195,
0.00018066268239635974,
0.0001650168269407004,
0.00017861672677099705,
0.000012784899809048511
] |
{
"id": 2,
"code_window": [
"\tresolve(folder: IWorkspaceFolder | undefined, value: string[]): string[];\n",
"\tresolve(folder: IWorkspaceFolder | undefined, value: IStringDictionary<string>): IStringDictionary<string>;\n",
"\n",
"\t/**\n",
"\t * Recursively resolves all variables in the given config and returns a copy of it with substituted values.\n",
"\t * Command variables are only substituted if a \"commandValueMapping\" dictionary is given and if it contains an entry for the command.\n"
],
"labels": [
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t/**\n",
"\t * @deprecated Use the async version of `resolve` instead.\n",
"\t */\n"
],
"file_path": "src/vs/workbench/services/configurationResolver/common/configurationResolver.ts",
"type": "add",
"edit_start_line_idx": 17
} | Package: @@NAME@@
Version: @@VERSION@@
Section: devel
Depends: libnss3 (>= 2:3.26), gnupg, apt, libxkbfile1, libsecret-1-0, libgtk-3-0 (>= 3.10.0), libxss1, libgbm1
Priority: optional
Architecture: @@ARCHITECTURE@@
Maintainer: Microsoft Corporation <[email protected]>
Homepage: https://code.visualstudio.com/
Installed-Size: @@INSTALLEDSIZE@@
Provides: visual-studio-@@NAME@@
Conflicts: visual-studio-@@NAME@@
Replaces: visual-studio-@@NAME@@
Description: Code editing. Redefined.
Visual Studio Code is a new choice of tool that combines the simplicity of a
code editor with what developers need for the core edit-build-debug cycle.
See https://code.visualstudio.com/docs/setup/linux for installation
instructions and FAQ.
| resources/linux/debian/control.template | 0 | https://github.com/microsoft/vscode/commit/36ef468d4dd9a84203bdb2dba688ce395e4b4408 | [
0.00016700878040865064,
0.00016444080392830074,
0.00016187284199986607,
0.00016444080392830074,
0.000002567969204392284
] |
{
"id": 3,
"code_window": [
"\t/**\n",
"\t * Recursively resolves all variables in the given config and returns a copy of it with substituted values.\n",
"\t * Command variables are only substituted if a \"commandValueMapping\" dictionary is given and if it contains an entry for the command.\n",
"\t */\n",
"\tresolveAny(folder: IWorkspaceFolder | undefined, config: any, commandValueMapping?: IStringDictionary<string>): any;\n",
"\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t * @deprecated Use the async version of `resolveAny` instead.\n"
],
"file_path": "src/vs/workbench/services/configurationResolver/common/configurationResolver.ts",
"type": "add",
"edit_start_line_idx": 22
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { IStringDictionary } from 'vs/base/common/collections';
import { createDecorator } from 'vs/platform/instantiation/common/instantiation';
import { IWorkspaceFolder } from 'vs/platform/workspace/common/workspace';
import { ConfigurationTarget } from 'vs/platform/configuration/common/configuration';
export const IConfigurationResolverService = createDecorator<IConfigurationResolverService>('configurationResolverService');
export interface IConfigurationResolverService {
readonly _serviceBrand: undefined;
resolve(folder: IWorkspaceFolder | undefined, value: string): string;
resolve(folder: IWorkspaceFolder | undefined, value: string[]): string[];
resolve(folder: IWorkspaceFolder | undefined, value: IStringDictionary<string>): IStringDictionary<string>;
/**
* Recursively resolves all variables in the given config and returns a copy of it with substituted values.
* Command variables are only substituted if a "commandValueMapping" dictionary is given and if it contains an entry for the command.
*/
resolveAny(folder: IWorkspaceFolder | undefined, config: any, commandValueMapping?: IStringDictionary<string>): any;
/**
* Recursively resolves all variables (including commands and user input) in the given config and returns a copy of it with substituted values.
* If a "variables" dictionary (with names -> command ids) is given, command variables are first mapped through it before being resolved.
*
* @param section For example, 'tasks' or 'debug'. Used for resolving inputs.
* @param variables Aliases for commands.
*/
resolveWithInteractionReplace(folder: IWorkspaceFolder | undefined, config: any, section?: string, variables?: IStringDictionary<string>, target?: ConfigurationTarget): Promise<any>;
/**
* Similar to resolveWithInteractionReplace, except without the replace. Returns a map of variables and their resolution.
* Keys in the map will be of the format input:variableName or command:variableName.
*/
resolveWithInteraction(folder: IWorkspaceFolder | undefined, config: any, section?: string, variables?: IStringDictionary<string>, target?: ConfigurationTarget): Promise<Map<string, string> | undefined>;
/**
* Contributes a variable that can be resolved later. Consumers that use resolveAny, resolveWithInteraction,
* and resolveWithInteractionReplace will have contributed variables resolved.
*/
contributeVariable(variable: string, resolution: () => Promise<string | undefined>): void;
}
export interface PromptStringInputInfo {
id: string;
type: 'promptString';
description: string;
default?: string;
password?: boolean;
}
export interface PickStringInputInfo {
id: string;
type: 'pickString';
description: string;
options: (string | { value: string, label?: string })[];
default?: string;
}
export interface CommandInputInfo {
id: string;
type: 'command';
command: string;
args?: any;
}
export type ConfiguredInput = PromptStringInputInfo | PickStringInputInfo | CommandInputInfo;
| src/vs/workbench/services/configurationResolver/common/configurationResolver.ts | 1 | https://github.com/microsoft/vscode/commit/36ef468d4dd9a84203bdb2dba688ce395e4b4408 | [
0.9679945707321167,
0.34472617506980896,
0.00016379015869461,
0.010857341811060905,
0.4399348497390747
] |
{
"id": 3,
"code_window": [
"\t/**\n",
"\t * Recursively resolves all variables in the given config and returns a copy of it with substituted values.\n",
"\t * Command variables are only substituted if a \"commandValueMapping\" dictionary is given and if it contains an entry for the command.\n",
"\t */\n",
"\tresolveAny(folder: IWorkspaceFolder | undefined, config: any, commandValueMapping?: IStringDictionary<string>): any;\n",
"\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t * @deprecated Use the async version of `resolveAny` instead.\n"
],
"file_path": "src/vs/workbench/services/configurationResolver/common/configurationResolver.ts",
"type": "add",
"edit_start_line_idx": 22
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
.monaco-editor .accessibilityHelpWidget {
padding: 10px;
vertical-align: middle;
overflow: scroll;
} | src/vs/editor/standalone/browser/accessibilityHelp/accessibilityHelp.css | 0 | https://github.com/microsoft/vscode/commit/36ef468d4dd9a84203bdb2dba688ce395e4b4408 | [
0.0001760625746101141,
0.00017339699843432754,
0.000170731422258541,
0.00017339699843432754,
0.000002665576175786555
] |
{
"id": 3,
"code_window": [
"\t/**\n",
"\t * Recursively resolves all variables in the given config and returns a copy of it with substituted values.\n",
"\t * Command variables are only substituted if a \"commandValueMapping\" dictionary is given and if it contains an entry for the command.\n",
"\t */\n",
"\tresolveAny(folder: IWorkspaceFolder | undefined, config: any, commandValueMapping?: IStringDictionary<string>): any;\n",
"\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t * @deprecated Use the async version of `resolveAny` instead.\n"
],
"file_path": "src/vs/workbench/services/configurationResolver/common/configurationResolver.ts",
"type": "add",
"edit_start_line_idx": 22
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
.monaco-editor .peekview-widget .head {
box-sizing: border-box;
display: flex;
}
.monaco-editor .peekview-widget .head .peekview-title {
display: flex;
align-items: center;
font-size: 13px;
margin-left: 20px;
cursor: pointer;
min-width: 0;
}
.monaco-editor .peekview-widget .head .peekview-title .dirname:not(:empty) {
font-size: 0.9em;
margin-left: 0.5em;
}
.monaco-editor .peekview-widget .head .peekview-title .meta {
white-space: nowrap;
}
.monaco-editor .peekview-widget .head .peekview-title .dirname {
white-space: nowrap;
}
.monaco-editor .peekview-widget .head .peekview-title .filename {
overflow: hidden;
text-overflow: ellipsis;
}
.monaco-editor .peekview-widget .head .peekview-title .meta:not(:empty)::before {
content: '-';
padding: 0 0.3em;
}
.monaco-editor .peekview-widget .head .peekview-actions {
flex: 1;
text-align: right;
padding-right: 2px;
}
.monaco-editor .peekview-widget .head .peekview-actions > .monaco-action-bar {
display: inline-block;
}
.monaco-editor .peekview-widget .head .peekview-actions > .monaco-action-bar,
.monaco-editor .peekview-widget .head .peekview-actions > .monaco-action-bar > .actions-container {
height: 100%;
}
.monaco-editor .peekview-widget .head .peekview-actions > .monaco-action-bar .action-item {
margin-left: 4px;
}
.monaco-editor .peekview-widget .head .peekview-actions > .monaco-action-bar .action-label {
width: 16px;
height: 100%;
margin: 0;
line-height: inherit;
background-repeat: no-repeat;
background-position: center center;
}
.monaco-editor .peekview-widget .head .peekview-actions > .monaco-action-bar .action-label.codicon {
margin: 0;
}
.monaco-editor .peekview-widget > .body {
border-top: 1px solid;
position: relative;
}
.monaco-editor .peekview-widget .head .peekview-title .codicon {
margin-right: 4px;
}
| src/vs/editor/contrib/peekView/media/peekViewWidget.css | 0 | https://github.com/microsoft/vscode/commit/36ef468d4dd9a84203bdb2dba688ce395e4b4408 | [
0.00017663242761045694,
0.0001741602027323097,
0.0001711651566438377,
0.000173860156792216,
0.0000017904075093611027
] |
{
"id": 3,
"code_window": [
"\t/**\n",
"\t * Recursively resolves all variables in the given config and returns a copy of it with substituted values.\n",
"\t * Command variables are only substituted if a \"commandValueMapping\" dictionary is given and if it contains an entry for the command.\n",
"\t */\n",
"\tresolveAny(folder: IWorkspaceFolder | undefined, config: any, commandValueMapping?: IStringDictionary<string>): any;\n",
"\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t * @deprecated Use the async version of `resolveAny` instead.\n"
],
"file_path": "src/vs/workbench/services/configurationResolver/common/configurationResolver.ts",
"type": "add",
"edit_start_line_idx": 22
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as assert from 'assert';
import { Emitter, Event } from 'vs/base/common/event';
import { Disposable, IDisposable } from 'vs/base/common/lifecycle';
import { normalize } from 'vs/base/common/path';
import * as platform from 'vs/base/common/platform';
import { isObject } from 'vs/base/common/types';
import { URI as uri } from 'vs/base/common/uri';
import { Selection } from 'vs/editor/common/core/selection';
import { EditorType } from 'vs/editor/common/editorCommon';
import { ICommandService } from 'vs/platform/commands/common/commands';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { TestConfigurationService } from 'vs/platform/configuration/test/common/testConfigurationService';
import { IFormatterChangeEvent, ILabelService, ResourceLabelFormatter } from 'vs/platform/label/common/label';
import { IWorkspace, IWorkspaceFolder, Workspace } from 'vs/platform/workspace/common/workspace';
import { testWorkspace } from 'vs/platform/workspace/test/common/testWorkspace';
import { IWorkspaceIdentifier } from 'vs/platform/workspaces/common/workspaces';
import { BaseConfigurationResolverService } from 'vs/workbench/services/configurationResolver/browser/configurationResolverService';
import { IConfigurationResolverService } from 'vs/workbench/services/configurationResolver/common/configurationResolver';
import { NativeWorkbenchEnvironmentService } from 'vs/workbench/services/environment/electron-sandbox/environmentService';
import { TestEditorService, TestProductService, TestQuickInputService } from 'vs/workbench/test/browser/workbenchTestServices';
import { TestContextService } from 'vs/workbench/test/common/workbenchTestServices';
import { TestWorkbenchConfiguration, TestEnvironmentPaths } from 'vs/workbench/test/electron-browser/workbenchTestServices';
const mockLineNumber = 10;
class TestEditorServiceWithActiveEditor extends TestEditorService {
get activeTextEditorControl(): any {
return {
getEditorType() {
return EditorType.ICodeEditor;
},
getSelection() {
return new Selection(mockLineNumber, 1, mockLineNumber, 10);
}
};
}
get activeEditor(): any {
return {
get resource(): any {
return uri.parse('file:///VSCode/workspaceLocation/file');
}
};
}
}
class TestConfigurationResolverService extends BaseConfigurationResolverService {
}
const nullContext = {
getAppRoot: () => undefined,
getExecPath: () => undefined
};
suite('Configuration Resolver Service', () => {
let configurationResolverService: IConfigurationResolverService | null;
let envVariables: { [key: string]: string } = { key1: 'Value for key1', key2: 'Value for key2' };
let environmentService: MockWorkbenchEnvironmentService;
let mockCommandService: MockCommandService;
let editorService: TestEditorServiceWithActiveEditor;
let containingWorkspace: Workspace;
let workspace: IWorkspaceFolder;
let quickInputService: TestQuickInputService;
let labelService: MockLabelService;
setup(() => {
mockCommandService = new MockCommandService();
editorService = new TestEditorServiceWithActiveEditor();
quickInputService = new TestQuickInputService();
environmentService = new MockWorkbenchEnvironmentService(envVariables);
labelService = new MockLabelService();
containingWorkspace = testWorkspace(uri.parse('file:///VSCode/workspaceLocation'));
workspace = containingWorkspace.folders[0];
configurationResolverService = new TestConfigurationResolverService(nullContext, environmentService.userEnv, editorService, new MockInputsConfigurationService(), mockCommandService, new TestContextService(containingWorkspace), quickInputService, labelService);
});
teardown(() => {
configurationResolverService = null;
});
test('substitute one', () => {
if (platform.isWindows) {
assert.strictEqual(configurationResolverService!.resolve(workspace, 'abc ${workspaceFolder} xyz'), 'abc \\VSCode\\workspaceLocation xyz');
} else {
assert.strictEqual(configurationResolverService!.resolve(workspace, 'abc ${workspaceFolder} xyz'), 'abc /VSCode/workspaceLocation xyz');
}
});
test('workspace folder with argument', () => {
if (platform.isWindows) {
assert.strictEqual(configurationResolverService!.resolve(workspace, 'abc ${workspaceFolder:workspaceLocation} xyz'), 'abc \\VSCode\\workspaceLocation xyz');
} else {
assert.strictEqual(configurationResolverService!.resolve(workspace, 'abc ${workspaceFolder:workspaceLocation} xyz'), 'abc /VSCode/workspaceLocation xyz');
}
});
test('workspace folder with invalid argument', () => {
assert.throws(() => configurationResolverService!.resolve(workspace, 'abc ${workspaceFolder:invalidLocation} xyz'));
});
test('workspace folder with undefined workspace folder', () => {
assert.throws(() => configurationResolverService!.resolve(undefined, 'abc ${workspaceFolder} xyz'));
});
test('workspace folder with argument and undefined workspace folder', () => {
if (platform.isWindows) {
assert.strictEqual(configurationResolverService!.resolve(undefined, 'abc ${workspaceFolder:workspaceLocation} xyz'), 'abc \\VSCode\\workspaceLocation xyz');
} else {
assert.strictEqual(configurationResolverService!.resolve(undefined, 'abc ${workspaceFolder:workspaceLocation} xyz'), 'abc /VSCode/workspaceLocation xyz');
}
});
test('workspace folder with invalid argument and undefined workspace folder', () => {
assert.throws(() => configurationResolverService!.resolve(undefined, 'abc ${workspaceFolder:invalidLocation} xyz'));
});
test('workspace root folder name', () => {
assert.strictEqual(configurationResolverService!.resolve(workspace, 'abc ${workspaceRootFolderName} xyz'), 'abc workspaceLocation xyz');
});
test('current selected line number', () => {
assert.strictEqual(configurationResolverService!.resolve(workspace, 'abc ${lineNumber} xyz'), `abc ${mockLineNumber} xyz`);
});
test('relative file', () => {
assert.strictEqual(configurationResolverService!.resolve(workspace, 'abc ${relativeFile} xyz'), 'abc file xyz');
});
test('relative file with argument', () => {
assert.strictEqual(configurationResolverService!.resolve(workspace, 'abc ${relativeFile:workspaceLocation} xyz'), 'abc file xyz');
});
test('relative file with invalid argument', () => {
assert.throws(() => configurationResolverService!.resolve(workspace, 'abc ${relativeFile:invalidLocation} xyz'));
});
test('relative file with undefined workspace folder', () => {
if (platform.isWindows) {
assert.strictEqual(configurationResolverService!.resolve(undefined, 'abc ${relativeFile} xyz'), 'abc \\VSCode\\workspaceLocation\\file xyz');
} else {
assert.strictEqual(configurationResolverService!.resolve(undefined, 'abc ${relativeFile} xyz'), 'abc /VSCode/workspaceLocation/file xyz');
}
});
test('relative file with argument and undefined workspace folder', () => {
assert.strictEqual(configurationResolverService!.resolve(undefined, 'abc ${relativeFile:workspaceLocation} xyz'), 'abc file xyz');
});
test('relative file with invalid argument and undefined workspace folder', () => {
assert.throws(() => configurationResolverService!.resolve(undefined, 'abc ${relativeFile:invalidLocation} xyz'));
});
test('substitute many', () => {
if (platform.isWindows) {
assert.strictEqual(configurationResolverService!.resolve(workspace, '${workspaceFolder} - ${workspaceFolder}'), '\\VSCode\\workspaceLocation - \\VSCode\\workspaceLocation');
} else {
assert.strictEqual(configurationResolverService!.resolve(workspace, '${workspaceFolder} - ${workspaceFolder}'), '/VSCode/workspaceLocation - /VSCode/workspaceLocation');
}
});
test('substitute one env variable', () => {
if (platform.isWindows) {
assert.strictEqual(configurationResolverService!.resolve(workspace, 'abc ${workspaceFolder} ${env:key1} xyz'), 'abc \\VSCode\\workspaceLocation Value for key1 xyz');
} else {
assert.strictEqual(configurationResolverService!.resolve(workspace, 'abc ${workspaceFolder} ${env:key1} xyz'), 'abc /VSCode/workspaceLocation Value for key1 xyz');
}
});
test('substitute many env variable', () => {
if (platform.isWindows) {
assert.strictEqual(configurationResolverService!.resolve(workspace, '${workspaceFolder} - ${workspaceFolder} ${env:key1} - ${env:key2}'), '\\VSCode\\workspaceLocation - \\VSCode\\workspaceLocation Value for key1 - Value for key2');
} else {
assert.strictEqual(configurationResolverService!.resolve(workspace, '${workspaceFolder} - ${workspaceFolder} ${env:key1} - ${env:key2}'), '/VSCode/workspaceLocation - /VSCode/workspaceLocation Value for key1 - Value for key2');
}
});
test('disallows nested keys (#77289)', () => {
assert.strictEqual(configurationResolverService!.resolve(workspace, '${env:key1} ${env:key1${env:key2}}'), 'Value for key1 ${env:key1${env:key2}}');
});
// test('substitute keys and values in object', () => {
// const myObject = {
// '${workspaceRootFolderName}': '${lineNumber}',
// 'hey ${env:key1} ': '${workspaceRootFolderName}'
// };
// assert.deepStrictEqual(configurationResolverService!.resolve(workspace, myObject), {
// 'workspaceLocation': `${editorService.mockLineNumber}`,
// 'hey Value for key1 ': 'workspaceLocation'
// });
// });
test('substitute one env variable using platform case sensitivity', () => {
if (platform.isWindows) {
assert.strictEqual(configurationResolverService!.resolve(workspace, '${env:key1} - ${env:Key1}'), 'Value for key1 - Value for key1');
} else {
assert.strictEqual(configurationResolverService!.resolve(workspace, '${env:key1} - ${env:Key1}'), 'Value for key1 - ');
}
});
test('substitute one configuration variable', () => {
let configurationService: IConfigurationService = new TestConfigurationService({
editor: {
fontFamily: 'foo'
},
terminal: {
integrated: {
fontFamily: 'bar'
}
}
});
let service = new TestConfigurationResolverService(nullContext, environmentService.userEnv, new TestEditorServiceWithActiveEditor(), configurationService, mockCommandService, new TestContextService(), quickInputService, labelService);
assert.strictEqual(service.resolve(workspace, 'abc ${config:editor.fontFamily} xyz'), 'abc foo xyz');
});
test('substitute configuration variable with undefined workspace folder', () => {
let configurationService: IConfigurationService = new TestConfigurationService({
editor: {
fontFamily: 'foo'
}
});
let service = new TestConfigurationResolverService(nullContext, environmentService.userEnv, new TestEditorServiceWithActiveEditor(), configurationService, mockCommandService, new TestContextService(), quickInputService, labelService);
assert.strictEqual(service.resolve(undefined, 'abc ${config:editor.fontFamily} xyz'), 'abc foo xyz');
});
test('substitute many configuration variables', () => {
let configurationService: IConfigurationService;
configurationService = new TestConfigurationService({
editor: {
fontFamily: 'foo'
},
terminal: {
integrated: {
fontFamily: 'bar'
}
}
});
let service = new TestConfigurationResolverService(nullContext, environmentService.userEnv, new TestEditorServiceWithActiveEditor(), configurationService, mockCommandService, new TestContextService(), quickInputService, labelService);
assert.strictEqual(service.resolve(workspace, 'abc ${config:editor.fontFamily} ${config:terminal.integrated.fontFamily} xyz'), 'abc foo bar xyz');
});
test('substitute one env variable and a configuration variable', () => {
let configurationService: IConfigurationService;
configurationService = new TestConfigurationService({
editor: {
fontFamily: 'foo'
},
terminal: {
integrated: {
fontFamily: 'bar'
}
}
});
let service = new TestConfigurationResolverService(nullContext, environmentService.userEnv, new TestEditorServiceWithActiveEditor(), configurationService, mockCommandService, new TestContextService(), quickInputService, labelService);
if (platform.isWindows) {
assert.strictEqual(service.resolve(workspace, 'abc ${config:editor.fontFamily} ${workspaceFolder} ${env:key1} xyz'), 'abc foo \\VSCode\\workspaceLocation Value for key1 xyz');
} else {
assert.strictEqual(service.resolve(workspace, 'abc ${config:editor.fontFamily} ${workspaceFolder} ${env:key1} xyz'), 'abc foo /VSCode/workspaceLocation Value for key1 xyz');
}
});
test('substitute many env variable and a configuration variable', () => {
let configurationService: IConfigurationService;
configurationService = new TestConfigurationService({
editor: {
fontFamily: 'foo'
},
terminal: {
integrated: {
fontFamily: 'bar'
}
}
});
let service = new TestConfigurationResolverService(nullContext, environmentService.userEnv, new TestEditorServiceWithActiveEditor(), configurationService, mockCommandService, new TestContextService(), quickInputService, labelService);
if (platform.isWindows) {
assert.strictEqual(service.resolve(workspace, '${config:editor.fontFamily} ${config:terminal.integrated.fontFamily} ${workspaceFolder} - ${workspaceFolder} ${env:key1} - ${env:key2}'), 'foo bar \\VSCode\\workspaceLocation - \\VSCode\\workspaceLocation Value for key1 - Value for key2');
} else {
assert.strictEqual(service.resolve(workspace, '${config:editor.fontFamily} ${config:terminal.integrated.fontFamily} ${workspaceFolder} - ${workspaceFolder} ${env:key1} - ${env:key2}'), 'foo bar /VSCode/workspaceLocation - /VSCode/workspaceLocation Value for key1 - Value for key2');
}
});
test('mixed types of configuration variables', () => {
let configurationService: IConfigurationService;
configurationService = new TestConfigurationService({
editor: {
fontFamily: 'foo',
lineNumbers: 123,
insertSpaces: false
},
terminal: {
integrated: {
fontFamily: 'bar'
}
},
json: {
schemas: [
{
fileMatch: [
'/myfile',
'/myOtherfile'
],
url: 'schemaURL'
}
]
}
});
let service = new TestConfigurationResolverService(nullContext, environmentService.userEnv, new TestEditorServiceWithActiveEditor(), configurationService, mockCommandService, new TestContextService(), quickInputService, labelService);
assert.strictEqual(service.resolve(workspace, 'abc ${config:editor.fontFamily} ${config:editor.lineNumbers} ${config:editor.insertSpaces} xyz'), 'abc foo 123 false xyz');
});
test('uses original variable as fallback', () => {
let configurationService: IConfigurationService;
configurationService = new TestConfigurationService({
editor: {}
});
let service = new TestConfigurationResolverService(nullContext, environmentService.userEnv, new TestEditorServiceWithActiveEditor(), configurationService, mockCommandService, new TestContextService(), quickInputService, labelService);
assert.strictEqual(service.resolve(workspace, 'abc ${unknownVariable} xyz'), 'abc ${unknownVariable} xyz');
assert.strictEqual(service.resolve(workspace, 'abc ${env:unknownVariable} xyz'), 'abc xyz');
});
test('configuration variables with invalid accessor', () => {
let configurationService: IConfigurationService;
configurationService = new TestConfigurationService({
editor: {
fontFamily: 'foo'
}
});
let service = new TestConfigurationResolverService(nullContext, environmentService.userEnv, new TestEditorServiceWithActiveEditor(), configurationService, mockCommandService, new TestContextService(), quickInputService, labelService);
assert.throws(() => service.resolve(workspace, 'abc ${env} xyz'));
assert.throws(() => service.resolve(workspace, 'abc ${env:} xyz'));
assert.throws(() => service.resolve(workspace, 'abc ${config} xyz'));
assert.throws(() => service.resolve(workspace, 'abc ${config:} xyz'));
assert.throws(() => service.resolve(workspace, 'abc ${config:editor} xyz'));
assert.throws(() => service.resolve(workspace, 'abc ${config:editor..fontFamily} xyz'));
assert.throws(() => service.resolve(workspace, 'abc ${config:editor.none.none2} xyz'));
});
test('a single command variable', () => {
const configuration = {
'name': 'Attach to Process',
'type': 'node',
'request': 'attach',
'processId': '${command:command1}',
'port': 5858,
'sourceMaps': false,
'outDir': null
};
return configurationResolverService!.resolveWithInteractionReplace(undefined, configuration).then(result => {
assert.deepStrictEqual({ ...result }, {
'name': 'Attach to Process',
'type': 'node',
'request': 'attach',
'processId': 'command1-result',
'port': 5858,
'sourceMaps': false,
'outDir': null
});
assert.strictEqual(1, mockCommandService.callCount);
});
});
test('an old style command variable', () => {
const configuration = {
'name': 'Attach to Process',
'type': 'node',
'request': 'attach',
'processId': '${command:commandVariable1}',
'port': 5858,
'sourceMaps': false,
'outDir': null
};
const commandVariables = Object.create(null);
commandVariables['commandVariable1'] = 'command1';
return configurationResolverService!.resolveWithInteractionReplace(undefined, configuration, undefined, commandVariables).then(result => {
assert.deepStrictEqual({ ...result }, {
'name': 'Attach to Process',
'type': 'node',
'request': 'attach',
'processId': 'command1-result',
'port': 5858,
'sourceMaps': false,
'outDir': null
});
assert.strictEqual(1, mockCommandService.callCount);
});
});
test('multiple new and old-style command variables', () => {
const configuration = {
'name': 'Attach to Process',
'type': 'node',
'request': 'attach',
'processId': '${command:commandVariable1}',
'pid': '${command:command2}',
'sourceMaps': false,
'outDir': 'src/${command:command2}',
'env': {
'processId': '__${command:command2}__',
}
};
const commandVariables = Object.create(null);
commandVariables['commandVariable1'] = 'command1';
return configurationResolverService!.resolveWithInteractionReplace(undefined, configuration, undefined, commandVariables).then(result => {
const expected = {
'name': 'Attach to Process',
'type': 'node',
'request': 'attach',
'processId': 'command1-result',
'pid': 'command2-result',
'sourceMaps': false,
'outDir': 'src/command2-result',
'env': {
'processId': '__command2-result__',
}
};
assert.deepStrictEqual(Object.keys(result), Object.keys(expected));
Object.keys(result).forEach(property => {
const expectedProperty = (<any>expected)[property];
if (isObject(result[property])) {
assert.deepStrictEqual({ ...result[property] }, expectedProperty);
} else {
assert.deepStrictEqual(result[property], expectedProperty);
}
});
assert.strictEqual(2, mockCommandService.callCount);
});
});
test('a command variable that relies on resolved env vars', () => {
const configuration = {
'name': 'Attach to Process',
'type': 'node',
'request': 'attach',
'processId': '${command:commandVariable1}',
'value': '${env:key1}'
};
const commandVariables = Object.create(null);
commandVariables['commandVariable1'] = 'command1';
return configurationResolverService!.resolveWithInteractionReplace(undefined, configuration, undefined, commandVariables).then(result => {
assert.deepStrictEqual({ ...result }, {
'name': 'Attach to Process',
'type': 'node',
'request': 'attach',
'processId': 'Value for key1',
'value': 'Value for key1'
});
assert.strictEqual(1, mockCommandService.callCount);
});
});
test('a single prompt input variable', () => {
const configuration = {
'name': 'Attach to Process',
'type': 'node',
'request': 'attach',
'processId': '${input:input1}',
'port': 5858,
'sourceMaps': false,
'outDir': null
};
return configurationResolverService!.resolveWithInteractionReplace(workspace, configuration, 'tasks').then(result => {
assert.deepStrictEqual({ ...result }, {
'name': 'Attach to Process',
'type': 'node',
'request': 'attach',
'processId': 'resolvedEnterinput1',
'port': 5858,
'sourceMaps': false,
'outDir': null
});
assert.strictEqual(0, mockCommandService.callCount);
});
});
test('a single pick input variable', () => {
const configuration = {
'name': 'Attach to Process',
'type': 'node',
'request': 'attach',
'processId': '${input:input2}',
'port': 5858,
'sourceMaps': false,
'outDir': null
};
return configurationResolverService!.resolveWithInteractionReplace(workspace, configuration, 'tasks').then(result => {
assert.deepStrictEqual({ ...result }, {
'name': 'Attach to Process',
'type': 'node',
'request': 'attach',
'processId': 'selectedPick',
'port': 5858,
'sourceMaps': false,
'outDir': null
});
assert.strictEqual(0, mockCommandService.callCount);
});
});
test('a single command input variable', () => {
const configuration = {
'name': 'Attach to Process',
'type': 'node',
'request': 'attach',
'processId': '${input:input4}',
'port': 5858,
'sourceMaps': false,
'outDir': null
};
return configurationResolverService!.resolveWithInteractionReplace(workspace, configuration, 'tasks').then(result => {
assert.deepStrictEqual({ ...result }, {
'name': 'Attach to Process',
'type': 'node',
'request': 'attach',
'processId': 'arg for command',
'port': 5858,
'sourceMaps': false,
'outDir': null
});
assert.strictEqual(1, mockCommandService.callCount);
});
});
test('several input variables and command', () => {
const configuration = {
'name': '${input:input3}',
'type': '${command:command1}',
'request': '${input:input1}',
'processId': '${input:input2}',
'command': '${input:input4}',
'port': 5858,
'sourceMaps': false,
'outDir': null
};
return configurationResolverService!.resolveWithInteractionReplace(workspace, configuration, 'tasks').then(result => {
assert.deepStrictEqual({ ...result }, {
'name': 'resolvedEnterinput3',
'type': 'command1-result',
'request': 'resolvedEnterinput1',
'processId': 'selectedPick',
'command': 'arg for command',
'port': 5858,
'sourceMaps': false,
'outDir': null
});
assert.strictEqual(2, mockCommandService.callCount);
});
});
test('input variable with undefined workspace folder', () => {
const configuration = {
'name': 'Attach to Process',
'type': 'node',
'request': 'attach',
'processId': '${input:input1}',
'port': 5858,
'sourceMaps': false,
'outDir': null
};
return configurationResolverService!.resolveWithInteractionReplace(undefined, configuration, 'tasks').then(result => {
assert.deepStrictEqual({ ...result }, {
'name': 'Attach to Process',
'type': 'node',
'request': 'attach',
'processId': 'resolvedEnterinput1',
'port': 5858,
'sourceMaps': false,
'outDir': null
});
assert.strictEqual(0, mockCommandService.callCount);
});
});
test('contributed variable', () => {
const buildTask = 'npm: compile';
const variable = 'defaultBuildTask';
const configuration = {
'name': '${' + variable + '}',
};
configurationResolverService!.contributeVariable(variable, async () => { return buildTask; });
return configurationResolverService!.resolveWithInteractionReplace(workspace, configuration).then(result => {
assert.deepStrictEqual({ ...result }, {
'name': `${buildTask}`
});
});
});
});
class MockCommandService implements ICommandService {
public _serviceBrand: undefined;
public callCount = 0;
onWillExecuteCommand = () => Disposable.None;
onDidExecuteCommand = () => Disposable.None;
public executeCommand(commandId: string, ...args: any[]): Promise<any> {
this.callCount++;
let result = `${commandId}-result`;
if (args.length >= 1) {
if (args[0] && args[0].value) {
result = args[0].value;
}
}
return Promise.resolve(result);
}
}
class MockLabelService implements ILabelService {
_serviceBrand: undefined;
getUriLabel(resource: uri, options?: { relative?: boolean | undefined; noPrefix?: boolean | undefined; endWithSeparator?: boolean | undefined; }): string {
return normalize(resource.fsPath);
}
getUriBasenameLabel(resource: uri): string {
throw new Error('Method not implemented.');
}
getWorkspaceLabel(workspace: uri | IWorkspaceIdentifier | IWorkspace, options?: { verbose: boolean; }): string {
throw new Error('Method not implemented.');
}
getHostLabel(scheme: string, authority?: string): string {
throw new Error('Method not implemented.');
}
getSeparator(scheme: string, authority?: string): '/' | '\\' {
throw new Error('Method not implemented.');
}
registerFormatter(formatter: ResourceLabelFormatter): IDisposable {
throw new Error('Method not implemented.');
}
onDidChangeFormatters: Event<IFormatterChangeEvent> = new Emitter<IFormatterChangeEvent>().event;
}
class MockInputsConfigurationService extends TestConfigurationService {
public getValue(arg1?: any, arg2?: any): any {
let configuration;
if (arg1 === 'tasks') {
configuration = {
inputs: [
{
id: 'input1',
type: 'promptString',
description: 'Enterinput1',
default: 'default input1'
},
{
id: 'input2',
type: 'pickString',
description: 'Enterinput1',
default: 'option2',
options: ['option1', 'option2', 'option3']
},
{
id: 'input3',
type: 'promptString',
description: 'Enterinput3',
default: 'default input3',
password: true
},
{
id: 'input4',
type: 'command',
command: 'command1',
args: {
value: 'arg for command'
}
}
]
};
}
return configuration;
}
}
class MockWorkbenchEnvironmentService extends NativeWorkbenchEnvironmentService {
constructor(public userEnv: platform.IProcessEnvironment) {
super({ ...TestWorkbenchConfiguration, userEnv }, TestEnvironmentPaths, TestProductService);
}
}
| src/vs/workbench/services/configurationResolver/test/electron-browser/configurationResolverService.test.ts | 0 | https://github.com/microsoft/vscode/commit/36ef468d4dd9a84203bdb2dba688ce395e4b4408 | [
0.38340336084365845,
0.008911099284887314,
0.0001659058325458318,
0.00036465158336795866,
0.046197954565286636
] |
{
"id": 4,
"code_window": [
"\t */\n",
"\tresolveAny(folder: IWorkspaceFolder | undefined, config: any, commandValueMapping?: IStringDictionary<string>): any;\n",
"\n",
"\t/**\n",
"\t * Recursively resolves all variables (including commands and user input) in the given config and returns a copy of it with substituted values.\n",
"\t * If a \"variables\" dictionary (with names -> command ids) is given, command variables are first mapped through it before being resolved.\n",
"\t *\n",
"\t * @param section For example, 'tasks' or 'debug'. Used for resolving inputs.\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tresolveAsync(folder: IWorkspaceFolder | undefined, value: string): Promise<string>;\n",
"\tresolveAsync(folder: IWorkspaceFolder | undefined, value: string[]): Promise<string[]>;\n",
"\tresolveAsync(folder: IWorkspaceFolder | undefined, value: IStringDictionary<string>): Promise<IStringDictionary<string>>;\n",
"\n",
"\t/**\n",
"\t * Recursively resolves all variables in the given config and returns a copy of it with substituted values.\n",
"\t * Command variables are only substituted if a \"commandValueMapping\" dictionary is given and if it contains an entry for the command.\n",
"\t */\n",
"\tresolveAnyAsync(folder: IWorkspaceFolder | undefined, config: any, commandValueMapping?: IStringDictionary<string>): Promise<any>;\n",
"\n"
],
"file_path": "src/vs/workbench/services/configurationResolver/common/configurationResolver.ts",
"type": "add",
"edit_start_line_idx": 25
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { IStringDictionary } from 'vs/base/common/collections';
import { createDecorator } from 'vs/platform/instantiation/common/instantiation';
import { IWorkspaceFolder } from 'vs/platform/workspace/common/workspace';
import { ConfigurationTarget } from 'vs/platform/configuration/common/configuration';
export const IConfigurationResolverService = createDecorator<IConfigurationResolverService>('configurationResolverService');
export interface IConfigurationResolverService {
readonly _serviceBrand: undefined;
resolve(folder: IWorkspaceFolder | undefined, value: string): string;
resolve(folder: IWorkspaceFolder | undefined, value: string[]): string[];
resolve(folder: IWorkspaceFolder | undefined, value: IStringDictionary<string>): IStringDictionary<string>;
/**
* Recursively resolves all variables in the given config and returns a copy of it with substituted values.
* Command variables are only substituted if a "commandValueMapping" dictionary is given and if it contains an entry for the command.
*/
resolveAny(folder: IWorkspaceFolder | undefined, config: any, commandValueMapping?: IStringDictionary<string>): any;
/**
* Recursively resolves all variables (including commands and user input) in the given config and returns a copy of it with substituted values.
* If a "variables" dictionary (with names -> command ids) is given, command variables are first mapped through it before being resolved.
*
* @param section For example, 'tasks' or 'debug'. Used for resolving inputs.
* @param variables Aliases for commands.
*/
resolveWithInteractionReplace(folder: IWorkspaceFolder | undefined, config: any, section?: string, variables?: IStringDictionary<string>, target?: ConfigurationTarget): Promise<any>;
/**
* Similar to resolveWithInteractionReplace, except without the replace. Returns a map of variables and their resolution.
* Keys in the map will be of the format input:variableName or command:variableName.
*/
resolveWithInteraction(folder: IWorkspaceFolder | undefined, config: any, section?: string, variables?: IStringDictionary<string>, target?: ConfigurationTarget): Promise<Map<string, string> | undefined>;
/**
* Contributes a variable that can be resolved later. Consumers that use resolveAny, resolveWithInteraction,
* and resolveWithInteractionReplace will have contributed variables resolved.
*/
contributeVariable(variable: string, resolution: () => Promise<string | undefined>): void;
}
export interface PromptStringInputInfo {
id: string;
type: 'promptString';
description: string;
default?: string;
password?: boolean;
}
export interface PickStringInputInfo {
id: string;
type: 'pickString';
description: string;
options: (string | { value: string, label?: string })[];
default?: string;
}
export interface CommandInputInfo {
id: string;
type: 'command';
command: string;
args?: any;
}
export type ConfiguredInput = PromptStringInputInfo | PickStringInputInfo | CommandInputInfo;
| src/vs/workbench/services/configurationResolver/common/configurationResolver.ts | 1 | https://github.com/microsoft/vscode/commit/36ef468d4dd9a84203bdb2dba688ce395e4b4408 | [
0.2558183968067169,
0.03304266557097435,
0.00016399861488025635,
0.000497544533573091,
0.08421275019645691
] |
{
"id": 4,
"code_window": [
"\t */\n",
"\tresolveAny(folder: IWorkspaceFolder | undefined, config: any, commandValueMapping?: IStringDictionary<string>): any;\n",
"\n",
"\t/**\n",
"\t * Recursively resolves all variables (including commands and user input) in the given config and returns a copy of it with substituted values.\n",
"\t * If a \"variables\" dictionary (with names -> command ids) is given, command variables are first mapped through it before being resolved.\n",
"\t *\n",
"\t * @param section For example, 'tasks' or 'debug'. Used for resolving inputs.\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tresolveAsync(folder: IWorkspaceFolder | undefined, value: string): Promise<string>;\n",
"\tresolveAsync(folder: IWorkspaceFolder | undefined, value: string[]): Promise<string[]>;\n",
"\tresolveAsync(folder: IWorkspaceFolder | undefined, value: IStringDictionary<string>): Promise<IStringDictionary<string>>;\n",
"\n",
"\t/**\n",
"\t * Recursively resolves all variables in the given config and returns a copy of it with substituted values.\n",
"\t * Command variables are only substituted if a \"commandValueMapping\" dictionary is given and if it contains an entry for the command.\n",
"\t */\n",
"\tresolveAnyAsync(folder: IWorkspaceFolder | undefined, config: any, commandValueMapping?: IStringDictionary<string>): Promise<any>;\n",
"\n"
],
"file_path": "src/vs/workbench/services/configurationResolver/common/configurationResolver.ts",
"type": "add",
"edit_start_line_idx": 25
} | # Git integration for Visual Studio Code
**Notice:** This extension is bundled with Visual Studio Code. It can be disabled but not uninstalled.
## Features
See [Git support in VS Code](https://code.visualstudio.com/docs/editor/versioncontrol#_git-support) to learn about the features of this extension.
## API
The Git extension exposes an API, reachable by any other extension.
1. Copy `src/api/git.d.ts` to your extension's sources;
2. Include `git.d.ts` in your extension's compilation.
3. Get a hold of the API with the following snippet:
```ts
const gitExtension = vscode.extensions.getExtension<GitExtension>('vscode.git').exports;
const git = gitExtension.getAPI(1);
``` | extensions/git/README.md | 0 | https://github.com/microsoft/vscode/commit/36ef468d4dd9a84203bdb2dba688ce395e4b4408 | [
0.0001752203534124419,
0.0001689348282525316,
0.00016361329471692443,
0.00016797083662822843,
0.0000047873386392893735
] |
{
"id": 4,
"code_window": [
"\t */\n",
"\tresolveAny(folder: IWorkspaceFolder | undefined, config: any, commandValueMapping?: IStringDictionary<string>): any;\n",
"\n",
"\t/**\n",
"\t * Recursively resolves all variables (including commands and user input) in the given config and returns a copy of it with substituted values.\n",
"\t * If a \"variables\" dictionary (with names -> command ids) is given, command variables are first mapped through it before being resolved.\n",
"\t *\n",
"\t * @param section For example, 'tasks' or 'debug'. Used for resolving inputs.\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tresolveAsync(folder: IWorkspaceFolder | undefined, value: string): Promise<string>;\n",
"\tresolveAsync(folder: IWorkspaceFolder | undefined, value: string[]): Promise<string[]>;\n",
"\tresolveAsync(folder: IWorkspaceFolder | undefined, value: IStringDictionary<string>): Promise<IStringDictionary<string>>;\n",
"\n",
"\t/**\n",
"\t * Recursively resolves all variables in the given config and returns a copy of it with substituted values.\n",
"\t * Command variables are only substituted if a \"commandValueMapping\" dictionary is given and if it contains an entry for the command.\n",
"\t */\n",
"\tresolveAnyAsync(folder: IWorkspaceFolder | undefined, config: any, commandValueMapping?: IStringDictionary<string>): Promise<any>;\n",
"\n"
],
"file_path": "src/vs/workbench/services/configurationResolver/common/configurationResolver.ts",
"type": "add",
"edit_start_line_idx": 25
} | {
"registrations": [
{
"component": {
"type": "git",
"git": {
"name": "Ikuyadeu/vscode-R",
"repositoryUrl": "https://github.com/Ikuyadeu/vscode-R",
"commitHash": "e03ba9cb9b19412f48c73ea73deb6746d50bbf23"
}
},
"license": "MIT",
"version": "1.3.0"
}
],
"version": 1
} | extensions/r/cgmanifest.json | 0 | https://github.com/microsoft/vscode/commit/36ef468d4dd9a84203bdb2dba688ce395e4b4408 | [
0.0001666921889409423,
0.0001663966686464846,
0.00016610116290394217,
0.0001663966686464846,
2.9551301850005984e-7
] |
{
"id": 4,
"code_window": [
"\t */\n",
"\tresolveAny(folder: IWorkspaceFolder | undefined, config: any, commandValueMapping?: IStringDictionary<string>): any;\n",
"\n",
"\t/**\n",
"\t * Recursively resolves all variables (including commands and user input) in the given config and returns a copy of it with substituted values.\n",
"\t * If a \"variables\" dictionary (with names -> command ids) is given, command variables are first mapped through it before being resolved.\n",
"\t *\n",
"\t * @param section For example, 'tasks' or 'debug'. Used for resolving inputs.\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tresolveAsync(folder: IWorkspaceFolder | undefined, value: string): Promise<string>;\n",
"\tresolveAsync(folder: IWorkspaceFolder | undefined, value: string[]): Promise<string[]>;\n",
"\tresolveAsync(folder: IWorkspaceFolder | undefined, value: IStringDictionary<string>): Promise<IStringDictionary<string>>;\n",
"\n",
"\t/**\n",
"\t * Recursively resolves all variables in the given config and returns a copy of it with substituted values.\n",
"\t * Command variables are only substituted if a \"commandValueMapping\" dictionary is given and if it contains an entry for the command.\n",
"\t */\n",
"\tresolveAnyAsync(folder: IWorkspaceFolder | undefined, config: any, commandValueMapping?: IStringDictionary<string>): Promise<any>;\n",
"\n"
],
"file_path": "src/vs/workbench/services/configurationResolver/common/configurationResolver.ts",
"type": "add",
"edit_start_line_idx": 25
} | Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur vulputate, ipsum quis interdum fermentum, lorem sem fermentum eros, vitae auctor neque lacus in nisi. Suspendisse potenti. Maecenas et scelerisque elit, in tincidunt quam. Sed eu tincidunt quam. Nullam justo ex, imperdiet a imperdiet et, fermentum sit amet eros. Aenean quis tempus sem. Pellentesque accumsan magna mi, ut mollis velit sagittis id. Etiam quis ipsum orci. Fusce purus ante, accumsan a lobortis at, venenatis eu nisl. Praesent ornare sed ante placerat accumsan. Suspendisse tempus dignissim fermentum. Nunc a leo ac lacus sodales iaculis eu vitae mi. In feugiat ante at massa finibus cursus. Suspendisse posuere fringilla ornare. Mauris elementum ac quam id convallis. Vestibulum non elit quis urna volutpat aliquam a eu lacus.
Aliquam vestibulum imperdiet neque, suscipit aliquam elit ultrices bibendum. Suspendisse ultrices pulvinar cursus. Morbi risus nisi, cursus consequat rutrum vitae, molestie sed dui. Fusce posuere, augue quis dignissim aliquam, nisi ipsum porttitor ante, quis fringilla nisl turpis ac nisi. Nulla varius enim eget lorem vehicula gravida. Donec finibus malesuada leo nec semper. Proin ac enim eros. Vivamus non tincidunt nisi, vel tristique lorem.
Nunc consequat ex id eros dignissim, id rutrum risus laoreet. Sed euismod non erat eu ultricies. Etiam vehicula gravida lacus ut porta. Vestibulum eu eros quis nunc aliquet luctus. Cras quis semper ligula. Nullam gravida vehicula quam sed porta. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. In porta cursus vulputate. Quisque porta a nisi eget cursus. Aliquam risus leo, luctus ac magna in, efficitur cursus magna. In condimentum non mi id semper. Donec interdum ante eget commodo maximus.
Vivamus sit amet vestibulum lectus. Fusce tincidunt mi sapien, dictum sollicitudin diam vulputate in. Integer fringilla consequat mollis. Cras aliquet consequat felis eget feugiat. Nunc tempor cursus arcu, vitae ornare nunc varius et. Vestibulum et tortor vel ante viverra porttitor. Nam at tortor ullamcorper, facilisis augue quis, tristique erat. Aenean ut euismod nibh. Quisque eu tincidunt est, nec euismod eros.
Proin vehicula nibh non viverra egestas. Phasellus sem dolor, ultricies ac sagittis tristique, lacinia a purus. Vestibulum in ante eros. Pellentesque lacus nulla, tristique vitae interdum vel, malesuada ac diam. Aenean bibendum posuere turpis in accumsan. Ut est nulla, ullamcorper quis turpis at, viverra sagittis mauris. Sed in interdum purus. Praesent scelerisque nibh eget sem euismod, ut imperdiet mi venenatis. Vivamus pulvinar orci sed dapibus auctor. Nulla facilisi. Vestibulum tincidunt erat nec porttitor egestas. Mauris quis risus ante. Nulla facilisi.
Aliquam ullamcorper ornare lobortis. Phasellus quis sem et ipsum mollis malesuada sed in ex. Ut aliquam ex eget metus finibus maximus. Proin suscipit mauris eu nibh lacinia, quis feugiat dui dapibus. Nam sed libero est. Aenean vulputate orci sit amet diam faucibus, eu sagittis sapien volutpat. Nam imperdiet felis turpis, at pretium odio pulvinar in. Sed vestibulum id eros nec ultricies. Sed quis aliquam tortor, vitae ullamcorper tellus. Donec egestas laoreet eros, id suscipit est rutrum nec. Sed auctor nulla eget metus aliquam, ut condimentum enim elementum.
Aliquam suscipit non turpis sit amet bibendum. Fusce velit ligula, euismod et maximus at, luctus sed neque. Quisque pretium, nisl at ullamcorper finibus, lectus leo mattis sapien, vel euismod mauris diam ullamcorper ex. Nulla ut risus finibus, lacinia ligula at, auctor erat. Mauris consectetur sagittis ligula vel dapibus. Nullam libero libero, lobortis aliquam libero vel, venenatis ultricies leo. Duis porttitor, nibh congue fermentum posuere, erat libero pulvinar tortor, a pellentesque nunc ipsum vel sem. Nullam volutpat, eros sit amet facilisis consectetur, ipsum est vehicula massa, non vestibulum neque elit in mauris. Nunc hendrerit ipsum non enim bibendum, vitae rhoncus mi egestas. Etiam ullamcorper massa vel nisl sagittis, nec bibendum arcu malesuada. Aenean aliquet turpis justo, a consectetur arcu mollis convallis. Etiam tellus ipsum, ultricies vitae lorem et, ornare facilisis orci. Praesent fringilla justo urna, vel mollis neque pulvinar vestibulum.
Donec non iaculis erat. Aliquam et mi sed nunc pulvinar ultricies in ut ipsum. Interdum et malesuada fames ac ante ipsum primis in faucibus. Praesent feugiat lacus ac dignissim semper. Phasellus vitae quam nisi. Morbi vel diam ultricies risus lobortis ornare. Fusce maximus et ligula quis iaculis. Sed congue ex eget felis convallis, sit amet hendrerit elit tempor. Donec vehicula blandit ante eget commodo. Vestibulum eleifend diam at feugiat euismod. Etiam magna tellus, dignissim eget fermentum vel, vestibulum vitae mauris. Nam accumsan et erat id sagittis. Donec lacinia, odio ut ornare ultricies, dolor velit accumsan tortor, non finibus erat tellus quis ligula. Nunc quis metus in leo volutpat ornare vulputate eu nisl.
Donec quis viverra ex. Nullam id feugiat mauris, eu fringilla nulla. Vestibulum id maximus elit. Cras elementum elit sed felis lobortis, eget sagittis nisi hendrerit. Vivamus vitae elit neque. Donec vulputate lacus ut libero ultrices accumsan. Vivamus accumsan nulla orci, in dignissim est laoreet sagittis. Proin at commodo velit. Curabitur in velit felis. Aliquam erat volutpat. Sed consequat, nulla et cursus sodales, nisi lacus mattis risus, quis eleifend erat ex nec turpis. Sed suscipit ultrices lorem in hendrerit.
Morbi vitae lacus nec libero ornare tempus eu et diam. Suspendisse magna ipsum, fermentum vel odio quis, molestie aliquam urna. Fusce mollis turpis a eros accumsan porttitor. Pellentesque rhoncus dolor sit amet magna rutrum, et dapibus justo tempor. Sed purus nisi, maximus vitae fringilla eu, molestie nec urna. Fusce malesuada finibus pretium. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Donec sed aliquet eros. Pellentesque luctus diam ante, eget euismod nisl aliquet eu. Sed accumsan elit purus, tempor varius ligula tempus nec. Curabitur ornare leo suscipit suscipit fermentum. Morbi eget nulla est. Maecenas faucibus interdum tristique.
Etiam ut elit eros. Nulla pharetra suscipit molestie. Nulla facilisis bibendum nisl non molestie. Curabitur turpis lectus, facilisis vel diam non, vulputate ultrices mauris. Aenean placerat aliquam convallis. Suspendisse sed scelerisque tellus. Vivamus lacinia neque eget risus cursus suscipit. Proin consequat dolor vel neque tempor, eu aliquam sem scelerisque. Duis non eros a purus malesuada pharetra non et nulla. Suspendisse potenti. Mauris libero eros, finibus vel nulla id, sagittis dapibus ante. Proin iaculis sed nunc et cursus.
Quisque accumsan lorem sit amet lorem aliquet euismod. Curabitur fermentum rutrum posuere. Etiam ultricies, sem id pellentesque suscipit, urna magna lacinia eros, quis efficitur risus nisl at lacus. Nulla quis lacus tortor. Mauris placerat ex in dolor tincidunt, vel aliquet nisi pretium. Cras iaculis risus vitae pellentesque aliquet. Quisque a enim imperdiet, ullamcorper arcu vitae, rutrum risus. Nullam consectetur libero at felis fringilla, nec congue nibh dignissim. Nam et lobortis felis, eu pellentesque ligula. Aenean facilisis, ligula non imperdiet maximus, massa orci gravida sapien, at sagittis lacus nisl in lacus. Nulla quis mauris luctus, scelerisque felis consequat, tempus risus. Fusce auctor nisl non nulla luctus molestie. Maecenas sapien nisl, auctor non dolor et, iaculis scelerisque lorem. Suspendisse egestas enim aliquet, accumsan mauris nec, posuere quam. Nulla iaculis dui dui, sit amet vestibulum erat ultricies ac.
Cras eget dolor erat. Proin at nisl ut leo consectetur ultricies vel ut arcu. Nulla in felis malesuada, ullamcorper tortor et, convallis massa. Nunc urna justo, ornare in nibh vitae, hendrerit condimentum libero. Etiam vitae libero in purus venenatis fringilla. Nullam velit nulla, consequat ut turpis non, egestas hendrerit nibh. Duis tortor turpis, interdum non ante ac, cursus accumsan lectus. Cras pharetra bibendum augue quis dictum. Sed euismod vestibulum justo. Proin porta lobortis purus. Duis venenatis diam tortor, sit amet condimentum eros rhoncus a. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nunc at magna nec diam lobortis efficitur sit amet ut lacus. Nulla quis orci tortor. Pellentesque tempus velit a odio finibus porta.
Proin feugiat mauris a tellus scelerisque convallis. Maecenas libero magna, blandit nec ultrices id, congue vel mi. Aliquam lacinia, quam vel condimentum convallis, tortor turpis aliquam odio, sed blandit libero lacus et eros. In eleifend iaculis magna ac finibus. Praesent auctor facilisis tellus in congue. Sed molestie lobortis dictum. Nam quis dignissim augue, vel euismod lorem. Curabitur posuere dapibus luctus. Donec ultricies dictum lectus, quis blandit arcu commodo ac. Aenean tincidunt ligula in nunc imperdiet dignissim. Curabitur egestas sollicitudin sapien ut semper. Aenean nec dignissim lacus.
Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Donec aliquam dictum vehicula. Donec tortor est, volutpat non nisi nec, varius gravida ex. Nunc vel tristique nunc, vitae mattis nisi. Nunc nec luctus ex, vitae tincidunt lectus. In hac habitasse platea dictumst. Curabitur lobortis ex eget tincidunt tempor. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Ut a vehicula mi.
Fusce eu libero finibus, interdum nulla a, placerat neque. Cras bibendum tempor libero nec feugiat. Cras ut sodales eros. Proin viverra, massa sit amet viverra egestas, neque nisl porta ex, sit amet hendrerit libero ligula vel urna. Mauris suscipit lacus id justo rhoncus suscipit. Etiam vel libero tellus. Maecenas non diam molestie, condimentum tellus a, bibendum enim. Mauris aliquet imperdiet tellus, eget sagittis dolor. Sed blandit in neque et luctus. Cras elementum sagittis nunc, vel mollis lorem euismod et. Donec posuere at lacus eget suscipit.
Nulla nunc mi, pretium non massa vel, tempor semper magna. Nunc a leo pulvinar, tincidunt nunc at, dignissim mi. Aliquam erat volutpat. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Ut viverra nulla a nisl finibus, at hendrerit ligula ullamcorper. Donec a lorem semper, tempor magna et, lobortis libero. Mauris id sapien leo. Donec dignissim, quam vitae porttitor dignissim, quam justo mattis dui, vel consequat odio elit quis orci. Etiam nec pretium neque, sit amet pretium orci. Duis ac tortor venenatis, feugiat purus non, feugiat nunc. Proin scelerisque nisl in turpis aliquam vulputate.
Praesent sed est semper, fringilla lorem vitae, tincidunt nibh. Cras eros metus, auctor at mauris sit amet, sodales semper orci. Nunc a ornare ex. Curabitur bibendum arcu congue urna vulputate egestas. Vestibulum finibus id risus et accumsan. Aenean ut volutpat tellus. Aenean tincidunt malesuada urna sit amet vestibulum. Mauris vel tellus dictum, varius lacus quis, dictum arcu.
Aenean quis metus eu erat feugiat cursus vel at ligula. Proin dapibus sodales urna, id euismod lectus tempus id. Pellentesque ex ligula, convallis et erat vel, vulputate condimentum nisl. Pellentesque pharetra nulla quis massa eleifend hendrerit. Praesent sed massa ipsum. Maecenas vehicula dolor massa, id sodales urna faucibus et. Mauris ac quam non massa tincidunt feugiat et at lacus. Fusce libero massa, vulputate vel scelerisque non, mollis in leo. Ut sit amet ultricies odio. Suspendisse in sapien viverra, facilisis purus ut, pretium libero.
Vivamus tristique pharetra molestie. Nam a volutpat purus. Praesent consequat gravida nisi, ac blandit nisi suscipit ut. Quisque posuere, ligula a ultrices laoreet, ligula nunc vulputate libero, ut rutrum erat odio tincidunt justo. Sed vitae leo at leo fringilla bibendum. Vestibulum ut augue nec dolor auctor accumsan. Praesent laoreet id eros pulvinar commodo. Suspendisse potenti. Ut pharetra, mauris vitae blandit fringilla, odio ante tincidunt lorem, sit amet tempor metus diam ut turpis.
Praesent quis egestas arcu. Nullam at porta arcu. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Morbi vulputate ligula malesuada ligula luctus, vulputate tempus erat bibendum. Nunc ullamcorper non lectus at euismod. Etiam nibh felis, tincidunt a metus vel, pellentesque rhoncus neque. Etiam at diam in erat luctus interdum. Nunc vel ipsum pulvinar, sollicitudin lacus ac, tempus urna. Etiam vel lacinia sapien. Pellentesque sagittis velit vel mi efficitur iaculis. Integer euismod sit amet urna in sagittis. Cras eleifend ut nibh in facilisis. Donec et lacus vitae nunc placerat sodales. Nulla sed hendrerit ligula, at dapibus sapien.
Praesent at iaculis ex. Curabitur est purus, cursus a faucibus quis, dictum id velit. Donec dignissim fringilla viverra. Nunc mauris felis, laoreet sit amet sagittis at, vestibulum in libero. Maecenas quis orci turpis. Quisque ut nibh vitae magna mollis consequat id at mauris. Aliquam eu odio eget nulla bibendum sodales. Quisque vel orci eleifend nisi pretium lacinia. Suspendisse eget risus eget mi volutpat molestie eget quis lacus. Duis nisi libero, tincidunt nec nulla id, faucibus cursus felis.
Donec tempor eget risus pellentesque molestie. Phasellus porta neque vel arcu egestas, nec blandit velit fringilla. Nullam porta faucibus justo vitae laoreet. Pellentesque viverra id nunc eu varius. Nulla pulvinar lobortis iaculis. Etiam vestibulum odio nec velit tristique, a tristique nisi mattis. In sed fringilla orci, vitae efficitur odio. Quisque dui odio, ornare eget velit at, lacinia consequat libero. Quisque lectus nulla, aliquet eu leo in, porta rutrum diam. Donec nec mattis neque. Nam rutrum, odio ac eleifend bibendum, dolor arcu rutrum neque, eget porta elit tellus a lacus. Sed massa metus, sollicitudin et sapien eu, finibus tempus orci. Proin et sapien sit amet erat molestie interdum. In quis rutrum velit, faucibus ultrices tellus.
Sed sagittis sed justo eget tincidunt. Maecenas ut leo sagittis, feugiat magna et, viverra velit. Maecenas ex arcu, feugiat at consequat vitae, auctor eu massa. Integer egestas, enim vitae maximus convallis, est lectus pretium mauris, ac posuere lectus nisl quis quam. Aliquam tempus laoreet mi, vitae dapibus dolor varius dapibus. Suspendisse potenti. Donec sit amet purus nec libero dapibus tristique. Pellentesque viverra bibendum ligula. Donec sed felis et ex lobortis laoreet. Phasellus a fringilla libero, vitae malesuada nulla. Pellentesque blandit mattis lacus, et blandit tortor laoreet consequat. Suspendisse libero nunc, viverra sed fermentum in, accumsan egestas arcu. Proin in placerat elit. Sed interdum imperdiet malesuada. Suspendisse aliquet quis mauris eget sollicitudin.
Vivamus accumsan tellus non erat volutpat, quis dictum dolor feugiat. Praesent rutrum nunc ac est mollis cursus. Fusce semper volutpat dui ut egestas. Curabitur sit amet posuere massa. Cras tincidunt nulla et mi mollis imperdiet. Suspendisse scelerisque ex id sodales vulputate. In nunc augue, pharetra in placerat eu, mattis id tellus. Vivamus cursus efficitur vehicula. Nulla aliquet vehicula aliquet.
Sed cursus tellus sed porta pulvinar. Sed vitae nisi neque. Nullam aliquet, lorem et efficitur scelerisque, arcu diam aliquam felis, sed pulvinar lorem odio et turpis. Praesent convallis pulvinar turpis eu iaculis. Aliquam nec gravida mi. Curabitur eu nibh tempor, blandit justo in, ultrices felis. Fusce placerat metus non mi sagittis rutrum. Morbi sed dui fringilla, sagittis mauris eget, imperdiet nunc. Phasellus hendrerit sem elit, id hendrerit libero auctor sit amet. Integer sodales elit sit amet consequat cursus.
Nam semper est eget nunc mollis, in pellentesque lectus fringilla. In finibus vel diam id semper. Nunc mattis quis erat eu consectetur. In hac habitasse platea dictumst. Nullam et ipsum vestibulum ex pulvinar ultricies sit amet id velit. Aenean suscipit mi tortor, a lobortis magna viverra non. Nulla condimentum aliquet ante et ullamcorper. Pellentesque porttitor arcu a posuere tempus. Aenean lacus quam, imperdiet eu justo vitae, pretium efficitur ex. Duis id purus id magna rhoncus ultrices id eu risus. Nunc dignissim et libero id dictum.
Quisque a tincidunt neque. Phasellus commodo mi sit amet tempor fringilla. Ut rhoncus, neque non porttitor elementum, libero nulla egestas augue, sed fringilla sapien felis ac velit. Phasellus viverra rhoncus mollis. Nam ullamcorper leo vel erat laoreet luctus. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Vivamus semper a metus a cursus. Nulla sed orci egestas, efficitur purus ac, malesuada tellus. Aenean rutrum velit at tellus fermentum mollis. Aliquam eleifend euismod metus.
In hac habitasse platea dictumst. Vestibulum volutpat neque vitae porttitor laoreet. Nam at tellus consequat, sodales quam in, pulvinar arcu. Maecenas varius convallis diam, ac lobortis tellus pellentesque quis. Maecenas eget augue massa. Nullam volutpat nibh ac justo rhoncus, ut iaculis tellus rutrum. Fusce efficitur efficitur libero quis condimentum. Curabitur congue neque non tincidunt tristique. Fusce eget tempor ex, at pellentesque odio. Praesent luctus dictum vestibulum. Etiam non orci nunc. Vivamus vitae laoreet purus, a lobortis velit. Curabitur tincidunt purus ac lectus elementum pellentesque. Quisque sed tincidunt est.
Sed vel ultrices massa, vitae ultricies justo. Cras finibus mauris nec lacus tempus dignissim. Cras faucibus maximus velit, eget faucibus orci luctus vehicula. Nulla massa nunc, porta ac consequat eget, rhoncus non tellus. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Fusce sed maximus metus, vel imperdiet ipsum. Ut scelerisque lectus at blandit porttitor. Ut vulputate nunc pharetra, aliquet sapien ac, sollicitudin sapien. Aenean eget ante lorem. Nam accumsan venenatis tellus id dignissim.
Curabitur fringilla, magna non maximus dapibus, nulla sapien vestibulum lectus, sit amet semper dolor neque vitae nisl. Nunc ultrices vehicula augue sed iaculis. Maecenas nec diam mollis, suscipit orci et, vestibulum ante. Pellentesque eu nisl tortor. Nunc eleifend, lacus quis volutpat volutpat, nisi mi molestie sem, quis mollis ipsum libero a tellus. Ut viverra dolor mattis convallis interdum. Sed tempus nisl at nunc scelerisque aliquet. Quisque tempor tempor lorem id feugiat. Nullam blandit lectus velit, vitae porta lacus tincidunt a. Vivamus sit amet arcu ultrices, tincidunt mi quis, viverra quam. Aenean fringilla libero elementum lorem semper, quis pulvinar eros gravida. Nullam sodales blandit mauris, sed fermentum velit fermentum sit amet. Donec malesuada mauris in augue sodales vulputate. Vestibulum gravida turpis id elit rhoncus dignissim. Integer non congue lorem, eu viverra orci.
Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Donec at dolor magna. Aliquam consectetur erat augue, id iaculis velit pharetra ac. Integer rutrum venenatis dignissim. Integer non sodales elit. Curabitur ut magna ut nibh feugiat aliquam ac ut risus. Morbi nibh quam, aliquam id placerat nec, vestibulum eget velit. Suspendisse at dignissim quam. Vivamus aliquet sem sed nisl volutpat, ut cursus orci ultrices. Aliquam ultrices lacinia enim, vitae aliquet neque.
Quisque scelerisque finibus diam in mattis. Cras cursus auctor velit. Aliquam sem leo, fermentum et maximus et, molestie a libero. Aenean justo elit, rutrum a ornare id, egestas eget enim. Aenean auctor tristique erat. Curabitur condimentum libero lacus, nec consequat orci vestibulum sed. Fusce elit ligula, blandit vitae sapien vitae, dictum ultrices risus. Nam laoreet suscipit sapien, at interdum velit faucibus sit amet. Duis quis metus egestas lectus elementum posuere non nec libero. Aliquam a dolor bibendum, facilisis nunc a, maximus diam. Vestibulum suscipit tristique magna, non dignissim turpis sodales sed. Nunc ornare, velit ac facilisis fringilla, dolor mi consectetur lorem, vitae finibus erat justo suscipit urna. Maecenas sit amet eros erat. Nunc non arcu ornare, suscipit lorem eget, sodales mauris. Aliquam tincidunt, quam nec mollis lacinia, nisi orci fermentum libero, consequat eleifend lectus quam et sapien. Vestibulum a quam urna.
Cras arcu leo, euismod ac ullamcorper at, faucibus sed massa. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Vivamus porttitor velit in enim interdum, non commodo metus ornare. Morbi vel lorem quis nisl luctus tristique quis vitae nisl. Suspendisse condimentum tortor enim, nec eleifend ipsum euismod et. Sed gravida quam ut tristique lacinia. Mauris eu interdum ipsum, ac ultrices odio. Nullam auctor tellus a risus porttitor vehicula. Nulla blandit euismod dictum. In pharetra, enim iaculis pulvinar interdum, dui nunc placerat nunc, sit amet pretium lectus nulla vitae quam. Phasellus quis enim sollicitudin, varius nulla id, ornare purus. Donec quam lacus, vestibulum quis nunc ac, mollis dictum nisi. Cras ut mollis elit. Maecenas ultrices ligula at risus faucibus scelerisque. Etiam vitae porttitor purus. Curabitur blandit lectus urna, ut hendrerit tortor feugiat ut.
Phasellus fringilla, sapien pellentesque commodo pharetra, ante libero aliquam tellus, ut consectetur augue libero a sapien. Maecenas blandit luctus nisl eget aliquet. Maecenas vitae porta dolor, faucibus laoreet sapien. Suspendisse lobortis, ipsum sed vehicula aliquam, elit purus scelerisque dui, rutrum consectetur diam odio et lorem. In nec lacinia metus. Donec viverra libero est, vel bibendum erat condimentum quis. Donec feugiat purus leo. In laoreet vitae felis a porttitor. Mauris ullamcorper, lacus id condimentum suscipit, neque magna pellentesque arcu, eget cursus neque tellus id metus. Curabitur volutpat ac orci vel ultricies.
Sed ut finibus erat. Sed diam purus, varius non tincidunt quis, ultrices sit amet ipsum. Donec et egestas nulla. Suspendisse placerat nisi at dui laoreet iaculis. Aliquam aliquet leo at augue faucibus molestie. Nullam lacus augue, hendrerit sed nisi eu, faucibus porta est. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Nam ut leo aliquet sem fermentum rutrum quis ac justo. Integer placerat aliquam nisl ut sagittis. Proin erat orci, lobortis et sem eget, eleifend fringilla augue. Mauris varius laoreet arcu, sed tincidunt felis. Pellentesque venenatis lorem odio, id pulvinar velit molestie feugiat. Donec mattis lacus sed eleifend pulvinar.
Sed condimentum ex in tincidunt hendrerit. Etiam eget risus lacinia, euismod nibh eu, pellentesque quam. Proin elit eros, convallis id mauris ac, bibendum ultrices lectus. Morbi venenatis, purus id fermentum consequat, nunc libero tincidunt ligula, non dictum ligula orci nec quam. Nulla nec ultrices lorem. Aenean maximus augue vel dictum pharetra. Etiam turpis urna, pellentesque quis malesuada eu, molestie faucibus felis.
Vestibulum pharetra augue ut quam blandit congue in nec risus. Proin eu nibh eu dui eleifend porta vitae id lectus. Proin lacus nibh, lobortis sed ligula vitae, interdum lobortis erat. Suspendisse potenti. In sollicitudin quis sapien ut aliquet. Mauris ac nulla arcu. Fusce tristique justo quis lectus mollis, eu volutpat lectus finibus. Vivamus venenatis facilisis ex ut vestibulum.
Etiam varius lobortis purus, in hendrerit elit tristique at. In tempus, augue vestibulum fermentum gravida, ligula tellus vulputate arcu, eu molestie ex sapien at purus. Vestibulum nec egestas metus. Duis pulvinar quam nec consequat interdum. Aenean non dapibus lacus. Aliquam sit amet aliquet nulla. Sed venenatis volutpat purus nec convallis. Phasellus aliquet semper sodales. Cras risus sapien, condimentum auctor urna a, pulvinar ornare nisl. Sed tincidunt felis elit, ut elementum est bibendum ac. Morbi interdum justo vel dui faucibus condimentum.
Sed convallis eu sem at tincidunt. Nullam at auctor est, et ullamcorper ipsum. Pellentesque eget ante ante. Interdum et malesuada fames ac ante ipsum primis in faucibus. Integer euismod, sapien sed dapibus ornare, nibh enim maximus lacus, lacinia placerat urna quam quis felis. Morbi accumsan id nisl ut condimentum. Donec bibendum nisi est, sed volutpat lorem rhoncus in. Vestibulum ac lacinia nunc, eget volutpat magna. Integer aliquam pharetra ipsum, id placerat nunc volutpat quis. Etiam urna diam, rhoncus sit amet varius vel, euismod vel sem. Nullam vel molestie urna. Vivamus ornare erat at venenatis euismod. Suspendisse potenti. Fusce diam justo, tincidunt vel sem at, commodo faucibus nisl. Duis gravida efficitur diam, vel sagittis erat pulvinar ut.
Quisque vel pharetra felis. Duis efficitur tortor dolor, vitae porttitor erat fermentum sed. Sed eu mi purus. Etiam dignissim tortor eu tempus molestie. Aenean pretium erat enim, in hendrerit ante hendrerit at. Sed ut risus vel nunc venenatis ultricies quis in lacus. Pellentesque vitae purus euismod, placerat risus non, ullamcorper augue. Quisque varius quam ligula, nec aliquet ex faucibus vitae. Quisque rhoncus sit amet leo tincidunt mattis. Cras id mauris eget purus pretium gravida sit amet eu augue. Aliquam dapibus odio augue, id lacinia velit pulvinar eu.
Mauris fringilla, tellus nec pharetra iaculis, neque nisi ultrices massa, et tincidunt sem dui sed mi. Curabitur erat lorem, venenatis quis tempus lacinia, tempus sit amet nunc. Aliquam at neque ac metus commodo dictum quis vitae justo. Phasellus eget lacus tempus, blandit lorem vel, rutrum est. Aenean pharetra sem ut augue lobortis dignissim. Sed rhoncus at nulla id ultrices. Cras id condimentum felis. In suscipit luctus vulputate. Donec tincidunt lacus nec enim tincidunt sollicitudin ut quis enim. Nam at libero urna. Praesent sit amet massa vitae massa ullamcorper vehicula.
Nullam bibendum augue ut turpis condimentum bibendum. Proin sit amet urna hendrerit, sodales tortor a, lobortis lectus. Integer sagittis velit turpis, et tincidunt nisi commodo eget. Duis tincidunt elit finibus accumsan cursus. Aenean dignissim scelerisque felis vel lacinia. Nunc lacinia maximus luctus. In hac habitasse platea dictumst. Vestibulum eget urna et enim tempor tempor. Nam feugiat, felis vel vestibulum tempus, orci justo viverra diam, id dapibus lorem justo in ligula.
Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. In ac pellentesque sem. Vestibulum lacinia magna dui, eu lacinia augue placerat et. Maecenas pulvinar congue est. Pellentesque commodo dui non pulvinar scelerisque. Etiam interdum est posuere sem bibendum, ac commodo magna dictum. Cras ipsum turpis, rhoncus nec posuere vitae, laoreet a arcu. Integer ac massa sit amet enim placerat lacinia sed ultrices arcu. Suspendisse sem nibh, luctus sit amet volutpat in, pellentesque eu metus. Ut gravida neque eget mi accumsan tempus. Nam sit amet aliquet nibh.
Pellentesque a purus cursus nulla hendrerit congue quis et odio. Aenean hendrerit, leo ullamcorper sagittis hendrerit, erat dui molestie quam, sed condimentum lacus risus sed tellus. Morbi a dapibus lectus, ut feugiat ex. Phasellus pretium quam et sapien mollis, vel iaculis dui dignissim. Sed ullamcorper est turpis, a viverra lorem consectetur in. Aenean aliquet nibh non cursus rutrum. Suspendisse at tristique urna, id lobortis urna. In hac habitasse platea dictumst. Phasellus libero velit, rutrum sed tellus nec, dapibus tincidunt ligula. Quisque vel dui venenatis, consequat nisl ut, lacinia ipsum. Phasellus vitae magna pellentesque, lobortis est id, faucibus quam. Nam eleifend faucibus dui vel pellentesque.
Etiam ut est non lacus tincidunt interdum. Maecenas sed massa urna. Quisque ut nibh tortor. Pellentesque felis ipsum, tempor finibus ipsum et, euismod pretium metus. Donec sit amet est ipsum. Quisque rhoncus justo non finibus elementum. Nulla nec lectus ac tortor placerat fringilla. Phasellus ac ultrices nunc, eu efficitur nisl. Nulla rhoncus nunc vitae ante dictum tincidunt. Nunc ultrices, massa sit amet malesuada dignissim, lectus lacus consequat sapien, non eleifend metus sem in eros. Phasellus mauris ante, dictum sit amet suscipit ac, rhoncus eget nisi. Phasellus at orci mollis, imperdiet neque eget, faucibus nulla. In at purus massa. Pellentesque quis rutrum lectus.
Integer eu faucibus turpis, sit amet mollis massa. Vestibulum id nulla commodo, rutrum ipsum sed, semper ante. Phasellus condimentum orci nec nibh convallis, ac maximus orci ullamcorper. Maecenas vitae sollicitudin mi. Integer et finibus lectus, et condimentum ligula. Donec elementum tristique quam vitae dapibus. Morbi euismod ipsum in tristique ullamcorper.
Duis fermentum non enim eu auctor. Quisque lacinia nibh vehicula nibh posuere, eu volutpat turpis facilisis. Ut ac faucibus nulla. Sed eleifend quis ex et pellentesque. Vestibulum sollicitudin in libero id fringilla. Phasellus dignissim purus consequat, condimentum dui sit amet, condimentum ante. Pellentesque ac consectetur massa, quis sagittis est. Nulla maximus tristique risus accumsan convallis. Curabitur imperdiet ac lacus a ultrices. Nulla facilisi. Sed quis quam quis lectus placerat lobortis vel sed turpis. In mollis dui id neque iaculis, ut aliquet tellus malesuada. Proin at luctus odio, vel blandit sapien. Praesent dignissim tortor vehicula libero fringilla, nec ultrices erat suscipit. Maecenas scelerisque purus in dapibus fermentum.
Curabitur magna odio, mattis in tortor ut, porttitor congue est. Vestibulum mollis lacinia elementum. Fusce maximus erat vitae nunc rutrum lobortis. Integer ligula eros, auctor vel elit non, posuere luctus lacus. Maecenas quis auctor massa. Ut ipsum lacus, efficitur posuere euismod et, hendrerit efficitur est. Phasellus fringilla, quam id tincidunt pretium, nunc dui sollicitudin orci, eu dignissim nisi metus ut magna. Integer lobortis interdum dolor, non bibendum purus posuere et. Donec non lectus aliquet, pretium dolor eu, cursus massa. Sed ut dui sapien. In sed vestibulum massa. Pellentesque blandit, dui non sodales vehicula, orci metus mollis nunc, non pharetra ex tellus ac est. Mauris sagittis metus et fermentum pretium. Nulla facilisi. Quisque quis ante ut nulla placerat mattis ut quis nisi.
Sed quis nulla ligula. Quisque dignissim ligula urna, sed aliquam purus semper at. Suspendisse potenti. Nunc massa lectus, pharetra vehicula arcu bibendum, imperdiet sodales ipsum. Nam ac sapien diam. Mauris iaculis fringilla mattis. Pellentesque tempus eros sit amet justo volutpat mollis. Phasellus ac turpis ipsum. Morbi vel ante elit. Aenean posuere quam consequat velit varius suscipit. Donec tempor quam ut nibh cursus efficitur.
Morbi molestie dolor nec sem egestas suscipit. Etiam placerat pharetra lectus, et ullamcorper risus tristique in. Sed faucibus ullamcorper lectus eget fringilla. Maecenas malesuada hendrerit congue. Sed eget neque a erat placerat tincidunt. Aliquam vitae dignissim turpis. Fusce at placerat magna, a laoreet lectus. Maecenas a purus nec diam gravida fringilla. Nam malesuada euismod ante non vehicula. In faucibus bibendum leo, faucibus posuere nisl pretium quis. Fusce finibus bibendum finibus. Vestibulum eu justo maximus, hendrerit diam nec, dignissim sapien. Aenean dolor lacus, malesuada quis vestibulum ac, venenatis ac ipsum. Cras a est id nunc finibus facilisis. Cras lacinia neque et interdum vehicula. Suspendisse vulputate tellus elit, eget tempor dui finibus vel.
Cras sed pretium odio. Proin hendrerit elementum felis in tincidunt. Nam sed turpis vel justo molestie accumsan condimentum eu nunc. Praesent lobortis euismod rhoncus. Nulla vitae euismod nibh, quis mattis mi. Fusce ultrices placerat porttitor. Duis sem ipsum, pellentesque sit amet odio a, molestie vulputate mauris.
Duis blandit mollis ligula, sit amet mattis ligula finibus sit amet. Nunc a leo molestie, placerat diam et, vestibulum leo. Suspendisse facilisis neque purus, nec pellentesque ligula fermentum nec. Aenean malesuada mauris lorem, eu blandit arcu pulvinar quis. Duis laoreet urna lacus, non maximus arcu rutrum ultricies. Nulla augue dolor, suscipit eu mollis eu, aliquam condimentum diam. Ut semper orci luctus, pharetra turpis at, euismod mi. Nulla leo diam, finibus sit amet purus sed, maximus dictum lorem. Integer eu mi id turpis laoreet rhoncus.
Integer a mauris tincidunt, finibus orci ut, pretium mauris. Nulla molestie nunc mi, id finibus lorem elementum sed. Proin quis laoreet ante. Integer nulla augue, commodo id molestie quis, rutrum ut turpis. Suspendisse et tortor turpis. Sed ut pharetra massa. Pellentesque elementum blandit sem, ut elementum tellus egestas a. Fusce eu purus nibh.
Cras dignissim ligula scelerisque magna faucibus ullamcorper. Proin at condimentum risus, auctor malesuada quam. Nullam interdum interdum egestas. Nulla aliquam nisi vitae felis mollis dictum. Suspendisse dapibus consectetur tortor. Ut ut nisi non sem bibendum tincidunt. Vivamus suscipit leo quis gravida dignissim.
Aliquam interdum, leo id vehicula mollis, eros eros rhoncus diam, non mollis ligula mi eu mauris. Sed ultrices vel velit sollicitudin tincidunt. Nunc auctor metus at ligula gravida elementum. Praesent interdum eu elit et mollis. Duis egestas quam sit amet velit dignissim consequat. Aliquam ac turpis nec nunc convallis sagittis. Fusce blandit, erat ac fringilla consectetur, dolor eros sodales leo, vel aliquet risus nisl et diam. Aliquam luctus felis vitae est eleifend euismod facilisis et lacus. Sed leo tellus, auctor eu arcu in, volutpat sagittis nisl. Pellentesque nisl ligula, placerat vel ullamcorper at, vulputate ac odio. Morbi ac faucibus orci, et tempus nulla. Proin rhoncus rutrum dolor, in venenatis mauris. Suspendisse a fermentum augue, non semper mi. Nunc eget pretium neque. Phasellus augue erat, feugiat ac aliquam congue, rutrum non sapien. Pellentesque ac diam gravida, consectetur felis at, ornare neque.
Nullam interdum mattis sapien quis porttitor. Interdum et malesuada fames ac ante ipsum primis in faucibus. Phasellus aliquet rutrum ipsum id euismod. Maecenas consectetur massa et mi porta viverra. Nunc quam nibh, dignissim vitae maximus et, ullamcorper nec lorem. Nunc vitae justo dapibus, luctus lacus vitae, pretium elit. Maecenas et efficitur leo. Curabitur mauris lectus, placerat quis vehicula vitae, auctor ut urna. Quisque rhoncus pharetra luctus. In hac habitasse platea dictumst. Integer sit amet metus nec eros malesuada aliquam. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Morbi hendrerit mi ac leo aliquam, sit amet ultricies libero commodo. Mauris dapibus purus metus, sit amet viverra nibh imperdiet et. Nullam porta nulla tellus, quis vehicula diam imperdiet non. Vivamus enim massa, bibendum in fermentum in, ultrices at ex.
Suspendisse fermentum id nibh eget accumsan. Duis dapibus bibendum erat ut sollicitudin. Aliquam nec felis risus. Pellentesque rhoncus ligula id sem maximus mollis sed nec massa. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus ipsum ipsum, sodales sed enim id, convallis faucibus eros. Donec ultricies dictum tincidunt. Cras vitae nibh arcu. Pellentesque cursus, sapien nec consequat fermentum, ipsum ante suscipit dui, imperdiet hendrerit est nisl eu massa. Quisque vitae sem ligula. Aenean iaculis metus ut mauris interdum laoreet. Vivamus sed gravida dolor.
Morbi nulla metus, porttitor sed eros sit amet, efficitur efficitur est. In vel nisl urna. Ut aliquet tellus at congue convallis. Phasellus imperdiet lobortis sollicitudin. Integer sodales, sem eu ultricies pharetra, erat erat porttitor odio, eget dapibus libero ipsum eget velit. Phasellus gravida nulla nisl, eu pharetra mi auctor vel. Sed blandit pharetra velit, ut egestas libero placerat non. Aliquam a interdum quam. Proin at tortor nec dui sollicitudin tempus sed vestibulum elit. Nunc non sollicitudin velit.
Aenean consequat diam velit, sed rutrum tortor faucibus dictum. Quisque at semper augue. Duis ut est eget mi ornare bibendum id et ligula. Phasellus consequat tortor non leo pulvinar posuere. Proin vestibulum eleifend felis, in hendrerit tortor sollicitudin eu. Phasellus hendrerit, lacus vel laoreet interdum, dui tortor consequat justo, commodo ultricies arcu felis vitae enim. Vivamus eu sapien at leo suscipit rutrum eu at justo. Aenean et dolor a libero ullamcorper posuere. Integer laoreet placerat nisi in vulputate. Mauris laoreet eget risus sed cursus. Donec scelerisque neque a libero eleifend hendrerit. Nulla varius condimentum nunc sit amet fermentum. Aliquam lorem ex, varius nec mollis ut, ultrices in neque. Morbi sit amet porta leo. Integer iaculis fermentum lacus in vestibulum.
Ut gravida, tellus ut maximus ultrices, erat est venenatis nisl, vitae pretium massa ex ac magna. Sed non purus eget ligula aliquet volutpat non quis arcu. Nam aliquam tincidunt risus, sit amet fringilla sapien vulputate ut. Mauris luctus suscipit pellentesque. Nunc porttitor dapibus ex quis tempus. Ut ullamcorper metus a eros vulputate, vitae viverra lectus convallis. Mauris semper imperdiet augue quis tincidunt. Integer porta pretium magna, sed cursus sem scelerisque sollicitudin. Nam efficitur, nibh pretium eleifend vestibulum, purus diam posuere sem, in egestas mauris augue sit amet urna.
Vestibulum tincidunt euismod massa in congue. Duis interdum metus non laoreet fringilla. Donec at ligula congue, tincidunt nunc non, scelerisque nunc. Donec bibendum magna non est scelerisque feugiat at nec neque. Ut orci tortor, tempus eget massa non, dignissim faucibus dolor. Nam odio risus, accumsan pretium neque eget, accumsan dignissim dui. In ut neque auctor, scelerisque tellus sed, ullamcorper nisi. Suspendisse varius cursus quam at hendrerit. Vivamus elit libero, sagittis vitae sem ac, vulputate iaculis ligula.
Sed lobortis laoreet purus sit amet rutrum. Pellentesque feugiat non leo vel lacinia. Quisque feugiat nisl a orci bibendum vestibulum. In et sollicitudin urna. Morbi a arcu ac metus faucibus tempus. Nam eu imperdiet sapien, suscipit mattis tortor. Aenean blandit ipsum nisi, a eleifend ligula euismod at. Integer tincidunt pharetra felis, mollis placerat mauris hendrerit at. Curabitur convallis, est sit amet luctus volutpat, massa lacus cursus augue, sed eleifend magna quam et risus. Aliquam lobortis tincidunt metus vitae porttitor. Suspendisse potenti. Aenean ullamcorper, neque id commodo luctus, nulla nunc lobortis quam, id dapibus neque dui nec mauris. Etiam quis lorem quis elit commodo ornare. Ut pharetra purus ultricies enim ultrices efficitur. Proin vehicula tincidunt molestie. Mauris et placerat sem.
Aliquam erat volutpat. Suspendisse velit turpis, posuere ac lacus eu, lacinia laoreet velit. Sed interdum felis neque, id blandit sem malesuada sit amet. Ut sagittis justo erat, efficitur semper orci tempor sed. Donec enim massa, posuere varius lectus egestas, pellentesque posuere mi. Cras tincidunt ut libero sed mattis. Suspendisse quis magna et tellus posuere interdum vel at purus. Pellentesque fringilla tristique neque, id aliquet tellus ultricies non. Duis ut tellus vel odio lobortis vulputate.
Integer at magna ac erat convallis vestibulum. Sed lobortis porttitor mauris. Fusce varius lorem et volutpat pulvinar. Aenean ac vulputate lectus, vitae consequat velit. Suspendisse ex dui, varius ut risus ut, dictum scelerisque sem. Vivamus urna orci, volutpat ut convallis ac, venenatis vitae urna. In hac habitasse platea dictumst. Etiam eu purus arcu. Aenean vulputate leo urna, vel tristique dui sagittis euismod. Suspendisse non tellus efficitur ante rhoncus volutpat at et sapien.
Sed dapibus accumsan porttitor. Phasellus facilisis lectus finibus ligula dignissim, id pulvinar lectus feugiat. Nullam egestas commodo nisi posuere aliquet. Morbi sit amet tortor sagittis, rutrum dui nec, dapibus sapien. Sed posuere tortor tortor, interdum auctor magna varius vitae. Vestibulum id sagittis augue. Curabitur fermentum arcu sem, eu condimentum quam rutrum non. Phasellus rutrum nibh quis lectus rhoncus pretium. Curabitur dictum interdum elit. Vestibulum maximus sodales imperdiet. Mauris auctor nec purus sed venenatis. In in urna purus.
Duis placerat molestie suscipit. Morbi a elit id purus efficitur consequat. Nunc ac commodo turpis. Etiam sit amet lacus a ipsum tempus venenatis sed vel nibh. Duis elementum aliquam mi sed tristique. Morbi ligula tortor, semper ac est vel, lobortis maximus erat. Curabitur ipsum felis, laoreet vel condimentum eget, ullamcorper sit amet mauris. Nulla facilisi. Nam at purus sed mi egestas placerat vitae vel magna. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Suspendisse at dignissim diam. Phasellus consectetur eget neque vel viverra. Donec sollicitudin mattis dolor vel malesuada. Vivamus vehicula leo neque, vitae fermentum leo posuere et. Praesent dui est, finibus sit amet tristique quis, pharetra vel nibh.
Duis nulla leo, accumsan eu odio eget, sagittis semper orci. Quisque ullamcorper ligula quam, commodo porttitor mauris ullamcorper eu. Cras varius sagittis felis in aliquam. Duis sodales risus ac justo vehicula, nec mattis diam lacinia. Cras eget lectus ipsum. Ut commodo, enim vitae malesuada hendrerit, ex dolor egestas lectus, sit amet hendrerit metus diam nec est. Vestibulum tortor metus, lobortis sit amet ante eget, tempor molestie lacus. In molestie et urna et semper. Mauris mollis, sem non hendrerit condimentum, sapien nisi cursus est, non suscipit quam justo non metus. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam enim est, porta ac feugiat vitae, rutrum in lorem. Duis vehicula tortor ut posuere maximus.
Nullam vestibulum non tellus sed commodo. Quisque mattis elit sit amet sapien sollicitudin, ut condimentum nisl congue. Aenean sagittis massa vel elit faucibus fermentum. Donec tincidunt nisi nec nisl sodales pellentesque. Mauris congue congue ligula ut suscipit. Vivamus velit tortor, tempor et gravida eget, fermentum sit amet ante. Nullam fringilla, lorem at ultrices cursus, urna neque ornare dolor, eu lacinia orci enim sed nibh. Ut a ullamcorper lectus, id mattis purus. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Aenean maximus sollicitudin posuere. Nunc at augue lacus. Aenean efficitur leo sit amet lacinia efficitur.
Quisque venenatis quam mi, in pharetra odio vulputate eu. In vel nisl pulvinar, pulvinar ligula ut, sodales risus. Sed efficitur lectus at vestibulum tincidunt. Vestibulum eu ullamcorper elit. Fusce vestibulum magna enim, et tempor lacus posuere vitae. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Integer leo elit, luctus nec mattis sit amet, sollicitudin in turpis.
Proin convallis venenatis leo, vitae tristique erat iaculis nec. Nulla facilisi. Duis porttitor, sapien et bibendum vulputate, sem libero sodales lacus, non malesuada felis erat ut libero. Nam non felis semper, finibus est a, mattis mauris. Praesent nec eros quam. Nulla hendrerit, augue consectetur eleifend ultricies, purus mi condimentum nulla, eget dapibus est nunc sed libero. Nullam elementum dui erat, vitae luctus libero sollicitudin et. Nulla odio magna, placerat in augue eu, dapibus imperdiet odio. Suspendisse imperdiet metus sit amet rhoncus dapibus. Cras at enim et urna vehicula cursus eu a mauris. Integer magna ante, eleifend ac placerat vitae, porta at nisi. Cras eget malesuada orci. Curabitur nunc est, vulputate id viverra et, dignissim sed odio. Curabitur non mattis sem. Sed bibendum, turpis vitae vehicula faucibus, nunc quam ultricies lectus, vitae viverra felis turpis at libero.
Nullam ut egestas ligula. Proin hendrerit justo a lectus commodo venenatis. Nulla facilisi. Ut cursus lorem quis est bibendum condimentum. Aenean in tristique odio. Fusce tempor hendrerit ipsum. Curabitur mollis felis justo, quis dapibus erat auctor vel. Sed augue lectus, finibus ut urna quis, ullamcorper vestibulum dui. Etiam molestie aliquam tempor. Integer mattis sollicitudin erat, et tristique elit varius vel. Mauris a ex justo.
Nam eros est, imperdiet non volutpat rutrum, pellentesque accumsan ligula. Duis sit amet turpis metus. Aenean in rhoncus metus, ac fringilla ex. Suspendisse condimentum egestas purus, ut pharetra odio vulputate vel. Duis tincidunt massa a placerat ultrices. Mauris ultricies nibh sit amet condimentum malesuada. Duis tincidunt id ipsum sed congue.
Praesent eu ex augue. Nullam in porta ligula. In tincidunt accumsan arcu, in pellentesque magna tristique in. Mauris eleifend libero ac nisl viverra faucibus. Nam sollicitudin dolor in commodo hendrerit. Cras at orci metus. Ut quis laoreet orci. Vivamus ultrices leo pellentesque tempor aliquet. Maecenas ut eros vitae purus placerat vestibulum. Etiam vitae gravida dolor, quis rhoncus diam. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos.
Suspendisse fringilla lacinia sagittis. Integer tincidunt consectetur tristique. Morbi non orci convallis, congue sapien quis, vulputate nunc. Donec a libero vel magna elementum facilisis non quis mi. Mauris posuere tellus non ipsum ultrices elementum. Vivamus massa velit, facilisis quis placerat aliquet, aliquet nec leo. Praesent a maximus sem. Sed neque elit, feugiat vel quam non, molestie sagittis nunc. Etiam luctus nunc ac mauris scelerisque, nec rhoncus lacus convallis. Nunc pharetra, nunc ac pulvinar aliquam, ex ipsum euismod augue, nec porttitor lacus turpis vitae neque. Fusce bibendum odio id tortor faucibus pellentesque. Sed ac porta nibh, eu gravida erat.
Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Aliquam quis ullamcorper felis. Nulla mattis sagittis ante ac tincidunt. Integer ac felis efficitur, viverra libero et, facilisis ligula. Suspendisse a metus a massa rhoncus posuere. Phasellus suscipit ligula ut lacus facilisis, ac pellentesque ex tempor. Quisque consectetur massa mi, ac molestie libero dictum quis. Proin porttitor ligula quis erat tincidunt venenatis. Proin congue nunc sed elit gravida, nec consectetur lectus sodales. Etiam tincidunt convallis ipsum at vestibulum. Quisque maximus enim et mauris porttitor, et molestie magna tristique. Morbi vitae metus elit. Maecenas sed volutpat turpis. Aliquam vitae dolor vestibulum, elementum purus eget, dapibus nibh. Nullam egestas dui ac rutrum semper.
Etiam hendrerit est metus, et condimentum metus aliquam ac. Pellentesque id neque id ipsum rhoncus vulputate. Aliquam erat nisl, posuere sit amet ligula ac, fermentum blandit felis. Vivamus fermentum mi risus, non lacinia purus viverra id. Aenean ac sapien consequat, finibus mauris nec, porta sem. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Sed quis consectetur ex, dignissim bibendum nulla. Phasellus ac libero at quam vehicula euismod non eu leo. Phasellus a sapien augue.
Maecenas ligula dui, bibendum vitae mauris et, auctor laoreet felis. Duis non libero a mi semper mattis. Quisque consequat luctus massa, quis tristique eros auctor feugiat. Maecenas sodales euismod neque vitae facilisis. Nullam laoreet imperdiet velit at pellentesque. Etiam massa odio, facilisis a consequat vitae, placerat vel magna. Nunc sagittis eros nec urna fringilla, pulvinar vestibulum nibh scelerisque. Sed magna metus, cursus eu consequat et, pharetra a est. Suspendisse elementum neque a dui malesuada lacinia. Donec sed ipsum volutpat, cursus urna id, ullamcorper arcu. Maecenas laoreet nisl eget velit egestas sollicitudin. Etiam nisl turpis, mollis id dignissim vitae, tristique vehicula ante. Maecenas eget placerat est, at rutrum augue. Vivamus faucibus lacinia ullamcorper. Sed pulvinar urna sodales ante sodales, at gravida leo dictum.
Morbi maximus, quam a lobortis bibendum, enim felis varius elit, ac vehicula elit nisl ut lacus. Quisque ut arcu augue. Praesent id turpis quam. Sed sed arcu eros. Maecenas at cursus lorem, ac eleifend nisi. Fusce mattis felis at commodo pharetra. Praesent ac commodo ipsum. Quisque finibus et eros vitae tincidunt. In hac habitasse platea dictumst. Praesent purus ipsum, luctus lobortis ornare quis, auctor eget justo. Nam vel enim sollicitudin, faucibus tortor eu, sagittis eros. Ut nec consectetur erat. Donec ultricies malesuada ligula, a hendrerit sapien volutpat in. Maecenas sed enim vitae sapien pulvinar faucibus.
Proin semper nunc nibh, non consequat neque ullamcorper vel. Maecenas lobortis sagittis blandit. Aenean et arcu ultricies turpis malesuada malesuada. Ut quam ex, laoreet ut blandit cursus, feugiat vitae dolor. Etiam ex lacus, scelerisque vel erat vel, efficitur tincidunt magna. Morbi tristique lacinia dolor, in egestas magna ultrices vitae. Integer ultrices leo ac tempus venenatis. Praesent ac porta tortor. Vivamus ornare blandit tristique. Nulla rutrum finibus pellentesque. In non dui elementum, fermentum ipsum vel, varius magna. Pellentesque euismod tortor risus, ac pellentesque nisl faucibus eget.
Vivamus eu enim purus. Cras ultrices rutrum egestas. Sed mollis erat nibh, at posuere nisl luctus nec. Nunc vulputate, sapien id auctor molestie, nisi diam tristique ante, non convallis tellus nibh at orci. Morbi a posuere purus, in ullamcorper ligula. Etiam elementum sit amet dui imperdiet iaculis. Proin vitae tincidunt ipsum, sit amet placerat lectus. Curabitur commodo sapien quam, et accumsan lectus fringilla non. Nullam eget accumsan enim, ac pharetra mauris. Sed quis tristique velit, vitae commodo nisi. Duis turpis dui, maximus ut risus at, finibus consequat nunc. Maecenas sed est accumsan, aliquet diam in, facilisis risus. Curabitur vehicula rutrum auctor. Nam iaculis risus pulvinar maximus viverra. Nulla vel augue et ex sagittis blandit.
Ut sem nulla, porta ac ante ac, posuere laoreet eros. Donec sodales posuere justo a auctor. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Cras mollis at orci hendrerit porta. Nullam sodales tortor tortor, non lacinia diam finibus id. Duis libero orci, suscipit ac odio et, dictum consequat ipsum. Pellentesque eu ligula sagittis, volutpat eros at, lacinia lorem. Cras euismod tellus in iaculis tempor. Quisque accumsan, magna a congue venenatis, ante ipsum aliquam lectus, at egestas enim nunc at justo. Quisque sem purus, viverra ut tristique ut, maximus id enim. Etiam quis placerat sem. In sollicitudin, lacus eu rutrum mollis, nulla eros luctus elit, vel dapibus urna purus nec urna. Phasellus egestas massa quam, ac molestie erat hendrerit a. Praesent ultrices neque ut turpis molestie auctor. Etiam molestie placerat purus, et euismod erat aliquam in. Morbi id suscipit justo.
Proin est ante, consequat at varius a, mattis quis felis. Sed accumsan nibh sit amet ipsum elementum posuere. Vestibulum bibendum id diam sit amet gravida. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Morbi nec dolor vel ipsum dignissim hendrerit vel non ipsum. Praesent facilisis orci quis elit auctor lobortis. Phasellus cursus risus lectus, vel lobortis libero dapibus in. Quisque tristique tempus leo a pulvinar. Pellentesque a magna tincidunt, pellentesque massa nec, laoreet orci. Morbi congue ornare dolor quis commodo. Phasellus massa nisi, tincidunt at eros dictum, hendrerit lobortis urna. Maecenas porta, magna id mattis molestie, nibh tellus lobortis sem, eget tincidunt ipsum quam eu turpis.
Ut gravida orci risus, vel rutrum mauris vehicula id. Etiam bibendum, neque a placerat condimentum, ex orci imperdiet lectus, quis dapibus arcu lacus eget lectus. Sed consequat non mi sit amet venenatis. Fusce vestibulum erat libero, eget hendrerit risus vulputate sollicitudin. Integer sed eleifend felis. Donec commodo, sem eu mattis placerat, urna odio aliquam tellus, et laoreet justo tellus eget erat. Fusce sed suscipit tortor. Nam hendrerit nibh ac nunc auctor lacinia. Pellentesque placerat condimentum ipsum, eget semper tortor hendrerit vel. Nullam non urna eu lacus pellentesque congue ut id eros.
Nunc finibus leo in rhoncus tristique. Sed eu ipsum nec nisl egestas faucibus eget a felis. Pellentesque vitae nisi in nulla accumsan fermentum. Sed venenatis feugiat eleifend. Fusce porttitor varius placerat. Aliquam aliquet lacus sit amet mattis mollis. Sed vel nulla quis dolor suscipit vehicula ac viverra lorem. Duis viverra ipsum eget nulla ullamcorper fermentum. Mauris tincidunt arcu quis quam fringilla ornare. Donec et iaculis tortor. Nam ultricies libero vel ipsum aliquet efficitur. Morbi eget dolor aliquam, tempus sapien eget, viverra ante. Donec varius mollis ex, sed efficitur purus euismod interdum. Quisque vel sapien non neque tincidunt semper. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.
Suspendisse sit amet purus leo. Fusce lectus lorem, aliquam ac nulla eget, imperdiet ornare eros. Nullam sem augue, varius in nisi non, sollicitudin pellentesque ante. Etiam eu odio condimentum, tempor libero et, egestas arcu. Cras pellentesque eleifend aliquet. Pellentesque non blandit ligula. Ut congue viverra rhoncus. Phasellus mattis mi ac eros placerat, eu feugiat tellus ultrices. Aenean mollis laoreet libero eu imperdiet. Cras sed pulvinar mi, ac vehicula ligula. Vestibulum sit amet ex massa. In a egestas eros.
Mauris pretium ipsum risus, venenatis cursus ante imperdiet id. Praesent eu turpis nec risus feugiat maximus ullamcorper ac lectus. Integer placerat at mi vel dapibus. Vestibulum fermentum turpis sit amet turpis viverra, id aliquet diam suscipit. Nam nec ex sed ante ullamcorper pharetra quis sit amet risus. Sed ac faucibus velit, id feugiat nibh. Nullam eget ipsum ex. Vivamus tincidunt non nunc non faucibus. Quisque bibendum viverra facilisis. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur at nisi hendrerit quam suscipit egestas. Curabitur laoreet maximus ultricies. Duis ut tellus ac augue molestie dictum.
Suspendisse rhoncus iaculis erat, ut ullamcorper est tristique eget. Donec auctor nec risus at gravida. Vivamus volutpat vulputate tellus, vel ultricies eros suscipit eget. Ut pulvinar id mi eu tempus. Morbi malesuada augue in dui varius, nec blandit neque vehicula. Donec ornare nec nisl in mollis. Morbi enim nisi, rhoncus nec est id, dapibus tempus urna. Ut id elit a felis vestibulum consectetur. Duis lectus quam, pharetra sit amet diam sed, posuere vestibulum erat. Fusce vitae maximus massa. Nullam id metus tempus, iaculis risus eu, lobortis urna. Quisque in congue urna. Pellentesque placerat neque in augue dapibus, non varius ex malesuada. Curabitur ut eleifend libero. Fusce vitae ligula luctus, fermentum enim vitae, ultrices erat.
Sed viverra augue turpis, scelerisque egestas sapien mattis eu. Duis laoreet magna at ex pharetra dapibus. Praesent eget odio vel quam venenatis dictum. Nulla in sollicitudin dolor. Mauris lobortis nec eros vel rhoncus. Vestibulum porta viverra venenatis. Curabitur vel scelerisque quam, a egestas velit. Praesent volutpat tincidunt magna at laoreet.
Cras nec lorem odio. Pellentesque quis dui urna. Praesent at tellus ac lectus scelerisque placerat nec eu risus. Vestibulum sit amet mattis ligula. Vivamus sed nisi at leo elementum accumsan at sit amet arcu. Aenean mattis tellus nec leo gravida, eget hendrerit nisl faucibus. Mauris pellentesque luctus condimentum. Maecenas pretium sapien nunc, eget commodo dolor maximus id. Mauris vestibulum accumsan massa a dictum. Phasellus interdum quam ligula, ut maximus diam blandit aliquam. Nunc vitae ex eu erat condimentum consectetur. Maecenas interdum condimentum volutpat.
Donec et enim a libero rutrum laoreet. Praesent a condimentum sem, at tincidunt quam. In vel molestie risus. Sed urna dui, molestie vitae mollis laoreet, tempor quis lectus. Praesent vitae auctor est, et aliquet nunc. Curabitur vulputate blandit nulla, at gravida metus. Maecenas gravida dui eu iaculis tristique. Pellentesque posuere turpis nec auctor eleifend. Suspendisse bibendum diam eu tellus lobortis, et laoreet quam congue. In hac habitasse platea dictumst. Morbi dictum neque velit, eget rutrum eros ultrices sit amet.
Phasellus fermentum risus pharetra consectetur bibendum. Donec magna tortor, lacinia vitae nibh quis, aliquet pretium lorem. Donec turpis nisi, pretium eu enim volutpat, mattis malesuada augue. Nullam vel tellus iaculis, sollicitudin elit eget, tincidunt lacus. Fusce elementum elementum felis et iaculis. Suspendisse porta eros nec neque malesuada, in malesuada ante sollicitudin. Vivamus bibendum viverra molestie.
Integer feugiat, erat nec convallis aliquam, velit felis congue erat, molestie eleifend tellus erat in tellus. Nunc et justo purus. Donec egestas fermentum dui non feugiat. Quisque in sapien sagittis, gravida quam id, iaculis lectus. Cras sagittis rhoncus bibendum. Fusce quis metus in velit scelerisque tincidunt at non ipsum. Vivamus efficitur ante eu odio vulputate, vitae ultricies risus vehicula. Proin eget odio eu sem tincidunt feugiat vel id lorem.
Vestibulum sit amet nulla dignissim, euismod mi in, fermentum tortor. Donec ut aliquet libero, lacinia accumsan velit. Donec et nulla quam. Nullam laoreet odio nec nunc imperdiet, a congue eros venenatis. Quisque nec tellus sit amet neque interdum posuere. Duis quis mi gravida, tincidunt diam convallis, ultricies augue. Mauris consequat risus non porttitor congue. Ut in ligula consequat, viverra nunc a, eleifend enim. Duis ligula urna, imperdiet nec facilisis et, ornare eu ex. Proin lobortis lectus a lobortis porttitor. Nulla leo metus, egestas eu libero sed, pretium faucibus felis. Vestibulum non sem tortor. Nam cursus est leo. Vivamus luctus enim odio, non interdum sem dapibus a. Aenean accumsan consequat lectus in imperdiet.
Donec vehicula laoreet ipsum in posuere. Quisque vel quam imperdiet, sollicitudin nisi quis, suscipit velit. Morbi id sodales mauris. Curabitur tellus arcu, feugiat sed dui sit amet, sodales sagittis libero. Aenean vel suscipit metus, non placerat leo. Vestibulum quis nulla elit. Proin scelerisque non ante ut commodo. Interdum et malesuada fames ac ante ipsum primis in faucibus.
Sed non urna dolor. Suspendisse convallis mi porta pulvinar ultrices. Suspendisse quam ipsum, hendrerit non scelerisque molestie, interdum dictum nunc. Morbi condimentum condimentum turpis eu luctus. Pellentesque sagittis sollicitudin odio, sed ultricies felis ornare sit amet. Sed ultrices ex leo, a tincidunt nisl gravida sed. Nullam ornare accumsan porta. Praesent consectetur id est nec sollicitudin.
In hac habitasse platea dictumst. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Sed sed ultrices nibh. Duis accumsan suscipit eros, a dictum odio tempus sit amet. Aenean imperdiet erat ac lacus finibus, scelerisque cursus massa imperdiet. Mauris molestie risus ut lacinia posuere. Nulla et sodales purus. Maecenas orci erat, placerat in tristique quis, placerat in mi.
Donec sollicitudin pellentesque odio in feugiat. Morbi eu dolor ut mauris congue sollicitudin. Aliquam erat volutpat. Nulla id varius dui. Curabitur finibus urna ante, consectetur interdum nisi volutpat a. Quisque quis mi tristique, consequat tellus eget, rutrum sapien. Vivamus vitae tellus vulputate, rutrum ex eu, vulputate sem. Suspendisse viverra lorem tellus, vel interdum orci gravida quis. Ut laoreet arcu at mi ullamcorper finibus. Duis porta sagittis vestibulum. Sed commodo nisl vitae urna sollicitudin, nec lacinia est sodales. Curabitur imperdiet sodales dui sed iaculis. Sed ac tellus maximus, eleifend quam sit amet, feugiat elit. Aenean viverra, dui at mattis varius, est odio vestibulum sapien, sit amet mollis libero massa nec velit. Etiam quis sodales justo.
Ut ultricies, sem eget sodales feugiat, nunc arcu congue elit, ac tempor justo massa nec purus. Maecenas enim nunc, pharetra eget dictum sit amet, tempus pellentesque velit. Suspendisse venenatis ligula in nulla mattis, et imperdiet ex tincidunt. Etiam vulputate, tellus et ultrices suscipit, enim velit laoreet massa, vitae congue odio enim ac urna. Morbi quam lorem, iaculis ac varius sagittis, euismod quis dolor. In ut dui eu purus feugiat consectetur. Vestibulum cursus velit quis lacus pellentesque iaculis. Cras in risus sed mauris porta rutrum. Nulla facilisi. Nullam eu bibendum est, non pellentesque lectus. Sed imperdiet feugiat lorem, quis convallis ante auctor in. Maecenas justo magna, scelerisque sit amet tellus eget, varius elementum risus. Duis placerat et quam sed varius.
Duis nec nibh vitae nibh dignissim mollis quis sed felis. Curabitur vitae quam placerat, venenatis purus ut, euismod nisl. Curabitur porttitor nibh eu pulvinar ullamcorper. Suspendisse posuere nec ipsum ac dapibus. Cras convallis consectetur urna. Phasellus a nibh in dolor lacinia posuere id eget augue. In eu pharetra lorem, vitae cursus lacus. Aliquam tincidunt nibh lectus. Aenean facilisis ultricies posuere. Sed ut placerat orci. Curabitur scelerisque gravida blandit. Maecenas placerat ligula eget suscipit fringilla. Mauris a tortor justo. Aliquam hendrerit semper mollis. Phasellus et tincidunt libero. Etiam vel quam libero.
Quisque aliquet tempor ex. Ut ante sem, vehicula at enim vel, gravida porta elit. Etiam vitae lacus a neque lobortis consectetur. Mauris sed interdum odio. Mauris elementum ex blandit tempor cursus. Integer in enim in leo viverra elementum. Fusce consectetur metus et sem rutrum, mattis euismod diam semper. Nunc sed ipsum vel urna consequat vehicula. Donec cursus pretium lorem, vestibulum pretium felis commodo sit amet. Nam blandit felis enim, eget gravida ex faucibus a. In nec neque massa. Etiam laoreet posuere ipsum. Praesent volutpat nunc dolor, ac vulputate magna facilisis non. Aenean congue turpis vel lectus sollicitudin tristique. Sed nec consequat purus, non vehicula quam. Etiam ultricies, est ac dictum tincidunt, turpis turpis pretium massa, a vulputate libero justo at nibh.
Aliquam erat volutpat. Cras ultrices augue ac sollicitudin lobortis. Curabitur et aliquet purus. Duis feugiat semper facilisis. Phasellus lobortis cursus velit, a sollicitudin tortor. Nam feugiat sapien non dapibus condimentum. Morbi at mi bibendum, commodo quam at, laoreet enim. Integer eu ultrices enim. Sed vestibulum eu urna ut dictum. Curabitur at mattis leo, sed cursus massa. Aliquam porttitor, felis quis fermentum porttitor, justo velit feugiat nulla, eget condimentum sem dui ut sapien.
In fringilla elit eu orci aliquam consequat. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Ut eget fringilla tellus. Curabitur fermentum, mi et condimentum suscipit, elit neque bibendum dui, et hendrerit nunc metus id ipsum. Morbi placerat mi in hendrerit congue. Ut feugiat mauris eget scelerisque viverra. Vivamus sit amet erat dictum, sagittis lectus nec, pulvinar lorem. Sed non enim ac dui sollicitudin aliquet. Quisque ut lacus dolor. Fusce hendrerit malesuada euismod. Nulla faucibus vel mauris eu mollis. Mauris est diam, fringilla ac arcu feugiat, efficitur volutpat turpis. Aliquam venenatis cursus massa sed porttitor. Ut ac finibus enim, in tincidunt sapien.
Nunc faucibus semper turpis a lacinia. Phasellus gravida, libero vel pulvinar ornare, ex sem tincidunt lectus, sit amet convallis augue risus at tortor. Quisque sit amet ipsum id nulla posuere vestibulum. Pellentesque scelerisque mauris vel leo viverra sodales. Nulla viverra aliquam ex, ut rutrum enim fermentum venenatis. Aenean eget dapibus ex, eget faucibus metus. Vestibulum volutpat leo in diam semper, eget porta magna suscipit. Sed sit amet nulla blandit, aliquam dolor ac, gravida velit. Sed vel velit viverra, maximus est id, convallis justo.
Curabitur nulla ante, vulputate at libero vel, ullamcorper rutrum nibh. Pellentesque porttitor eu mauris id mattis. Duis vulputate augue elit, eget interdum justo pretium vel. Maecenas eu vulputate arcu, eget posuere purus. Suspendisse viverra a velit dictum eleifend. Suspendisse vitae dapibus diam. Donec vehicula justo in ante interdum, eu luctus diam placerat. Vivamus convallis ipsum eu orci suscipit, sed fermentum enim euismod. Maecenas faucibus elit vitae ex ornare tristique. Donec vestibulum nec elit sit amet porttitor. Aenean tempor lectus eget tortor hendrerit luctus. Nullam interdum vitae lectus vel feugiat. Cras in risus non magna consectetur lobortis. Sed faucibus enim quis gravida convallis.
Phasellus eget massa sit amet libero ultrices suscipit. Vivamus at risus sapien. Nam mollis nunc eget velit dictum maximus. Sed pellentesque, nunc ac fringilla lacinia, quam enim mattis ex, sed euismod tortor metus eu neque. Ut mattis nisl ut lectus rhoncus, sodales bibendum eros porta. Nulla porttitor enim nec diam sagittis, eget porta velit efficitur. Vestibulum ultricies eros neque. Phasellus rutrum suscipit enim, in interdum ante gravida vitae. Sed in sagittis diam, non commodo velit.
Morbi hendrerit odio orci, nec tincidunt odio rhoncus nec. Mauris neque velit, vehicula a lorem at, suscipit tristique dui. Sed finibus, nisl in mattis convallis, turpis neque sodales lacus, eu porta enim magna non diam. Nam commodo sodales risus consectetur malesuada. In eget elementum justo. Phasellus sit amet massa imperdiet, dapibus nunc sit amet, suscipit orci. Fusce condimentum laoreet feugiat. Ut ut viverra ante. Praesent bibendum interdum commodo. Nulla mollis nisi a est ornare volutpat. Sed at ligula eu nisi dapibus tempus. Proin cursus vestibulum justo, nec efficitur justo dignissim vel. Nunc quis maximus eros.
Cras viverra, diam a tristique mattis, libero felis vulputate tellus, a ornare felis leo a dui. Nulla ante nulla, finibus ut tellus ut, blandit pharetra nibh. Proin eleifend fermentum ex, eget auctor libero vulputate in. Nullam ultricies, mauris placerat pretium placerat, leo urna lobortis leo, vel placerat arcu libero sed mauris. Aliquam mauris ligula, ornare at urna at, eleifend gravida ligula. Vestibulum consectetur ut nulla non scelerisque. Donec ornare, sem nec elementum aliquam, urna nulla bibendum metus, eu euismod dui ligula ac est. Fusce laoreet erat eu ex lobortis, quis bibendum ligula interdum. Sed vel mi erat. Vivamus id lacus ac enim mattis tempor. Nunc ultricies pellentesque enim sed euismod. Fusce tincidunt convallis elit quis aliquam. Mauris nulla ipsum, sollicitudin quis diam ac, feugiat volutpat tellus. In nibh nibh, vulputate quis tincidunt quis, pulvinar eget magna. Pellentesque quis finibus dolor. Suspendisse viverra vitae lectus non eleifend.
Nunc ut orci et sapien maximus semper. Nulla dignissim sem urna, ac varius lectus ultricies id. Quisque aliquet pulvinar pretium. In ultricies molestie tellus vehicula porta. Nam enim lorem, aliquam eget ex et, hendrerit volutpat quam. Maecenas diam lacus, pellentesque eget tempus ac, pharetra eu elit. Donec vel eros a sem facilisis vulputate. Nullam ac nisi vulputate, laoreet nisl ac, eleifend sem. Nullam mi massa, rhoncus sed pharetra interdum, tincidunt eget nunc. Aliquam viverra mattis posuere. Mauris et dui sed nisl sollicitudin fermentum quis ut arcu. Nam placerat eget orci at tincidunt. Curabitur vel turpis metus. Phasellus nibh nulla, fermentum scelerisque sem vel, gravida tincidunt velit. Pellentesque vel quam tempor, finibus massa pellentesque, condimentum dui.
Donec at mattis neque. Etiam velit diam, consequat auctor mauris id, hendrerit faucibus metus. Maecenas ullamcorper eros a est sodales, ac consectetur odio scelerisque. Donec leo metus, imperdiet at pellentesque vel, feugiat id erat. Suspendisse at magna enim. Vestibulum placerat sodales lorem id sollicitudin. Aenean at euismod ligula, eget mollis diam. Phasellus pulvinar, orci nec pretium condimentum, est erat facilisis purus, quis feugiat augue elit aliquam nulla. Aenean vitae tortor id risus congue tincidunt. Sed dolor enim, mattis a ullamcorper id, volutpat ac leo.
Proin vehicula feugiat augue, id feugiat quam sodales quis. Donec et ultricies massa, a lacinia nulla. Duis aliquam augue ornare euismod viverra. Ut lectus risus, rutrum sit amet efficitur a, luctus nec nisl. Cras volutpat ullamcorper congue. Sed vitae odio metus. Phasellus aliquet euismod varius.
Nullam sem ex, malesuada ut magna ut, pretium mollis arcu. Nam porttitor eros cursus mi lacinia faucibus. Suspendisse aliquet eleifend iaculis. Maecenas sit amet viverra tortor. Nunc a mollis risus. Etiam tempus dolor in tortor malesuada mattis. Ut tincidunt venenatis est sit amet dignissim. Vestibulum massa enim, tristique sed scelerisque eu, fringilla ac velit. Donec efficitur quis urna sit amet malesuada. Vestibulum consequat ac ligula in dapibus. Maecenas massa massa, molestie non posuere nec, elementum ut magna. In nisi erat, mollis non venenatis eu, faucibus in justo. Morbi gravida non ex non egestas. Pellentesque finibus laoreet diam, eu commodo augue congue vitae.
Aenean sem mi, ullamcorper dapibus lobortis vitae, interdum tincidunt tortor. Vivamus eget vulputate libero. Ut bibendum posuere lectus, vel tincidunt tortor aliquet at. Phasellus malesuada orci et bibendum accumsan. Aliquam quis libero vel leo mollis porta. Sed sagittis leo ac lacus dictum, ac malesuada elit finibus. Suspendisse pharetra luctus commodo. Vivamus ultricies a odio non interdum. Vivamus scelerisque tincidunt turpis quis tempor. Pellentesque tortor ligula, varius non nunc eu, blandit sollicitudin neque. Nunc imperdiet, diam et tristique luctus, ipsum ex condimentum nunc, sit amet aliquam justo velit sed libero. Duis vel suscipit ligula. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Sed tincidunt neque vel massa ultricies, id dictum leo consequat. Curabitur lobortis ultricies tellus, eget mattis nisl aliquam sit amet.
Proin at suscipit justo. Vivamus ut vestibulum nisl. Pellentesque enim odio, pharetra non magna sed, efficitur auctor magna. Praesent tincidunt ante quis ante hendrerit viverra. Pellentesque vel ipsum id magna vulputate efficitur. Sed nec neque accumsan, pulvinar sapien quis, euismod mauris. Donec condimentum laoreet sapien quis gravida. Quisque sed mattis purus. Vestibulum placerat vel neque maximus scelerisque.
Vestibulum mattis quam quis efficitur elementum. Duis dictum dolor ac scelerisque commodo. Fusce sollicitudin nisi sit amet dictum placerat. Suspendisse euismod pharetra eleifend. In eros nisl, porttitor sed mauris at, consectetur aliquet mauris. Donec euismod viverra neque sed fermentum. Phasellus libero magna, accumsan ut ultricies vitae, dignissim eget metus. Donec tellus turpis, interdum eget maximus nec, hendrerit eget massa. Curabitur auctor ligula in iaculis auctor. In ultrices quam suscipit cursus finibus. Aenean id mi at dolor interdum iaculis vitae ut lorem. Nullam sed nibh fringilla, lacinia odio nec, placerat erat. In dui libero, viverra ac viverra ac, pellentesque sit amet turpis.
Nulla in enim ex. Sed feugiat est et consectetur venenatis. Cras varius facilisis dui vel convallis. Vestibulum et elit eget tellus feugiat pellentesque. In ut ante eu purus aliquet posuere. Nulla nec ornare sem, sed luctus lorem. Nam varius iaculis odio, eget faucibus nisl ullamcorper in. Sed eget cursus felis, nec efficitur nisi.
Vivamus commodo et sem quis pulvinar. Pellentesque libero ante, venenatis vitae ligula sit amet, ornare sollicitudin nulla. Mauris eget tellus hendrerit, pulvinar metus quis, tempor nisi. Proin magna ex, laoreet sed tortor quis, varius fermentum enim. Integer eu dolor dictum, vulputate tortor et, aliquet ligula. Vestibulum vitae justo id mauris luctus sollicitudin. Suspendisse eget auctor neque, sodales egestas lorem. Vestibulum lacinia egestas metus vitae euismod. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Vivamus ex tellus, volutpat nec pulvinar sit amet, condimentum vitae dui. Curabitur vel felis sodales, lacinia nunc iaculis, ullamcorper augue. Pellentesque consequat dolor quis eros efficitur malesuada. Nulla ut malesuada lectus.
Morbi et tristique ante. Aliquam erat volutpat. Vivamus vitae dui nec turpis pellentesque fermentum. Quisque eget velit massa. Pellentesque tristique aliquam nisl, eu sollicitudin justo venenatis sed. Duis eleifend sem eros, ut aliquam libero porttitor id. Sed non nunc consequat, rhoncus diam eu, commodo erat. Praesent fermentum in lectus id blandit. Donec quis ipsum at justo volutpat finibus. Nulla blandit justo nulla, at mollis lacus consequat eget. Aenean sollicitudin quis eros ut ullamcorper.
Pellentesque venenatis nulla ut mi aliquet feugiat. Cras semper vel magna nec pharetra. Integer mattis felis et sapien commodo imperdiet. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Duis quis luctus felis. Vestibulum justo nibh, aliquam non lectus vitae, molestie placerat justo. Donec lorem nibh, gravida sit amet hendrerit ac, maximus id ipsum. Nunc ac libero sodales risus eleifend sagittis. Phasellus est massa, lobortis elementum ex sed, scelerisque consectetur neque. Nunc faucibus neque id lorem malesuada, eget convallis ex mattis.
Sed turpis tortor, fermentum non turpis id, posuere varius nibh. Donec iaculis lorem dui. Etiam eros ante, sodales eget venenatis at, consectetur eget risus. Curabitur non aliquam ante, a pretium justo. Maecenas tempor nisl tortor, vitae dictum nisi ultrices eu. Duis eget dui ultrices, porttitor lacus sed, lobortis purus. Quisque mattis elit nec neque sagittis, sed commodo leo blandit. Mauris sodales interdum eleifend. Vestibulum condimentum consectetur augue, id luctus diam convallis et.
Nunc suscipit risus in justo accumsan, a placerat magna tincidunt. Proin a nisl ipsum. Sed libero dui, tristique in augue quis, auctor tristique risus. Sed porttitor ex augue, eu porta augue molestie a. Duis rhoncus purus libero, eu tempus turpis condimentum at. Sed mollis nisi id lectus placerat tincidunt. Maecenas non scelerisque elit, quis rutrum orci. Donec in tellus pharetra urna ornare lobortis. Phasellus id risus at nisi varius rutrum eu ut turpis.
Duis dictum justo quis nisl porta, eget tincidunt magna suscipit. Sed velit massa, ullamcorper eu sodales ac, pretium a massa. Duis et rutrum tortor. Nulla accumsan hendrerit sapien, cursus volutpat eros egestas eget. Donec sollicitudin at ante quis sollicitudin. Aenean blandit feugiat diam, id feugiat eros faucibus eget. Donec viverra dolor vel justo scelerisque dignissim. Nulla semper sem nunc, rhoncus semper tellus ultricies sed. Duis in ornare diam. Donec vehicula feugiat varius. Maecenas ut suscipit est. Vivamus sem sem, finibus at dolor sit amet, euismod dapibus ligula. Vestibulum fringilla odio dapibus, congue massa eget, congue sem. Donec feugiat magna eget tortor lacinia scelerisque non et ipsum.
Suspendisse potenti. Nunc convallis sollicitudin ex eget venenatis. Sed iaculis nibh ex, vel ornare ligula congue dignissim. Quisque sollicitudin dolor ac dui vestibulum, sit amet molestie nisi aliquet. Donec at risus felis. Aenean sollicitudin metus a feugiat porta. Aenean a tortor ut dolor cursus sagittis. Vivamus consectetur porttitor nunc in facilisis. Proin sit amet mi vel lectus consectetur ultrices.
Sed cursus lectus vitae nunc tristique, nec commodo turpis dapibus. Pellentesque luctus ex id facilisis ornare. Morbi quis placerat dolor. Donec in lectus in arcu mattis porttitor ac sit amet metus. Cras congue mauris non risus sodales, vitae feugiat ipsum bibendum. Nulla venenatis urna sed libero elementum, a cursus lorem commodo. Mauris faucibus lobortis eros nec commodo.
Nullam suscipit ligula ullamcorper lorem commodo blandit. Nulla porta nibh quis pulvinar placerat. Vivamus eu arcu justo. Vestibulum imperdiet est ut fermentum porttitor. Pellentesque consectetur libero in sapien efficitur scelerisque. Curabitur ac erat sit amet odio aliquet dignissim. Pellentesque mi sem, rhoncus et luctus at, porttitor rutrum lectus. Vestibulum sollicitudin sollicitudin suscipit. Aenean efficitur dolor non ultrices imperdiet. Donec vel sem ex.
Sed convallis mauris aliquam rutrum cursus. Ut tempor porttitor sodales. Etiam eu risus ac augue gravida egestas et eu dolor. Proin id magna ex. Suspendisse quis lectus quis lorem ultricies tempus. Donec porttitor velit vitae tincidunt faucibus. Aliquam vitae semper nisi. Morbi ultrices, leo non pretium dapibus, dui libero pellentesque ex, vel placerat enim ante vitae dui. Nunc varius, sem sit amet sagittis lobortis, lectus odio scelerisque mauris, ut vestibulum orci magna quis neque. Sed id congue justo. Interdum et malesuada fames ac ante ipsum primis in faucibus. Mauris congue nisi est, malesuada mollis elit tincidunt sed. Curabitur sed ex sit amet felis tristique elementum vitae vel nibh.
Etiam mollis pretium lobortis. Mauris augue lacus, efficitur at lacus sed, mollis tincidunt lectus. Aliquam erat volutpat. Donec at euismod elit, et mattis felis. Sed id lobortis urna. Morbi imperdiet vestibulum leo, sed maximus leo blandit eu. Aliquam semper lorem neque, nec euismod turpis mattis mollis. Quisque lobortis urna ultrices odio pretium, ac venenatis orci faucibus. Suspendisse bibendum odio ligula, sed lobortis massa pharetra nec. Donec turpis justo, iaculis at dictum ac, finibus eu libero. Maecenas quis porttitor mi, sit amet aliquet neque.
Vivamus auctor vulputate ante, at egestas lorem. Donec eu risus in nulla mollis ultricies at et urna. Duis accumsan porta egestas. Ut vel euismod augue. Fusce convallis nulla ante, nec fringilla velit aliquet at. Nam malesuada dapibus ligula, a aliquam nibh scelerisque ac. Praesent malesuada neque et pellentesque interdum. Curabitur volutpat at turpis vitae tristique. Vivamus porttitor semper congue. Quisque suscipit lacus mi, rhoncus ultrices tortor auctor quis. Maecenas neque neque, molestie ac facilisis eget, luctus ac lorem. In ut odio ut lacus suscipit pulvinar vitae sed elit. Nulla imperdiet, sem quis euismod sagittis, dui erat luctus dolor, faucibus faucibus erat sem eget nunc. Nam accumsan placerat malesuada. Maecenas convallis finibus pulvinar.
Cras at placerat tortor. Morbi facilisis auctor felis sit amet molestie. Donec sodales sed lorem vitae suscipit. Etiam fermentum pharetra ipsum, nec luctus orci gravida eu. Pellentesque gravida, est non condimentum tempus, mauris ligula molestie est, in congue dolor nisl vel sapien. Duis congue tempor augue, id rutrum eros porta dapibus. Etiam rutrum eget est eget vestibulum. Aenean mollis arcu vel consequat varius. Praesent at condimentum felis. Duis nec interdum nisl. Donec commodo lorem sed sapien scelerisque malesuada non eu urna. In blandit non ipsum at porta. Nam lobortis leo vitae dui auctor, non feugiat quam bibendum. Donec auctor lectus sagittis laoreet maximus. Maecenas rhoncus laoreet porttitor. Vestibulum porttitor augue ut lectus hendrerit, eget posuere mi gravida.
Sed mattis ex in erat pulvinar, eu imperdiet magna dapibus. Etiam nisi nibh, tempus non tellus sit amet, mattis tempor odio. Quisque nec lorem feugiat, lobortis odio et, commodo nunc. Maecenas semper purus nisi, nec vehicula nibh eleifend vitae. Nulla fermentum a lectus at maximus. Phasellus finibus metus non euismod ultrices. Etiam a pulvinar ante. Quisque convallis nec metus sit amet facilisis. Praesent laoreet massa et sollicitudin laoreet. Vestibulum in mauris aliquet, convallis mi ut, elementum purus. Nulla purus nulla, sodales at hendrerit quis, tempus sed lectus.
Nam ut laoreet neque, ut maximus nibh. Maecenas quis justo pellentesque, sollicitudin elit at, venenatis velit. Aenean nunc velit, vehicula scelerisque odio at, consectetur laoreet purus. Duis dui purus, malesuada quis ipsum sit amet, tempor interdum libero. Curabitur porta scelerisque sapien, vitae cursus diam condimentum eu. Phasellus sed orci quam. Nullam vitae dui quis purus tincidunt vestibulum. Curabitur quis nulla porta, cursus arcu non, auctor enim. Etiam sollicitudin ex id sem vehicula mollis. Morbi viverra laoreet tincidunt. Praesent ut semper dui. Nam sit amet pretium neque. Mauris vitae luctus diam, in lacinia purus. Maecenas ut placerat justo, ut porta felis. Integer eu mauris ante.
Aenean porttitor tellus diam, tempor consequat metus efficitur id. Suspendisse ut felis at erat tempor dictum at nec sapien. Sed vestibulum interdum felis, ac mattis mauris porta in. Nunc et condimentum massa. Sed cursus dictum justo et luctus. Integer convallis enim nisl, a rutrum lectus ultricies in. Donec dapibus lacus at nulla dapibus, id sollicitudin velit hendrerit. Fusce a magna at orci mollis rutrum ac a dolor. Aliquam erat volutpat. Morbi varius porta nunc, sit amet sodales ex hendrerit commodo. Donec tincidunt tortor sapien, vitae egestas sapien vehicula eget.
Suspendisse potenti. Donec pulvinar felis nec leo malesuada interdum. Integer posuere placerat maximus. Donec nibh ipsum, tincidunt vitae luctus vitae, bibendum at leo. Sed cursus nisl ut ex faucibus aliquet sed nec eros. Curabitur molestie posuere felis. Integer faucibus velit eget consequat iaculis. Mauris sed vulputate odio. Phasellus maximus, elit a pharetra egestas, lorem magna semper tellus, vestibulum semper diam felis at sapien. Suspendisse facilisis, nisl sit amet euismod vehicula, libero nulla vehicula dolor, quis fermentum nibh elit sit amet diam.
Morbi lorem enim, euismod eu varius ut, scelerisque quis odio. Nam tempus vitae eros id molestie. Nunc pretium in nulla eget accumsan. Quisque mattis est ut semper aliquet. Maecenas eget diam elementum, fermentum ipsum a, euismod sapien. Duis quam ligula, cursus et velit nec, ullamcorper tincidunt magna. Donec vulputate nisl est, et ullamcorper urna tempor sit amet.
Proin lacinia dui non turpis congue pretium. Morbi posuere metus vel purus imperdiet interdum. Morbi venenatis vel eros non ultricies. Nulla vel semper elit. Ut quis purus tincidunt, auctor justo ut, faucibus turpis. Proin quis mattis erat, at faucibus ligula. Mauris in mauris enim. Donec facilisis enim at est feugiat hendrerit. Nam vel nisi lorem. Fusce ultricies convallis diam, in feugiat tortor luctus quis. Donec tempor, leo vitae volutpat aliquam, magna elit feugiat leo, quis placerat sapien felis eget arcu. Donec ornare fermentum eleifend. Integer a est orci.
Proin rhoncus egestas leo. Nulla ultricies porta elit quis ornare. Nunc fermentum interdum vehicula. In in ligula lorem. Donec nec arcu sit amet orci lobortis iaculis. Mauris at mollis erat, sit amet mollis tortor. Mauris laoreet justo ullamcorper porttitor auctor. Aenean sit amet aliquam lectus, id fermentum eros. Praesent urna sem, vehicula ac fermentum id, dapibus ut purus. Vestibulum vitae tempus nunc. Donec at nunc ornare metus volutpat porta at eget magna. Donec varius aliquet metus, eu lobortis risus aliquam sed. Ut dapibus fermentum velit, ac tincidunt libero faucibus at.
In in purus auctor, feugiat massa quis, facilisis nisi. Donec dolor purus, gravida eget dolor ac, porttitor imperdiet urna. Donec faucibus placerat erat, a sagittis ante finibus ac. Sed venenatis dignissim elit, in iaculis felis posuere faucibus. Praesent sed viverra dolor. Mauris sed nulla consectetur nunc laoreet molestie in ut metus. Proin ac ex sit amet magna vulputate hendrerit ac condimentum urna. Proin ligula metus, gravida et sollicitudin facilisis, iaculis ut odio. Cras tincidunt urna et augue varius, ut facilisis urna consequat. Aenean vehicula finibus quam. Ut iaculis eu diam ac mollis. Nam mi lorem, tristique eget varius at, sodales at urna.
Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Proin vitae dictum erat, et auctor ipsum. Nullam nunc nunc, sollicitudin quis magna a, vestibulum fermentum mauris. Praesent at erat dolor. Proin laoreet tristique nulla vel efficitur. Nam sed ultrices nibh, id rutrum nunc. Curabitur eleifend a erat sit amet sollicitudin. Nullam metus quam, laoreet vitae dapibus id, placerat sed leo. Aliquam erat volutpat. Donec turpis nisl, cursus eu ex sit amet, lacinia pellentesque nisl. Sed id ipsum massa. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Donec interdum scelerisque lorem eu mattis.
Vivamus ac tristique massa, nec facilisis nisl. Nam ipsum neque, tincidunt vel urna in, cursus imperdiet enim. Nam pellentesque egestas tempus. Morbi facilisis imperdiet libero vitae fringilla. Nam lacinia ligula at sapien facilisis malesuada. Nullam accumsan pulvinar sem, et cursus libero porta sit amet. Curabitur vulputate erat elit, ut pulvinar erat maximus vel.
Cras aliquet metus ut purus sagittis, vel venenatis ante consectetur. Pellentesque nulla lacus, viverra viverra mattis non, placerat vitae nibh. Donec enim turpis, accumsan sit amet tincidunt eu, imperdiet non metus. Morbi ipsum eros, tincidunt vel est ac, tristique porttitor nibh. Praesent ut ullamcorper mauris. Sed laoreet sit amet diam congue venenatis. Integer porta purus nec orci sagittis posuere.
Donec vehicula mauris eget lacus mollis venenatis et sed nibh. Nam sodales ligula ipsum, scelerisque lacinia ligula sagittis in. Nam sit amet ipsum at erat malesuada congue. Aenean ut sollicitudin sapien. Etiam at tempor odio. Mauris vitae purus ut magna suscipit consequat. Vivamus quis sapien neque. Nulla vulputate sem sit amet massa pellentesque, eleifend tristique ligula egestas. Suspendisse tincidunt gravida mi, in pulvinar lectus egestas non. Aenean imperdiet ex sit amet nunc sollicitudin porta. Integer justo odio, ultricies at interdum in, rhoncus vitae sem. Sed porttitor arcu quis purus aliquet hendrerit. Praesent tempor tortor at dolor dictum pulvinar. Nulla aliquet nunc non ligula scelerisque accumsan. Donec nulla justo, congue vitae massa in, faucibus hendrerit magna. Donec non egestas purus.
Vivamus iaculis, lacus efficitur faucibus porta, dui nulla facilisis ligula, ut sodales odio nunc id sapien. Cras viverra auctor ipsum, dapibus mattis neque dictum sed. Sed convallis fermentum molestie. Nulla facilisi turpis duis. | src/vs/workbench/services/textfile/test/electron-browser/fixtures/lorem.txt | 0 | https://github.com/microsoft/vscode/commit/36ef468d4dd9a84203bdb2dba688ce395e4b4408 | [
0.00023197330301627517,
0.0001769450173014775,
0.00016451736155431718,
0.00017253996338695288,
0.000014473021110461559
] |
{
"id": 5,
"code_window": [
"\t\t}\n",
"\t}\n",
"\n",
"\tpublic resolve(root: IWorkspaceFolder | undefined, value: string): string;\n",
"\tpublic resolve(root: IWorkspaceFolder | undefined, value: string[]): string[];\n",
"\tpublic resolve(root: IWorkspaceFolder | undefined, value: IStringDictionary<string>): IStringDictionary<string>;\n",
"\tpublic resolve(root: IWorkspaceFolder | undefined, value: any): any {\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tpublic async resolveAsync(root: IWorkspaceFolder | undefined, value: string): Promise<string>;\n",
"\tpublic async resolveAsync(root: IWorkspaceFolder | undefined, value: string[]): Promise<string[]>;\n",
"\tpublic async resolveAsync(root: IWorkspaceFolder | undefined, value: IStringDictionary<string>): Promise<IStringDictionary<string>>;\n",
"\tpublic async resolveAsync(root: IWorkspaceFolder | undefined, value: any): Promise<any> {\n",
"\t\treturn this.recursiveResolve(root ? root.uri : undefined, value);\n",
"\t}\n",
"\n"
],
"file_path": "src/vs/workbench/services/configurationResolver/common/variableResolver.ts",
"type": "add",
"edit_start_line_idx": 60
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as paths from 'vs/base/common/path';
import * as process from 'vs/base/common/process';
import * as types from 'vs/base/common/types';
import * as objects from 'vs/base/common/objects';
import { IStringDictionary } from 'vs/base/common/collections';
import { IProcessEnvironment, isWindows, isMacintosh, isLinux } from 'vs/base/common/platform';
import { normalizeDriveLetter } from 'vs/base/common/labels';
import { localize } from 'vs/nls';
import { URI as uri } from 'vs/base/common/uri';
import { IConfigurationResolverService } from 'vs/workbench/services/configurationResolver/common/configurationResolver';
import { IWorkspaceFolder } from 'vs/platform/workspace/common/workspace';
import { ILabelService } from 'vs/platform/label/common/label';
export interface IVariableResolveContext {
getFolderUri(folderName: string): uri | undefined;
getWorkspaceFolderCount(): number;
getConfigurationValue(folderUri: uri | undefined, section: string): string | undefined;
getAppRoot(): string | undefined;
getExecPath(): string | undefined;
getFilePath(): string | undefined;
getWorkspaceFolderPathForFile?(): string | undefined;
getSelectedText(): string | undefined;
getLineNumber(): string | undefined;
}
export class AbstractVariableResolverService implements IConfigurationResolverService {
static readonly VARIABLE_LHS = '${';
static readonly VARIABLE_REGEXP = /\$\{(.*?)\}/g;
declare readonly _serviceBrand: undefined;
private _context: IVariableResolveContext;
private _labelService?: ILabelService;
private _envVariables?: IProcessEnvironment;
protected _contributedVariables: Map<string, () => Promise<string | undefined>> = new Map();
constructor(_context: IVariableResolveContext, _labelService?: ILabelService, _envVariables?: IProcessEnvironment) {
this._context = _context;
this._labelService = _labelService;
if (_envVariables) {
if (isWindows) {
// windows env variables are case insensitive
const ev: IProcessEnvironment = Object.create(null);
this._envVariables = ev;
Object.keys(_envVariables).forEach(key => {
ev[key.toLowerCase()] = _envVariables[key];
});
} else {
this._envVariables = _envVariables;
}
}
}
public resolve(root: IWorkspaceFolder | undefined, value: string): string;
public resolve(root: IWorkspaceFolder | undefined, value: string[]): string[];
public resolve(root: IWorkspaceFolder | undefined, value: IStringDictionary<string>): IStringDictionary<string>;
public resolve(root: IWorkspaceFolder | undefined, value: any): any {
return this.recursiveResolve(root ? root.uri : undefined, value);
}
public resolveAnyBase(workspaceFolder: IWorkspaceFolder | undefined, config: any, commandValueMapping?: IStringDictionary<string>, resolvedVariables?: Map<string, string>): any {
const result = objects.deepClone(config) as any;
// hoist platform specific attributes to top level
if (isWindows && result.windows) {
Object.keys(result.windows).forEach(key => result[key] = result.windows[key]);
} else if (isMacintosh && result.osx) {
Object.keys(result.osx).forEach(key => result[key] = result.osx[key]);
} else if (isLinux && result.linux) {
Object.keys(result.linux).forEach(key => result[key] = result.linux[key]);
}
// delete all platform specific sections
delete result.windows;
delete result.osx;
delete result.linux;
// substitute all variables recursively in string values
return this.recursiveResolve(workspaceFolder ? workspaceFolder.uri : undefined, result, commandValueMapping, resolvedVariables);
}
public resolveAny(workspaceFolder: IWorkspaceFolder | undefined, config: any, commandValueMapping?: IStringDictionary<string>): any {
return this.resolveAnyBase(workspaceFolder, config, commandValueMapping);
}
public resolveAnyMap(workspaceFolder: IWorkspaceFolder | undefined, config: any, commandValueMapping?: IStringDictionary<string>): { newConfig: any, resolvedVariables: Map<string, string> } {
const resolvedVariables = new Map<string, string>();
const newConfig = this.resolveAnyBase(workspaceFolder, config, commandValueMapping, resolvedVariables);
return { newConfig, resolvedVariables };
}
public resolveWithInteractionReplace(folder: IWorkspaceFolder | undefined, config: any, section?: string, variables?: IStringDictionary<string>): Promise<any> {
throw new Error('resolveWithInteractionReplace not implemented.');
}
public resolveWithInteraction(folder: IWorkspaceFolder | undefined, config: any, section?: string, variables?: IStringDictionary<string>): Promise<Map<string, string> | undefined> {
throw new Error('resolveWithInteraction not implemented.');
}
public contributeVariable(variable: string, resolution: () => Promise<string | undefined>): void {
if (this._contributedVariables.has(variable)) {
throw new Error('Variable ' + variable + ' is contributed twice.');
} else {
this._contributedVariables.set(variable, resolution);
}
}
private recursiveResolve(folderUri: uri | undefined, value: any, commandValueMapping?: IStringDictionary<string>, resolvedVariables?: Map<string, string>): any {
if (types.isString(value)) {
return this.resolveString(folderUri, value, commandValueMapping, resolvedVariables);
} else if (types.isArray(value)) {
return value.map(s => this.recursiveResolve(folderUri, s, commandValueMapping, resolvedVariables));
} else if (types.isObject(value)) {
let result: IStringDictionary<string | IStringDictionary<string> | string[]> = Object.create(null);
Object.keys(value).forEach(key => {
const replaced = this.resolveString(folderUri, key, commandValueMapping, resolvedVariables);
result[replaced] = this.recursiveResolve(folderUri, value[key], commandValueMapping, resolvedVariables);
});
return result;
}
return value;
}
private resolveString(folderUri: uri | undefined, value: string, commandValueMapping: IStringDictionary<string> | undefined, resolvedVariables?: Map<string, string>): string {
// loop through all variables occurrences in 'value'
const replaced = value.replace(AbstractVariableResolverService.VARIABLE_REGEXP, (match: string, variable: string) => {
// disallow attempted nesting, see #77289
if (variable.includes(AbstractVariableResolverService.VARIABLE_LHS)) {
return match;
}
let resolvedValue = this.evaluateSingleVariable(match, variable, folderUri, commandValueMapping);
if (resolvedVariables) {
resolvedVariables.set(variable, resolvedValue);
}
return resolvedValue;
});
return replaced;
}
private fsPath(displayUri: uri): string {
return this._labelService ? this._labelService.getUriLabel(displayUri, { noPrefix: true }) : displayUri.fsPath;
}
private evaluateSingleVariable(match: string, variable: string, folderUri: uri | undefined, commandValueMapping: IStringDictionary<string> | undefined): string {
// try to separate variable arguments from variable name
let argument: string | undefined;
const parts = variable.split(':');
if (parts.length > 1) {
variable = parts[0];
argument = parts[1];
}
// common error handling for all variables that require an open editor
const getFilePath = (): string => {
const filePath = this._context.getFilePath();
if (filePath) {
return filePath;
}
throw new Error(localize('canNotResolveFile', "Variable {0} can not be resolved. Please open an editor.", match));
};
// common error handling for all variables that require an open editor
const getFolderPathForFile = (): string => {
const filePath = getFilePath(); // throws error if no editor open
if (this._context.getWorkspaceFolderPathForFile) {
const folderPath = this._context.getWorkspaceFolderPathForFile();
if (folderPath) {
return folderPath;
}
}
throw new Error(localize('canNotResolveFolderForFile', "Variable {0}: can not find workspace folder of '{1}'.", match, paths.basename(filePath)));
};
// common error handling for all variables that require an open folder and accept a folder name argument
const getFolderUri = (): uri => {
if (argument) {
const folder = this._context.getFolderUri(argument);
if (folder) {
return folder;
}
throw new Error(localize('canNotFindFolder', "Variable {0} can not be resolved. No such folder '{1}'.", match, argument));
}
if (folderUri) {
return folderUri;
}
if (this._context.getWorkspaceFolderCount() > 1) {
throw new Error(localize('canNotResolveWorkspaceFolderMultiRoot', "Variable {0} can not be resolved in a multi folder workspace. Scope this variable using ':' and a workspace folder name.", match));
}
throw new Error(localize('canNotResolveWorkspaceFolder', "Variable {0} can not be resolved. Please open a folder.", match));
};
switch (variable) {
case 'env':
if (argument) {
if (this._envVariables) {
const env = this._envVariables[isWindows ? argument.toLowerCase() : argument];
if (types.isString(env)) {
return env;
}
}
// For `env` we should do the same as a normal shell does - evaluates undefined envs to an empty string #46436
return '';
}
throw new Error(localize('missingEnvVarName', "Variable {0} can not be resolved because no environment variable name is given.", match));
case 'config':
if (argument) {
const config = this._context.getConfigurationValue(folderUri, argument);
if (types.isUndefinedOrNull(config)) {
throw new Error(localize('configNotFound', "Variable {0} can not be resolved because setting '{1}' not found.", match, argument));
}
if (types.isObject(config)) {
throw new Error(localize('configNoString', "Variable {0} can not be resolved because '{1}' is a structured value.", match, argument));
}
return config;
}
throw new Error(localize('missingConfigName', "Variable {0} can not be resolved because no settings name is given.", match));
case 'command':
return this.resolveFromMap(match, argument, commandValueMapping, 'command');
case 'input':
return this.resolveFromMap(match, argument, commandValueMapping, 'input');
default: {
switch (variable) {
case 'workspaceRoot':
case 'workspaceFolder':
return normalizeDriveLetter(this.fsPath(getFolderUri()));
case 'cwd':
return ((folderUri || argument) ? normalizeDriveLetter(this.fsPath(getFolderUri())) : process.cwd());
case 'workspaceRootFolderName':
case 'workspaceFolderBasename':
return paths.basename(this.fsPath(getFolderUri()));
case 'lineNumber':
const lineNumber = this._context.getLineNumber();
if (lineNumber) {
return lineNumber;
}
throw new Error(localize('canNotResolveLineNumber', "Variable {0} can not be resolved. Make sure to have a line selected in the active editor.", match));
case 'selectedText':
const selectedText = this._context.getSelectedText();
if (selectedText) {
return selectedText;
}
throw new Error(localize('canNotResolveSelectedText', "Variable {0} can not be resolved. Make sure to have some text selected in the active editor.", match));
case 'file':
return getFilePath();
case 'fileWorkspaceFolder':
return getFolderPathForFile();
case 'relativeFile':
if (folderUri || argument) {
return paths.relative(this.fsPath(getFolderUri()), getFilePath());
}
return getFilePath();
case 'relativeFileDirname':
const dirname = paths.dirname(getFilePath());
if (folderUri || argument) {
const relative = paths.relative(this.fsPath(getFolderUri()), dirname);
return relative.length === 0 ? '.' : relative;
}
return dirname;
case 'fileDirname':
return paths.dirname(getFilePath());
case 'fileExtname':
return paths.extname(getFilePath());
case 'fileBasename':
return paths.basename(getFilePath());
case 'fileBasenameNoExtension':
const basename = paths.basename(getFilePath());
return (basename.slice(0, basename.length - paths.extname(basename).length));
case 'fileDirnameBasename':
return paths.basename(paths.dirname(getFilePath()));
case 'execPath':
const ep = this._context.getExecPath();
if (ep) {
return ep;
}
return match;
case 'execInstallFolder':
const ar = this._context.getAppRoot();
if (ar) {
return ar;
}
return match;
case 'pathSeparator':
return paths.sep;
default:
try {
const key = argument ? `${variable}:${argument}` : variable;
return this.resolveFromMap(match, key, commandValueMapping, undefined);
} catch (error) {
return match;
}
}
}
}
}
private resolveFromMap(match: string, argument: string | undefined, commandValueMapping: IStringDictionary<string> | undefined, prefix: string | undefined): string {
if (argument && commandValueMapping) {
const v = (prefix === undefined) ? commandValueMapping[argument] : commandValueMapping[prefix + ':' + argument];
if (typeof v === 'string') {
return v;
}
throw new Error(localize('noValueForCommand', "Variable {0} can not be resolved because the command has no value.", match));
}
return match;
}
}
| src/vs/workbench/services/configurationResolver/common/variableResolver.ts | 1 | https://github.com/microsoft/vscode/commit/36ef468d4dd9a84203bdb2dba688ce395e4b4408 | [
0.9970038533210754,
0.1597583293914795,
0.00016768902423791587,
0.0002824926341418177,
0.34076642990112305
] |
{
"id": 5,
"code_window": [
"\t\t}\n",
"\t}\n",
"\n",
"\tpublic resolve(root: IWorkspaceFolder | undefined, value: string): string;\n",
"\tpublic resolve(root: IWorkspaceFolder | undefined, value: string[]): string[];\n",
"\tpublic resolve(root: IWorkspaceFolder | undefined, value: IStringDictionary<string>): IStringDictionary<string>;\n",
"\tpublic resolve(root: IWorkspaceFolder | undefined, value: any): any {\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tpublic async resolveAsync(root: IWorkspaceFolder | undefined, value: string): Promise<string>;\n",
"\tpublic async resolveAsync(root: IWorkspaceFolder | undefined, value: string[]): Promise<string[]>;\n",
"\tpublic async resolveAsync(root: IWorkspaceFolder | undefined, value: IStringDictionary<string>): Promise<IStringDictionary<string>>;\n",
"\tpublic async resolveAsync(root: IWorkspaceFolder | undefined, value: any): Promise<any> {\n",
"\t\treturn this.recursiveResolve(root ? root.uri : undefined, value);\n",
"\t}\n",
"\n"
],
"file_path": "src/vs/workbench/services/configurationResolver/common/variableResolver.ts",
"type": "add",
"edit_start_line_idx": 60
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as assert from 'assert';
import { Range } from 'vs/editor/common/core/range';
import { EndOfLineSequence } from 'vs/editor/common/model';
import { testViewModel } from 'vs/editor/test/common/viewModel/testViewModel';
import { ViewEventHandler } from 'vs/editor/common/viewModel/viewEventHandler';
import { ViewEvent } from 'vs/editor/common/view/viewEvents';
suite('ViewModel', () => {
test('issue #21073: SplitLinesCollection: attempt to access a \'newer\' model', () => {
const text = [''];
const opts = {
lineNumbersMinChars: 1
};
testViewModel(text, opts, (viewModel, model) => {
assert.strictEqual(viewModel.getLineCount(), 1);
viewModel.setViewport(1, 1, 1);
model.applyEdits([{
range: new Range(1, 1, 1, 1),
text: [
'line01',
'line02',
'line03',
'line04',
'line05',
'line06',
'line07',
'line08',
'line09',
'line10',
].join('\n')
}]);
assert.strictEqual(viewModel.getLineCount(), 10);
});
});
test('issue #44805: SplitLinesCollection: attempt to access a \'newer\' model', () => {
const text = [''];
testViewModel(text, {}, (viewModel, model) => {
assert.strictEqual(viewModel.getLineCount(), 1);
model.pushEditOperations([], [{
range: new Range(1, 1, 1, 1),
text: '\ninsert1'
}], () => ([]));
model.pushEditOperations([], [{
range: new Range(1, 1, 1, 1),
text: '\ninsert2'
}], () => ([]));
model.pushEditOperations([], [{
range: new Range(1, 1, 1, 1),
text: '\ninsert3'
}], () => ([]));
let viewLineCount: number[] = [];
viewLineCount.push(viewModel.getLineCount());
viewModel.addViewEventHandler(new class extends ViewEventHandler {
handleEvents(events: ViewEvent[]): void {
// Access the view model
viewLineCount.push(viewModel.getLineCount());
}
});
model.undo();
viewLineCount.push(viewModel.getLineCount());
assert.deepStrictEqual(viewLineCount, [4, 1, 1, 1, 1]);
});
});
test('issue #44805: No visible lines via API call', () => {
const text = [
'line1',
'line2',
'line3'
];
testViewModel(text, {}, (viewModel, model) => {
assert.strictEqual(viewModel.getLineCount(), 3);
viewModel.setHiddenAreas([new Range(1, 1, 3, 1)]);
assert.ok(viewModel.getVisibleRanges() !== null);
});
});
test('issue #44805: No visible lines via undoing', () => {
const text = [
''
];
testViewModel(text, {}, (viewModel, model) => {
assert.strictEqual(viewModel.getLineCount(), 1);
model.pushEditOperations([], [{
range: new Range(1, 1, 1, 1),
text: 'line1\nline2\nline3'
}], () => ([]));
viewModel.setHiddenAreas([new Range(1, 1, 1, 1)]);
assert.strictEqual(viewModel.getLineCount(), 2);
model.undo();
assert.ok(viewModel.getVisibleRanges() !== null);
});
});
function assertGetPlainTextToCopy(text: string[], ranges: Range[], emptySelectionClipboard: boolean, expected: string | string[]): void {
testViewModel(text, {}, (viewModel, model) => {
let actual = viewModel.getPlainTextToCopy(ranges, emptySelectionClipboard, false);
assert.deepStrictEqual(actual, expected);
});
}
const USUAL_TEXT = [
'',
'line2',
'line3',
'line4',
''
];
test('getPlainTextToCopy 0/1', () => {
assertGetPlainTextToCopy(
USUAL_TEXT,
[
new Range(2, 2, 2, 2)
],
false,
''
);
});
test('getPlainTextToCopy 0/1 - emptySelectionClipboard', () => {
assertGetPlainTextToCopy(
USUAL_TEXT,
[
new Range(2, 2, 2, 2)
],
true,
'line2\n'
);
});
test('getPlainTextToCopy 1/1', () => {
assertGetPlainTextToCopy(
USUAL_TEXT,
[
new Range(2, 2, 2, 6)
],
false,
'ine2'
);
});
test('getPlainTextToCopy 1/1 - emptySelectionClipboard', () => {
assertGetPlainTextToCopy(
USUAL_TEXT,
[
new Range(2, 2, 2, 6)
],
true,
'ine2'
);
});
test('getPlainTextToCopy 0/2', () => {
assertGetPlainTextToCopy(
USUAL_TEXT,
[
new Range(2, 2, 2, 2),
new Range(3, 2, 3, 2),
],
false,
''
);
});
test('getPlainTextToCopy 0/2 - emptySelectionClipboard', () => {
assertGetPlainTextToCopy(
USUAL_TEXT,
[
new Range(2, 2, 2, 2),
new Range(3, 2, 3, 2),
],
true,
'line2\nline3\n'
);
});
test('getPlainTextToCopy 1/2', () => {
assertGetPlainTextToCopy(
USUAL_TEXT,
[
new Range(2, 2, 2, 6),
new Range(3, 2, 3, 2),
],
false,
'ine2'
);
});
test('getPlainTextToCopy 1/2 - emptySelectionClipboard', () => {
assertGetPlainTextToCopy(
USUAL_TEXT,
[
new Range(2, 2, 2, 6),
new Range(3, 2, 3, 2),
],
true,
['ine2', 'line3']
);
});
test('getPlainTextToCopy 2/2', () => {
assertGetPlainTextToCopy(
USUAL_TEXT,
[
new Range(2, 2, 2, 6),
new Range(3, 2, 3, 6),
],
false,
['ine2', 'ine3']
);
});
test('getPlainTextToCopy 2/2 reversed', () => {
assertGetPlainTextToCopy(
USUAL_TEXT,
[
new Range(3, 2, 3, 6),
new Range(2, 2, 2, 6),
],
false,
['ine2', 'ine3']
);
});
test('getPlainTextToCopy 0/3 - emptySelectionClipboard', () => {
assertGetPlainTextToCopy(
USUAL_TEXT,
[
new Range(2, 2, 2, 2),
new Range(2, 3, 2, 3),
new Range(3, 2, 3, 2),
],
true,
'line2\nline3\n'
);
});
test('issue #22688 - always use CRLF for clipboard on Windows', () => {
testViewModel(USUAL_TEXT, {}, (viewModel, model) => {
model.setEOL(EndOfLineSequence.LF);
let actual = viewModel.getPlainTextToCopy([new Range(2, 1, 5, 1)], true, true);
assert.deepStrictEqual(actual, 'line2\r\nline3\r\nline4\r\n');
});
});
test('issue #40926: Incorrect spacing when inserting new line after multiple folded blocks of code', () => {
testViewModel(
[
'foo = {',
' foobar: function() {',
' this.foobar();',
' },',
' foobar: function() {',
' this.foobar();',
' },',
' foobar: function() {',
' this.foobar();',
' },',
'}',
], {}, (viewModel, model) => {
viewModel.setHiddenAreas([
new Range(3, 1, 3, 1),
new Range(6, 1, 6, 1),
new Range(9, 1, 9, 1),
]);
model.applyEdits([
{ range: new Range(4, 7, 4, 7), text: '\n ' },
{ range: new Range(7, 7, 7, 7), text: '\n ' },
{ range: new Range(10, 7, 10, 7), text: '\n ' }
]);
assert.strictEqual(viewModel.getLineCount(), 11);
}
);
});
});
| src/vs/editor/test/common/viewModel/viewModelImpl.test.ts | 0 | https://github.com/microsoft/vscode/commit/36ef468d4dd9a84203bdb2dba688ce395e4b4408 | [
0.00023544946452602744,
0.0001714142708806321,
0.0001668578915996477,
0.0001692138030193746,
0.000011990563507424667
] |
{
"id": 5,
"code_window": [
"\t\t}\n",
"\t}\n",
"\n",
"\tpublic resolve(root: IWorkspaceFolder | undefined, value: string): string;\n",
"\tpublic resolve(root: IWorkspaceFolder | undefined, value: string[]): string[];\n",
"\tpublic resolve(root: IWorkspaceFolder | undefined, value: IStringDictionary<string>): IStringDictionary<string>;\n",
"\tpublic resolve(root: IWorkspaceFolder | undefined, value: any): any {\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tpublic async resolveAsync(root: IWorkspaceFolder | undefined, value: string): Promise<string>;\n",
"\tpublic async resolveAsync(root: IWorkspaceFolder | undefined, value: string[]): Promise<string[]>;\n",
"\tpublic async resolveAsync(root: IWorkspaceFolder | undefined, value: IStringDictionary<string>): Promise<IStringDictionary<string>>;\n",
"\tpublic async resolveAsync(root: IWorkspaceFolder | undefined, value: any): Promise<any> {\n",
"\t\treturn this.recursiveResolve(root ? root.uri : undefined, value);\n",
"\t}\n",
"\n"
],
"file_path": "src/vs/workbench/services/configurationResolver/common/variableResolver.ts",
"type": "add",
"edit_start_line_idx": 60
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
.monaco-workbench .bulk-edit-panel .highlight.remove {
text-decoration: line-through;
}
.monaco-workbench .bulk-edit-panel .message {
padding: 10px 20px
}
.monaco-workbench .bulk-edit-panel [data-state="message"] .message,
.monaco-workbench .bulk-edit-panel [data-state="data"] .tree
{
display: inherit;
}
.monaco-workbench .bulk-edit-panel [data-state="data"] .message,
.monaco-workbench .bulk-edit-panel [data-state="message"] .tree
{
display: none;
}
.monaco-workbench .bulk-edit-panel .monaco-tl-contents {
display: flex;
}
.monaco-workbench .bulk-edit-panel .monaco-tl-contents .edit-checkbox {
align-self: center;
}
.monaco-workbench .bulk-edit-panel .monaco-tl-contents .edit-checkbox.disabled {
opacity: .5;
}
.monaco-workbench .bulk-edit-panel .monaco-tl-contents .monaco-icon-label.delete .monaco-icon-label-container {
text-decoration: line-through;
}
.monaco-workbench .bulk-edit-panel .monaco-tl-contents .details {
margin-left: .5em;
opacity: .7;
font-size: 0.9em;
white-space: pre
}
.monaco-workbench .bulk-edit-panel .monaco-tl-contents.category {
display: flex;
flex: 1;
flex-flow: row nowrap;
align-items: center;
}
.monaco-workbench .bulk-edit-panel .monaco-tl-contents.category .theme-icon,
.monaco-workbench .bulk-edit-panel .monaco-tl-contents.textedit .theme-icon {
margin-right: 4px;
}
.monaco-workbench .bulk-edit-panel .monaco-tl-contents.category .uri-icon,
.monaco-workbench .bulk-edit-panel .monaco-tl-contents.textedit .uri-icon {
background-repeat: no-repeat;
background-image: var(--background-light);
background-position: left center;
background-size: contain;
margin-right: 4px;
height: 100%;
width: 16px;
min-width: 16px;
}
.monaco-workbench.vs-dark .bulk-edit-panel .monaco-tl-contents.category .uri-icon,
.monaco-workbench.hc-black .bulk-edit-panel .monaco-tl-contents.category .uri-icon,
.monaco-workbench.vs-dark .bulk-edit-panel .monaco-tl-contents.textedit .uri-icon,
.monaco-workbench.hc-black .bulk-edit-panel .monaco-tl-contents.textedit .uri-icon
{
background-image: var(--background-dark);
}
.monaco-workbench .bulk-edit-panel .monaco-tl-contents.textedit .monaco-highlighted-label {
overflow: hidden;
text-overflow: ellipsis;
}
| src/vs/workbench/contrib/bulkEdit/browser/preview/bulkEdit.css | 0 | https://github.com/microsoft/vscode/commit/36ef468d4dd9a84203bdb2dba688ce395e4b4408 | [
0.00017051144095603377,
0.000167620659340173,
0.00016434270946774632,
0.00016780018631834537,
0.0000020116110590606695
] |
{
"id": 5,
"code_window": [
"\t\t}\n",
"\t}\n",
"\n",
"\tpublic resolve(root: IWorkspaceFolder | undefined, value: string): string;\n",
"\tpublic resolve(root: IWorkspaceFolder | undefined, value: string[]): string[];\n",
"\tpublic resolve(root: IWorkspaceFolder | undefined, value: IStringDictionary<string>): IStringDictionary<string>;\n",
"\tpublic resolve(root: IWorkspaceFolder | undefined, value: any): any {\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tpublic async resolveAsync(root: IWorkspaceFolder | undefined, value: string): Promise<string>;\n",
"\tpublic async resolveAsync(root: IWorkspaceFolder | undefined, value: string[]): Promise<string[]>;\n",
"\tpublic async resolveAsync(root: IWorkspaceFolder | undefined, value: IStringDictionary<string>): Promise<IStringDictionary<string>>;\n",
"\tpublic async resolveAsync(root: IWorkspaceFolder | undefined, value: any): Promise<any> {\n",
"\t\treturn this.recursiveResolve(root ? root.uri : undefined, value);\n",
"\t}\n",
"\n"
],
"file_path": "src/vs/workbench/services/configurationResolver/common/variableResolver.ts",
"type": "add",
"edit_start_line_idx": 60
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { Event } from 'vs/base/common/event';
import { createDecorator } from 'vs/platform/instantiation/common/instantiation';
import { IDimension } from 'vs/base/browser/dom';
export const ILayoutService = createDecorator<ILayoutService>('layoutService');
export interface ILayoutService {
readonly _serviceBrand: undefined;
/**
* The dimensions of the container.
*/
readonly dimension: IDimension;
/**
* Container of the application.
*/
readonly container: HTMLElement;
/**
* An offset to use for positioning elements inside the container.
*/
readonly offset?: { top: number };
/**
* An event that is emitted when the container is layed out. The
* event carries the dimensions of the container as part of it.
*/
readonly onDidLayout: Event<IDimension>;
/**
* Focus the primary component of the container.
*/
focus(): void;
}
| src/vs/platform/layout/browser/layoutService.ts | 0 | https://github.com/microsoft/vscode/commit/36ef468d4dd9a84203bdb2dba688ce395e4b4408 | [
0.00017293609562329948,
0.00016908792895264924,
0.00016639966634102166,
0.0001670366618782282,
0.0000030245641937654
] |
{
"id": 6,
"code_window": [
"\tpublic resolveAny(workspaceFolder: IWorkspaceFolder | undefined, config: any, commandValueMapping?: IStringDictionary<string>): any {\n",
"\t\treturn this.resolveAnyBase(workspaceFolder, config, commandValueMapping);\n",
"\t}\n",
"\n",
"\tpublic resolveAnyMap(workspaceFolder: IWorkspaceFolder | undefined, config: any, commandValueMapping?: IStringDictionary<string>): { newConfig: any, resolvedVariables: Map<string, string> } {\n",
"\t\tconst resolvedVariables = new Map<string, string>();\n",
"\t\tconst newConfig = this.resolveAnyBase(workspaceFolder, config, commandValueMapping, resolvedVariables);\n",
"\t\treturn { newConfig, resolvedVariables };\n",
"\t}\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tpublic async resolveAnyAsync(workspaceFolder: IWorkspaceFolder | undefined, config: any, commandValueMapping?: IStringDictionary<string>): Promise<any> {\n",
"\t\treturn this.resolveAnyBase(workspaceFolder, config, commandValueMapping);\n",
"\t}\n",
"\n"
],
"file_path": "src/vs/workbench/services/configurationResolver/common/variableResolver.ts",
"type": "add",
"edit_start_line_idx": 93
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { IStringDictionary } from 'vs/base/common/collections';
import { createDecorator } from 'vs/platform/instantiation/common/instantiation';
import { IWorkspaceFolder } from 'vs/platform/workspace/common/workspace';
import { ConfigurationTarget } from 'vs/platform/configuration/common/configuration';
export const IConfigurationResolverService = createDecorator<IConfigurationResolverService>('configurationResolverService');
export interface IConfigurationResolverService {
readonly _serviceBrand: undefined;
resolve(folder: IWorkspaceFolder | undefined, value: string): string;
resolve(folder: IWorkspaceFolder | undefined, value: string[]): string[];
resolve(folder: IWorkspaceFolder | undefined, value: IStringDictionary<string>): IStringDictionary<string>;
/**
* Recursively resolves all variables in the given config and returns a copy of it with substituted values.
* Command variables are only substituted if a "commandValueMapping" dictionary is given and if it contains an entry for the command.
*/
resolveAny(folder: IWorkspaceFolder | undefined, config: any, commandValueMapping?: IStringDictionary<string>): any;
/**
* Recursively resolves all variables (including commands and user input) in the given config and returns a copy of it with substituted values.
* If a "variables" dictionary (with names -> command ids) is given, command variables are first mapped through it before being resolved.
*
* @param section For example, 'tasks' or 'debug'. Used for resolving inputs.
* @param variables Aliases for commands.
*/
resolveWithInteractionReplace(folder: IWorkspaceFolder | undefined, config: any, section?: string, variables?: IStringDictionary<string>, target?: ConfigurationTarget): Promise<any>;
/**
* Similar to resolveWithInteractionReplace, except without the replace. Returns a map of variables and their resolution.
* Keys in the map will be of the format input:variableName or command:variableName.
*/
resolveWithInteraction(folder: IWorkspaceFolder | undefined, config: any, section?: string, variables?: IStringDictionary<string>, target?: ConfigurationTarget): Promise<Map<string, string> | undefined>;
/**
* Contributes a variable that can be resolved later. Consumers that use resolveAny, resolveWithInteraction,
* and resolveWithInteractionReplace will have contributed variables resolved.
*/
contributeVariable(variable: string, resolution: () => Promise<string | undefined>): void;
}
export interface PromptStringInputInfo {
id: string;
type: 'promptString';
description: string;
default?: string;
password?: boolean;
}
export interface PickStringInputInfo {
id: string;
type: 'pickString';
description: string;
options: (string | { value: string, label?: string })[];
default?: string;
}
export interface CommandInputInfo {
id: string;
type: 'command';
command: string;
args?: any;
}
export type ConfiguredInput = PromptStringInputInfo | PickStringInputInfo | CommandInputInfo;
| src/vs/workbench/services/configurationResolver/common/configurationResolver.ts | 1 | https://github.com/microsoft/vscode/commit/36ef468d4dd9a84203bdb2dba688ce395e4b4408 | [
0.0034909008536487818,
0.0008977742400020361,
0.0001645125012146309,
0.0002693872374948114,
0.0011657025897875428
] |
{
"id": 6,
"code_window": [
"\tpublic resolveAny(workspaceFolder: IWorkspaceFolder | undefined, config: any, commandValueMapping?: IStringDictionary<string>): any {\n",
"\t\treturn this.resolveAnyBase(workspaceFolder, config, commandValueMapping);\n",
"\t}\n",
"\n",
"\tpublic resolveAnyMap(workspaceFolder: IWorkspaceFolder | undefined, config: any, commandValueMapping?: IStringDictionary<string>): { newConfig: any, resolvedVariables: Map<string, string> } {\n",
"\t\tconst resolvedVariables = new Map<string, string>();\n",
"\t\tconst newConfig = this.resolveAnyBase(workspaceFolder, config, commandValueMapping, resolvedVariables);\n",
"\t\treturn { newConfig, resolvedVariables };\n",
"\t}\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tpublic async resolveAnyAsync(workspaceFolder: IWorkspaceFolder | undefined, config: any, commandValueMapping?: IStringDictionary<string>): Promise<any> {\n",
"\t\treturn this.resolveAnyBase(workspaceFolder, config, commandValueMapping);\n",
"\t}\n",
"\n"
],
"file_path": "src/vs/workbench/services/configurationResolver/common/variableResolver.ts",
"type": "add",
"edit_start_line_idx": 93
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as vscode from 'vscode';
import * as fileSchemes from '../utils/fileSchemes';
/**
* Maps of file resources
*
* Attempts to handle correct mapping on both case sensitive and case in-sensitive
* file systems.
*/
export class ResourceMap<T> {
private static readonly defaultPathNormalizer = (resource: vscode.Uri): string => {
if (resource.scheme === fileSchemes.file) {
return resource.fsPath;
}
return resource.toString(true);
};
private readonly _map = new Map<string, { readonly resource: vscode.Uri, value: T }>();
constructor(
protected readonly _normalizePath: (resource: vscode.Uri) => string | undefined = ResourceMap.defaultPathNormalizer,
protected readonly config: {
readonly onCaseInsenitiveFileSystem: boolean,
},
) { }
public get size() {
return this._map.size;
}
public has(resource: vscode.Uri): boolean {
const file = this.toKey(resource);
return !!file && this._map.has(file);
}
public get(resource: vscode.Uri): T | undefined {
const file = this.toKey(resource);
if (!file) {
return undefined;
}
const entry = this._map.get(file);
return entry ? entry.value : undefined;
}
public set(resource: vscode.Uri, value: T) {
const file = this.toKey(resource);
if (!file) {
return;
}
const entry = this._map.get(file);
if (entry) {
entry.value = value;
} else {
this._map.set(file, { resource, value });
}
}
public delete(resource: vscode.Uri): void {
const file = this.toKey(resource);
if (file) {
this._map.delete(file);
}
}
public clear(): void {
this._map.clear();
}
public get values(): Iterable<T> {
return Array.from(this._map.values()).map(x => x.value);
}
public get entries(): Iterable<{ resource: vscode.Uri, value: T }> {
return this._map.values();
}
private toKey(resource: vscode.Uri): string | undefined {
const key = this._normalizePath(resource);
if (!key) {
return key;
}
return this.isCaseInsensitivePath(key) ? key.toLowerCase() : key;
}
private isCaseInsensitivePath(path: string) {
if (isWindowsPath(path)) {
return true;
}
return path[0] === '/' && this.config.onCaseInsenitiveFileSystem;
}
}
function isWindowsPath(path: string): boolean {
return /^[a-zA-Z]:[\/\\]/.test(path);
}
| extensions/typescript-language-features/src/utils/resourceMap.ts | 0 | https://github.com/microsoft/vscode/commit/36ef468d4dd9a84203bdb2dba688ce395e4b4408 | [
0.00018486526096239686,
0.00017162338190246373,
0.00016230404435191303,
0.00017067590670194477,
0.0000053595927056449
] |
{
"id": 6,
"code_window": [
"\tpublic resolveAny(workspaceFolder: IWorkspaceFolder | undefined, config: any, commandValueMapping?: IStringDictionary<string>): any {\n",
"\t\treturn this.resolveAnyBase(workspaceFolder, config, commandValueMapping);\n",
"\t}\n",
"\n",
"\tpublic resolveAnyMap(workspaceFolder: IWorkspaceFolder | undefined, config: any, commandValueMapping?: IStringDictionary<string>): { newConfig: any, resolvedVariables: Map<string, string> } {\n",
"\t\tconst resolvedVariables = new Map<string, string>();\n",
"\t\tconst newConfig = this.resolveAnyBase(workspaceFolder, config, commandValueMapping, resolvedVariables);\n",
"\t\treturn { newConfig, resolvedVariables };\n",
"\t}\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tpublic async resolveAnyAsync(workspaceFolder: IWorkspaceFolder | undefined, config: any, commandValueMapping?: IStringDictionary<string>): Promise<any> {\n",
"\t\treturn this.resolveAnyBase(workspaceFolder, config, commandValueMapping);\n",
"\t}\n",
"\n"
],
"file_path": "src/vs/workbench/services/configurationResolver/common/variableResolver.ts",
"type": "add",
"edit_start_line_idx": 93
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { zoomLevelToZoomFactor } from 'vs/platform/windows/common/windows';
import { mark } from 'vs/base/common/performance';
import { Workbench } from 'vs/workbench/browser/workbench';
import { NativeWindow } from 'vs/workbench/electron-sandbox/window';
import { setZoomLevel, setZoomFactor, setFullscreen } from 'vs/base/browser/browser';
import { domContentLoaded } from 'vs/base/browser/dom';
import { onUnexpectedError } from 'vs/base/common/errors';
import { URI } from 'vs/base/common/uri';
import { WorkspaceService } from 'vs/workbench/services/configuration/browser/configurationService';
import { INativeWorkbenchConfiguration, INativeWorkbenchEnvironmentService } from 'vs/workbench/services/environment/electron-sandbox/environmentService';
import { ServiceCollection } from 'vs/platform/instantiation/common/serviceCollection';
import { isSingleFolderWorkspaceIdentifier, isWorkspaceIdentifier, IWorkspaceInitializationPayload, reviveIdentifier } from 'vs/platform/workspaces/common/workspaces';
import { ILoggerService, ILogService } from 'vs/platform/log/common/log';
import { NativeStorageService } from 'vs/platform/storage/electron-sandbox/storageService';
import { Schemas } from 'vs/base/common/network';
import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace';
import { IWorkbenchConfigurationService } from 'vs/workbench/services/configuration/common/configuration';
import { IStorageService } from 'vs/platform/storage/common/storage';
import { Disposable } from 'vs/base/common/lifecycle';
import { IMainProcessService } from 'vs/platform/ipc/electron-sandbox/services';
import { RemoteAuthorityResolverService } from 'vs/platform/remote/electron-sandbox/remoteAuthorityResolverService';
import { IRemoteAuthorityResolverService } from 'vs/platform/remote/common/remoteAuthorityResolver';
import { RemoteAgentService } from 'vs/workbench/services/remote/electron-sandbox/remoteAgentServiceImpl';
import { IRemoteAgentService } from 'vs/workbench/services/remote/common/remoteAgentService';
import { FileService } from 'vs/platform/files/common/fileService';
import { IFileService } from 'vs/platform/files/common/files';
import { RemoteFileSystemProvider } from 'vs/workbench/services/remote/common/remoteAgentFileSystemChannel';
import { ConfigurationCache } from 'vs/workbench/services/configuration/electron-sandbox/configurationCache';
import { ISignService } from 'vs/platform/sign/common/sign';
import { basename } from 'vs/base/common/path';
import { IProductService } from 'vs/platform/product/common/productService';
import { INativeHostService } from 'vs/platform/native/electron-sandbox/native';
import { NativeHostService } from 'vs/platform/native/electron-sandbox/nativeHostService';
import { IUriIdentityService } from 'vs/workbench/services/uriIdentity/common/uriIdentity';
import { UriIdentityService } from 'vs/workbench/services/uriIdentity/common/uriIdentityService';
import { KeyboardLayoutService } from 'vs/workbench/services/keybinding/electron-sandbox/nativeKeyboardLayout';
import { IKeyboardLayoutService } from 'vs/platform/keyboardLayout/common/keyboardLayout';
import { ElectronIPCMainProcessService } from 'vs/platform/ipc/electron-sandbox/mainProcessService';
import { LoggerChannelClient } from 'vs/platform/log/common/logIpc';
import { ProxyChannel } from 'vs/base/parts/ipc/common/ipc';
import product from 'vs/platform/product/common/product';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { NativeLogService } from 'vs/workbench/services/log/electron-sandbox/logService';
export const productService = { _serviceBrand: undefined, ...product };
export abstract class SharedDesktopMain extends Disposable {
protected readonly productService: IProductService = productService;
constructor(
protected readonly configuration: INativeWorkbenchConfiguration,
protected readonly environmentService: INativeWorkbenchEnvironmentService
) {
super();
this.init();
}
private init(): void {
// Massage configuration file URIs
this.reviveUris();
// Browser config
const zoomLevel = this.configuration.zoomLevel || 0;
setZoomFactor(zoomLevelToZoomFactor(zoomLevel));
setZoomLevel(zoomLevel, true /* isTrusted */);
setFullscreen(!!this.configuration.fullscreen);
}
private reviveUris() {
// Workspace
const workspace = reviveIdentifier(this.configuration.workspace);
if (isWorkspaceIdentifier(workspace) || isSingleFolderWorkspaceIdentifier(workspace)) {
this.configuration.workspace = workspace;
}
// Files
const filesToWait = this.configuration.filesToWait;
const filesToWaitPaths = filesToWait?.paths;
[filesToWaitPaths, this.configuration.filesToOpenOrCreate, this.configuration.filesToDiff].forEach(paths => {
if (Array.isArray(paths)) {
paths.forEach(path => {
if (path.fileUri) {
path.fileUri = URI.revive(path.fileUri);
}
});
}
});
if (filesToWait) {
filesToWait.waitMarkerFileUri = URI.revive(filesToWait.waitMarkerFileUri);
}
}
async open(): Promise<void> {
const services = await this.initServices();
await domContentLoaded();
mark('code/willStartWorkbench');
// Create Workbench
const workbench = new Workbench(document.body, services.serviceCollection, services.logService);
// Listeners
this.registerListeners(workbench, services.storageService);
// Startup
const instantiationService = workbench.startup();
// Window
this._register(instantiationService.createInstance(NativeWindow));
// Logging
services.logService.trace('workbench configuration', JSON.stringify(this.configuration));
// Allow subclass to participate
this.joinOpen(instantiationService);
}
private registerListeners(workbench: Workbench, storageService: NativeStorageService): void {
// Workbench Lifecycle
this._register(workbench.onWillShutdown(event => event.join(storageService.close(), 'join.closeStorage')));
this._register(workbench.onShutdown(() => this.dispose()));
}
protected abstract registerFileSystemProviders(fileService: IFileService, logService: ILogService, nativeHostService: INativeHostService): void;
protected joinOpen(instantiationService: IInstantiationService): void { }
private async initServices(): Promise<{ serviceCollection: ServiceCollection, logService: ILogService, storageService: NativeStorageService }> {
const serviceCollection = new ServiceCollection();
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
//
// NOTE: Please do NOT register services here. Use `registerSingleton()`
// from `workbench.common.main.ts` if the service is shared between
// desktop and web or `workbench.sandbox.main.ts` if the service
// is desktop only.
//
// DO NOT add services to `workbench.desktop.main.ts`, always add
// to `workbench.sandbox.main.ts` to support our Electron sandbox
//
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// Main Process
const mainProcessService = this._register(new ElectronIPCMainProcessService(this.configuration.windowId));
serviceCollection.set(IMainProcessService, mainProcessService);
// Environment
serviceCollection.set(INativeWorkbenchEnvironmentService, this.environmentService);
// Product
serviceCollection.set(IProductService, this.productService);
// Logger
const loggerService = new LoggerChannelClient(mainProcessService.getChannel('logger'));
serviceCollection.set(ILoggerService, loggerService);
// Log
const logService = this._register(new NativeLogService(`renderer${this.configuration.windowId}`, loggerService, mainProcessService, this.environmentService));
serviceCollection.set(ILogService, logService);
// Remote
const remoteAuthorityResolverService = new RemoteAuthorityResolverService();
serviceCollection.set(IRemoteAuthorityResolverService, remoteAuthorityResolverService);
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
//
// NOTE: Please do NOT register services here. Use `registerSingleton()`
// from `workbench.common.main.ts` if the service is shared between
// desktop and web or `workbench.sandbox.main.ts` if the service
// is desktop only.
//
// DO NOT add services to `workbench.desktop.main.ts`, always add
// to `workbench.sandbox.main.ts` to support our Electron sandbox
//
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// Sign
const signService = ProxyChannel.toService<ISignService>(mainProcessService.getChannel('sign'));
serviceCollection.set(ISignService, signService);
// Remote Agent
const remoteAgentService = this._register(new RemoteAgentService(this.environmentService, this.productService, remoteAuthorityResolverService, signService, logService));
serviceCollection.set(IRemoteAgentService, remoteAgentService);
// Native Host
const nativeHostService = new NativeHostService(this.configuration.windowId, mainProcessService) as INativeHostService;
serviceCollection.set(INativeHostService, nativeHostService);
// Files
const fileService = this._register(new FileService(logService));
serviceCollection.set(IFileService, fileService);
this.registerFileSystemProviders(fileService, logService, nativeHostService);
// Uri Identity
const uriIdentityService = new UriIdentityService(fileService);
serviceCollection.set(IUriIdentityService, uriIdentityService);
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
//
// NOTE: Please do NOT register services here. Use `registerSingleton()`
// from `workbench.common.main.ts` if the service is shared between
// desktop and web or `workbench.sandbox.main.ts` if the service
// is desktop only.
//
// DO NOT add services to `workbench.desktop.main.ts`, always add
// to `workbench.sandbox.main.ts` to support our Electron sandbox
//
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
const connection = remoteAgentService.getConnection();
if (connection) {
const remoteFileSystemProvider = this._register(new RemoteFileSystemProvider(remoteAgentService));
fileService.registerProvider(Schemas.vscodeRemote, remoteFileSystemProvider);
}
const payload = this.resolveWorkspaceInitializationPayload();
const services = await Promise.all([
this.createWorkspaceService(payload, fileService, remoteAgentService, uriIdentityService, logService).then(service => {
// Workspace
serviceCollection.set(IWorkspaceContextService, service);
// Configuration
serviceCollection.set(IWorkbenchConfigurationService, service);
return service;
}),
this.createStorageService(payload, mainProcessService).then(service => {
// Storage
serviceCollection.set(IStorageService, service);
return service;
}),
this.createKeyboardLayoutService(mainProcessService).then(service => {
// KeyboardLayout
serviceCollection.set(IKeyboardLayoutService, service);
return service;
})
]);
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
//
// NOTE: Please do NOT register services here. Use `registerSingleton()`
// from `workbench.common.main.ts` if the service is shared between
// desktop and web or `workbench.sandbox.main.ts` if the service
// is desktop only.
//
// DO NOT add services to `workbench.desktop.main.ts`, always add
// to `workbench.sandbox.main.ts` to support our Electron sandbox
//
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
return { serviceCollection, logService, storageService: services[1] };
}
private resolveWorkspaceInitializationPayload(): IWorkspaceInitializationPayload {
let workspaceInitializationPayload: IWorkspaceInitializationPayload | undefined = this.configuration.workspace;
// Fallback to empty workspace if we have no payload yet.
if (!workspaceInitializationPayload) {
let id: string;
if (this.configuration.backupPath) {
id = basename(this.configuration.backupPath); // we know the backupPath must be a unique path so we leverage its name as workspace ID
} else if (this.environmentService.isExtensionDevelopment) {
id = 'ext-dev'; // extension development window never stores backups and is a singleton
} else {
throw new Error('Unexpected window configuration without backupPath');
}
workspaceInitializationPayload = { id };
}
return workspaceInitializationPayload;
}
private async createWorkspaceService(payload: IWorkspaceInitializationPayload, fileService: FileService, remoteAgentService: IRemoteAgentService, uriIdentityService: IUriIdentityService, logService: ILogService): Promise<WorkspaceService> {
const workspaceService = new WorkspaceService({ remoteAuthority: this.environmentService.remoteAuthority, configurationCache: new ConfigurationCache(URI.file(this.environmentService.userDataPath), fileService) }, this.environmentService, fileService, remoteAgentService, uriIdentityService, logService);
try {
await workspaceService.initialize(payload);
return workspaceService;
} catch (error) {
onUnexpectedError(error);
return workspaceService;
}
}
private async createStorageService(payload: IWorkspaceInitializationPayload, mainProcessService: IMainProcessService): Promise<NativeStorageService> {
const storageService = new NativeStorageService(payload, mainProcessService, this.environmentService);
try {
await storageService.initialize();
return storageService;
} catch (error) {
onUnexpectedError(error);
return storageService;
}
}
private async createKeyboardLayoutService(mainProcessService: IMainProcessService): Promise<KeyboardLayoutService> {
const keyboardLayoutService = new KeyboardLayoutService(mainProcessService);
try {
await keyboardLayoutService.initialize();
return keyboardLayoutService;
} catch (error) {
onUnexpectedError(error);
return keyboardLayoutService;
}
}
}
| src/vs/workbench/electron-sandbox/shared.desktop.main.ts | 0 | https://github.com/microsoft/vscode/commit/36ef468d4dd9a84203bdb2dba688ce395e4b4408 | [
0.0015737315407022834,
0.00027457234682515264,
0.00016453885473310947,
0.00017297269369009882,
0.00031803263118490577
] |
{
"id": 6,
"code_window": [
"\tpublic resolveAny(workspaceFolder: IWorkspaceFolder | undefined, config: any, commandValueMapping?: IStringDictionary<string>): any {\n",
"\t\treturn this.resolveAnyBase(workspaceFolder, config, commandValueMapping);\n",
"\t}\n",
"\n",
"\tpublic resolveAnyMap(workspaceFolder: IWorkspaceFolder | undefined, config: any, commandValueMapping?: IStringDictionary<string>): { newConfig: any, resolvedVariables: Map<string, string> } {\n",
"\t\tconst resolvedVariables = new Map<string, string>();\n",
"\t\tconst newConfig = this.resolveAnyBase(workspaceFolder, config, commandValueMapping, resolvedVariables);\n",
"\t\treturn { newConfig, resolvedVariables };\n",
"\t}\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"\tpublic async resolveAnyAsync(workspaceFolder: IWorkspaceFolder | undefined, config: any, commandValueMapping?: IStringDictionary<string>): Promise<any> {\n",
"\t\treturn this.resolveAnyBase(workspaceFolder, config, commandValueMapping);\n",
"\t}\n",
"\n"
],
"file_path": "src/vs/workbench/services/configurationResolver/common/variableResolver.ts",
"type": "add",
"edit_start_line_idx": 93
} | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { URI, UriComponents } from 'vs/base/common/uri';
import { Event, Emitter } from 'vs/base/common/event';
import { debounce } from 'vs/base/common/decorators';
import { DisposableStore, IDisposable, MutableDisposable } from 'vs/base/common/lifecycle';
import { asPromise } from 'vs/base/common/async';
import { ExtHostCommands } from 'vs/workbench/api/common/extHostCommands';
import { MainContext, MainThreadSCMShape, SCMRawResource, SCMRawResourceSplice, SCMRawResourceSplices, IMainContext, ExtHostSCMShape, ICommandDto, MainThreadTelemetryShape, SCMGroupFeatures } from './extHost.protocol';
import { sortedDiff, equals } from 'vs/base/common/arrays';
import { comparePaths } from 'vs/base/common/comparers';
import type * as vscode from 'vscode';
import { ISplice } from 'vs/base/common/sequence';
import { ILogService } from 'vs/platform/log/common/log';
import { CancellationToken } from 'vs/base/common/cancellation';
import { ExtensionIdentifier, IExtensionDescription } from 'vs/platform/extensions/common/extensions';
import { checkProposedApiEnabled } from 'vs/workbench/services/extensions/common/extensions';
type ProviderHandle = number;
type GroupHandle = number;
type ResourceStateHandle = number;
function getIconResource(decorations?: vscode.SourceControlResourceThemableDecorations): vscode.Uri | undefined {
if (!decorations) {
return undefined;
} else if (typeof decorations.iconPath === 'string') {
return URI.file(decorations.iconPath);
} else {
return decorations.iconPath;
}
}
function compareResourceThemableDecorations(a: vscode.SourceControlResourceThemableDecorations, b: vscode.SourceControlResourceThemableDecorations): number {
if (!a.iconPath && !b.iconPath) {
return 0;
} else if (!a.iconPath) {
return -1;
} else if (!b.iconPath) {
return 1;
}
const aPath = typeof a.iconPath === 'string' ? a.iconPath : a.iconPath.fsPath;
const bPath = typeof b.iconPath === 'string' ? b.iconPath : b.iconPath.fsPath;
return comparePaths(aPath, bPath);
}
function compareResourceStatesDecorations(a: vscode.SourceControlResourceDecorations, b: vscode.SourceControlResourceDecorations): number {
let result = 0;
if (a.strikeThrough !== b.strikeThrough) {
return a.strikeThrough ? 1 : -1;
}
if (a.faded !== b.faded) {
return a.faded ? 1 : -1;
}
if (a.tooltip !== b.tooltip) {
return (a.tooltip || '').localeCompare(b.tooltip || '');
}
result = compareResourceThemableDecorations(a, b);
if (result !== 0) {
return result;
}
if (a.light && b.light) {
result = compareResourceThemableDecorations(a.light, b.light);
} else if (a.light) {
return 1;
} else if (b.light) {
return -1;
}
if (result !== 0) {
return result;
}
if (a.dark && b.dark) {
result = compareResourceThemableDecorations(a.dark, b.dark);
} else if (a.dark) {
return 1;
} else if (b.dark) {
return -1;
}
return result;
}
function compareCommands(a: vscode.Command, b: vscode.Command): number {
if (a.command !== b.command) {
return a.command < b.command ? -1 : 1;
}
if (a.title !== b.title) {
return a.title < b.title ? -1 : 1;
}
if (a.tooltip !== b.tooltip) {
if (a.tooltip !== undefined && b.tooltip !== undefined) {
return a.tooltip < b.tooltip ? -1 : 1;
} else if (a.tooltip !== undefined) {
return 1;
} else if (b.tooltip !== undefined) {
return -1;
}
}
if (a.arguments === b.arguments) {
return 0;
} else if (!a.arguments) {
return -1;
} else if (!b.arguments) {
return 1;
} else if (a.arguments.length !== b.arguments.length) {
return a.arguments.length - b.arguments.length;
}
for (let i = 0; i < a.arguments.length; i++) {
const aArg = a.arguments[i];
const bArg = b.arguments[i];
if (aArg === bArg) {
continue;
}
return aArg < bArg ? -1 : 1;
}
return 0;
}
function compareResourceStates(a: vscode.SourceControlResourceState, b: vscode.SourceControlResourceState): number {
let result = comparePaths(a.resourceUri.fsPath, b.resourceUri.fsPath, true);
if (result !== 0) {
return result;
}
if (a.command && b.command) {
result = compareCommands(a.command, b.command);
} else if (a.command) {
return 1;
} else if (b.command) {
return -1;
}
if (result !== 0) {
return result;
}
if (a.decorations && b.decorations) {
result = compareResourceStatesDecorations(a.decorations, b.decorations);
} else if (a.decorations) {
return 1;
} else if (b.decorations) {
return -1;
}
return result;
}
function compareArgs(a: any[], b: any[]): boolean {
for (let i = 0; i < a.length; i++) {
if (a[i] !== b[i]) {
return false;
}
}
return true;
}
function commandEquals(a: vscode.Command, b: vscode.Command): boolean {
return a.command === b.command
&& a.title === b.title
&& a.tooltip === b.tooltip
&& (a.arguments && b.arguments ? compareArgs(a.arguments, b.arguments) : a.arguments === b.arguments);
}
function commandListEquals(a: readonly vscode.Command[], b: readonly vscode.Command[]): boolean {
return equals(a, b, commandEquals);
}
export interface IValidateInput {
(value: string, cursorPosition: number): vscode.ProviderResult<vscode.SourceControlInputBoxValidation | undefined | null>;
}
export class ExtHostSCMInputBox implements vscode.SourceControlInputBox {
private _value: string = '';
get value(): string {
return this._value;
}
set value(value: string) {
this._proxy.$setInputBoxValue(this._sourceControlHandle, value);
this.updateValue(value);
}
private readonly _onDidChange = new Emitter<string>();
get onDidChange(): Event<string> {
return this._onDidChange.event;
}
private _placeholder: string = '';
get placeholder(): string {
return this._placeholder;
}
set placeholder(placeholder: string) {
this._proxy.$setInputBoxPlaceholder(this._sourceControlHandle, placeholder);
this._placeholder = placeholder;
}
private _validateInput: IValidateInput | undefined;
get validateInput(): IValidateInput | undefined {
checkProposedApiEnabled(this._extension);
return this._validateInput;
}
set validateInput(fn: IValidateInput | undefined) {
checkProposedApiEnabled(this._extension);
if (fn && typeof fn !== 'function') {
throw new Error(`[${this._extension.identifier.value}]: Invalid SCM input box validation function`);
}
this._validateInput = fn;
this._proxy.$setValidationProviderIsEnabled(this._sourceControlHandle, !!fn);
}
private _visible: boolean = true;
get visible(): boolean {
return this._visible;
}
set visible(visible: boolean) {
visible = !!visible;
if (this._visible === visible) {
return;
}
this._visible = visible;
this._proxy.$setInputBoxVisibility(this._sourceControlHandle, visible);
}
constructor(private _extension: IExtensionDescription, private _proxy: MainThreadSCMShape, private _sourceControlHandle: number) {
// noop
}
$onInputBoxValueChange(value: string): void {
this.updateValue(value);
}
private updateValue(value: string): void {
this._value = value;
this._onDidChange.fire(value);
}
}
class ExtHostSourceControlResourceGroup implements vscode.SourceControlResourceGroup {
private static _handlePool: number = 0;
private _resourceHandlePool: number = 0;
private _resourceStates: vscode.SourceControlResourceState[] = [];
private _resourceStatesMap = new Map<ResourceStateHandle, vscode.SourceControlResourceState>();
private _resourceStatesCommandsMap = new Map<ResourceStateHandle, vscode.Command>();
private _resourceStatesDisposablesMap = new Map<ResourceStateHandle, IDisposable>();
private readonly _onDidUpdateResourceStates = new Emitter<void>();
readonly onDidUpdateResourceStates = this._onDidUpdateResourceStates.event;
private _disposed = false;
get disposed(): boolean { return this._disposed; }
private readonly _onDidDispose = new Emitter<void>();
readonly onDidDispose = this._onDidDispose.event;
private _handlesSnapshot: number[] = [];
private _resourceSnapshot: vscode.SourceControlResourceState[] = [];
get id(): string { return this._id; }
get label(): string { return this._label; }
set label(label: string) {
this._label = label;
this._proxy.$updateGroupLabel(this._sourceControlHandle, this.handle, label);
}
private _hideWhenEmpty: boolean | undefined = undefined;
get hideWhenEmpty(): boolean | undefined { return this._hideWhenEmpty; }
set hideWhenEmpty(hideWhenEmpty: boolean | undefined) {
this._hideWhenEmpty = hideWhenEmpty;
this._proxy.$updateGroup(this._sourceControlHandle, this.handle, this.features);
}
get features(): SCMGroupFeatures {
return {
hideWhenEmpty: this.hideWhenEmpty
};
}
get resourceStates(): vscode.SourceControlResourceState[] { return [...this._resourceStates]; }
set resourceStates(resources: vscode.SourceControlResourceState[]) {
this._resourceStates = [...resources];
this._onDidUpdateResourceStates.fire();
}
readonly handle = ExtHostSourceControlResourceGroup._handlePool++;
constructor(
private _proxy: MainThreadSCMShape,
private _commands: ExtHostCommands,
private _sourceControlHandle: number,
private _id: string,
private _label: string,
) { }
getResourceState(handle: number): vscode.SourceControlResourceState | undefined {
return this._resourceStatesMap.get(handle);
}
$executeResourceCommand(handle: number, preserveFocus: boolean): Promise<void> {
const command = this._resourceStatesCommandsMap.get(handle);
if (!command) {
return Promise.resolve(undefined);
}
return asPromise(() => this._commands.executeCommand(command.command, ...(command.arguments || []), preserveFocus));
}
_takeResourceStateSnapshot(): SCMRawResourceSplice[] {
const snapshot = [...this._resourceStates].sort(compareResourceStates);
const diffs = sortedDiff(this._resourceSnapshot, snapshot, compareResourceStates);
const splices = diffs.map<ISplice<{ rawResource: SCMRawResource, handle: number }>>(diff => {
const toInsert = diff.toInsert.map(r => {
const handle = this._resourceHandlePool++;
this._resourceStatesMap.set(handle, r);
const sourceUri = r.resourceUri;
const iconUri = getIconResource(r.decorations);
const lightIconUri = r.decorations && getIconResource(r.decorations.light) || iconUri;
const darkIconUri = r.decorations && getIconResource(r.decorations.dark) || iconUri;
const icons: UriComponents[] = [];
let command: ICommandDto | undefined;
if (r.command) {
if (r.command.command === 'vscode.open' || r.command.command === 'vscode.diff') {
const disposables = new DisposableStore();
command = this._commands.converter.toInternal(r.command, disposables);
this._resourceStatesDisposablesMap.set(handle, disposables);
} else {
this._resourceStatesCommandsMap.set(handle, r.command);
}
}
if (lightIconUri) {
icons.push(lightIconUri);
}
if (darkIconUri && (darkIconUri.toString() !== lightIconUri?.toString())) {
icons.push(darkIconUri);
}
const tooltip = (r.decorations && r.decorations.tooltip) || '';
const strikeThrough = r.decorations && !!r.decorations.strikeThrough;
const faded = r.decorations && !!r.decorations.faded;
const contextValue = r.contextValue || '';
const rawResource = [handle, sourceUri, icons, tooltip, strikeThrough, faded, contextValue, command] as SCMRawResource;
return { rawResource, handle };
});
return { start: diff.start, deleteCount: diff.deleteCount, toInsert };
});
const rawResourceSplices = splices
.map(({ start, deleteCount, toInsert }) => [start, deleteCount, toInsert.map(i => i.rawResource)] as SCMRawResourceSplice);
const reverseSplices = splices.reverse();
for (const { start, deleteCount, toInsert } of reverseSplices) {
const handles = toInsert.map(i => i.handle);
const handlesToDelete = this._handlesSnapshot.splice(start, deleteCount, ...handles);
for (const handle of handlesToDelete) {
this._resourceStatesMap.delete(handle);
this._resourceStatesCommandsMap.delete(handle);
this._resourceStatesDisposablesMap.get(handle)?.dispose();
this._resourceStatesDisposablesMap.delete(handle);
}
}
this._resourceSnapshot = snapshot;
return rawResourceSplices;
}
dispose(): void {
this._disposed = true;
this._onDidDispose.fire();
}
}
class ExtHostSourceControl implements vscode.SourceControl {
private static _handlePool: number = 0;
private _groups: Map<GroupHandle, ExtHostSourceControlResourceGroup> = new Map<GroupHandle, ExtHostSourceControlResourceGroup>();
get id(): string {
return this._id;
}
get label(): string {
return this._label;
}
get rootUri(): vscode.Uri | undefined {
return this._rootUri;
}
private _inputBox: ExtHostSCMInputBox;
get inputBox(): ExtHostSCMInputBox { return this._inputBox; }
private _count: number | undefined = undefined;
get count(): number | undefined {
return this._count;
}
set count(count: number | undefined) {
if (this._count === count) {
return;
}
this._count = count;
this._proxy.$updateSourceControl(this.handle, { count });
}
private _quickDiffProvider: vscode.QuickDiffProvider | undefined = undefined;
get quickDiffProvider(): vscode.QuickDiffProvider | undefined {
return this._quickDiffProvider;
}
set quickDiffProvider(quickDiffProvider: vscode.QuickDiffProvider | undefined) {
this._quickDiffProvider = quickDiffProvider;
this._proxy.$updateSourceControl(this.handle, { hasQuickDiffProvider: !!quickDiffProvider });
}
private _commitTemplate: string | undefined = undefined;
get commitTemplate(): string | undefined {
return this._commitTemplate;
}
set commitTemplate(commitTemplate: string | undefined) {
if (commitTemplate === this._commitTemplate) {
return;
}
this._commitTemplate = commitTemplate;
this._proxy.$updateSourceControl(this.handle, { commitTemplate });
}
private _acceptInputDisposables = new MutableDisposable<DisposableStore>();
private _acceptInputCommand: vscode.Command | undefined = undefined;
get acceptInputCommand(): vscode.Command | undefined {
return this._acceptInputCommand;
}
set acceptInputCommand(acceptInputCommand: vscode.Command | undefined) {
this._acceptInputDisposables.value = new DisposableStore();
this._acceptInputCommand = acceptInputCommand;
const internal = this._commands.converter.toInternal(acceptInputCommand, this._acceptInputDisposables.value);
this._proxy.$updateSourceControl(this.handle, { acceptInputCommand: internal });
}
private _statusBarDisposables = new MutableDisposable<DisposableStore>();
private _statusBarCommands: vscode.Command[] | undefined = undefined;
get statusBarCommands(): vscode.Command[] | undefined {
return this._statusBarCommands;
}
set statusBarCommands(statusBarCommands: vscode.Command[] | undefined) {
if (this._statusBarCommands && statusBarCommands && commandListEquals(this._statusBarCommands, statusBarCommands)) {
return;
}
this._statusBarDisposables.value = new DisposableStore();
this._statusBarCommands = statusBarCommands;
const internal = (statusBarCommands || []).map(c => this._commands.converter.toInternal(c, this._statusBarDisposables.value!)) as ICommandDto[];
this._proxy.$updateSourceControl(this.handle, { statusBarCommands: internal });
}
private _selected: boolean = false;
get selected(): boolean {
return this._selected;
}
private readonly _onDidChangeSelection = new Emitter<boolean>();
readonly onDidChangeSelection = this._onDidChangeSelection.event;
private handle: number = ExtHostSourceControl._handlePool++;
constructor(
_extension: IExtensionDescription,
private _proxy: MainThreadSCMShape,
private _commands: ExtHostCommands,
private _id: string,
private _label: string,
private _rootUri?: vscode.Uri
) {
this._inputBox = new ExtHostSCMInputBox(_extension, this._proxy, this.handle);
this._proxy.$registerSourceControl(this.handle, _id, _label, _rootUri);
}
private createdResourceGroups = new Map<ExtHostSourceControlResourceGroup, IDisposable>();
private updatedResourceGroups = new Set<ExtHostSourceControlResourceGroup>();
createResourceGroup(id: string, label: string): ExtHostSourceControlResourceGroup {
const group = new ExtHostSourceControlResourceGroup(this._proxy, this._commands, this.handle, id, label);
const disposable = Event.once(group.onDidDispose)(() => this.createdResourceGroups.delete(group));
this.createdResourceGroups.set(group, disposable);
this.eventuallyAddResourceGroups();
return group;
}
@debounce(100)
eventuallyAddResourceGroups(): void {
const groups: [number /*handle*/, string /*id*/, string /*label*/, SCMGroupFeatures][] = [];
const splices: SCMRawResourceSplices[] = [];
for (const [group, disposable] of this.createdResourceGroups) {
disposable.dispose();
const updateListener = group.onDidUpdateResourceStates(() => {
this.updatedResourceGroups.add(group);
this.eventuallyUpdateResourceStates();
});
Event.once(group.onDidDispose)(() => {
this.updatedResourceGroups.delete(group);
updateListener.dispose();
this._groups.delete(group.handle);
this._proxy.$unregisterGroup(this.handle, group.handle);
});
groups.push([group.handle, group.id, group.label, group.features]);
const snapshot = group._takeResourceStateSnapshot();
if (snapshot.length > 0) {
splices.push([group.handle, snapshot]);
}
this._groups.set(group.handle, group);
}
this._proxy.$registerGroups(this.handle, groups, splices);
this.createdResourceGroups.clear();
}
@debounce(100)
eventuallyUpdateResourceStates(): void {
const splices: SCMRawResourceSplices[] = [];
this.updatedResourceGroups.forEach(group => {
const snapshot = group._takeResourceStateSnapshot();
if (snapshot.length === 0) {
return;
}
splices.push([group.handle, snapshot]);
});
if (splices.length > 0) {
this._proxy.$spliceResourceStates(this.handle, splices);
}
this.updatedResourceGroups.clear();
}
getResourceGroup(handle: GroupHandle): ExtHostSourceControlResourceGroup | undefined {
return this._groups.get(handle);
}
setSelectionState(selected: boolean): void {
this._selected = selected;
this._onDidChangeSelection.fire(selected);
}
dispose(): void {
this._acceptInputDisposables.dispose();
this._statusBarDisposables.dispose();
this._groups.forEach(group => group.dispose());
this._proxy.$unregisterSourceControl(this.handle);
}
}
export class ExtHostSCM implements ExtHostSCMShape {
private static _handlePool: number = 0;
private _proxy: MainThreadSCMShape;
private readonly _telemetry: MainThreadTelemetryShape;
private _sourceControls: Map<ProviderHandle, ExtHostSourceControl> = new Map<ProviderHandle, ExtHostSourceControl>();
private _sourceControlsByExtension: Map<string, ExtHostSourceControl[]> = new Map<string, ExtHostSourceControl[]>();
private readonly _onDidChangeActiveProvider = new Emitter<vscode.SourceControl>();
get onDidChangeActiveProvider(): Event<vscode.SourceControl> { return this._onDidChangeActiveProvider.event; }
private _selectedSourceControlHandle: number | undefined;
constructor(
mainContext: IMainContext,
private _commands: ExtHostCommands,
@ILogService private readonly logService: ILogService
) {
this._proxy = mainContext.getProxy(MainContext.MainThreadSCM);
this._telemetry = mainContext.getProxy(MainContext.MainThreadTelemetry);
_commands.registerArgumentProcessor({
processArgument: arg => {
if (arg && arg.$mid === 3) {
const sourceControl = this._sourceControls.get(arg.sourceControlHandle);
if (!sourceControl) {
return arg;
}
const group = sourceControl.getResourceGroup(arg.groupHandle);
if (!group) {
return arg;
}
return group.getResourceState(arg.handle);
} else if (arg && arg.$mid === 4) {
const sourceControl = this._sourceControls.get(arg.sourceControlHandle);
if (!sourceControl) {
return arg;
}
return sourceControl.getResourceGroup(arg.groupHandle);
} else if (arg && arg.$mid === 5) {
const sourceControl = this._sourceControls.get(arg.handle);
if (!sourceControl) {
return arg;
}
return sourceControl;
}
return arg;
}
});
}
createSourceControl(extension: IExtensionDescription, id: string, label: string, rootUri: vscode.Uri | undefined): vscode.SourceControl {
this.logService.trace('ExtHostSCM#createSourceControl', extension.identifier.value, id, label, rootUri);
type TEvent = { extensionId: string; };
type TMeta = { extensionId: { classification: 'SystemMetaData', purpose: 'FeatureInsight' }; };
this._telemetry.$publicLog2<TEvent, TMeta>('api/scm/createSourceControl', {
extensionId: extension.identifier.value,
});
const handle = ExtHostSCM._handlePool++;
const sourceControl = new ExtHostSourceControl(extension, this._proxy, this._commands, id, label, rootUri);
this._sourceControls.set(handle, sourceControl);
const sourceControls = this._sourceControlsByExtension.get(ExtensionIdentifier.toKey(extension.identifier)) || [];
sourceControls.push(sourceControl);
this._sourceControlsByExtension.set(ExtensionIdentifier.toKey(extension.identifier), sourceControls);
return sourceControl;
}
// Deprecated
getLastInputBox(extension: IExtensionDescription): ExtHostSCMInputBox | undefined {
this.logService.trace('ExtHostSCM#getLastInputBox', extension.identifier.value);
const sourceControls = this._sourceControlsByExtension.get(ExtensionIdentifier.toKey(extension.identifier));
const sourceControl = sourceControls && sourceControls[sourceControls.length - 1];
return sourceControl && sourceControl.inputBox;
}
$provideOriginalResource(sourceControlHandle: number, uriComponents: UriComponents, token: CancellationToken): Promise<UriComponents | null> {
const uri = URI.revive(uriComponents);
this.logService.trace('ExtHostSCM#$provideOriginalResource', sourceControlHandle, uri.toString());
const sourceControl = this._sourceControls.get(sourceControlHandle);
if (!sourceControl || !sourceControl.quickDiffProvider || !sourceControl.quickDiffProvider.provideOriginalResource) {
return Promise.resolve(null);
}
return asPromise(() => sourceControl.quickDiffProvider!.provideOriginalResource!(uri, token))
.then<UriComponents | null>(r => r || null);
}
$onInputBoxValueChange(sourceControlHandle: number, value: string): Promise<void> {
this.logService.trace('ExtHostSCM#$onInputBoxValueChange', sourceControlHandle);
const sourceControl = this._sourceControls.get(sourceControlHandle);
if (!sourceControl) {
return Promise.resolve(undefined);
}
sourceControl.inputBox.$onInputBoxValueChange(value);
return Promise.resolve(undefined);
}
$executeResourceCommand(sourceControlHandle: number, groupHandle: number, handle: number, preserveFocus: boolean): Promise<void> {
this.logService.trace('ExtHostSCM#$executeResourceCommand', sourceControlHandle, groupHandle, handle);
const sourceControl = this._sourceControls.get(sourceControlHandle);
if (!sourceControl) {
return Promise.resolve(undefined);
}
const group = sourceControl.getResourceGroup(groupHandle);
if (!group) {
return Promise.resolve(undefined);
}
return group.$executeResourceCommand(handle, preserveFocus);
}
$validateInput(sourceControlHandle: number, value: string, cursorPosition: number): Promise<[string, number] | undefined> {
this.logService.trace('ExtHostSCM#$validateInput', sourceControlHandle);
const sourceControl = this._sourceControls.get(sourceControlHandle);
if (!sourceControl) {
return Promise.resolve(undefined);
}
if (!sourceControl.inputBox.validateInput) {
return Promise.resolve(undefined);
}
return asPromise(() => sourceControl.inputBox.validateInput!(value, cursorPosition)).then(result => {
if (!result) {
return Promise.resolve(undefined);
}
return Promise.resolve<[string, number]>([result.message, result.type]);
});
}
$setSelectedSourceControl(selectedSourceControlHandle: number | undefined): Promise<void> {
this.logService.trace('ExtHostSCM#$setSelectedSourceControl', selectedSourceControlHandle);
if (selectedSourceControlHandle !== undefined) {
this._sourceControls.get(selectedSourceControlHandle)?.setSelectionState(true);
}
if (this._selectedSourceControlHandle !== undefined) {
this._sourceControls.get(this._selectedSourceControlHandle)?.setSelectionState(false);
}
this._selectedSourceControlHandle = selectedSourceControlHandle;
return Promise.resolve(undefined);
}
}
| src/vs/workbench/api/common/extHostSCM.ts | 0 | https://github.com/microsoft/vscode/commit/36ef468d4dd9a84203bdb2dba688ce395e4b4408 | [
0.0001769724622135982,
0.00017231129459105432,
0.00016155780758708715,
0.00017323208157904446,
0.000003069489821427851
] |
{
"id": 0,
"code_window": [
" });\n",
"\n",
" it('allows custom elevations via theme.shadows', () => {\n",
" const theme = createMuiTheme();\n",
" // Theme.shadows holds a reference to `@material-ui/core/styles#shadows`\n",
" // Mutating it causes side effects in other tests\n",
" theme.shadows = theme.shadows.slice();\n",
" theme.shadows.push('20px 20px');\n",
" const { getByTestId } = render(\n",
" <ThemeProvider theme={theme}>\n",
" <Paper data-testid=\"root\" classes={{ elevation25: 'custom-elevation' }} elevation={25} />\n",
" </ThemeProvider>,\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "packages/material-ui/src/Paper/Paper.test.js",
"type": "replace",
"edit_start_line_idx": 74
} | import { deepmerge } from '@material-ui/utils';
import createBreakpoints from './createBreakpoints';
import createMixins from './createMixins';
import createPalette from './createPalette';
import createTypography from './createTypography';
import shadows from './shadows';
import shape from './shape';
import createSpacing from './createSpacing';
import { duration, easing, create, getAutoHeightDuration } from './transitions';
import zIndex from './zIndex';
function createMuiTheme(options = {}, ...args) {
const {
breakpoints: breakpointsInput = {},
mixins: mixinsInput = {},
palette: paletteInput = {},
spacing: spacingInput,
typography: typographyInput = {},
...other
} = options;
const palette = createPalette(paletteInput);
const breakpoints = createBreakpoints(breakpointsInput);
const spacing = createSpacing(spacingInput);
let muiTheme = deepmerge(
{
breakpoints,
direction: 'ltr',
mixins: createMixins(breakpoints, spacing, mixinsInput),
components: {}, // Inject component definitions
palette,
shadows,
typography: createTypography(palette, typographyInput),
spacing,
shape,
transitions: { duration, easing, create, getAutoHeightDuration },
zIndex,
},
other,
);
muiTheme = args.reduce((acc, argument) => deepmerge(acc, argument), muiTheme);
if (process.env.NODE_ENV !== 'production') {
const pseudoClasses = [
'checked',
'disabled',
'error',
'focused',
'focusVisible',
'required',
'expanded',
'selected',
];
const traverse = (node, component) => {
let key;
// eslint-disable-next-line guard-for-in, no-restricted-syntax
for (key in node) {
const child = node[key];
if (pseudoClasses.indexOf(key) !== -1 && Object.keys(child).length > 0) {
if (process.env.NODE_ENV !== 'production') {
console.error(
[
`Material-UI: The \`${component}\` component increases ` +
`the CSS specificity of the \`${key}\` internal state.`,
'You can not override it like this: ',
JSON.stringify(node, null, 2),
'',
'Instead, you need to use the $ruleName syntax:',
JSON.stringify(
{
root: {
[`&$${key}`]: child,
},
},
null,
2,
),
'',
'https://material-ui.com/r/pseudo-classes-guide',
].join('\n'),
);
}
// Remove the style to prevent global conflicts.
node[key] = {};
}
}
};
Object.keys(muiTheme.components).forEach((component) => {
const styleOverrides = muiTheme.components[component].styleOverrides;
if (styleOverrides && component.indexOf('Mui') === 0) {
traverse(styleOverrides, component);
}
});
}
return muiTheme;
}
export default createMuiTheme;
| packages/material-ui/src/styles/createMuiTheme.js | 1 | https://github.com/mui/material-ui/commit/27fe6a30e5e5432036e8a0ce8a409b75dfb7f2dc | [
0.007517778314650059,
0.0013342942111194134,
0.00016437435988336802,
0.0001701656583463773,
0.0021021319553256035
] |
{
"id": 0,
"code_window": [
" });\n",
"\n",
" it('allows custom elevations via theme.shadows', () => {\n",
" const theme = createMuiTheme();\n",
" // Theme.shadows holds a reference to `@material-ui/core/styles#shadows`\n",
" // Mutating it causes side effects in other tests\n",
" theme.shadows = theme.shadows.slice();\n",
" theme.shadows.push('20px 20px');\n",
" const { getByTestId } = render(\n",
" <ThemeProvider theme={theme}>\n",
" <Paper data-testid=\"root\" classes={{ elevation25: 'custom-elevation' }} elevation={25} />\n",
" </ThemeProvider>,\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "packages/material-ui/src/Paper/Paper.test.js",
"type": "replace",
"edit_start_line_idx": 74
} | import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<React.Fragment><path fillOpacity=".3" d="M23.64 7c-.45-.34-4.93-4-11.64-4C5.28 3 .81 6.66.36 7L12 21.5 23.64 7z" /><path d="M4.79 12.52L12 21.5l7.21-8.99C18.85 12.24 16.1 10 12 10s-6.85 2.24-7.21 2.52z" /></React.Fragment>
, 'SignalWifi2BarOutlined');
| packages/material-ui-icons/src/SignalWifi2BarOutlined.js | 0 | https://github.com/mui/material-ui/commit/27fe6a30e5e5432036e8a0ce8a409b75dfb7f2dc | [
0.00017627034685574472,
0.00017627034685574472,
0.00017627034685574472,
0.00017627034685574472,
0
] |
{
"id": 0,
"code_window": [
" });\n",
"\n",
" it('allows custom elevations via theme.shadows', () => {\n",
" const theme = createMuiTheme();\n",
" // Theme.shadows holds a reference to `@material-ui/core/styles#shadows`\n",
" // Mutating it causes side effects in other tests\n",
" theme.shadows = theme.shadows.slice();\n",
" theme.shadows.push('20px 20px');\n",
" const { getByTestId } = render(\n",
" <ThemeProvider theme={theme}>\n",
" <Paper data-testid=\"root\" classes={{ elevation25: 'custom-elevation' }} elevation={25} />\n",
" </ThemeProvider>,\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "packages/material-ui/src/Paper/Paper.test.js",
"type": "replace",
"edit_start_line_idx": 74
} | {
"extends": "../../tsconfig",
"include": ["src/**/*", "test/**/*"]
}
| packages/material-ui-lab/tsconfig.json | 0 | https://github.com/mui/material-ui/commit/27fe6a30e5e5432036e8a0ce8a409b75dfb7f2dc | [
0.00017004854453261942,
0.00017004854453261942,
0.00017004854453261942,
0.00017004854453261942,
0
] |
{
"id": 0,
"code_window": [
" });\n",
"\n",
" it('allows custom elevations via theme.shadows', () => {\n",
" const theme = createMuiTheme();\n",
" // Theme.shadows holds a reference to `@material-ui/core/styles#shadows`\n",
" // Mutating it causes side effects in other tests\n",
" theme.shadows = theme.shadows.slice();\n",
" theme.shadows.push('20px 20px');\n",
" const { getByTestId } = render(\n",
" <ThemeProvider theme={theme}>\n",
" <Paper data-testid=\"root\" classes={{ elevation25: 'custom-elevation' }} elevation={25} />\n",
" </ThemeProvider>,\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "packages/material-ui/src/Paper/Paper.test.js",
"type": "replace",
"edit_start_line_idx": 74
} | /* tslint:disable max-line-length */
/**
*              
*/
declare const cyan: {
/**
* Preview: 
*/
50: '#e0f7fa';
/**
* Preview: 
*/
100: '#b2ebf2';
/**
* Preview: 
*/
200: '#80deea';
/**
* Preview: 
*/
300: '#4dd0e1';
/**
* Preview: 
*/
400: '#26c6da';
/**
* Preview: 
*/
500: '#00bcd4';
/**
* Preview: 
*/
600: '#00acc1';
/**
* Preview: 
*/
700: '#0097a7';
/**
* Preview: 
*/
800: '#00838f';
/**
* Preview: 
*/
900: '#006064';
/**
* Preview: 
*/
A100: '#84ffff';
/**
* Preview: 
*/
A200: '#18ffff';
/**
* Preview: 
*/
A400: '#00e5ff';
/**
* Preview: 
*/
A700: '#00b8d4';
};
export default cyan;
| packages/material-ui/src/colors/cyan.d.ts | 0 | https://github.com/mui/material-ui/commit/27fe6a30e5e5432036e8a0ce8a409b75dfb7f2dc | [
0.00017287903756368905,
0.00016666950250510126,
0.0001629959006095305,
0.00016604828124400228,
0.0000028135855245636776
] |
{
"id": 1,
"code_window": [
" mixins: createMixins(breakpoints, spacing, mixinsInput),\n",
" components: {}, // Inject component definitions\n",
" palette,\n",
" shadows,\n",
" typography: createTypography(palette, typographyInput),\n",
" spacing,\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep"
],
"after_edit": [
" // Don't use [...shadows] until you've verified its transpiled code is not invoking the iterator protocol.\n",
" shadows: shadows.slice(),\n"
],
"file_path": "packages/material-ui/src/styles/createMuiTheme.js",
"type": "replace",
"edit_start_line_idx": 32
} | import { deepmerge } from '@material-ui/utils';
import createBreakpoints from './createBreakpoints';
import createMixins from './createMixins';
import createPalette from './createPalette';
import createTypography from './createTypography';
import shadows from './shadows';
import shape from './shape';
import createSpacing from './createSpacing';
import { duration, easing, create, getAutoHeightDuration } from './transitions';
import zIndex from './zIndex';
function createMuiTheme(options = {}, ...args) {
const {
breakpoints: breakpointsInput = {},
mixins: mixinsInput = {},
palette: paletteInput = {},
spacing: spacingInput,
typography: typographyInput = {},
...other
} = options;
const palette = createPalette(paletteInput);
const breakpoints = createBreakpoints(breakpointsInput);
const spacing = createSpacing(spacingInput);
let muiTheme = deepmerge(
{
breakpoints,
direction: 'ltr',
mixins: createMixins(breakpoints, spacing, mixinsInput),
components: {}, // Inject component definitions
palette,
shadows,
typography: createTypography(palette, typographyInput),
spacing,
shape,
transitions: { duration, easing, create, getAutoHeightDuration },
zIndex,
},
other,
);
muiTheme = args.reduce((acc, argument) => deepmerge(acc, argument), muiTheme);
if (process.env.NODE_ENV !== 'production') {
const pseudoClasses = [
'checked',
'disabled',
'error',
'focused',
'focusVisible',
'required',
'expanded',
'selected',
];
const traverse = (node, component) => {
let key;
// eslint-disable-next-line guard-for-in, no-restricted-syntax
for (key in node) {
const child = node[key];
if (pseudoClasses.indexOf(key) !== -1 && Object.keys(child).length > 0) {
if (process.env.NODE_ENV !== 'production') {
console.error(
[
`Material-UI: The \`${component}\` component increases ` +
`the CSS specificity of the \`${key}\` internal state.`,
'You can not override it like this: ',
JSON.stringify(node, null, 2),
'',
'Instead, you need to use the $ruleName syntax:',
JSON.stringify(
{
root: {
[`&$${key}`]: child,
},
},
null,
2,
),
'',
'https://material-ui.com/r/pseudo-classes-guide',
].join('\n'),
);
}
// Remove the style to prevent global conflicts.
node[key] = {};
}
}
};
Object.keys(muiTheme.components).forEach((component) => {
const styleOverrides = muiTheme.components[component].styleOverrides;
if (styleOverrides && component.indexOf('Mui') === 0) {
traverse(styleOverrides, component);
}
});
}
return muiTheme;
}
export default createMuiTheme;
| packages/material-ui/src/styles/createMuiTheme.js | 1 | https://github.com/mui/material-ui/commit/27fe6a30e5e5432036e8a0ce8a409b75dfb7f2dc | [
0.07400071620941162,
0.007886502891778946,
0.00016698618128430098,
0.00017466038116253912,
0.02099057286977768
] |
{
"id": 1,
"code_window": [
" mixins: createMixins(breakpoints, spacing, mixinsInput),\n",
" components: {}, // Inject component definitions\n",
" palette,\n",
" shadows,\n",
" typography: createTypography(palette, typographyInput),\n",
" spacing,\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep"
],
"after_edit": [
" // Don't use [...shadows] until you've verified its transpiled code is not invoking the iterator protocol.\n",
" shadows: shadows.slice(),\n"
],
"file_path": "packages/material-ui/src/styles/createMuiTheme.js",
"type": "replace",
"edit_start_line_idx": 32
} | import * as React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<path d="M7 16c.55 0 1 .45 1 1 0 1.1-.9 2-2 2-.17 0-.33-.02-.5-.05.31-.55.5-1.21.5-1.95 0-.55.45-1 1-1M18.67 3c-.26 0-.51.1-.71.29L9 12.25 11.75 15l8.96-8.96c.39-.39.39-1.02 0-1.41l-1.34-1.34c-.2-.2-.45-.29-.7-.29zM7 14c-1.66 0-3 1.34-3 3 0 1.31-1.16 2-2 2 .92 1.22 2.49 2 4 2 2.21 0 4-1.79 4-4 0-1.66-1.34-3-3-3z" />
, 'BrushOutlined');
| packages/material-ui-icons/src/BrushOutlined.js | 0 | https://github.com/mui/material-ui/commit/27fe6a30e5e5432036e8a0ce8a409b75dfb7f2dc | [
0.00017136357200797647,
0.00017136357200797647,
0.00017136357200797647,
0.00017136357200797647,
0
] |
{
"id": 1,
"code_window": [
" mixins: createMixins(breakpoints, spacing, mixinsInput),\n",
" components: {}, // Inject component definitions\n",
" palette,\n",
" shadows,\n",
" typography: createTypography(palette, typographyInput),\n",
" spacing,\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep"
],
"after_edit": [
" // Don't use [...shadows] until you've verified its transpiled code is not invoking the iterator protocol.\n",
" shadows: shadows.slice(),\n"
],
"file_path": "packages/material-ui/src/styles/createMuiTheme.js",
"type": "replace",
"edit_start_line_idx": 32
} | import * as React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<path d="M7.77 6.76L6.23 5.48.82 12l5.41 6.52 1.54-1.28L3.42 12l4.35-5.24zM7 13h2v-2H7v2zm10-2h-2v2h2v-2zm-6 2h2v-2h-2v2zm6.77-7.52l-1.54 1.28L20.58 12l-4.35 5.24 1.54 1.28L23.18 12l-5.41-6.52z" />
, 'SettingsEthernetTwoTone');
| packages/material-ui-icons/src/SettingsEthernetTwoTone.js | 0 | https://github.com/mui/material-ui/commit/27fe6a30e5e5432036e8a0ce8a409b75dfb7f2dc | [
0.00017063473933376372,
0.00017063473933376372,
0.00017063473933376372,
0.00017063473933376372,
0
] |
{
"id": 1,
"code_window": [
" mixins: createMixins(breakpoints, spacing, mixinsInput),\n",
" components: {}, // Inject component definitions\n",
" palette,\n",
" shadows,\n",
" typography: createTypography(palette, typographyInput),\n",
" spacing,\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep"
],
"after_edit": [
" // Don't use [...shadows] until you've verified its transpiled code is not invoking the iterator protocol.\n",
" shadows: shadows.slice(),\n"
],
"file_path": "packages/material-ui/src/styles/createMuiTheme.js",
"type": "replace",
"edit_start_line_idx": 32
} | <svg xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 0 24 24" width="24">
<rect width="100%" height="100%" fill="#fdd835"/>
</svg> | docs/public/static/colors-preview/yellow-600-24x24.svg | 0 | https://github.com/mui/material-ui/commit/27fe6a30e5e5432036e8a0ce8a409b75dfb7f2dc | [
0.00017192067753057927,
0.00017192067753057927,
0.00017192067753057927,
0.00017192067753057927,
0
] |
{
"id": 2,
"code_window": [
" typography: createTypography(palette, typographyInput),\n",
" spacing,\n",
" shape,\n",
" transitions: { duration, easing, create, getAutoHeightDuration },\n"
],
"labels": [
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
" shape: { ...shape },\n"
],
"file_path": "packages/material-ui/src/styles/createMuiTheme.js",
"type": "replace",
"edit_start_line_idx": 35
} | import { deepmerge } from '@material-ui/utils';
import createBreakpoints from './createBreakpoints';
import createMixins from './createMixins';
import createPalette from './createPalette';
import createTypography from './createTypography';
import shadows from './shadows';
import shape from './shape';
import createSpacing from './createSpacing';
import { duration, easing, create, getAutoHeightDuration } from './transitions';
import zIndex from './zIndex';
function createMuiTheme(options = {}, ...args) {
const {
breakpoints: breakpointsInput = {},
mixins: mixinsInput = {},
palette: paletteInput = {},
spacing: spacingInput,
typography: typographyInput = {},
...other
} = options;
const palette = createPalette(paletteInput);
const breakpoints = createBreakpoints(breakpointsInput);
const spacing = createSpacing(spacingInput);
let muiTheme = deepmerge(
{
breakpoints,
direction: 'ltr',
mixins: createMixins(breakpoints, spacing, mixinsInput),
components: {}, // Inject component definitions
palette,
shadows,
typography: createTypography(palette, typographyInput),
spacing,
shape,
transitions: { duration, easing, create, getAutoHeightDuration },
zIndex,
},
other,
);
muiTheme = args.reduce((acc, argument) => deepmerge(acc, argument), muiTheme);
if (process.env.NODE_ENV !== 'production') {
const pseudoClasses = [
'checked',
'disabled',
'error',
'focused',
'focusVisible',
'required',
'expanded',
'selected',
];
const traverse = (node, component) => {
let key;
// eslint-disable-next-line guard-for-in, no-restricted-syntax
for (key in node) {
const child = node[key];
if (pseudoClasses.indexOf(key) !== -1 && Object.keys(child).length > 0) {
if (process.env.NODE_ENV !== 'production') {
console.error(
[
`Material-UI: The \`${component}\` component increases ` +
`the CSS specificity of the \`${key}\` internal state.`,
'You can not override it like this: ',
JSON.stringify(node, null, 2),
'',
'Instead, you need to use the $ruleName syntax:',
JSON.stringify(
{
root: {
[`&$${key}`]: child,
},
},
null,
2,
),
'',
'https://material-ui.com/r/pseudo-classes-guide',
].join('\n'),
);
}
// Remove the style to prevent global conflicts.
node[key] = {};
}
}
};
Object.keys(muiTheme.components).forEach((component) => {
const styleOverrides = muiTheme.components[component].styleOverrides;
if (styleOverrides && component.indexOf('Mui') === 0) {
traverse(styleOverrides, component);
}
});
}
return muiTheme;
}
export default createMuiTheme;
| packages/material-ui/src/styles/createMuiTheme.js | 1 | https://github.com/mui/material-ui/commit/27fe6a30e5e5432036e8a0ce8a409b75dfb7f2dc | [
0.15692397952079773,
0.016681205481290817,
0.00016753959062043577,
0.0001699427084531635,
0.044691722840070724
] |
{
"id": 2,
"code_window": [
" typography: createTypography(palette, typographyInput),\n",
" spacing,\n",
" shape,\n",
" transitions: { duration, easing, create, getAutoHeightDuration },\n"
],
"labels": [
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
" shape: { ...shape },\n"
],
"file_path": "packages/material-ui/src/styles/createMuiTheme.js",
"type": "replace",
"edit_start_line_idx": 35
} | import * as React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<React.Fragment><path d="M18 20H6V8c0-1.1.9-2 2-2h8c1.1 0 2 .9 2 2v12zM7.5 12v2h7v2h2v-4h-9z" opacity=".3" /><path d="M17 4.14V2h-3v2h-4V2H7v2.14c-1.72.45-3 2-3 3.86v12c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V8c0-1.86-1.28-3.41-3-3.86zM18 20H6V8c0-1.1.9-2 2-2h8c1.1 0 2 .9 2 2v12zM7.5 12v2h7v2h2v-4h-9z" /></React.Fragment>
, 'BackpackTwoTone');
| packages/material-ui-icons/src/BackpackTwoTone.js | 0 | https://github.com/mui/material-ui/commit/27fe6a30e5e5432036e8a0ce8a409b75dfb7f2dc | [
0.00016860933101270348,
0.00016860933101270348,
0.00016860933101270348,
0.00016860933101270348,
0
] |
{
"id": 2,
"code_window": [
" typography: createTypography(palette, typographyInput),\n",
" spacing,\n",
" shape,\n",
" transitions: { duration, easing, create, getAutoHeightDuration },\n"
],
"labels": [
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
" shape: { ...shape },\n"
],
"file_path": "packages/material-ui/src/styles/createMuiTheme.js",
"type": "replace",
"edit_start_line_idx": 35
} | export { default } from './Slider';
| packages/material-ui/src/Slider/index.js | 0 | https://github.com/mui/material-ui/commit/27fe6a30e5e5432036e8a0ce8a409b75dfb7f2dc | [
0.0001717245759209618,
0.0001717245759209618,
0.0001717245759209618,
0.0001717245759209618,
0
] |
{
"id": 2,
"code_window": [
" typography: createTypography(palette, typographyInput),\n",
" spacing,\n",
" shape,\n",
" transitions: { duration, easing, create, getAutoHeightDuration },\n"
],
"labels": [
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
" shape: { ...shape },\n"
],
"file_path": "packages/material-ui/src/styles/createMuiTheme.js",
"type": "replace",
"edit_start_line_idx": 35
} | import * as React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<path d="M22 5h-5.17L15 3H9L7.17 5H2v16h9v-2.09c-2.83-.48-5-2.94-5-5.91h2c0 2.21 1.79 4 4 4s4-1.79 4-4h2c0 2.97-2.17 5.43-5 5.91V21h9V5zm-8 8c0 1.1-.9 2-2 2s-2-.9-2-2V9c0-1.1.9-2 2-2s2 .9 2 2v4z" />
, 'PermCameraMicSharp');
| packages/material-ui-icons/src/PermCameraMicSharp.js | 0 | https://github.com/mui/material-ui/commit/27fe6a30e5e5432036e8a0ce8a409b75dfb7f2dc | [
0.00017190739163197577,
0.00017190739163197577,
0.00017190739163197577,
0.00017190739163197577,
0
] |
{
"id": 3,
"code_window": [
" transitions: { duration, easing, create, getAutoHeightDuration },\n",
" zIndex,\n",
" },\n",
" other,\n",
" );\n",
"\n",
" muiTheme = args.reduce((acc, argument) => deepmerge(acc, argument), muiTheme);\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" zIndex: { ...zIndex },\n"
],
"file_path": "packages/material-ui/src/styles/createMuiTheme.js",
"type": "replace",
"edit_start_line_idx": 37
} | import * as React from 'react';
import { expect } from 'chai';
import { createClientRender, getClasses, createMount, describeConformance } from 'test/utils';
import Paper from './Paper';
import { createMuiTheme, ThemeProvider } from '../styles';
describe('<Paper />', () => {
const mount = createMount();
const render = createClientRender();
let classes;
before(() => {
classes = getClasses(<Paper />);
});
describeConformance(<Paper />, () => ({
classes,
inheritComponent: 'div',
mount,
refInstanceof: window.HTMLDivElement,
testComponentPropWith: 'header',
}));
describe('prop: square', () => {
it('can disable the rounded class', () => {
const { getByTestId } = render(
<Paper data-testid="root" square>
Hello World
</Paper>,
);
expect(getByTestId('root')).not.to.have.class(classes.rounded);
});
it('adds a rounded class to the root when omitted', () => {
const { getByTestId } = render(<Paper data-testid="root">Hello World</Paper>);
expect(getByTestId('root')).to.have.class(classes.rounded);
});
});
describe('prop: variant', () => {
it('adds a outlined class', () => {
const { getByTestId } = render(
<Paper data-testid="root" variant="outlined">
Hello World
</Paper>,
);
expect(getByTestId('root')).to.have.class(classes.outlined);
});
});
it('should set the elevation elevation class', () => {
const { getByTestId, setProps } = render(
<Paper data-testid="root" elevation={16}>
Hello World
</Paper>,
);
const root = getByTestId('root');
expect(root).to.have.class(classes.elevation16);
setProps({ elevation: 24 });
expect(root).to.have.class(classes.elevation24);
setProps({ elevation: 2 });
expect(root).to.have.class(classes.elevation2);
});
it('allows custom elevations via theme.shadows', () => {
const theme = createMuiTheme();
// Theme.shadows holds a reference to `@material-ui/core/styles#shadows`
// Mutating it causes side effects in other tests
theme.shadows = theme.shadows.slice();
theme.shadows.push('20px 20px');
const { getByTestId } = render(
<ThemeProvider theme={theme}>
<Paper data-testid="root" classes={{ elevation25: 'custom-elevation' }} elevation={25} />
</ThemeProvider>,
);
expect(getByTestId('root')).to.have.class('custom-elevation');
});
it('warns if the given `elevation` is not implemented in the theme', () => {
expect(() => {
render(<Paper elevation={25} />);
}).toErrorDev(
'Material-UI: The elevation provided <Paper elevation={25}> is not available in the theme.',
);
});
});
| packages/material-ui/src/Paper/Paper.test.js | 1 | https://github.com/mui/material-ui/commit/27fe6a30e5e5432036e8a0ce8a409b75dfb7f2dc | [
0.00017991199274547398,
0.0001739934232318774,
0.0001678123662713915,
0.00017365659005008638,
0.000003426052444410743
] |
{
"id": 3,
"code_window": [
" transitions: { duration, easing, create, getAutoHeightDuration },\n",
" zIndex,\n",
" },\n",
" other,\n",
" );\n",
"\n",
" muiTheme = args.reduce((acc, argument) => deepmerge(acc, argument), muiTheme);\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" zIndex: { ...zIndex },\n"
],
"file_path": "packages/material-ui/src/styles/createMuiTheme.js",
"type": "replace",
"edit_start_line_idx": 37
} | import * as React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<path d="M9 16.2L4.8 12l-1.4 1.4L9 19 21 7l-1.4-1.4L9 16.2z" />
, 'DoneSharp');
| packages/material-ui-icons/src/DoneSharp.js | 0 | https://github.com/mui/material-ui/commit/27fe6a30e5e5432036e8a0ce8a409b75dfb7f2dc | [
0.0001776956341927871,
0.0001776956341927871,
0.0001776956341927871,
0.0001776956341927871,
0
] |
{
"id": 3,
"code_window": [
" transitions: { duration, easing, create, getAutoHeightDuration },\n",
" zIndex,\n",
" },\n",
" other,\n",
" );\n",
"\n",
" muiTheme = args.reduce((acc, argument) => deepmerge(acc, argument), muiTheme);\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" zIndex: { ...zIndex },\n"
],
"file_path": "packages/material-ui/src/styles/createMuiTheme.js",
"type": "replace",
"edit_start_line_idx": 37
} | import * as React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<React.Fragment><path d="M15 2h-3.5l-1-1h-5l-1 1H1v2h14zM16 9c-.7 0-1.37.1-2 .29V5H2v12c0 1.1.9 2 2 2h5.68c1.12 2.36 3.53 4 6.32 4 3.87 0 7-3.13 7-7s-3.13-7-7-7zm0 12c-2.76 0-5-2.24-5-5s2.24-5 5-5 5 2.24 5 5-2.24 5-5 5z" /><path d="M16.5 12H15v5l3.6 2.1.8-1.2-2.9-1.7z" /></React.Fragment>
, 'AutoDelete');
| packages/material-ui-icons/src/AutoDelete.js | 0 | https://github.com/mui/material-ui/commit/27fe6a30e5e5432036e8a0ce8a409b75dfb7f2dc | [
0.0001718343119136989,
0.0001718343119136989,
0.0001718343119136989,
0.0001718343119136989,
0
] |
{
"id": 3,
"code_window": [
" transitions: { duration, easing, create, getAutoHeightDuration },\n",
" zIndex,\n",
" },\n",
" other,\n",
" );\n",
"\n",
" muiTheme = args.reduce((acc, argument) => deepmerge(acc, argument), muiTheme);\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" zIndex: { ...zIndex },\n"
],
"file_path": "packages/material-ui/src/styles/createMuiTheme.js",
"type": "replace",
"edit_start_line_idx": 37
} | import * as React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<path d="M9.56 8l-2-2-4.15-4.14L2 3.27 4.73 6H4c-.55 0-1 .45-1 1v10c0 .55.45 1 1 1h12c.21 0 .39-.08.55-.18L19.73 21l1.41-1.41-8.86-8.86L9.56 8zM5 16V8h1.73l8 8H5zm10-8v2.61l6 6V6.5l-4 4V7c0-.55-.45-1-1-1h-5.61l2 2H15z" />
, 'VideocamOffOutlined');
| packages/material-ui-icons/src/VideocamOffOutlined.js | 0 | https://github.com/mui/material-ui/commit/27fe6a30e5e5432036e8a0ce8a409b75dfb7f2dc | [
0.00017428223509341478,
0.00017428223509341478,
0.00017428223509341478,
0.00017428223509341478,
0
] |
{
"id": 0,
"code_window": [
" const { id: storyId, args } = useStoryContext();\n",
"\n",
" const updateArgs = useCallback(\n",
" (newArgs: Args) => channel.emit(UPDATE_STORY_ARGS, storyId, newArgs),\n",
" [channel, storyId]\n",
" );\n",
"\n",
" return [args, updateArgs];\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" (updatedArgs: Args) => channel.emit(UPDATE_STORY_ARGS, { storyId, updatedArgs }),\n"
],
"file_path": "lib/addons/src/hooks.ts",
"type": "replace",
"edit_start_line_idx": 409
} | import createChannel from '@storybook/channel-postmessage';
import { toId } from '@storybook/csf';
import addons, { mockChannel } from '@storybook/addons';
import Events from '@storybook/core-events';
import store2 from 'store2';
import StoryStore from './story_store';
import { defaultDecorateStory } from './decorators';
jest.mock('@storybook/node-logger', () => ({
logger: {
info: jest.fn(),
warn: jest.fn(),
error: jest.fn(),
},
}));
jest.mock('store2');
let channel;
beforeEach(() => {
channel = createChannel({ page: 'preview' });
});
function addReverseSorting(store) {
store.addGlobalMetadata({
decorators: [],
parameters: {
options: {
// Test function does reverse alphabetical ordering.
storySort: (a: any, b: any): number =>
a[1].kind === b[1].kind
? 0
: -1 * a[1].id.localeCompare(b[1].id, undefined, { numeric: true }),
},
},
});
}
// make a story and add it to the store
const addStoryToStore = (store, kind, name, storyFn, parameters = {}) =>
store.addStory(
{
kind,
name,
storyFn,
parameters,
id: toId(kind, name),
},
{
applyDecorators: defaultDecorateStory,
}
);
describe('preview.story_store', () => {
describe('extract', () => {
it('produces stories objects with inherited (denormalized) metadata', () => {
const store = new StoryStore({ channel });
store.addGlobalMetadata({ parameters: { global: 'global' }, decorators: [] });
store.addKindMetadata('a', { parameters: { kind: 'kind' }, decorators: [] });
addStoryToStore(store, 'a', '1', () => 0, { story: 'story' });
addStoryToStore(store, 'a', '2', () => 0);
addStoryToStore(store, 'b', '1', () => 0);
const extracted = store.extract();
// We need exact key ordering, even if in theory JS doesn't guarantee it
expect(Object.keys(extracted)).toEqual(['a--1', 'a--2', 'b--1']);
// content of item should be correct
expect(extracted['a--1']).toMatchObject({
id: 'a--1',
kind: 'a',
name: '1',
parameters: { global: 'global', kind: 'kind', story: 'story' },
});
});
});
describe('getDataForManager', () => {
it('produces stories objects with normalized metadata', () => {
const store = new StoryStore({ channel });
store.addGlobalMetadata({ parameters: { global: 'global' }, decorators: [] });
store.addKindMetadata('a', { parameters: { kind: 'kind' }, decorators: [] });
addStoryToStore(store, 'a', '1', () => 0, { story: 'story' });
const { v, globalParameters, kindParameters, stories } = store.getDataForManager();
expect(v).toBe(2);
expect(globalParameters).toEqual({ global: 'global' });
expect(Object.keys(kindParameters)).toEqual(['a']);
expect(kindParameters.a).toEqual({ kind: 'kind' });
expect(Object.keys(stories)).toEqual(['a--1']);
expect(stories['a--1']).toMatchObject({
id: 'a--1',
kind: 'a',
name: '1',
parameters: { story: 'story' },
});
});
});
describe('getRawStory', () => {
it('produces a story with inherited decorators applied', () => {
const store = new StoryStore({ channel });
const globalDecorator = jest.fn().mockImplementation((s) => s());
store.addGlobalMetadata({ parameters: {}, decorators: [globalDecorator] });
const kindDecorator = jest.fn().mockImplementation((s) => s());
store.addKindMetadata('a', { parameters: {}, decorators: [kindDecorator] });
const story = jest.fn();
addStoryToStore(store, 'a', '1', story);
const { getDecorated } = store.getRawStory('a', '1');
getDecorated()();
expect(globalDecorator).toHaveBeenCalled();
expect(kindDecorator).toHaveBeenCalled();
expect(story).toHaveBeenCalled();
});
});
describe('args', () => {
it('is initialized to the value stored in parameters.args[name] || parameters.argType[name].defaultValue', () => {
const store = new StoryStore({ channel });
addStoryToStore(store, 'a', '1', () => 0, {
argTypes: {
arg1: { defaultValue: 'arg1' },
arg2: { defaultValue: 2 },
arg3: { defaultValue: { complex: { object: ['type'] } } },
arg4: {},
arg5: {},
},
args: {
arg2: 3,
arg4: 'foo',
arg6: false,
},
});
expect(store.getRawStory('a', '1').args).toEqual({
arg1: 'arg1',
arg2: 3,
arg3: { complex: { object: ['type'] } },
arg4: 'foo',
arg6: false,
});
});
it('updateStoryArgs changes the args of a story, per-key', () => {
const store = new StoryStore({ channel });
addStoryToStore(store, 'a', '1', () => 0);
expect(store.getRawStory('a', '1').args).toEqual({});
store.updateStoryArgs('a--1', { foo: 'bar' });
expect(store.getRawStory('a', '1').args).toEqual({ foo: 'bar' });
store.updateStoryArgs('a--1', { baz: 'bing' });
expect(store.getRawStory('a', '1').args).toEqual({ foo: 'bar', baz: 'bing' });
});
it('is passed to the story in the context', () => {
const storyFn = jest.fn();
const store = new StoryStore({ channel });
addStoryToStore(store, 'a', '1', storyFn, { passArgsFirst: false });
store.updateStoryArgs('a--1', { foo: 'bar' });
store.getRawStory('a', '1').storyFn();
expect(storyFn).toHaveBeenCalledWith(
expect.objectContaining({
args: { foo: 'bar' },
})
);
});
it('updateStoryArgs emits STORY_ARGS_UPDATED', () => {
const onArgsChangedChannel = jest.fn();
const testChannel = mockChannel();
testChannel.on(Events.STORY_ARGS_UPDATED, onArgsChangedChannel);
const store = new StoryStore({ channel: testChannel });
addStoryToStore(store, 'a', '1', () => 0);
store.updateStoryArgs('a--1', { foo: 'bar' });
expect(onArgsChangedChannel).toHaveBeenCalledWith('a--1', { foo: 'bar' });
store.updateStoryArgs('a--1', { baz: 'bing' });
expect(onArgsChangedChannel).toHaveBeenCalledWith('a--1', { foo: 'bar', baz: 'bing' });
});
it('should update if the UPDATE_STORY_ARGS event is received', () => {
const testChannel = mockChannel();
const store = new StoryStore({ channel: testChannel });
addStoryToStore(store, 'a', '1', () => 0);
testChannel.emit(Events.UPDATE_STORY_ARGS, 'a--1', { foo: 'bar' });
expect(store.getRawStory('a', '1').args).toEqual({ foo: 'bar' });
});
it('passes args as the first argument to the story if `parameters.passArgsFirst` is true', () => {
const store = new StoryStore({ channel });
store.addKindMetadata('a', {
parameters: {
argTypes: {
a: { defaultValue: 1 },
},
},
decorators: [],
});
const storyOne = jest.fn();
addStoryToStore(store, 'a', '1', storyOne, { passArgsFirst: false });
store.getRawStory('a', '1').storyFn();
expect(storyOne).toHaveBeenCalledWith(
expect.objectContaining({
args: { a: 1 },
parameters: expect.objectContaining({}),
})
);
const storyTwo = jest.fn();
addStoryToStore(store, 'a', '2', storyTwo, { passArgsFirst: true });
store.getRawStory('a', '2').storyFn();
expect(storyTwo).toHaveBeenCalledWith(
{ a: 1 },
expect.objectContaining({
args: { a: 1 },
parameters: expect.objectContaining({}),
})
);
});
});
describe('globals', () => {
it('is initialized to the value stored in parameters.globals on the first story', () => {
const store = new StoryStore({ channel });
store.addGlobalMetadata({
decorators: [],
parameters: {
globals: {
arg1: 'arg1',
arg2: 2,
arg3: { complex: { object: ['type'] } },
},
},
});
addStoryToStore(store, 'a', '1', () => 0);
store.finishConfiguring();
expect(store.getRawStory('a', '1').globals).toEqual({
arg1: 'arg1',
arg2: 2,
arg3: { complex: { object: ['type'] } },
});
});
it('is initialized to the default values stored in parameters.globalsTypes on the first story', () => {
const store = new StoryStore({ channel });
store.addGlobalMetadata({
decorators: [],
parameters: {
globals: {
arg1: 'arg1',
arg2: 2,
},
globalTypes: {
arg2: { defaultValue: 'arg2' },
arg3: { defaultValue: { complex: { object: ['type'] } } },
},
},
});
addStoryToStore(store, 'a', '1', () => 0);
store.finishConfiguring();
expect(store.getRawStory('a', '1').globals).toEqual({
// NOTE: we keep arg1, even though it doesn't have a globalArgType
arg1: 'arg1',
arg2: 2,
arg3: { complex: { object: ['type'] } },
});
});
it('it sets session storage on initialization', () => {
(store2.session.set as any).mockClear();
const store = new StoryStore({ channel });
addStoryToStore(store, 'a', '1', () => 0);
store.finishConfiguring();
expect(store2.session.set).toHaveBeenCalled();
});
it('on HMR it sensibly re-initializes with memory', () => {
const store = new StoryStore({ channel });
addons.setChannel(channel);
store.addGlobalMetadata({
decorators: [],
parameters: {
globals: {
arg1: 'arg1',
arg2: 2,
arg4: 4,
},
globalTypes: {
arg2: { defaultValue: 'arg2' },
arg3: { defaultValue: { complex: { object: ['type'] } } },
arg4: {},
},
},
});
addStoryToStore(store, 'a', '1', () => 0);
store.finishConfiguring();
expect(store.getRawStory('a', '1').globals).toEqual({
// We keep arg1, even though it doesn't have a globalArgType, as it is set in globals
arg1: 'arg1',
// We use the value of arg2 that was set in globals
arg2: 2,
arg3: { complex: { object: ['type'] } },
arg4: 4,
});
// HMR
store.startConfiguring();
store.addGlobalMetadata({
decorators: [],
parameters: {
globals: {
arg2: 3,
},
globalTypes: {
arg2: { defaultValue: 'arg2' },
arg3: { defautlValue: { complex: { object: ['changed'] } } },
// XXX: note this currently wouldn't fail because parameters.globals.arg4 isn't cleared
// due to #10005, see below
arg4: {}, // has no default value set but we need to make sure we don't lose it
arg5: { defaultValue: 'new' },
},
},
});
store.finishConfiguring();
expect(store.getRawStory('a', '1').globals).toEqual({
// You cannot remove a global arg in HMR currently, because you cannot remove the
// parameter (see https://github.com/storybookjs/storybook/issues/10005)
arg1: 'arg1',
// We should keep the previous values because we cannot tell if the user changed it or not in the UI
// and we don't want to revert to the defaults every HMR
arg2: 2,
arg3: { complex: { object: ['type'] } },
arg4: 4,
// We take the new value here as it wasn't defined before
arg5: 'new',
});
});
it('it sensibly re-initializes with memory based on session storage', () => {
(store2.session.get as any).mockReturnValueOnce({
globals: {
arg1: 'arg1',
arg2: 2,
arg3: { complex: { object: ['type'] } },
arg4: 4,
},
});
const store = new StoryStore({ channel });
addons.setChannel(channel);
addStoryToStore(store, 'a', '1', () => 0);
store.addGlobalMetadata({
decorators: [],
parameters: {
globals: {
arg2: 3,
},
globalTypes: {
arg2: { defaultValue: 'arg2' },
arg3: { defaultValue: { complex: { object: ['changed'] } } },
arg4: {}, // has no default value set but we need to make sure we don't lose it
arg5: { defaultValue: 'new' },
},
},
});
store.finishConfiguring();
expect(store.getRawStory('a', '1').globals).toEqual({
// We should keep the previous values because we cannot tell if the user changed it or not in the UI
// and we don't want to revert to the defaults every HMR
arg2: 2,
arg3: { complex: { object: ['type'] } },
arg4: 4,
// We take the new value here as it wasn't defined before
arg5: 'new',
});
});
it('updateGlobals changes the global args', () => {
const store = new StoryStore({ channel });
addStoryToStore(store, 'a', '1', () => 0);
expect(store.getRawStory('a', '1').globals).toEqual({});
store.updateGlobals({ foo: 'bar' });
expect(store.getRawStory('a', '1').globals).toEqual({ foo: 'bar' });
store.updateGlobals({ baz: 'bing' });
expect(store.getRawStory('a', '1').globals).toEqual({ foo: 'bar', baz: 'bing' });
});
it('updateGlobals sets session storage', () => {
const store = new StoryStore({ channel });
addStoryToStore(store, 'a', '1', () => 0);
(store2.session.set as any).mockClear();
store.updateGlobals({ foo: 'bar' });
expect(store2.session.set).toHaveBeenCalled();
});
it('is passed to the story in the context', () => {
const storyFn = jest.fn();
const store = new StoryStore({ channel });
store.updateGlobals({ foo: 'bar' });
addStoryToStore(store, 'a', '1', storyFn, { passArgsFirst: false });
store.getRawStory('a', '1').storyFn();
expect(storyFn).toHaveBeenCalledWith(
expect.objectContaining({
globals: { foo: 'bar' },
})
);
store.updateGlobals({ baz: 'bing' });
store.getRawStory('a', '1').storyFn();
expect(storyFn).toHaveBeenCalledWith(
expect.objectContaining({
globals: { foo: 'bar', baz: 'bing' },
})
);
});
it('updateGlobals emits GLOBALS_UPDATED', () => {
const onGlobalsChangedChannel = jest.fn();
const testChannel = mockChannel();
testChannel.on(Events.GLOBALS_UPDATED, onGlobalsChangedChannel);
const store = new StoryStore({ channel: testChannel });
addStoryToStore(store, 'a', '1', () => 0);
store.updateGlobals({ foo: 'bar' });
expect(onGlobalsChangedChannel).toHaveBeenCalledWith({ foo: 'bar' });
store.updateGlobals({ baz: 'bing' });
expect(onGlobalsChangedChannel).toHaveBeenCalledWith({ foo: 'bar', baz: 'bing' });
});
it('should update if the UPDATE_GLOBALS event is received', () => {
const testChannel = mockChannel();
const store = new StoryStore({ channel: testChannel });
addStoryToStore(store, 'a', '1', () => 0);
testChannel.emit(Events.UPDATE_GLOBALS, { foo: 'bar' });
expect(store.getRawStory('a', '1').globals).toEqual({ foo: 'bar' });
});
it('DOES NOT pass globals as the first argument to the story if `parameters.passArgsFirst` is true', () => {
const store = new StoryStore({ channel });
const storyOne = jest.fn();
addStoryToStore(store, 'a', '1', storyOne, { passArgsFirst: false });
store.updateGlobals({ foo: 'bar' });
store.getRawStory('a', '1').storyFn();
expect(storyOne).toHaveBeenCalledWith(
expect.objectContaining({
globals: { foo: 'bar' },
})
);
const storyTwo = jest.fn();
addStoryToStore(store, 'a', '2', storyTwo, { passArgsFirst: true });
store.getRawStory('a', '2').storyFn();
expect(storyTwo).toHaveBeenCalledWith(
{},
expect.objectContaining({
globals: { foo: 'bar' },
})
);
});
});
describe('argTypesEnhancer', () => {
it('allows you to alter argTypes when stories are added', () => {
const store = new StoryStore({ channel });
const enhancer = jest.fn((context) => ({ ...context.parameters.argTypes, c: 'd' }));
store.addArgTypesEnhancer(enhancer);
addStoryToStore(store, 'a', '1', () => 0, { argTypes: { a: 'b' } });
expect(enhancer).toHaveBeenCalledWith(
expect.objectContaining({ parameters: { argTypes: { a: 'b' } } })
);
expect(store.getRawStory('a', '1').parameters.argTypes).toEqual({ a: 'b', c: 'd' });
});
it('recursively passes argTypes to successive enhancers', () => {
const store = new StoryStore({ channel });
const firstEnhancer = jest.fn((context) => ({ ...context.parameters.argTypes, c: 'd' }));
store.addArgTypesEnhancer(firstEnhancer);
const secondEnhancer = jest.fn((context) => ({ ...context.parameters.argTypes, e: 'f' }));
store.addArgTypesEnhancer(secondEnhancer);
addStoryToStore(store, 'a', '1', () => 0, { argTypes: { a: 'b' } });
expect(firstEnhancer).toHaveBeenCalledWith(
expect.objectContaining({ parameters: { argTypes: { a: 'b' } } })
);
expect(secondEnhancer).toHaveBeenCalledWith(
expect.objectContaining({ parameters: { argTypes: { a: 'b', c: 'd' } } })
);
expect(store.getRawStory('a', '1').parameters.argTypes).toEqual({ a: 'b', c: 'd', e: 'f' });
});
it('does not merge argType enhancer results', () => {
const store = new StoryStore({ channel });
const enhancer = jest.fn().mockReturnValue({ c: 'd' });
store.addArgTypesEnhancer(enhancer);
addStoryToStore(store, 'a', '1', () => 0, { argTypes: { a: 'b' } });
expect(enhancer).toHaveBeenCalledWith(
expect.objectContaining({ parameters: { argTypes: { a: 'b' } } })
);
expect(store.getRawStory('a', '1').parameters.argTypes).toEqual({ c: 'd' });
});
it('allows you to alter argTypes when stories are re-added', () => {
const store = new StoryStore({ channel });
addons.setChannel(channel);
const enhancer = jest.fn((context) => ({ ...context.parameters.argTypes, c: 'd' }));
store.addArgTypesEnhancer(enhancer);
addStoryToStore(store, 'a', '1', () => 0, { argTypes: { a: 'b' } });
enhancer.mockClear();
store.removeStoryKind('a');
addStoryToStore(store, 'a', '1', () => 0, { argTypes: { e: 'f' } });
expect(enhancer).toHaveBeenCalledWith(
expect.objectContaining({ parameters: { argTypes: { e: 'f' } } })
);
expect(store.getRawStory('a', '1').parameters.argTypes).toEqual({ e: 'f', c: 'd' });
});
});
describe('selection specifiers', () => {
describe('if you use *', () => {
it('selects the first story in the store', () => {
const store = new StoryStore({ channel });
store.setSelectionSpecifier({ storySpecifier: '*', viewMode: 'story' });
addStoryToStore(store, 'a', '1', () => 0);
addStoryToStore(store, 'a', '2', () => 0);
addStoryToStore(store, 'b', '1', () => 0);
store.finishConfiguring();
expect(store.getSelection()).toEqual({ storyId: 'a--1', viewMode: 'story' });
});
it('takes into account sorting', () => {
const store = new StoryStore({ channel });
store.setSelectionSpecifier({ storySpecifier: '*', viewMode: 'story' });
addReverseSorting(store);
addStoryToStore(store, 'a', '1', () => 0);
addStoryToStore(store, 'a', '2', () => 0);
addStoryToStore(store, 'b', '1', () => 0);
store.finishConfiguring();
expect(store.getSelection()).toEqual({ storyId: 'b--1', viewMode: 'story' });
});
it('selects nothing if there are no stories', () => {
const store = new StoryStore({ channel });
store.setSelectionSpecifier({ storySpecifier: '*', viewMode: 'story' });
store.finishConfiguring();
expect(store.getSelection()).toEqual(undefined);
});
});
describe('if you use a component or group id', () => {
it('selects the first story for the component', () => {
const store = new StoryStore({ channel });
store.setSelectionSpecifier({ storySpecifier: 'b', viewMode: 'story' });
addStoryToStore(store, 'a', '1', () => 0);
addStoryToStore(store, 'a', '2', () => 0);
addStoryToStore(store, 'b', '1', () => 0);
store.finishConfiguring();
expect(store.getSelection()).toEqual({ storyId: 'b--1', viewMode: 'story' });
});
it('selects the first story for the group', () => {
const store = new StoryStore({ channel });
store.setSelectionSpecifier({ storySpecifier: 'g2', viewMode: 'story' });
addStoryToStore(store, 'g1/a', '1', () => 0);
addStoryToStore(store, 'g2/a', '1', () => 0);
addStoryToStore(store, 'g2/b', '1', () => 0);
store.finishConfiguring();
expect(store.getSelection()).toEqual({ storyId: 'g2-a--1', viewMode: 'story' });
});
it('selects nothing if the component or group does not exist', () => {
const store = new StoryStore({ channel });
store.setSelectionSpecifier({ storySpecifier: 'c', viewMode: 'story' });
addStoryToStore(store, 'a', '1', () => 0);
addStoryToStore(store, 'a', '2', () => 0);
addStoryToStore(store, 'b', '1', () => 0);
store.finishConfiguring();
expect(store.getSelection()).toEqual(undefined);
});
});
describe('if you use a storyId', () => {
it('selects a specific story', () => {
const store = new StoryStore({ channel });
store.setSelectionSpecifier({ storySpecifier: 'a--2', viewMode: 'story' });
addStoryToStore(store, 'a', '1', () => 0);
addStoryToStore(store, 'a', '2', () => 0);
addStoryToStore(store, 'b', '1', () => 0);
store.finishConfiguring();
expect(store.getSelection()).toEqual({ storyId: 'a--2', viewMode: 'story' });
});
it('selects nothing if you the story does not exist', () => {
const store = new StoryStore({ channel });
store.setSelectionSpecifier({ storySpecifier: 'a--3', viewMode: 'story' });
addStoryToStore(store, 'a', '1', () => 0);
addStoryToStore(store, 'a', '2', () => 0);
addStoryToStore(store, 'b', '1', () => 0);
store.finishConfiguring();
expect(store.getSelection()).toEqual(undefined);
});
});
describe('if you use no specifier', () => {
it('selects nothing', () => {
const store = new StoryStore({ channel });
addStoryToStore(store, 'a', '1', () => 0);
addStoryToStore(store, 'a', '2', () => 0);
addStoryToStore(store, 'b', '1', () => 0);
store.finishConfiguring();
expect(store.getSelection()).toEqual(undefined);
});
});
describe('HMR behaviour', () => {
it('retains successful selection', () => {
const store = new StoryStore({ channel });
store.setSelectionSpecifier({ storySpecifier: 'a--1', viewMode: 'story' });
addStoryToStore(store, 'a', '1', () => 0);
store.finishConfiguring();
expect(store.getSelection()).toEqual({ storyId: 'a--1', viewMode: 'story' });
store.startConfiguring();
store.removeStoryKind('a');
addStoryToStore(store, 'a', '1', () => 0);
store.finishConfiguring();
expect(store.getSelection()).toEqual({ storyId: 'a--1', viewMode: 'story' });
});
it('tries again with a specifier if it failed the first time', () => {
const store = new StoryStore({ channel });
store.setSelectionSpecifier({ storySpecifier: 'a--2', viewMode: 'story' });
addStoryToStore(store, 'a', '1', () => 0);
store.finishConfiguring();
expect(store.getSelection()).toEqual(undefined);
store.startConfiguring();
store.removeStoryKind('a');
addStoryToStore(store, 'a', '1', () => 0);
addStoryToStore(store, 'a', '2', () => 0);
store.finishConfiguring();
expect(store.getSelection()).toEqual({ storyId: 'a--2', viewMode: 'story' });
});
it('DOES NOT try again if the selection changed in the meantime', () => {
const store = new StoryStore({ channel });
store.setSelectionSpecifier({ storySpecifier: 'a--2', viewMode: 'story' });
addStoryToStore(store, 'a', '1', () => 0);
store.finishConfiguring();
expect(store.getSelection()).toEqual(undefined);
store.setSelection({ storyId: 'a--1', viewMode: 'story' });
expect(store.getSelection()).toEqual({ storyId: 'a--1', viewMode: 'story' });
store.startConfiguring();
store.removeStoryKind('a');
addStoryToStore(store, 'a', '1', () => 0);
addStoryToStore(store, 'a', '2', () => 0);
store.finishConfiguring();
expect(store.getSelection()).toEqual({ storyId: 'a--1', viewMode: 'story' });
});
});
});
describe('storySort', () => {
it('sorts stories using given function', () => {
const store = new StoryStore({ channel });
addReverseSorting(store);
addStoryToStore(store, 'a/a', '1', () => 0);
addStoryToStore(store, 'a/a', '2', () => 0);
addStoryToStore(store, 'a/b', '1', () => 0);
addStoryToStore(store, 'b/b1', '1', () => 0);
addStoryToStore(store, 'b/b10', '1', () => 0);
addStoryToStore(store, 'b/b9', '1', () => 0);
addStoryToStore(store, 'c', '1', () => 0);
const extracted = store.extract();
expect(Object.keys(extracted)).toEqual([
'c--1',
'b-b10--1',
'b-b9--1',
'b-b1--1',
'a-b--1',
'a-a--1',
'a-a--2',
]);
});
it('sorts stories alphabetically', () => {
const store = new StoryStore({ channel });
store.addGlobalMetadata({
decorators: [],
parameters: {
options: {
storySort: {
method: 'alphabetical',
},
},
},
});
addStoryToStore(store, 'a/b', '1', () => 0);
addStoryToStore(store, 'a/a', '2', () => 0);
addStoryToStore(store, 'a/a', '1', () => 0);
addStoryToStore(store, 'c', '1', () => 0);
addStoryToStore(store, 'b/b10', '1', () => 0);
addStoryToStore(store, 'b/b9', '1', () => 0);
addStoryToStore(store, 'b/b1', '1', () => 0);
const extracted = store.extract();
expect(Object.keys(extracted)).toEqual([
'a-a--2',
'a-a--1',
'a-b--1',
'b-b1--1',
'b-b9--1',
'b-b10--1',
'c--1',
]);
});
it('sorts stories in specified order or alphabetically', () => {
const store = new StoryStore({ channel });
store.addGlobalMetadata({
decorators: [],
parameters: {
options: {
storySort: {
method: 'alphabetical',
order: ['b', ['bc', 'ba', 'bb'], 'a', 'c'],
},
},
},
});
addStoryToStore(store, 'a/b', '1', () => 0);
addStoryToStore(store, 'a', '1', () => 0);
addStoryToStore(store, 'c', '1', () => 0);
addStoryToStore(store, 'b/bd', '1', () => 0);
addStoryToStore(store, 'b/bb', '1', () => 0);
addStoryToStore(store, 'b/ba', '1', () => 0);
addStoryToStore(store, 'b/bc', '1', () => 0);
addStoryToStore(store, 'b', '1', () => 0);
const extracted = store.extract();
expect(Object.keys(extracted)).toEqual([
'b--1',
'b-bc--1',
'b-ba--1',
'b-bb--1',
'b-bd--1',
'a--1',
'a-b--1',
'c--1',
]);
});
it('sorts stories in specified order or by configure order', () => {
const store = new StoryStore({ channel });
store.addGlobalMetadata({
decorators: [],
parameters: {
options: {
storySort: {
method: 'configure',
order: ['b', 'a', 'c'],
},
},
},
});
addStoryToStore(store, 'a/b', '1', () => 0);
addStoryToStore(store, 'a', '1', () => 0);
addStoryToStore(store, 'c', '1', () => 0);
addStoryToStore(store, 'b/bd', '1', () => 0);
addStoryToStore(store, 'b/bb', '1', () => 0);
addStoryToStore(store, 'b/ba', '1', () => 0);
addStoryToStore(store, 'b/bc', '1', () => 0);
addStoryToStore(store, 'b', '1', () => 0);
const extracted = store.extract();
expect(Object.keys(extracted)).toEqual([
'b--1',
'b-bd--1',
'b-bb--1',
'b-ba--1',
'b-bc--1',
'a--1',
'a-b--1',
'c--1',
]);
});
});
describe('configuration', () => {
it('does not allow addStory if not configuring, unless allowUsafe=true', () => {
const store = new StoryStore({ channel });
store.finishConfiguring();
expect(() => addStoryToStore(store, 'a', '1', () => 0)).toThrow(
'Cannot add a story when not configuring'
);
expect(() =>
store.addStory(
{
kind: 'a',
name: '1',
storyFn: () => 0,
parameters: {},
id: 'a--1',
},
{
applyDecorators: defaultDecorateStory,
allowUnsafe: true,
}
)
).not.toThrow();
});
it('does not allow remove if not configuring, unless allowUsafe=true', () => {
const store = new StoryStore({ channel });
addons.setChannel(channel);
addStoryToStore(store, 'a', '1', () => 0);
store.finishConfiguring();
expect(() => store.remove('a--1')).toThrow('Cannot remove a story when not configuring');
expect(() => store.remove('a--1', { allowUnsafe: true })).not.toThrow();
});
it('does not allow removeStoryKind if not configuring, unless allowUsafe=true', () => {
const store = new StoryStore({ channel });
addons.setChannel(channel);
addStoryToStore(store, 'a', '1', () => 0);
store.finishConfiguring();
expect(() => store.removeStoryKind('a')).toThrow('Cannot remove a kind when not configuring');
expect(() => store.removeStoryKind('a', { allowUnsafe: true })).not.toThrow();
});
it('waits for configuration to be over before emitting SET_STORIES', () => {
const onSetStories = jest.fn();
channel.on(Events.SET_STORIES, onSetStories);
const store = new StoryStore({ channel });
addStoryToStore(store, 'a', '1', () => 0);
expect(onSetStories).not.toHaveBeenCalled();
store.finishConfiguring();
expect(onSetStories).toHaveBeenCalledWith({
v: 2,
globals: {},
globalParameters: {},
kindParameters: { a: {} },
stories: {
'a--1': expect.objectContaining({
id: 'a--1',
}),
},
});
});
it('correctly emits globals with SET_STORIES', () => {
const onSetStories = jest.fn();
channel.on(Events.SET_STORIES, onSetStories);
const store = new StoryStore({ channel });
store.addGlobalMetadata({
decorators: [],
parameters: {
globalTypes: {
arg1: { defaultValue: 'arg1' },
},
},
});
addStoryToStore(store, 'a', '1', () => 0);
expect(onSetStories).not.toHaveBeenCalled();
store.finishConfiguring();
expect(onSetStories).toHaveBeenCalledWith({
v: 2,
globals: { arg1: 'arg1' },
globalParameters: {
// NOTE: Currently globalArg[Types] are emitted as parameters but this may not remain
globalTypes: {
arg1: { defaultValue: 'arg1' },
},
},
kindParameters: { a: {} },
stories: {
'a--1': expect.objectContaining({
id: 'a--1',
}),
},
});
});
it('emits an empty SET_STORIES if no stories were added during configuration', () => {
const onSetStories = jest.fn();
channel.on(Events.SET_STORIES, onSetStories);
const store = new StoryStore({ channel });
store.finishConfiguring();
expect(onSetStories).toHaveBeenCalledWith({
v: 2,
globals: {},
globalParameters: {},
kindParameters: {},
stories: {},
});
});
it('allows configuration as second time (HMR)', () => {
const onSetStories = jest.fn();
channel.on(Events.SET_STORIES, onSetStories);
const store = new StoryStore({ channel });
store.finishConfiguring();
onSetStories.mockClear();
store.startConfiguring();
addStoryToStore(store, 'a', '1', () => 0);
store.finishConfiguring();
expect(onSetStories).toHaveBeenCalledWith({
v: 2,
globals: {},
globalParameters: {},
kindParameters: { a: {} },
stories: {
'a--1': expect.objectContaining({
id: 'a--1',
}),
},
});
});
});
describe('HMR behaviour', () => {
it('emits the right things after removing a story', () => {
const onSetStories = jest.fn();
channel.on(Events.SET_STORIES, onSetStories);
const store = new StoryStore({ channel });
// For hooks
addons.setChannel(channel);
store.startConfiguring();
addStoryToStore(store, 'kind-1', 'story-1.1', () => 0);
addStoryToStore(store, 'kind-1', 'story-1.2', () => 0);
store.finishConfiguring();
onSetStories.mockClear();
store.startConfiguring();
store.remove(toId('kind-1', 'story-1.1'));
store.finishConfiguring();
expect(onSetStories).toHaveBeenCalledWith({
v: 2,
globals: {},
globalParameters: {},
kindParameters: { 'kind-1': {} },
stories: {
'kind-1--story-1-2': expect.objectContaining({
id: 'kind-1--story-1-2',
}),
},
});
expect(store.fromId(toId('kind-1', 'story-1.1'))).toBeFalsy();
expect(store.fromId(toId('kind-1', 'story-1.2'))).toBeTruthy();
});
it('emits the right things after removing a kind', () => {
const onSetStories = jest.fn();
channel.on(Events.SET_STORIES, onSetStories);
const store = new StoryStore({ channel });
// For hooks
addons.setChannel(channel);
store.startConfiguring();
addStoryToStore(store, 'kind-1', 'story-1.1', () => 0);
addStoryToStore(store, 'kind-1', 'story-1.2', () => 0);
addStoryToStore(store, 'kind-2', 'story-2.1', () => 0);
addStoryToStore(store, 'kind-2', 'story-2.2', () => 0);
store.finishConfiguring();
onSetStories.mockClear();
store.startConfiguring();
store.removeStoryKind('kind-1');
store.finishConfiguring();
expect(onSetStories).toHaveBeenCalledWith({
v: 2,
globals: {},
globalParameters: {},
kindParameters: { 'kind-1': {}, 'kind-2': {} },
stories: {
'kind-2--story-2-1': expect.objectContaining({
id: 'kind-2--story-2-1',
}),
'kind-2--story-2-2': expect.objectContaining({
id: 'kind-2--story-2-2',
}),
},
});
expect(store.fromId(toId('kind-1', 'story-1.1'))).toBeFalsy();
expect(store.fromId(toId('kind-2', 'story-2.1'))).toBeTruthy();
});
// eslint-disable-next-line jest/expect-expect
it('should not error even if you remove a kind that does not exist', () => {
const store = new StoryStore({ channel });
store.removeStoryKind('kind');
});
});
describe('CURRENT_STORY_WAS_SET', () => {
it('is emitted when configuration ends', () => {
const onCurrentStoryWasSet = jest.fn();
channel.on(Events.CURRENT_STORY_WAS_SET, onCurrentStoryWasSet);
const store = new StoryStore({ channel });
store.finishConfiguring();
expect(onCurrentStoryWasSet).toHaveBeenCalled();
});
it('is emitted when setSelection is called', () => {
const onCurrentStoryWasSet = jest.fn();
channel.on(Events.CURRENT_STORY_WAS_SET, onCurrentStoryWasSet);
const store = new StoryStore({ channel });
store.finishConfiguring();
onCurrentStoryWasSet.mockClear();
store.setSelection({ storyId: 'a--1', viewMode: 'story' });
expect(onCurrentStoryWasSet).toHaveBeenCalled();
});
});
});
| lib/client-api/src/story_store.test.ts | 1 | https://github.com/storybookjs/storybook/commit/962ab44d1155bfc8707695757726149be8713760 | [
0.9206730723381042,
0.008587050251662731,
0.00016303943993989378,
0.00020081880211364478,
0.08657410740852356
] |
{
"id": 0,
"code_window": [
" const { id: storyId, args } = useStoryContext();\n",
"\n",
" const updateArgs = useCallback(\n",
" (newArgs: Args) => channel.emit(UPDATE_STORY_ARGS, storyId, newArgs),\n",
" [channel, storyId]\n",
" );\n",
"\n",
" return [args, updateArgs];\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" (updatedArgs: Args) => channel.emit(UPDATE_STORY_ARGS, { storyId, updatedArgs }),\n"
],
"file_path": "lib/addons/src/hooks.ts",
"type": "replace",
"edit_start_line_idx": 409
} | {
"title": "Welcome",
"stories": [
{
"name": "Welcome",
"parameters": {
"server": {
"id": "welcome/welcome"
}
}
}
]
}
| examples/server-kitchen-sink/stories/welcome.stories.json | 0 | https://github.com/storybookjs/storybook/commit/962ab44d1155bfc8707695757726149be8713760 | [
0.00017896926146931946,
0.0001788539666449651,
0.00017873867182061076,
0.0001788539666449651,
1.1529482435435057e-7
] |
{
"id": 0,
"code_window": [
" const { id: storyId, args } = useStoryContext();\n",
"\n",
" const updateArgs = useCallback(\n",
" (newArgs: Args) => channel.emit(UPDATE_STORY_ARGS, storyId, newArgs),\n",
" [channel, storyId]\n",
" );\n",
"\n",
" return [args, updateArgs];\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" (updatedArgs: Args) => channel.emit(UPDATE_STORY_ARGS, { storyId, updatedArgs }),\n"
],
"file_path": "lib/addons/src/hooks.ts",
"type": "replace",
"edit_start_line_idx": 409
} | // Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`mdx-to-csf transforms correctly using "story-refs.input.js" data 1`] = `
"import React from 'react';
import { action } from '@storybook/addon-actions';
import { Button } from '@storybook/react/demo';
export default {
title: 'Addons|Docs/mdx',
component: Button,
decorators: [
(storyFn) => (
<div
style={{
backgroundColor: 'yellow',
}}
>
{storyFn()}
</div>
),
],
parameters: {
notes: 'component notes',
},
};
export const SoloStory = () => <Button onClick={action('clicked')}>solo</Button>;
SoloStory.story = {
name: 'solo story',
};"
`;
| lib/codemod/src/transforms/__testfixtures__/mdx-to-csf/story-refs.output.snapshot | 0 | https://github.com/storybookjs/storybook/commit/962ab44d1155bfc8707695757726149be8713760 | [
0.0001753583928802982,
0.00017112589557655156,
0.00016578535723965615,
0.00017167993064504117,
0.000003483716454866226
] |
{
"id": 0,
"code_window": [
" const { id: storyId, args } = useStoryContext();\n",
"\n",
" const updateArgs = useCallback(\n",
" (newArgs: Args) => channel.emit(UPDATE_STORY_ARGS, storyId, newArgs),\n",
" [channel, storyId]\n",
" );\n",
"\n",
" return [args, updateArgs];\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" (updatedArgs: Args) => channel.emit(UPDATE_STORY_ARGS, { storyId, updatedArgs }),\n"
],
"file_path": "lib/addons/src/hooks.ts",
"type": "replace",
"edit_start_line_idx": 409
} | import React from 'react';
import { storiesOf } from '@storybook/react';
import { Button } from './Button';
import { Icons } from '../icon/icon';
import { Form } from '../form/index';
const { Button: FormButton } = Form;
storiesOf('Basics/Button', module).add('all buttons', () => (
<div>
<p>Button that is used for forms</p>
<FormButton>Form.Button</FormButton>
<br />
<p>Buttons that are used for everything else</p>
<Button primary>Primary</Button>
<Button secondary>Secondary</Button>
<Button outline containsIcon title="link">
<Icons icon="link" />
</Button>
<br />
<Button outline>Outline</Button>
<Button outline primary>
Outline primary
</Button>
<Button outline secondary>
Outline secondary
</Button>
<Button primary disabled>
Disabled
</Button>
<br />
<Button primary small>
Primary
</Button>
<Button secondary small>
Secondary
</Button>
<Button gray small>
Secondary
</Button>
<Button outline small>
Outline
</Button>
<Button primary disabled small>
Disabled
</Button>
<Button outline small containsIcon title="link">
<Icons icon="link" />
</Button>
<Button outline small>
<Icons icon="link" />
Link
</Button>
</div>
));
| lib/components/src/Button/Button.stories.tsx | 0 | https://github.com/storybookjs/storybook/commit/962ab44d1155bfc8707695757726149be8713760 | [
0.00017840054351836443,
0.00017541808483656496,
0.00017110150656662881,
0.0001754060504026711,
0.0000024193736862798687
] |
{
"id": 1,
"code_window": [
" const data = getCurrentStoryData();\n",
" const args = isStory(data) ? data.args : {};\n",
"\n",
" return [args, (newArgs: Args) => updateStoryArgs(data.id, newArgs)];\n",
"}\n",
"\n",
"export function useGlobals(): [Args, (newGlobals: Args) => void] {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" console.log('in use args');\n",
" return [\n",
" args,\n",
" (newArgs: Args) => {\n",
" console.log('upSArgs');\n",
" updateStoryArgs(data as Story, newArgs);\n",
" },\n",
" ];\n"
],
"file_path": "lib/api/src/index.tsx",
"type": "replace",
"edit_start_line_idx": 417
} | /* eslint no-underscore-dangle: 0 */
import memoize from 'memoizerific';
import dedent from 'ts-dedent';
import stable from 'stable';
import mapValues from 'lodash/mapValues';
import store from 'store2';
import { Channel } from '@storybook/channels';
import Events from '@storybook/core-events';
import { logger } from '@storybook/client-logger';
import {
Comparator,
Parameters,
Args,
LegacyStoryFn,
ArgsStoryFn,
StoryContext,
StoryKind,
} from '@storybook/addons';
import {
DecoratorFunction,
StoryMetadata,
StoreData,
AddStoryArgs,
StoreItem,
PublishedStoreItem,
ErrorLike,
GetStorybookKind,
ArgTypesEnhancer,
StoreSelectionSpecifier,
StoreSelection,
} from './types';
import { HooksContext } from './hooks';
import storySort from './storySort';
import { combineParameters } from './parameters';
interface StoryOptions {
includeDocsOnly?: boolean;
}
type KindMetadata = StoryMetadata & { order: number };
const STORAGE_KEY = '@storybook/preview/store';
const isStoryDocsOnly = (parameters?: Parameters) => {
return parameters && parameters.docsOnly;
};
const includeStory = (story: StoreItem, options: StoryOptions = { includeDocsOnly: false }) => {
if (options.includeDocsOnly) {
return true;
}
return !isStoryDocsOnly(story.parameters);
};
const checkGlobals = (parameters: Parameters) => {
const { globals, globalTypes } = parameters;
if (globals || globalTypes) {
logger.error(
'Global args/argTypes can only be set globally',
JSON.stringify({
globals,
globalTypes,
})
);
}
};
const checkStorySort = (parameters: Parameters) => {
const { options } = parameters;
if (options?.storySort) logger.error('The storySort option parameter can only be set globally');
};
const getSortedStories = memoize(1)(
(storiesData: StoreData, kindOrder: Record<StoryKind, number>, storySortParameter) => {
const stories = Object.entries(storiesData);
if (storySortParameter) {
let sortFn: Comparator<any>;
if (typeof storySortParameter === 'function') {
sortFn = storySortParameter;
} else {
sortFn = storySort(storySortParameter);
}
stable.inplace(stories, sortFn);
} else {
stable.inplace(stories, (s1, s2) => kindOrder[s1[1].kind] - kindOrder[s2[1].kind]);
}
return stories.map(([id, s]) => s);
}
);
interface AllowUnsafeOption {
allowUnsafe?: boolean;
}
const toExtracted = <T>(obj: T) =>
Object.entries(obj).reduce((acc, [key, value]) => {
if (typeof value === 'function') {
return acc;
}
if (key === 'hooks') {
return acc;
}
if (Array.isArray(value)) {
return Object.assign(acc, { [key]: value.slice().sort() });
}
return Object.assign(acc, { [key]: value });
}, {});
export default class StoryStore {
_error?: ErrorLike;
_channel: Channel;
_configuring: boolean;
_globals: Args;
_globalMetadata: StoryMetadata;
// Keyed on kind name
_kinds: Record<string, KindMetadata>;
// Keyed on storyId
_stories: StoreData;
_argTypesEnhancers: ArgTypesEnhancer[];
_selectionSpecifier?: StoreSelectionSpecifier;
_selection?: StoreSelection;
constructor(params: { channel: Channel }) {
// Assume we are configuring until we hear otherwise
this._configuring = true;
// We store global args in session storage. Note that when we finish
// configuring below we will ensure we only use values here that make sense
this._globals = store.session.get(STORAGE_KEY)?.globals || {};
this._globalMetadata = { parameters: {}, decorators: [] };
this._kinds = {};
this._stories = {};
this._argTypesEnhancers = [];
this._error = undefined;
this._channel = params.channel;
this.setupListeners();
}
setupListeners() {
// Channel can be null in StoryShots
if (!this._channel) return;
this._channel.on(Events.SET_CURRENT_STORY, ({ storyId, viewMode }) =>
this.setSelection({ storyId, viewMode })
);
this._channel.on(Events.UPDATE_STORY_ARGS, (id: string, newArgs: Args) =>
this.updateStoryArgs(id, newArgs)
);
this._channel.on(Events.UPDATE_GLOBALS, (newGlobals: Args) => this.updateGlobals(newGlobals));
}
startConfiguring() {
this._configuring = true;
}
storeGlobals() {
// Store the global args on the session
store.session.set(STORAGE_KEY, { globals: this._globals });
}
finishConfiguring() {
this._configuring = false;
const { globals: initialGlobals = {}, globalTypes = {} } = this._globalMetadata.parameters;
const defaultGlobals: Args = Object.entries(
globalTypes as Record<string, { defaultValue: any }>
).reduce((acc, [arg, { defaultValue }]) => {
if (defaultValue) acc[arg] = defaultValue;
return acc;
}, {} as Args);
const allowedGlobals = new Set([...Object.keys(initialGlobals), ...Object.keys(globalTypes)]);
// To deal with HMR & persistence, we consider the previous value of global args, and:
// 1. Remove any keys that are not in the new parameter
// 2. Preference any keys that were already set
// 3. Use any new keys from the new parameter
this._globals = Object.entries(this._globals || {}).reduce(
(acc, [key, previousValue]) => {
if (allowedGlobals.has(key)) acc[key] = previousValue;
return acc;
},
{ ...defaultGlobals, ...initialGlobals }
);
this.storeGlobals();
// Set the current selection based on the current selection specifier, if selection is not yet set
const stories = this.sortedStories();
let foundStory;
if (this._selectionSpecifier && !this._selection) {
const { storySpecifier, viewMode } = this._selectionSpecifier;
if (storySpecifier === '*') {
// '*' means select the first story. If there is none, we have no selection.
[foundStory] = stories;
} else if (typeof storySpecifier === 'string') {
foundStory = Object.values(stories).find((s) => s.id.startsWith(storySpecifier));
} else {
// Try and find a story matching the name/kind, setting no selection if they don't exist.
const { name, kind } = storySpecifier;
foundStory = this.getRawStory(kind, name);
}
if (foundStory) {
this.setSelection({ storyId: foundStory.id, viewMode });
}
}
// If we didn't find a story matching the specifier, we always want to emit CURRENT_STORY_WAS_SET anyway
if (!foundStory && this._channel) {
this._channel.emit(Events.CURRENT_STORY_WAS_SET, this._selection);
}
this.pushToManager();
}
addGlobalMetadata({ parameters, decorators }: StoryMetadata) {
if (parameters) {
const { args, argTypes } = parameters;
if (args || argTypes)
logger.warn(
'Found args/argTypes in global parameters.',
JSON.stringify({ args, argTypes })
);
}
const globalParameters = this._globalMetadata.parameters;
this._globalMetadata.parameters = combineParameters(globalParameters, parameters);
this._globalMetadata.decorators.push(...decorators);
}
clearGlobalDecorators() {
this._globalMetadata.decorators = [];
}
ensureKind(kind: string) {
if (!this._kinds[kind]) {
this._kinds[kind] = {
order: Object.keys(this._kinds).length,
parameters: {},
decorators: [],
};
}
}
addKindMetadata(kind: string, { parameters, decorators }: StoryMetadata) {
this.ensureKind(kind);
if (parameters) {
checkGlobals(parameters);
checkStorySort(parameters);
}
this._kinds[kind].parameters = combineParameters(this._kinds[kind].parameters, parameters);
this._kinds[kind].decorators.push(...decorators);
}
addArgTypesEnhancer(argTypesEnhancer: ArgTypesEnhancer) {
if (Object.keys(this._stories).length > 0)
throw new Error('Cannot add a parameter enhancer to the store after a story has been added.');
this._argTypesEnhancers.push(argTypesEnhancer);
}
// Combine the global, kind & story parameters of a story
combineStoryParameters(parameters: Parameters, kind: StoryKind) {
return combineParameters(
this._globalMetadata.parameters,
this._kinds[kind].parameters,
parameters
);
}
addStory(
{
id,
kind,
name,
storyFn: original,
parameters: storyParameters = {},
decorators: storyDecorators = [],
}: AddStoryArgs,
{
applyDecorators,
allowUnsafe = false,
}: {
applyDecorators: (fn: LegacyStoryFn, decorators: DecoratorFunction[]) => any;
} & AllowUnsafeOption
) {
if (!this._configuring && !allowUnsafe)
throw new Error(
'Cannot add a story when not configuring, see https://github.com/storybookjs/storybook/blob/next/MIGRATION.md#story-store-immutable-outside-of-configuration'
);
if (storyParameters) {
checkGlobals(storyParameters);
checkStorySort(storyParameters);
}
const { _stories } = this;
if (_stories[id]) {
logger.warn(dedent`
Story with id ${id} already exists in the store!
Perhaps you added the same story twice, or you have a name collision?
Story ids need to be unique -- ensure you aren't using the same names modulo url-sanitization.
`);
}
const identification = {
id,
kind,
name,
story: name, // legacy
};
// immutable original storyFn
const getOriginal = () => original;
this.ensureKind(kind);
const kindMetadata: KindMetadata = this._kinds[kind];
const decorators = [
...storyDecorators,
...kindMetadata.decorators,
...this._globalMetadata.decorators,
];
const finalStoryFn = (context: StoryContext) => {
const { passArgsFirst } = context.parameters;
return passArgsFirst || typeof passArgsFirst === 'undefined'
? (original as ArgsStoryFn)(context.args, context)
: original(context);
};
// lazily decorate the story when it's loaded
const getDecorated: () => LegacyStoryFn = memoize(1)(() =>
applyDecorators(finalStoryFn, decorators)
);
const hooks = new HooksContext();
// We need the combined parameters now in order to calculate argTypes, but we won't keep them
const combinedParameters = this.combineStoryParameters(storyParameters, kind);
const { argTypes = {} } = this._argTypesEnhancers.reduce(
(accumlatedParameters: Parameters, enhancer) => ({
...accumlatedParameters,
argTypes: enhancer({
...identification,
storyFn: original,
parameters: accumlatedParameters,
args: {},
globals: {},
}),
}),
combinedParameters
);
const storyParametersWithArgTypes = { ...storyParameters, argTypes };
const storyFn: LegacyStoryFn = (runtimeContext: StoryContext) =>
getDecorated()({
...identification,
...runtimeContext,
// Calculate "combined" parameters at render time (NOTE: for perf we could just use combinedParameters from above?)
parameters: this.combineStoryParameters(storyParametersWithArgTypes, kind),
hooks,
args: _stories[id].args,
globals: this._globals,
});
// Pull out parameters.args.$ || .argTypes.$.defaultValue into initialArgs
const initialArgs: Args = combinedParameters.args;
const defaultArgs: Args = Object.entries(
argTypes as Record<string, { defaultValue: any }>
).reduce((acc, [arg, { defaultValue }]) => {
if (defaultValue) acc[arg] = defaultValue;
return acc;
}, {} as Args);
_stories[id] = {
...identification,
hooks,
getDecorated,
getOriginal,
storyFn,
parameters: { ...storyParameters, argTypes },
args: { ...defaultArgs, ...initialArgs },
};
}
remove = (id: string, { allowUnsafe = false }: AllowUnsafeOption = {}): void => {
if (!this._configuring && !allowUnsafe)
throw new Error(
'Cannot remove a story when not configuring, see https://github.com/storybookjs/storybook/blob/next/MIGRATION.md#story-store-immutable-outside-of-configuration'
);
const { _stories } = this;
const story = _stories[id];
delete _stories[id];
if (story) story.hooks.clean();
};
removeStoryKind(kind: string, { allowUnsafe = false }: AllowUnsafeOption = {}) {
if (!this._configuring && !allowUnsafe)
throw new Error(
'Cannot remove a kind when not configuring, see https://github.com/storybookjs/storybook/blob/next/MIGRATION.md#story-store-immutable-outside-of-configuration'
);
if (!this._kinds[kind]) return;
this._kinds[kind].parameters = {};
this._kinds[kind].decorators = [];
this.cleanHooksForKind(kind);
this._stories = Object.entries(this._stories).reduce((acc: StoreData, [id, story]) => {
if (story.kind !== kind) acc[id] = story;
return acc;
}, {});
}
updateGlobals(newGlobals: Args) {
this._globals = { ...this._globals, ...newGlobals };
this.storeGlobals();
this._channel.emit(Events.GLOBALS_UPDATED, this._globals);
}
updateStoryArgs(id: string, newArgs: Args) {
if (!this._stories[id]) throw new Error(`No story for id ${id}`);
const { args } = this._stories[id];
this._stories[id].args = { ...args, ...newArgs };
this._channel.emit(Events.STORY_ARGS_UPDATED, id, this._stories[id].args);
}
fromId = (id: string): PublishedStoreItem | null => {
try {
const data = this._stories[id as string];
if (!data || !data.getDecorated) {
return null;
}
return this.mergeAdditionalDataToStory(data);
} catch (e) {
logger.warn('failed to get story:', this._stories);
logger.error(e);
return null;
}
};
raw(options?: StoryOptions): PublishedStoreItem[] {
return Object.values(this._stories)
.filter((i) => !!i.getDecorated)
.filter((i) => includeStory(i, options))
.map((i) => this.mergeAdditionalDataToStory(i));
}
sortedStories(): StoreItem[] {
// NOTE: when kinds are HMR'ed they get temporarily removed from the `_stories` array
// and thus lose order. However `_kinds[x].order` preservers the original load order
const kindOrder = mapValues(this._kinds, ({ order }) => order);
const storySortParameter = this._globalMetadata.parameters?.options?.storySort;
return getSortedStories(this._stories, kindOrder, storySortParameter);
}
extract(options: StoryOptions & { normalizeParameters?: boolean } = {}) {
const stories = this.sortedStories();
// removes function values from all stories so they are safe to transport over the channel
return stories.reduce((acc, story) => {
if (!includeStory(story, options)) return acc;
const extracted = toExtracted(story);
if (options.normalizeParameters) return Object.assign(acc, { [story.id]: extracted });
const { parameters, kind } = extracted as {
parameters: Parameters;
kind: StoryKind;
};
return Object.assign(acc, {
[story.id]: Object.assign(extracted, {
parameters: this.combineStoryParameters(parameters, kind),
}),
});
}, {});
}
clearError() {
this._error = null;
}
setError = (err: ErrorLike) => {
this._error = err;
};
getError = (): ErrorLike | undefined => this._error;
setSelectionSpecifier(selectionSpecifier: StoreSelectionSpecifier): void {
this._selectionSpecifier = selectionSpecifier;
}
setSelection(selection: StoreSelection): void {
this._selection = selection;
if (this._channel) {
this._channel.emit(Events.CURRENT_STORY_WAS_SET, this._selection);
}
}
getSelection = (): StoreSelection => this._selection;
getDataForManager = () => {
return {
v: 2,
globalParameters: this._globalMetadata.parameters,
globals: this._globals,
error: this.getError(),
kindParameters: mapValues(this._kinds, (metadata) => metadata.parameters),
stories: this.extract({ includeDocsOnly: true, normalizeParameters: true }),
};
};
pushToManager = () => {
if (this._channel) {
// send to the parent frame.
this._channel.emit(Events.SET_STORIES, this.getDataForManager());
}
};
getStoryKinds() {
return Array.from(new Set(this.raw().map((s) => s.kind)));
}
getStoriesForKind(kind: string) {
return this.raw().filter((story) => story.kind === kind);
}
getRawStory(kind: string, name: string) {
return this.getStoriesForKind(kind).find((s) => s.name === name);
}
cleanHooks(id: string) {
if (this._stories[id]) {
this._stories[id].hooks.clean();
}
}
cleanHooksForKind(kind: string) {
this.getStoriesForKind(kind).map((story) => this.cleanHooks(story.id));
}
// This API is a reimplementation of Storybook's original getStorybook() API.
// As such it may not behave *exactly* the same, but aims to. Some notes:
// - It is *NOT* sorted by the user's sort function, but remains sorted in "insertion order"
// - It does not include docs-only stories
getStorybook(): GetStorybookKind[] {
return Object.values(
this.raw().reduce((kinds: { [kind: string]: GetStorybookKind }, story) => {
if (!includeStory(story)) return kinds;
const {
kind,
name,
storyFn,
parameters: { fileName },
} = story;
// eslint-disable-next-line no-param-reassign
if (!kinds[kind]) kinds[kind] = { kind, fileName, stories: [] };
kinds[kind].stories.push({ name, render: storyFn });
return kinds;
}, {})
).sort((s1, s2) => this._kinds[s1.kind].order - this._kinds[s2.kind].order);
}
private mergeAdditionalDataToStory(story: StoreItem): PublishedStoreItem {
return {
...story,
parameters: this.combineStoryParameters(story.parameters, story.kind),
globals: this._globals,
};
}
}
| lib/client-api/src/story_store.ts | 1 | https://github.com/storybookjs/storybook/commit/962ab44d1155bfc8707695757726149be8713760 | [
0.4072454273700714,
0.011652935296297073,
0.00016513314039912075,
0.0002388691937085241,
0.05471933260560036
] |
{
"id": 1,
"code_window": [
" const data = getCurrentStoryData();\n",
" const args = isStory(data) ? data.args : {};\n",
"\n",
" return [args, (newArgs: Args) => updateStoryArgs(data.id, newArgs)];\n",
"}\n",
"\n",
"export function useGlobals(): [Args, (newGlobals: Args) => void] {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" console.log('in use args');\n",
" return [\n",
" args,\n",
" (newArgs: Args) => {\n",
" console.log('upSArgs');\n",
" updateStoryArgs(data as Story, newArgs);\n",
" },\n",
" ];\n"
],
"file_path": "lib/api/src/index.tsx",
"type": "replace",
"edit_start_line_idx": 417
} | {
"extends": "../../tsconfig.json",
"compileOnSave": false,
"compilerOptions": {
"outDir": "dist",
"types": ["webpack-env"],
"rootDir": "./src",
"resolveJsonModule": true
}
}
| app/angular/tsconfig.json | 0 | https://github.com/storybookjs/storybook/commit/962ab44d1155bfc8707695757726149be8713760 | [
0.000175641558598727,
0.00017457704234402627,
0.00017351252608932555,
0.00017457704234402627,
0.0000010645162547007203
] |
{
"id": 1,
"code_window": [
" const data = getCurrentStoryData();\n",
" const args = isStory(data) ? data.args : {};\n",
"\n",
" return [args, (newArgs: Args) => updateStoryArgs(data.id, newArgs)];\n",
"}\n",
"\n",
"export function useGlobals(): [Args, (newGlobals: Args) => void] {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" console.log('in use args');\n",
" return [\n",
" args,\n",
" (newArgs: Args) => {\n",
" console.log('upSArgs');\n",
" updateStoryArgs(data as Story, newArgs);\n",
" },\n",
" ];\n"
],
"file_path": "lib/api/src/index.tsx",
"type": "replace",
"edit_start_line_idx": 417
} | import doctrine, { Annotation } from 'doctrine';
export interface ExtractedJsDocParam {
name: string;
type?: any;
description?: string;
getPrettyName: () => string;
getTypeName: () => string;
}
export interface ExtractedJsDocReturns {
type?: any;
description?: string;
getTypeName: () => string;
}
export interface ExtractedJsDoc {
params?: ExtractedJsDocParam[];
returns?: ExtractedJsDocReturns;
ignore: boolean;
}
export interface JsDocParsingOptions {
tags?: string[];
}
export interface JsDocParsingResult {
includesJsDoc: boolean;
ignore: boolean;
description?: string;
extractedTags?: ExtractedJsDoc;
}
export type ParseJsDoc = (value?: string, options?: JsDocParsingOptions) => JsDocParsingResult;
function containsJsDoc(value?: string): boolean {
return value != null && value.includes('@');
}
function parse(content: string, tags: string[]): Annotation {
let ast;
try {
ast = doctrine.parse(content, {
tags,
sloppy: true,
});
} catch (e) {
// eslint-disable-next-line no-console
console.error(e);
throw new Error('Cannot parse JSDoc tags.');
}
return ast;
}
const DEFAULT_OPTIONS = {
tags: ['param', 'arg', 'argument', 'returns', 'ignore'],
};
export const parseJsDoc: ParseJsDoc = (
value?: string,
options: JsDocParsingOptions = DEFAULT_OPTIONS
) => {
if (!containsJsDoc(value)) {
return {
includesJsDoc: false,
ignore: false,
};
}
const jsDocAst = parse(value, options.tags);
const extractedTags = extractJsDocTags(jsDocAst);
if (extractedTags.ignore) {
// There is no point in doing other stuff since this prop will not be rendered.
return {
includesJsDoc: true,
ignore: true,
};
}
return {
includesJsDoc: true,
ignore: false,
// Always use the parsed description to ensure JSDoc is removed from the description.
description: jsDocAst.description,
extractedTags,
};
};
function extractJsDocTags(ast: doctrine.Annotation): ExtractedJsDoc {
const extractedTags: ExtractedJsDoc = {
params: null,
returns: null,
ignore: false,
};
for (let i = 0; i < ast.tags.length; i += 1) {
const tag = ast.tags[i];
if (tag.title === 'ignore') {
extractedTags.ignore = true;
// Once we reach an @ignore tag, there is no point in parsing the other tags since we will not render the prop.
break;
} else {
switch (tag.title) {
// arg & argument are aliases for param.
case 'param':
case 'arg':
case 'argument': {
const paramTag = extractParam(tag);
if (paramTag != null) {
if (extractedTags.params == null) {
extractedTags.params = [];
}
extractedTags.params.push(paramTag);
}
break;
}
case 'returns': {
const returnsTag = extractReturns(tag);
if (returnsTag != null) {
extractedTags.returns = returnsTag;
}
break;
}
default:
break;
}
}
}
return extractedTags;
}
function extractParam(tag: doctrine.Tag): ExtractedJsDocParam {
const paramName = tag.name;
// When the @param doesn't have a name but have a type and a description, "null-null" is returned.
if (paramName != null && paramName !== 'null-null') {
return {
name: tag.name,
type: tag.type,
description: tag.description,
getPrettyName: () => {
if (paramName.includes('null')) {
// There is a few cases in which the returned param name contains "null".
// - @param {SyntheticEvent} event- Original SyntheticEvent
// - @param {SyntheticEvent} event.\n@returns {string}
return paramName.replace('-null', '').replace('.null', '');
}
return tag.name;
},
getTypeName: () => {
return tag.type != null ? extractTypeName(tag.type) : null;
},
};
}
return null;
}
function extractReturns(tag: doctrine.Tag): ExtractedJsDocReturns {
if (tag.type != null) {
return {
type: tag.type,
description: tag.description,
getTypeName: () => {
return extractTypeName(tag.type);
},
};
}
return null;
}
function extractTypeName(type: doctrine.Type): string {
if (type.type === 'NameExpression') {
return type.name;
}
if (type.type === 'RecordType') {
const recordFields = type.fields.map((field: doctrine.type.FieldType) => {
if (field.value != null) {
const valueTypeName = extractTypeName(field.value);
return `${field.key}: ${valueTypeName}`;
}
return field.key;
});
return `({${recordFields.join(', ')}})`;
}
if (type.type === 'UnionType') {
const unionElements = type.elements.map(extractTypeName);
return `(${unionElements.join('|')})`;
}
// Only support untyped array: []. Might add more support later if required.
if (type.type === 'ArrayType') {
return '[]';
}
if (type.type === 'TypeApplication') {
if (type.expression != null) {
if ((type.expression as doctrine.type.NameExpression).name === 'Array') {
const arrayType = extractTypeName(type.applications[0]);
return `${arrayType}[]`;
}
}
}
if (
type.type === 'NullableType' ||
type.type === 'NonNullableType' ||
type.type === 'OptionalType'
) {
return extractTypeName(type.expression);
}
if (type.type === 'AllLiteral') {
return 'any';
}
return null;
}
| addons/docs/src/lib/jsdocParser.ts | 0 | https://github.com/storybookjs/storybook/commit/962ab44d1155bfc8707695757726149be8713760 | [
0.0012992169940844178,
0.00024073202803265303,
0.00016477782628498971,
0.00017345100059174,
0.00023550693003926426
] |
{
"id": 1,
"code_window": [
" const data = getCurrentStoryData();\n",
" const args = isStory(data) ? data.args : {};\n",
"\n",
" return [args, (newArgs: Args) => updateStoryArgs(data.id, newArgs)];\n",
"}\n",
"\n",
"export function useGlobals(): [Args, (newGlobals: Args) => void] {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" console.log('in use args');\n",
" return [\n",
" args,\n",
" (newArgs: Args) => {\n",
" console.log('upSArgs');\n",
" updateStoryArgs(data as Story, newArgs);\n",
" },\n",
" ];\n"
],
"file_path": "lib/api/src/index.tsx",
"type": "replace",
"edit_start_line_idx": 417
} | # Storybook Web Components Demo
This example directory represents the application you wish to integrate storybook into.
Run `yarn install` to sync Storybook module with the source code and run `yarn storybook` to start the Storybook.
| examples/web-components-kitchen-sink/README.md | 0 | https://github.com/storybookjs/storybook/commit/962ab44d1155bfc8707695757726149be8713760 | [
0.00016485669766552746,
0.00016485669766552746,
0.00016485669766552746,
0.00016485669766552746,
0
] |
{
"id": 2,
"code_window": [
" () => {},\n",
" [\n",
" (storyFn) => {\n",
" useArgs()[1]({ a: 'b' });\n",
" expect(mockChannel.emit).toHaveBeenCalledWith(UPDATE_STORY_ARGS, '1', { a: 'b' });\n",
" return storyFn();\n",
" },\n",
" ],\n",
" { id: '1', args: {} }\n",
" );\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" expect(mockChannel.emit).toHaveBeenCalledWith(UPDATE_STORY_ARGS, {\n",
" storyId: '1',\n",
" updatedArgs: { a: 'b' },\n",
" });\n"
],
"file_path": "lib/client-api/src/hooks.test.js",
"type": "replace",
"edit_start_line_idx": 520
} | import React, {
Component,
Fragment,
FunctionComponent,
ReactElement,
ReactNode,
useContext,
useEffect,
useMemo,
useRef,
} from 'react';
import mergeWith from 'lodash/mergeWith';
import {
STORY_CHANGED,
SHARED_STATE_CHANGED,
SHARED_STATE_SET,
SET_STORIES,
} from '@storybook/core-events';
import { RenderData as RouterData } from '@storybook/router';
import { Listener } from '@storybook/channels';
import { createContext } from './context';
import Store, { Options } from './store';
import getInitialState from './initial-state';
import { StoriesHash, Story, Root, Group, isGroup, isRoot, isStory } from './lib/stories';
import * as provider from './modules/provider';
import * as addons from './modules/addons';
import * as channel from './modules/channel';
import * as notifications from './modules/notifications';
import * as stories from './modules/stories';
import * as refs from './modules/refs';
import * as layout from './modules/layout';
import * as shortcuts from './modules/shortcuts';
import * as url from './modules/url';
import * as version from './modules/versions';
import * as globals from './modules/globals';
const { ActiveTabs } = layout;
export { Options as StoreOptions, Listener as ChannelListener, ActiveTabs };
const ManagerContext = createContext({ api: undefined, state: getInitialState({}) });
export type ModuleArgs = RouterData &
ProviderData & {
mode?: 'production' | 'development';
state: State;
fullAPI: API;
store: Store;
};
export type State = layout.SubState &
stories.SubState &
refs.SubState &
notifications.SubState &
version.SubState &
url.SubState &
shortcuts.SubState &
globals.SubState &
RouterData &
Other;
export type API = addons.SubAPI &
channel.SubAPI &
provider.SubAPI &
stories.SubAPI &
refs.SubAPI &
globals.SubAPI &
layout.SubAPI &
notifications.SubAPI &
shortcuts.SubAPI &
version.SubAPI &
url.SubAPI &
Other;
interface Other {
[key: string]: any;
}
export interface Combo {
api: API;
state: State;
}
interface ProviderData {
provider: provider.Provider;
}
export type ManagerProviderProps = RouterData &
ProviderData & {
docsMode: boolean;
children: ReactNode | ((props: Combo) => ReactNode);
};
// These types are duplicated in addons.
export type StoryId = string;
export type StoryKind = string;
export interface Args {
[key: string]: any;
}
export interface ArgType {
name?: string;
description?: string;
defaultValue?: any;
[key: string]: any;
}
export interface ArgTypes {
[key: string]: ArgType;
}
export interface Parameters {
[key: string]: any;
}
// This is duplicated from @storybook/client-api for the reasons mentioned in lib-addons/types.js
export const combineParameters = (...parameterSets: Parameters[]) =>
mergeWith({}, ...parameterSets, (objValue: any, srcValue: any) => {
// Treat arrays as scalars:
if (Array.isArray(srcValue)) return srcValue;
return undefined;
});
export type ModuleFn = (m: ModuleArgs) => Module;
interface Module {
init?: () => void;
api?: unknown;
state?: unknown;
}
class ManagerProvider extends Component<ManagerProviderProps, State> {
api: API = {} as API;
modules: Module[];
static displayName = 'Manager';
constructor(props: ManagerProviderProps) {
super(props);
const {
location,
path,
refId,
viewMode = props.docsMode ? 'docs' : 'story',
storyId,
docsMode,
navigate,
} = props;
const store = new Store({
getState: () => this.state,
setState: (stateChange: Partial<State>, callback) => this.setState(stateChange, callback),
});
const routeData = { location, path, viewMode, storyId, refId };
// Initialize the state to be the initial (persisted) state of the store.
// This gives the modules the chance to read the persisted state, apply their defaults
// and override if necessary
const docsModeState = {
layout: { isToolshown: false, showPanel: false },
ui: { docsMode: true },
};
this.state = store.getInitialState(
getInitialState({
...routeData,
...(docsMode ? docsModeState : null),
})
);
const apiData = {
navigate,
store,
provider: props.provider,
};
this.modules = [
provider,
channel,
addons,
layout,
notifications,
shortcuts,
stories,
refs,
globals,
url,
version,
].map((m) => m.init({ ...routeData, ...apiData, state: this.state, fullAPI: this.api }));
// Create our initial state by combining the initial state of all modules, then overlaying any saved state
const state = getInitialState(this.state, ...this.modules.map((m) => m.state));
// Get our API by combining the APIs exported by each module
const api: API = Object.assign(this.api, { navigate }, ...this.modules.map((m) => m.api));
this.state = state;
this.api = api;
}
static getDerivedStateFromProps = (props: ManagerProviderProps, state: State) => {
if (state.path !== props.path) {
return {
...state,
location: props.location,
path: props.path,
refId: props.refId,
// if its a docsOnly page, even the 'story' view mode is considered 'docs'
viewMode: (props.docsMode && props.viewMode) === 'story' ? 'docs' : props.viewMode,
storyId: props.storyId,
};
}
return null;
};
componentDidMount() {
// Now every module has had a chance to set its API, call init on each module which gives it
// a chance to do things that call other modules' APIs.
this.modules.forEach(({ init }) => {
if (init) {
init();
}
});
}
shouldComponentUpdate(nextProps: ManagerProviderProps, nextState: State) {
const prevState = this.state;
const prevProps = this.props;
if (prevState !== nextState) {
return true;
}
if (prevProps.path !== nextProps.path) {
return true;
}
return false;
}
render() {
const { children } = this.props;
const value = {
state: this.state,
api: this.api,
};
return (
<ManagerContext.Provider value={value}>
<ManagerConsumer>{children}</ManagerConsumer>
</ManagerContext.Provider>
);
}
}
interface ManagerConsumerProps<P = unknown> {
filter?: (combo: Combo) => P;
children: FunctionComponent<P> | ReactNode;
}
const defaultFilter = (c: Combo) => c;
function ManagerConsumer<P = Combo>({
// @ts-ignore
filter = defaultFilter,
children,
}: ManagerConsumerProps<P>): ReactElement {
const c = useContext(ManagerContext);
const renderer = useRef(children);
const filterer = useRef(filter);
if (typeof renderer.current !== 'function') {
return <Fragment>{renderer.current}</Fragment>;
}
const data = filterer.current(c);
const l = useMemo(() => {
return [...Object.entries(data).reduce((acc, keyval) => acc.concat(keyval), [])];
}, [c.state]);
return useMemo(() => {
const Child = renderer.current as FunctionComponent<P>;
return <Child {...data} />;
}, l);
}
export function useStorybookState(): State {
const { state } = useContext(ManagerContext);
return state;
}
export function useStorybookApi(): API {
const { api } = useContext(ManagerContext);
return api;
}
export {
ManagerConsumer as Consumer,
ManagerProvider as Provider,
StoriesHash,
Story,
Root,
Group,
isGroup,
isRoot,
isStory,
};
export interface EventMap {
[eventId: string]: Listener;
}
function orDefault<S>(fromStore: S, defaultState: S): S {
if (typeof fromStore === 'undefined') {
return defaultState;
}
return fromStore;
}
export const useChannel = (eventMap: EventMap, deps: any[] = []) => {
const api = useStorybookApi();
useEffect(() => {
Object.entries(eventMap).forEach(([type, listener]) => api.on(type, listener));
return () => {
Object.entries(eventMap).forEach(([type, listener]) => api.off(type, listener));
};
}, deps);
return api.emit;
};
export function useParameter<S>(parameterKey: string, defaultValue?: S) {
const api = useStorybookApi();
const result = api.getCurrentParameter<S>(parameterKey);
return orDefault<S>(result, defaultValue);
}
type StateMerger<S> = (input: S) => S;
// cache for taking care of HMR
const addonStateCache: {
[key: string]: any;
} = {};
// shared state
export function useSharedState<S>(stateId: string, defaultState?: S) {
const api = useStorybookApi();
const existingState = api.getAddonState<S>(stateId);
const state = orDefault<S>(
existingState,
addonStateCache[stateId] ? addonStateCache[stateId] : defaultState
);
const setState = (s: S | StateMerger<S>, options?: Options) => {
// set only after the stories are loaded
if (addonStateCache[stateId]) {
addonStateCache[stateId] = s;
}
api.setAddonState<S>(stateId, s, options);
};
const allListeners = useMemo(() => {
const stateChangeHandlers = {
[`${SHARED_STATE_CHANGED}-client-${stateId}`]: (s: S) => setState(s),
[`${SHARED_STATE_SET}-client-${stateId}`]: (s: S) => setState(s),
};
const stateInitializationHandlers = {
[SET_STORIES]: () => {
if (addonStateCache[stateId]) {
// this happens when HMR
setState(addonStateCache[stateId]);
api.emit(`${SHARED_STATE_SET}-manager-${stateId}`, addonStateCache[stateId]);
} else if (defaultState !== undefined) {
// if not HMR, yet the defaults are form the manager
setState(defaultState);
// initialize addonStateCache after first load, so its available for subsequent HMR
addonStateCache[stateId] = defaultState;
api.emit(`${SHARED_STATE_SET}-manager-${stateId}`, defaultState);
}
},
[STORY_CHANGED]: () => {
if (api.getAddonState(stateId) !== undefined) {
api.emit(`${SHARED_STATE_SET}-manager-${stateId}`, api.getAddonState(stateId));
}
},
};
return {
...stateChangeHandlers,
...stateInitializationHandlers,
};
}, [stateId]);
const emit = useChannel(allListeners);
return [
state,
(newStateOrMerger: S | StateMerger<S>, options?: Options) => {
setState(newStateOrMerger, options);
emit(`${SHARED_STATE_CHANGED}-manager-${stateId}`, newStateOrMerger);
},
] as [S, (newStateOrMerger: S | StateMerger<S>, options?: Options) => void];
}
export function useAddonState<S>(addonId: string, defaultState?: S) {
return useSharedState<S>(addonId, defaultState);
}
export function useArgs(): [Args, (newArgs: Args) => void] {
const { getCurrentStoryData, updateStoryArgs } = useStorybookApi();
const data = getCurrentStoryData();
const args = isStory(data) ? data.args : {};
return [args, (newArgs: Args) => updateStoryArgs(data.id, newArgs)];
}
export function useGlobals(): [Args, (newGlobals: Args) => void] {
const {
state: { globals: oldGlobals },
api: { updateGlobals },
} = useContext(ManagerContext);
return [oldGlobals, updateGlobals];
}
export function useArgTypes(): ArgTypes {
return useParameter<ArgTypes>('argTypes', {});
}
export function useGlobalTypes(): ArgTypes {
return useParameter<ArgTypes>('globalTypes', {});
}
| lib/api/src/index.tsx | 1 | https://github.com/storybookjs/storybook/commit/962ab44d1155bfc8707695757726149be8713760 | [
0.0027786819264292717,
0.00031815815600566566,
0.00016233607311733067,
0.0001692329824436456,
0.0005004693521186709
] |
{
"id": 2,
"code_window": [
" () => {},\n",
" [\n",
" (storyFn) => {\n",
" useArgs()[1]({ a: 'b' });\n",
" expect(mockChannel.emit).toHaveBeenCalledWith(UPDATE_STORY_ARGS, '1', { a: 'b' });\n",
" return storyFn();\n",
" },\n",
" ],\n",
" { id: '1', args: {} }\n",
" );\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" expect(mockChannel.emit).toHaveBeenCalledWith(UPDATE_STORY_ARGS, {\n",
" storyId: '1',\n",
" updatedArgs: { a: 'b' },\n",
" });\n"
],
"file_path": "lib/client-api/src/hooks.test.js",
"type": "replace",
"edit_start_line_idx": 520
} | /* eslint-disable consistent-return */
import React from 'react';
import PropTypes from 'prop-types';
import { SyntaxHighlighter } from '@storybook/components';
import { ThemeProvider, convert, create } from '@storybook/theming';
import './style.css';
import parse from 'html-react-parser';
const DocsContent = ({ title, content, editUrl, ...rest }) => (
<div id="docs-content">
<div className="content">
<h2 className="title">{title}</h2>
<p>
<a className="edit-link" href={editUrl} target="_blank" rel="noopener noreferrer">
Edit this page
</a>
</p>
<div className="markdown">
<ThemeProvider theme={convert(create({ base: 'light' }))}>
{parse(content, {
replace: (domNode) => {
if (
domNode.name === 'pre' &&
domNode.children.find(
(n) => n.name === 'code' && n.attribs.class && n.attribs.class.match(/^language-/)
)
) {
const language = domNode.children[0].attribs.class.replace('language-', '');
const code = domNode.children[0].children[0].data;
return (
<SyntaxHighlighter copyable language={language}>
{code}
</SyntaxHighlighter>
);
}
},
})}
</ThemeProvider>
{/* <div dangerouslySetInnerHTML={{ __html: content }} /> */}
{/* <Highlight></Highlight> */}
</div>
</div>
</div>
);
DocsContent.propTypes = {
title: PropTypes.string.isRequired,
content: PropTypes.string.isRequired,
editUrl: PropTypes.string.isRequired,
};
export { DocsContent as default };
| docs/src/components/Docs/Content/index.js | 0 | https://github.com/storybookjs/storybook/commit/962ab44d1155bfc8707695757726149be8713760 | [
0.0001729580108076334,
0.00017031801689881831,
0.00016821814642753452,
0.00016978679923340678,
0.0000019843814698106144
] |
{
"id": 2,
"code_window": [
" () => {},\n",
" [\n",
" (storyFn) => {\n",
" useArgs()[1]({ a: 'b' });\n",
" expect(mockChannel.emit).toHaveBeenCalledWith(UPDATE_STORY_ARGS, '1', { a: 'b' });\n",
" return storyFn();\n",
" },\n",
" ],\n",
" { id: '1', args: {} }\n",
" );\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" expect(mockChannel.emit).toHaveBeenCalledWith(UPDATE_STORY_ARGS, {\n",
" storyId: '1',\n",
" updatedArgs: { a: 'b' },\n",
" });\n"
],
"file_path": "lib/client-api/src/hooks.test.js",
"type": "replace",
"edit_start_line_idx": 520
} | import React from 'react';
import { storiesOf } from '@storybook/react';
import ListItem from './ListItem';
import { Icons } from '../icon/icon';
storiesOf('basics/Tooltip/ListItem', module)
.add('all', () => (
<div>
<ListItem loading />
<ListItem title="Default" />
<ListItem title="Default icon" right={<Icons icon="eye" />} />
<ListItem left="left" title="title" center="center" right="right" />
<ListItem active left="left" title="active" center="center" right="right" />
<ListItem
active
left="left"
title="active icon"
center="center"
right={<Icons icon="eye" />}
/>
<ListItem disabled left="left" title="disabled" center="center" right="right" />
</div>
))
.add('loading', () => <ListItem loading />)
.add('default', () => <ListItem title="Default" />)
.add('default icon', () => <ListItem title="Default icon" right={<Icons icon="eye" />} />)
.add('active icon', () => <ListItem active title="active icon" right={<Icons icon="eye" />} />)
.add('w/positions', () => <ListItem left="left" title="title" center="center" right="right" />)
.add('w/positions active', () => (
<ListItem active left="left" title="active" center="center" right="right" />
))
.add('disabled', () => (
<ListItem disabled left="left" title="disabled" center="center" right="right" />
));
| lib/components/src/tooltip/ListItem.stories.tsx | 0 | https://github.com/storybookjs/storybook/commit/962ab44d1155bfc8707695757726149be8713760 | [
0.00017223884060513228,
0.00016885253717191517,
0.00016211705224122852,
0.00017052711336873472,
0.000004116897798667196
] |
{
"id": 2,
"code_window": [
" () => {},\n",
" [\n",
" (storyFn) => {\n",
" useArgs()[1]({ a: 'b' });\n",
" expect(mockChannel.emit).toHaveBeenCalledWith(UPDATE_STORY_ARGS, '1', { a: 'b' });\n",
" return storyFn();\n",
" },\n",
" ],\n",
" { id: '1', args: {} }\n",
" );\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" expect(mockChannel.emit).toHaveBeenCalledWith(UPDATE_STORY_ARGS, {\n",
" storyId: '1',\n",
" updatedArgs: { a: 'b' },\n",
" });\n"
],
"file_path": "lib/client-api/src/hooks.test.js",
"type": "replace",
"edit_start_line_idx": 520
} | <svg xmlns="http://www.w3.org/2000/svg" width="132.948" height="37.739"><path fill="#fff" d="M31.314 14.575c.36 0 .48.13.48.48v7.92h4.07c.35 0 .48.13.48.48v.7c0 .35-.13.48-.48.48h-5.36c-.35 0-.49-.13-.49-.48v-9.1c0-.35.14-.48.49-.48zM39.894 18.065c0-2.31 1.46-3.7 4-3.7s4 1.39 4 3.7v3.08c0 2.31-1.47 3.7-4 3.7s-4-1.39-4-3.7zm6.32 0c0-1.3-.81-2-2.27-2s-2.26.71-2.26 2v3.1c0 1.31.8 2 2.26 2s2.27-.72 2.27-2zM59.804 19.125c.39 0 .48.13.48.48v1.9a3 3 0 01-1.06 2.36 4.36 4.36 0 01-3 .94c-2.59 0-4-1.39-4-3.7v-3.1c0-2.28 1.46-3.68 4-3.68 2 0 3.3.79 3.85 2.37a.43.43 0 01-.3.62l-.78.27c-.34.12-.48.05-.6-.3a2.06 2.06 0 00-2.17-1.3c-1.47 0-2.27.71-2.27 2v3.18c0 1.31.81 2 2.27 2s2.36-.67 2.36-1.65v-.74h-2.17c-.36 0-.49-.14-.49-.49v-.68c0-.35.13-.48.49-.48zM64.414 18.065c0-2.31 1.46-3.7 4-3.7s4 1.39 4 3.7v3.08c0 2.31-1.47 3.7-4 3.7s-4-1.39-4-3.7zm6.31 0c0-1.3-.81-2-2.26-2s-2.27.71-2.27 2v3.1c0 1.31.81 2 2.27 2s2.26-.72 2.26-2zM77.124 14.865c0-.22.07-.29.29-.29h.46c.22 0 .27.07.27.29v9.48c0 .22 0 .29-.27.29h-.46c-.22 0-.29-.07-.29-.29zM87.254 14.575a3.14 3.14 0 110 6.28h-3v3.49c0 .22-.05.29-.26.29h-.47c-.21 0-.29-.07-.29-.29v-9.48c0-.22.08-.29.29-.29zm-.09 5.29a2.18 2.18 0 100-4.36h-3v4.36zM98.204 14.375a3.61 3.61 0 013.72 2.18c.08.16 0 .29-.16.37l-.44.2c-.18.07-.25.06-.36-.13a2.72 2.72 0 00-2.76-1.64c-1.69 0-2.61.67-2.61 1.87a1.52 1.52 0 001.27 1.54 6.79 6.79 0 001.66.32 6.88 6.88 0 012 .41 2.25 2.25 0 011.56 2.37c0 1.87-1.36 3-3.86 3a3.61 3.61 0 01-3.83-2.43.27.27 0 01.17-.38l.44-.16a.27.27 0 01.36.17 2.86 2.86 0 002.86 1.8c1.89 0 2.82-.66 2.82-2a1.49 1.49 0 00-1.17-1.53 7 7 0 00-1.59-.28l-1.08-.14a9.5 9.5 0 01-1-.27 2.63 2.63 0 01-.89-.47 2.44 2.44 0 01-.8-1.91c.07-1.75 1.38-2.89 3.69-2.89zM107.474 21.215a2.78 2.78 0 005.55 0v-6.35c0-.22.07-.29.29-.29h.46c.22 0 .29.07.29.29v6.34c0 2.27-1.34 3.64-3.81 3.64s-3.81-1.37-3.81-3.64v-6.34c0-.22.07-.29.28-.29h.47c.21 0 .28.07.28.29zM127.864 14.575c.22 0 .29.07.29.29v9.48c0 .22-.07.29-.29.29h-.42c-.21 0-.28-.07-.28-.29v-5.77a18.55 18.55 0 01.17-2.51h-.06a18 18 0 01-1.09 2.21l-2.15 3.79a.35.35 0 01-.33.22h-.28a.37.37 0 01-.34-.22l-2.18-3.83a16.07 16.07 0 01-1-2.18h-.06a21.76 21.76 0 01.16 2.53v5.76c0 .22-.07.29-.29.29h-.39c-.22 0-.29-.07-.29-.29v-9.48c0-.22.07-.29.29-.29h.36a.4.4 0 01.4.23l3.5 6.22 3.48-6.16c.11-.21.17-.24.39-.24zM13.524 22.415v7.23a1 1 0 01-2.09 0v-7.22a1.77 1.77 0 001 .34 1.72 1.72 0 001.09-.35zm8.9-2.09a1 1 0 00-1 1v1.26a1 1 0 102.09 0v-1.21a1 1 0 00-1.09-1.05zm-13.26 4.83a1.8 1.8 0 01-1-.34v7.25a1.05 1.05 0 002.1 0v-7.2a1.83 1.83 0 01-1.1.29zm10-7a1 1 0 00-1.05 1v5.57a1.05 1.05 0 102.1 0v-5.5a1 1 0 00-1.1-1.05zm-3.32 2.14a1.83 1.83 0 01-1.05-.34v7.27a1.05 1.05 0 102.1 0v-7.26a1.77 1.77 0 01-1.1.35zm-8.95 5.57V5.555a.94.94 0 00-.94-.93h-.22a.94.94 0 00-.94.93v20.31a.94.94 0 00.94.94h.22a.94.94 0 00.94-.94zm2.38-1.48h-.22a.94.94 0 01-.94-.94V7.975a.94.94 0 01.94-.93h.22a.94.94 0 01.94.93v15.49a.94.94 0 01-.94.94zm3.31-2.38h-.23a.93.93 0 01-.93-.93v-10.7a.93.93 0 01.93-.94h.23a.94.94 0 01.93.94v10.7a.93.93 0 01-.93.93zm3.31-2.45h-.21a.94.94 0 01-.94-.93v-5.76a.94.94 0 01.94-1h.22a.94.94 0 01.94.94v5.8a.94.94 0 01-.94.95zm3.32-2.15h-.22a.94.94 0 01-.94-.94v-1.49a.94.94 0 01.94-.93h.22a.94.94 0 01.94.93v1.49a.94.94 0 01-.93.94z"/></svg> | examples/dev-kits/logo.svg | 0 | https://github.com/storybookjs/storybook/commit/962ab44d1155bfc8707695757726149be8713760 | [
0.0003965150681324303,
0.0003965150681324303,
0.0003965150681324303,
0.0003965150681324303,
0
] |
{
"id": 3,
"code_window": [
" const testChannel = mockChannel();\n",
" const store = new StoryStore({ channel: testChannel });\n",
" addStoryToStore(store, 'a', '1', () => 0);\n",
"\n",
" testChannel.emit(Events.UPDATE_STORY_ARGS, 'a--1', { foo: 'bar' });\n",
"\n",
" expect(store.getRawStory('a', '1').args).toEqual({ foo: 'bar' });\n",
" });\n",
"\n",
" it('passes args as the first argument to the story if `parameters.passArgsFirst` is true', () => {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" testChannel.emit(Events.UPDATE_STORY_ARGS, { storyId: 'a--1', updatedArgs: { foo: 'bar' } });\n"
],
"file_path": "lib/client-api/src/story_store.test.ts",
"type": "replace",
"edit_start_line_idx": 203
} | /* eslint no-underscore-dangle: 0 */
import memoize from 'memoizerific';
import dedent from 'ts-dedent';
import stable from 'stable';
import mapValues from 'lodash/mapValues';
import store from 'store2';
import { Channel } from '@storybook/channels';
import Events from '@storybook/core-events';
import { logger } from '@storybook/client-logger';
import {
Comparator,
Parameters,
Args,
LegacyStoryFn,
ArgsStoryFn,
StoryContext,
StoryKind,
} from '@storybook/addons';
import {
DecoratorFunction,
StoryMetadata,
StoreData,
AddStoryArgs,
StoreItem,
PublishedStoreItem,
ErrorLike,
GetStorybookKind,
ArgTypesEnhancer,
StoreSelectionSpecifier,
StoreSelection,
} from './types';
import { HooksContext } from './hooks';
import storySort from './storySort';
import { combineParameters } from './parameters';
interface StoryOptions {
includeDocsOnly?: boolean;
}
type KindMetadata = StoryMetadata & { order: number };
const STORAGE_KEY = '@storybook/preview/store';
const isStoryDocsOnly = (parameters?: Parameters) => {
return parameters && parameters.docsOnly;
};
const includeStory = (story: StoreItem, options: StoryOptions = { includeDocsOnly: false }) => {
if (options.includeDocsOnly) {
return true;
}
return !isStoryDocsOnly(story.parameters);
};
const checkGlobals = (parameters: Parameters) => {
const { globals, globalTypes } = parameters;
if (globals || globalTypes) {
logger.error(
'Global args/argTypes can only be set globally',
JSON.stringify({
globals,
globalTypes,
})
);
}
};
const checkStorySort = (parameters: Parameters) => {
const { options } = parameters;
if (options?.storySort) logger.error('The storySort option parameter can only be set globally');
};
const getSortedStories = memoize(1)(
(storiesData: StoreData, kindOrder: Record<StoryKind, number>, storySortParameter) => {
const stories = Object.entries(storiesData);
if (storySortParameter) {
let sortFn: Comparator<any>;
if (typeof storySortParameter === 'function') {
sortFn = storySortParameter;
} else {
sortFn = storySort(storySortParameter);
}
stable.inplace(stories, sortFn);
} else {
stable.inplace(stories, (s1, s2) => kindOrder[s1[1].kind] - kindOrder[s2[1].kind]);
}
return stories.map(([id, s]) => s);
}
);
interface AllowUnsafeOption {
allowUnsafe?: boolean;
}
const toExtracted = <T>(obj: T) =>
Object.entries(obj).reduce((acc, [key, value]) => {
if (typeof value === 'function') {
return acc;
}
if (key === 'hooks') {
return acc;
}
if (Array.isArray(value)) {
return Object.assign(acc, { [key]: value.slice().sort() });
}
return Object.assign(acc, { [key]: value });
}, {});
export default class StoryStore {
_error?: ErrorLike;
_channel: Channel;
_configuring: boolean;
_globals: Args;
_globalMetadata: StoryMetadata;
// Keyed on kind name
_kinds: Record<string, KindMetadata>;
// Keyed on storyId
_stories: StoreData;
_argTypesEnhancers: ArgTypesEnhancer[];
_selectionSpecifier?: StoreSelectionSpecifier;
_selection?: StoreSelection;
constructor(params: { channel: Channel }) {
// Assume we are configuring until we hear otherwise
this._configuring = true;
// We store global args in session storage. Note that when we finish
// configuring below we will ensure we only use values here that make sense
this._globals = store.session.get(STORAGE_KEY)?.globals || {};
this._globalMetadata = { parameters: {}, decorators: [] };
this._kinds = {};
this._stories = {};
this._argTypesEnhancers = [];
this._error = undefined;
this._channel = params.channel;
this.setupListeners();
}
setupListeners() {
// Channel can be null in StoryShots
if (!this._channel) return;
this._channel.on(Events.SET_CURRENT_STORY, ({ storyId, viewMode }) =>
this.setSelection({ storyId, viewMode })
);
this._channel.on(Events.UPDATE_STORY_ARGS, (id: string, newArgs: Args) =>
this.updateStoryArgs(id, newArgs)
);
this._channel.on(Events.UPDATE_GLOBALS, (newGlobals: Args) => this.updateGlobals(newGlobals));
}
startConfiguring() {
this._configuring = true;
}
storeGlobals() {
// Store the global args on the session
store.session.set(STORAGE_KEY, { globals: this._globals });
}
finishConfiguring() {
this._configuring = false;
const { globals: initialGlobals = {}, globalTypes = {} } = this._globalMetadata.parameters;
const defaultGlobals: Args = Object.entries(
globalTypes as Record<string, { defaultValue: any }>
).reduce((acc, [arg, { defaultValue }]) => {
if (defaultValue) acc[arg] = defaultValue;
return acc;
}, {} as Args);
const allowedGlobals = new Set([...Object.keys(initialGlobals), ...Object.keys(globalTypes)]);
// To deal with HMR & persistence, we consider the previous value of global args, and:
// 1. Remove any keys that are not in the new parameter
// 2. Preference any keys that were already set
// 3. Use any new keys from the new parameter
this._globals = Object.entries(this._globals || {}).reduce(
(acc, [key, previousValue]) => {
if (allowedGlobals.has(key)) acc[key] = previousValue;
return acc;
},
{ ...defaultGlobals, ...initialGlobals }
);
this.storeGlobals();
// Set the current selection based on the current selection specifier, if selection is not yet set
const stories = this.sortedStories();
let foundStory;
if (this._selectionSpecifier && !this._selection) {
const { storySpecifier, viewMode } = this._selectionSpecifier;
if (storySpecifier === '*') {
// '*' means select the first story. If there is none, we have no selection.
[foundStory] = stories;
} else if (typeof storySpecifier === 'string') {
foundStory = Object.values(stories).find((s) => s.id.startsWith(storySpecifier));
} else {
// Try and find a story matching the name/kind, setting no selection if they don't exist.
const { name, kind } = storySpecifier;
foundStory = this.getRawStory(kind, name);
}
if (foundStory) {
this.setSelection({ storyId: foundStory.id, viewMode });
}
}
// If we didn't find a story matching the specifier, we always want to emit CURRENT_STORY_WAS_SET anyway
if (!foundStory && this._channel) {
this._channel.emit(Events.CURRENT_STORY_WAS_SET, this._selection);
}
this.pushToManager();
}
addGlobalMetadata({ parameters, decorators }: StoryMetadata) {
if (parameters) {
const { args, argTypes } = parameters;
if (args || argTypes)
logger.warn(
'Found args/argTypes in global parameters.',
JSON.stringify({ args, argTypes })
);
}
const globalParameters = this._globalMetadata.parameters;
this._globalMetadata.parameters = combineParameters(globalParameters, parameters);
this._globalMetadata.decorators.push(...decorators);
}
clearGlobalDecorators() {
this._globalMetadata.decorators = [];
}
ensureKind(kind: string) {
if (!this._kinds[kind]) {
this._kinds[kind] = {
order: Object.keys(this._kinds).length,
parameters: {},
decorators: [],
};
}
}
addKindMetadata(kind: string, { parameters, decorators }: StoryMetadata) {
this.ensureKind(kind);
if (parameters) {
checkGlobals(parameters);
checkStorySort(parameters);
}
this._kinds[kind].parameters = combineParameters(this._kinds[kind].parameters, parameters);
this._kinds[kind].decorators.push(...decorators);
}
addArgTypesEnhancer(argTypesEnhancer: ArgTypesEnhancer) {
if (Object.keys(this._stories).length > 0)
throw new Error('Cannot add a parameter enhancer to the store after a story has been added.');
this._argTypesEnhancers.push(argTypesEnhancer);
}
// Combine the global, kind & story parameters of a story
combineStoryParameters(parameters: Parameters, kind: StoryKind) {
return combineParameters(
this._globalMetadata.parameters,
this._kinds[kind].parameters,
parameters
);
}
addStory(
{
id,
kind,
name,
storyFn: original,
parameters: storyParameters = {},
decorators: storyDecorators = [],
}: AddStoryArgs,
{
applyDecorators,
allowUnsafe = false,
}: {
applyDecorators: (fn: LegacyStoryFn, decorators: DecoratorFunction[]) => any;
} & AllowUnsafeOption
) {
if (!this._configuring && !allowUnsafe)
throw new Error(
'Cannot add a story when not configuring, see https://github.com/storybookjs/storybook/blob/next/MIGRATION.md#story-store-immutable-outside-of-configuration'
);
if (storyParameters) {
checkGlobals(storyParameters);
checkStorySort(storyParameters);
}
const { _stories } = this;
if (_stories[id]) {
logger.warn(dedent`
Story with id ${id} already exists in the store!
Perhaps you added the same story twice, or you have a name collision?
Story ids need to be unique -- ensure you aren't using the same names modulo url-sanitization.
`);
}
const identification = {
id,
kind,
name,
story: name, // legacy
};
// immutable original storyFn
const getOriginal = () => original;
this.ensureKind(kind);
const kindMetadata: KindMetadata = this._kinds[kind];
const decorators = [
...storyDecorators,
...kindMetadata.decorators,
...this._globalMetadata.decorators,
];
const finalStoryFn = (context: StoryContext) => {
const { passArgsFirst } = context.parameters;
return passArgsFirst || typeof passArgsFirst === 'undefined'
? (original as ArgsStoryFn)(context.args, context)
: original(context);
};
// lazily decorate the story when it's loaded
const getDecorated: () => LegacyStoryFn = memoize(1)(() =>
applyDecorators(finalStoryFn, decorators)
);
const hooks = new HooksContext();
// We need the combined parameters now in order to calculate argTypes, but we won't keep them
const combinedParameters = this.combineStoryParameters(storyParameters, kind);
const { argTypes = {} } = this._argTypesEnhancers.reduce(
(accumlatedParameters: Parameters, enhancer) => ({
...accumlatedParameters,
argTypes: enhancer({
...identification,
storyFn: original,
parameters: accumlatedParameters,
args: {},
globals: {},
}),
}),
combinedParameters
);
const storyParametersWithArgTypes = { ...storyParameters, argTypes };
const storyFn: LegacyStoryFn = (runtimeContext: StoryContext) =>
getDecorated()({
...identification,
...runtimeContext,
// Calculate "combined" parameters at render time (NOTE: for perf we could just use combinedParameters from above?)
parameters: this.combineStoryParameters(storyParametersWithArgTypes, kind),
hooks,
args: _stories[id].args,
globals: this._globals,
});
// Pull out parameters.args.$ || .argTypes.$.defaultValue into initialArgs
const initialArgs: Args = combinedParameters.args;
const defaultArgs: Args = Object.entries(
argTypes as Record<string, { defaultValue: any }>
).reduce((acc, [arg, { defaultValue }]) => {
if (defaultValue) acc[arg] = defaultValue;
return acc;
}, {} as Args);
_stories[id] = {
...identification,
hooks,
getDecorated,
getOriginal,
storyFn,
parameters: { ...storyParameters, argTypes },
args: { ...defaultArgs, ...initialArgs },
};
}
remove = (id: string, { allowUnsafe = false }: AllowUnsafeOption = {}): void => {
if (!this._configuring && !allowUnsafe)
throw new Error(
'Cannot remove a story when not configuring, see https://github.com/storybookjs/storybook/blob/next/MIGRATION.md#story-store-immutable-outside-of-configuration'
);
const { _stories } = this;
const story = _stories[id];
delete _stories[id];
if (story) story.hooks.clean();
};
removeStoryKind(kind: string, { allowUnsafe = false }: AllowUnsafeOption = {}) {
if (!this._configuring && !allowUnsafe)
throw new Error(
'Cannot remove a kind when not configuring, see https://github.com/storybookjs/storybook/blob/next/MIGRATION.md#story-store-immutable-outside-of-configuration'
);
if (!this._kinds[kind]) return;
this._kinds[kind].parameters = {};
this._kinds[kind].decorators = [];
this.cleanHooksForKind(kind);
this._stories = Object.entries(this._stories).reduce((acc: StoreData, [id, story]) => {
if (story.kind !== kind) acc[id] = story;
return acc;
}, {});
}
updateGlobals(newGlobals: Args) {
this._globals = { ...this._globals, ...newGlobals };
this.storeGlobals();
this._channel.emit(Events.GLOBALS_UPDATED, this._globals);
}
updateStoryArgs(id: string, newArgs: Args) {
if (!this._stories[id]) throw new Error(`No story for id ${id}`);
const { args } = this._stories[id];
this._stories[id].args = { ...args, ...newArgs };
this._channel.emit(Events.STORY_ARGS_UPDATED, id, this._stories[id].args);
}
fromId = (id: string): PublishedStoreItem | null => {
try {
const data = this._stories[id as string];
if (!data || !data.getDecorated) {
return null;
}
return this.mergeAdditionalDataToStory(data);
} catch (e) {
logger.warn('failed to get story:', this._stories);
logger.error(e);
return null;
}
};
raw(options?: StoryOptions): PublishedStoreItem[] {
return Object.values(this._stories)
.filter((i) => !!i.getDecorated)
.filter((i) => includeStory(i, options))
.map((i) => this.mergeAdditionalDataToStory(i));
}
sortedStories(): StoreItem[] {
// NOTE: when kinds are HMR'ed they get temporarily removed from the `_stories` array
// and thus lose order. However `_kinds[x].order` preservers the original load order
const kindOrder = mapValues(this._kinds, ({ order }) => order);
const storySortParameter = this._globalMetadata.parameters?.options?.storySort;
return getSortedStories(this._stories, kindOrder, storySortParameter);
}
extract(options: StoryOptions & { normalizeParameters?: boolean } = {}) {
const stories = this.sortedStories();
// removes function values from all stories so they are safe to transport over the channel
return stories.reduce((acc, story) => {
if (!includeStory(story, options)) return acc;
const extracted = toExtracted(story);
if (options.normalizeParameters) return Object.assign(acc, { [story.id]: extracted });
const { parameters, kind } = extracted as {
parameters: Parameters;
kind: StoryKind;
};
return Object.assign(acc, {
[story.id]: Object.assign(extracted, {
parameters: this.combineStoryParameters(parameters, kind),
}),
});
}, {});
}
clearError() {
this._error = null;
}
setError = (err: ErrorLike) => {
this._error = err;
};
getError = (): ErrorLike | undefined => this._error;
setSelectionSpecifier(selectionSpecifier: StoreSelectionSpecifier): void {
this._selectionSpecifier = selectionSpecifier;
}
setSelection(selection: StoreSelection): void {
this._selection = selection;
if (this._channel) {
this._channel.emit(Events.CURRENT_STORY_WAS_SET, this._selection);
}
}
getSelection = (): StoreSelection => this._selection;
getDataForManager = () => {
return {
v: 2,
globalParameters: this._globalMetadata.parameters,
globals: this._globals,
error: this.getError(),
kindParameters: mapValues(this._kinds, (metadata) => metadata.parameters),
stories: this.extract({ includeDocsOnly: true, normalizeParameters: true }),
};
};
pushToManager = () => {
if (this._channel) {
// send to the parent frame.
this._channel.emit(Events.SET_STORIES, this.getDataForManager());
}
};
getStoryKinds() {
return Array.from(new Set(this.raw().map((s) => s.kind)));
}
getStoriesForKind(kind: string) {
return this.raw().filter((story) => story.kind === kind);
}
getRawStory(kind: string, name: string) {
return this.getStoriesForKind(kind).find((s) => s.name === name);
}
cleanHooks(id: string) {
if (this._stories[id]) {
this._stories[id].hooks.clean();
}
}
cleanHooksForKind(kind: string) {
this.getStoriesForKind(kind).map((story) => this.cleanHooks(story.id));
}
// This API is a reimplementation of Storybook's original getStorybook() API.
// As such it may not behave *exactly* the same, but aims to. Some notes:
// - It is *NOT* sorted by the user's sort function, but remains sorted in "insertion order"
// - It does not include docs-only stories
getStorybook(): GetStorybookKind[] {
return Object.values(
this.raw().reduce((kinds: { [kind: string]: GetStorybookKind }, story) => {
if (!includeStory(story)) return kinds;
const {
kind,
name,
storyFn,
parameters: { fileName },
} = story;
// eslint-disable-next-line no-param-reassign
if (!kinds[kind]) kinds[kind] = { kind, fileName, stories: [] };
kinds[kind].stories.push({ name, render: storyFn });
return kinds;
}, {})
).sort((s1, s2) => this._kinds[s1.kind].order - this._kinds[s2.kind].order);
}
private mergeAdditionalDataToStory(story: StoreItem): PublishedStoreItem {
return {
...story,
parameters: this.combineStoryParameters(story.parameters, story.kind),
globals: this._globals,
};
}
}
| lib/client-api/src/story_store.ts | 1 | https://github.com/storybookjs/storybook/commit/962ab44d1155bfc8707695757726149be8713760 | [
0.013231797143816948,
0.0007893016445450485,
0.00016312138177454472,
0.00017734240100253373,
0.001905340002849698
] |
{
"id": 3,
"code_window": [
" const testChannel = mockChannel();\n",
" const store = new StoryStore({ channel: testChannel });\n",
" addStoryToStore(store, 'a', '1', () => 0);\n",
"\n",
" testChannel.emit(Events.UPDATE_STORY_ARGS, 'a--1', { foo: 'bar' });\n",
"\n",
" expect(store.getRawStory('a', '1').args).toEqual({ foo: 'bar' });\n",
" });\n",
"\n",
" it('passes args as the first argument to the story if `parameters.passArgsFirst` is true', () => {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" testChannel.emit(Events.UPDATE_STORY_ARGS, { storyId: 'a--1', updatedArgs: { foo: 'bar' } });\n"
],
"file_path": "lib/client-api/src/story_store.test.ts",
"type": "replace",
"edit_start_line_idx": 203
} | body {
font-family: 'HelveticaNeue-Light', 'Helvetica Neue Light', 'Helvetica Neue', Helvetica, Arial,
'Lucida Grande', sans-serif;
font-weight: 300;
font-size: 16px;
margin: 0;
padding: 0;
}
.App {
text-align: center;
}
.App-logo {
animation: App-logo-spin infinite 20s linear;
height: 120px;
}
.App-header {
background-color: #ddd;
height: 170px;
padding: 20px;
color: black;
}
.App-title {
font-size: 1.5em;
}
.App-intro {
font-size: large;
}
@keyframes App-logo-spin {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}
| lib/cli/test/fixtures/react_static_next/src/app.css | 0 | https://github.com/storybookjs/storybook/commit/962ab44d1155bfc8707695757726149be8713760 | [
0.00017749481776263565,
0.00017570980708114803,
0.00017464604752603918,
0.00017525510338600725,
0.000001035065110954747
] |
{
"id": 3,
"code_window": [
" const testChannel = mockChannel();\n",
" const store = new StoryStore({ channel: testChannel });\n",
" addStoryToStore(store, 'a', '1', () => 0);\n",
"\n",
" testChannel.emit(Events.UPDATE_STORY_ARGS, 'a--1', { foo: 'bar' });\n",
"\n",
" expect(store.getRawStory('a', '1').args).toEqual({ foo: 'bar' });\n",
" });\n",
"\n",
" it('passes args as the first argument to the story if `parameters.passArgsFirst` is true', () => {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" testChannel.emit(Events.UPDATE_STORY_ARGS, { storyId: 'a--1', updatedArgs: { foo: 'bar' } });\n"
],
"file_path": "lib/client-api/src/story_store.test.ts",
"type": "replace",
"edit_start_line_idx": 203
} | module.exports = require('./dist/mdx/mdx-compiler-plugin');
| addons/docs/mdx-compiler-plugin.js | 0 | https://github.com/storybookjs/storybook/commit/962ab44d1155bfc8707695757726149be8713760 | [
0.00017539602413307875,
0.00017539602413307875,
0.00017539602413307875,
0.00017539602413307875,
0
] |
{
"id": 3,
"code_window": [
" const testChannel = mockChannel();\n",
" const store = new StoryStore({ channel: testChannel });\n",
" addStoryToStore(store, 'a', '1', () => 0);\n",
"\n",
" testChannel.emit(Events.UPDATE_STORY_ARGS, 'a--1', { foo: 'bar' });\n",
"\n",
" expect(store.getRawStory('a', '1').args).toEqual({ foo: 'bar' });\n",
" });\n",
"\n",
" it('passes args as the first argument to the story if `parameters.passArgsFirst` is true', () => {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" testChannel.emit(Events.UPDATE_STORY_ARGS, { storyId: 'a--1', updatedArgs: { foo: 'bar' } });\n"
],
"file_path": "lib/client-api/src/story_store.test.ts",
"type": "replace",
"edit_start_line_idx": 203
} | export { RenderContext } from '@storybook/core';
export type StoryFnServerReturnType = any;
export type FetchStoryHtmlType = (url: string, id: string, params: any) => Promise<string | Node>;
export interface IStorybookStory {
name: string;
render: () => any;
}
export interface IStorybookSection {
kind: string;
stories: IStorybookStory[];
}
export interface ShowErrorArgs {
title: string;
description: string;
}
export interface ConfigureOptionsArgs {
fetchStoryHtml: FetchStoryHtmlType;
}
| app/server/src/client/preview/types.ts | 0 | https://github.com/storybookjs/storybook/commit/962ab44d1155bfc8707695757726149be8713760 | [
0.0001856736489571631,
0.0001770654780557379,
0.00016350240912288427,
0.00018202037608716637,
0.000009705813681648578
] |
{
"id": 4,
"code_window": [
" this._channel.on(Events.SET_CURRENT_STORY, ({ storyId, viewMode }) =>\n",
" this.setSelection({ storyId, viewMode })\n",
" );\n",
"\n",
" this._channel.on(Events.UPDATE_STORY_ARGS, (id: string, newArgs: Args) =>\n",
" this.updateStoryArgs(id, newArgs)\n",
" );\n",
"\n",
" this._channel.on(Events.UPDATE_GLOBALS, (newGlobals: Args) => this.updateGlobals(newGlobals));\n",
" }\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" this._channel.on(\n",
" Events.UPDATE_STORY_ARGS,\n",
" ({ storyId, updatedArgs }: { storyId: string; updatedArgs: Args }) =>\n",
" this.updateStoryArgs(storyId, updatedArgs)\n"
],
"file_path": "lib/client-api/src/story_store.ts",
"type": "replace",
"edit_start_line_idx": 157
} | import createChannel from '@storybook/channel-postmessage';
import { toId } from '@storybook/csf';
import addons, { mockChannel } from '@storybook/addons';
import Events from '@storybook/core-events';
import store2 from 'store2';
import StoryStore from './story_store';
import { defaultDecorateStory } from './decorators';
jest.mock('@storybook/node-logger', () => ({
logger: {
info: jest.fn(),
warn: jest.fn(),
error: jest.fn(),
},
}));
jest.mock('store2');
let channel;
beforeEach(() => {
channel = createChannel({ page: 'preview' });
});
function addReverseSorting(store) {
store.addGlobalMetadata({
decorators: [],
parameters: {
options: {
// Test function does reverse alphabetical ordering.
storySort: (a: any, b: any): number =>
a[1].kind === b[1].kind
? 0
: -1 * a[1].id.localeCompare(b[1].id, undefined, { numeric: true }),
},
},
});
}
// make a story and add it to the store
const addStoryToStore = (store, kind, name, storyFn, parameters = {}) =>
store.addStory(
{
kind,
name,
storyFn,
parameters,
id: toId(kind, name),
},
{
applyDecorators: defaultDecorateStory,
}
);
describe('preview.story_store', () => {
describe('extract', () => {
it('produces stories objects with inherited (denormalized) metadata', () => {
const store = new StoryStore({ channel });
store.addGlobalMetadata({ parameters: { global: 'global' }, decorators: [] });
store.addKindMetadata('a', { parameters: { kind: 'kind' }, decorators: [] });
addStoryToStore(store, 'a', '1', () => 0, { story: 'story' });
addStoryToStore(store, 'a', '2', () => 0);
addStoryToStore(store, 'b', '1', () => 0);
const extracted = store.extract();
// We need exact key ordering, even if in theory JS doesn't guarantee it
expect(Object.keys(extracted)).toEqual(['a--1', 'a--2', 'b--1']);
// content of item should be correct
expect(extracted['a--1']).toMatchObject({
id: 'a--1',
kind: 'a',
name: '1',
parameters: { global: 'global', kind: 'kind', story: 'story' },
});
});
});
describe('getDataForManager', () => {
it('produces stories objects with normalized metadata', () => {
const store = new StoryStore({ channel });
store.addGlobalMetadata({ parameters: { global: 'global' }, decorators: [] });
store.addKindMetadata('a', { parameters: { kind: 'kind' }, decorators: [] });
addStoryToStore(store, 'a', '1', () => 0, { story: 'story' });
const { v, globalParameters, kindParameters, stories } = store.getDataForManager();
expect(v).toBe(2);
expect(globalParameters).toEqual({ global: 'global' });
expect(Object.keys(kindParameters)).toEqual(['a']);
expect(kindParameters.a).toEqual({ kind: 'kind' });
expect(Object.keys(stories)).toEqual(['a--1']);
expect(stories['a--1']).toMatchObject({
id: 'a--1',
kind: 'a',
name: '1',
parameters: { story: 'story' },
});
});
});
describe('getRawStory', () => {
it('produces a story with inherited decorators applied', () => {
const store = new StoryStore({ channel });
const globalDecorator = jest.fn().mockImplementation((s) => s());
store.addGlobalMetadata({ parameters: {}, decorators: [globalDecorator] });
const kindDecorator = jest.fn().mockImplementation((s) => s());
store.addKindMetadata('a', { parameters: {}, decorators: [kindDecorator] });
const story = jest.fn();
addStoryToStore(store, 'a', '1', story);
const { getDecorated } = store.getRawStory('a', '1');
getDecorated()();
expect(globalDecorator).toHaveBeenCalled();
expect(kindDecorator).toHaveBeenCalled();
expect(story).toHaveBeenCalled();
});
});
describe('args', () => {
it('is initialized to the value stored in parameters.args[name] || parameters.argType[name].defaultValue', () => {
const store = new StoryStore({ channel });
addStoryToStore(store, 'a', '1', () => 0, {
argTypes: {
arg1: { defaultValue: 'arg1' },
arg2: { defaultValue: 2 },
arg3: { defaultValue: { complex: { object: ['type'] } } },
arg4: {},
arg5: {},
},
args: {
arg2: 3,
arg4: 'foo',
arg6: false,
},
});
expect(store.getRawStory('a', '1').args).toEqual({
arg1: 'arg1',
arg2: 3,
arg3: { complex: { object: ['type'] } },
arg4: 'foo',
arg6: false,
});
});
it('updateStoryArgs changes the args of a story, per-key', () => {
const store = new StoryStore({ channel });
addStoryToStore(store, 'a', '1', () => 0);
expect(store.getRawStory('a', '1').args).toEqual({});
store.updateStoryArgs('a--1', { foo: 'bar' });
expect(store.getRawStory('a', '1').args).toEqual({ foo: 'bar' });
store.updateStoryArgs('a--1', { baz: 'bing' });
expect(store.getRawStory('a', '1').args).toEqual({ foo: 'bar', baz: 'bing' });
});
it('is passed to the story in the context', () => {
const storyFn = jest.fn();
const store = new StoryStore({ channel });
addStoryToStore(store, 'a', '1', storyFn, { passArgsFirst: false });
store.updateStoryArgs('a--1', { foo: 'bar' });
store.getRawStory('a', '1').storyFn();
expect(storyFn).toHaveBeenCalledWith(
expect.objectContaining({
args: { foo: 'bar' },
})
);
});
it('updateStoryArgs emits STORY_ARGS_UPDATED', () => {
const onArgsChangedChannel = jest.fn();
const testChannel = mockChannel();
testChannel.on(Events.STORY_ARGS_UPDATED, onArgsChangedChannel);
const store = new StoryStore({ channel: testChannel });
addStoryToStore(store, 'a', '1', () => 0);
store.updateStoryArgs('a--1', { foo: 'bar' });
expect(onArgsChangedChannel).toHaveBeenCalledWith('a--1', { foo: 'bar' });
store.updateStoryArgs('a--1', { baz: 'bing' });
expect(onArgsChangedChannel).toHaveBeenCalledWith('a--1', { foo: 'bar', baz: 'bing' });
});
it('should update if the UPDATE_STORY_ARGS event is received', () => {
const testChannel = mockChannel();
const store = new StoryStore({ channel: testChannel });
addStoryToStore(store, 'a', '1', () => 0);
testChannel.emit(Events.UPDATE_STORY_ARGS, 'a--1', { foo: 'bar' });
expect(store.getRawStory('a', '1').args).toEqual({ foo: 'bar' });
});
it('passes args as the first argument to the story if `parameters.passArgsFirst` is true', () => {
const store = new StoryStore({ channel });
store.addKindMetadata('a', {
parameters: {
argTypes: {
a: { defaultValue: 1 },
},
},
decorators: [],
});
const storyOne = jest.fn();
addStoryToStore(store, 'a', '1', storyOne, { passArgsFirst: false });
store.getRawStory('a', '1').storyFn();
expect(storyOne).toHaveBeenCalledWith(
expect.objectContaining({
args: { a: 1 },
parameters: expect.objectContaining({}),
})
);
const storyTwo = jest.fn();
addStoryToStore(store, 'a', '2', storyTwo, { passArgsFirst: true });
store.getRawStory('a', '2').storyFn();
expect(storyTwo).toHaveBeenCalledWith(
{ a: 1 },
expect.objectContaining({
args: { a: 1 },
parameters: expect.objectContaining({}),
})
);
});
});
describe('globals', () => {
it('is initialized to the value stored in parameters.globals on the first story', () => {
const store = new StoryStore({ channel });
store.addGlobalMetadata({
decorators: [],
parameters: {
globals: {
arg1: 'arg1',
arg2: 2,
arg3: { complex: { object: ['type'] } },
},
},
});
addStoryToStore(store, 'a', '1', () => 0);
store.finishConfiguring();
expect(store.getRawStory('a', '1').globals).toEqual({
arg1: 'arg1',
arg2: 2,
arg3: { complex: { object: ['type'] } },
});
});
it('is initialized to the default values stored in parameters.globalsTypes on the first story', () => {
const store = new StoryStore({ channel });
store.addGlobalMetadata({
decorators: [],
parameters: {
globals: {
arg1: 'arg1',
arg2: 2,
},
globalTypes: {
arg2: { defaultValue: 'arg2' },
arg3: { defaultValue: { complex: { object: ['type'] } } },
},
},
});
addStoryToStore(store, 'a', '1', () => 0);
store.finishConfiguring();
expect(store.getRawStory('a', '1').globals).toEqual({
// NOTE: we keep arg1, even though it doesn't have a globalArgType
arg1: 'arg1',
arg2: 2,
arg3: { complex: { object: ['type'] } },
});
});
it('it sets session storage on initialization', () => {
(store2.session.set as any).mockClear();
const store = new StoryStore({ channel });
addStoryToStore(store, 'a', '1', () => 0);
store.finishConfiguring();
expect(store2.session.set).toHaveBeenCalled();
});
it('on HMR it sensibly re-initializes with memory', () => {
const store = new StoryStore({ channel });
addons.setChannel(channel);
store.addGlobalMetadata({
decorators: [],
parameters: {
globals: {
arg1: 'arg1',
arg2: 2,
arg4: 4,
},
globalTypes: {
arg2: { defaultValue: 'arg2' },
arg3: { defaultValue: { complex: { object: ['type'] } } },
arg4: {},
},
},
});
addStoryToStore(store, 'a', '1', () => 0);
store.finishConfiguring();
expect(store.getRawStory('a', '1').globals).toEqual({
// We keep arg1, even though it doesn't have a globalArgType, as it is set in globals
arg1: 'arg1',
// We use the value of arg2 that was set in globals
arg2: 2,
arg3: { complex: { object: ['type'] } },
arg4: 4,
});
// HMR
store.startConfiguring();
store.addGlobalMetadata({
decorators: [],
parameters: {
globals: {
arg2: 3,
},
globalTypes: {
arg2: { defaultValue: 'arg2' },
arg3: { defautlValue: { complex: { object: ['changed'] } } },
// XXX: note this currently wouldn't fail because parameters.globals.arg4 isn't cleared
// due to #10005, see below
arg4: {}, // has no default value set but we need to make sure we don't lose it
arg5: { defaultValue: 'new' },
},
},
});
store.finishConfiguring();
expect(store.getRawStory('a', '1').globals).toEqual({
// You cannot remove a global arg in HMR currently, because you cannot remove the
// parameter (see https://github.com/storybookjs/storybook/issues/10005)
arg1: 'arg1',
// We should keep the previous values because we cannot tell if the user changed it or not in the UI
// and we don't want to revert to the defaults every HMR
arg2: 2,
arg3: { complex: { object: ['type'] } },
arg4: 4,
// We take the new value here as it wasn't defined before
arg5: 'new',
});
});
it('it sensibly re-initializes with memory based on session storage', () => {
(store2.session.get as any).mockReturnValueOnce({
globals: {
arg1: 'arg1',
arg2: 2,
arg3: { complex: { object: ['type'] } },
arg4: 4,
},
});
const store = new StoryStore({ channel });
addons.setChannel(channel);
addStoryToStore(store, 'a', '1', () => 0);
store.addGlobalMetadata({
decorators: [],
parameters: {
globals: {
arg2: 3,
},
globalTypes: {
arg2: { defaultValue: 'arg2' },
arg3: { defaultValue: { complex: { object: ['changed'] } } },
arg4: {}, // has no default value set but we need to make sure we don't lose it
arg5: { defaultValue: 'new' },
},
},
});
store.finishConfiguring();
expect(store.getRawStory('a', '1').globals).toEqual({
// We should keep the previous values because we cannot tell if the user changed it or not in the UI
// and we don't want to revert to the defaults every HMR
arg2: 2,
arg3: { complex: { object: ['type'] } },
arg4: 4,
// We take the new value here as it wasn't defined before
arg5: 'new',
});
});
it('updateGlobals changes the global args', () => {
const store = new StoryStore({ channel });
addStoryToStore(store, 'a', '1', () => 0);
expect(store.getRawStory('a', '1').globals).toEqual({});
store.updateGlobals({ foo: 'bar' });
expect(store.getRawStory('a', '1').globals).toEqual({ foo: 'bar' });
store.updateGlobals({ baz: 'bing' });
expect(store.getRawStory('a', '1').globals).toEqual({ foo: 'bar', baz: 'bing' });
});
it('updateGlobals sets session storage', () => {
const store = new StoryStore({ channel });
addStoryToStore(store, 'a', '1', () => 0);
(store2.session.set as any).mockClear();
store.updateGlobals({ foo: 'bar' });
expect(store2.session.set).toHaveBeenCalled();
});
it('is passed to the story in the context', () => {
const storyFn = jest.fn();
const store = new StoryStore({ channel });
store.updateGlobals({ foo: 'bar' });
addStoryToStore(store, 'a', '1', storyFn, { passArgsFirst: false });
store.getRawStory('a', '1').storyFn();
expect(storyFn).toHaveBeenCalledWith(
expect.objectContaining({
globals: { foo: 'bar' },
})
);
store.updateGlobals({ baz: 'bing' });
store.getRawStory('a', '1').storyFn();
expect(storyFn).toHaveBeenCalledWith(
expect.objectContaining({
globals: { foo: 'bar', baz: 'bing' },
})
);
});
it('updateGlobals emits GLOBALS_UPDATED', () => {
const onGlobalsChangedChannel = jest.fn();
const testChannel = mockChannel();
testChannel.on(Events.GLOBALS_UPDATED, onGlobalsChangedChannel);
const store = new StoryStore({ channel: testChannel });
addStoryToStore(store, 'a', '1', () => 0);
store.updateGlobals({ foo: 'bar' });
expect(onGlobalsChangedChannel).toHaveBeenCalledWith({ foo: 'bar' });
store.updateGlobals({ baz: 'bing' });
expect(onGlobalsChangedChannel).toHaveBeenCalledWith({ foo: 'bar', baz: 'bing' });
});
it('should update if the UPDATE_GLOBALS event is received', () => {
const testChannel = mockChannel();
const store = new StoryStore({ channel: testChannel });
addStoryToStore(store, 'a', '1', () => 0);
testChannel.emit(Events.UPDATE_GLOBALS, { foo: 'bar' });
expect(store.getRawStory('a', '1').globals).toEqual({ foo: 'bar' });
});
it('DOES NOT pass globals as the first argument to the story if `parameters.passArgsFirst` is true', () => {
const store = new StoryStore({ channel });
const storyOne = jest.fn();
addStoryToStore(store, 'a', '1', storyOne, { passArgsFirst: false });
store.updateGlobals({ foo: 'bar' });
store.getRawStory('a', '1').storyFn();
expect(storyOne).toHaveBeenCalledWith(
expect.objectContaining({
globals: { foo: 'bar' },
})
);
const storyTwo = jest.fn();
addStoryToStore(store, 'a', '2', storyTwo, { passArgsFirst: true });
store.getRawStory('a', '2').storyFn();
expect(storyTwo).toHaveBeenCalledWith(
{},
expect.objectContaining({
globals: { foo: 'bar' },
})
);
});
});
describe('argTypesEnhancer', () => {
it('allows you to alter argTypes when stories are added', () => {
const store = new StoryStore({ channel });
const enhancer = jest.fn((context) => ({ ...context.parameters.argTypes, c: 'd' }));
store.addArgTypesEnhancer(enhancer);
addStoryToStore(store, 'a', '1', () => 0, { argTypes: { a: 'b' } });
expect(enhancer).toHaveBeenCalledWith(
expect.objectContaining({ parameters: { argTypes: { a: 'b' } } })
);
expect(store.getRawStory('a', '1').parameters.argTypes).toEqual({ a: 'b', c: 'd' });
});
it('recursively passes argTypes to successive enhancers', () => {
const store = new StoryStore({ channel });
const firstEnhancer = jest.fn((context) => ({ ...context.parameters.argTypes, c: 'd' }));
store.addArgTypesEnhancer(firstEnhancer);
const secondEnhancer = jest.fn((context) => ({ ...context.parameters.argTypes, e: 'f' }));
store.addArgTypesEnhancer(secondEnhancer);
addStoryToStore(store, 'a', '1', () => 0, { argTypes: { a: 'b' } });
expect(firstEnhancer).toHaveBeenCalledWith(
expect.objectContaining({ parameters: { argTypes: { a: 'b' } } })
);
expect(secondEnhancer).toHaveBeenCalledWith(
expect.objectContaining({ parameters: { argTypes: { a: 'b', c: 'd' } } })
);
expect(store.getRawStory('a', '1').parameters.argTypes).toEqual({ a: 'b', c: 'd', e: 'f' });
});
it('does not merge argType enhancer results', () => {
const store = new StoryStore({ channel });
const enhancer = jest.fn().mockReturnValue({ c: 'd' });
store.addArgTypesEnhancer(enhancer);
addStoryToStore(store, 'a', '1', () => 0, { argTypes: { a: 'b' } });
expect(enhancer).toHaveBeenCalledWith(
expect.objectContaining({ parameters: { argTypes: { a: 'b' } } })
);
expect(store.getRawStory('a', '1').parameters.argTypes).toEqual({ c: 'd' });
});
it('allows you to alter argTypes when stories are re-added', () => {
const store = new StoryStore({ channel });
addons.setChannel(channel);
const enhancer = jest.fn((context) => ({ ...context.parameters.argTypes, c: 'd' }));
store.addArgTypesEnhancer(enhancer);
addStoryToStore(store, 'a', '1', () => 0, { argTypes: { a: 'b' } });
enhancer.mockClear();
store.removeStoryKind('a');
addStoryToStore(store, 'a', '1', () => 0, { argTypes: { e: 'f' } });
expect(enhancer).toHaveBeenCalledWith(
expect.objectContaining({ parameters: { argTypes: { e: 'f' } } })
);
expect(store.getRawStory('a', '1').parameters.argTypes).toEqual({ e: 'f', c: 'd' });
});
});
describe('selection specifiers', () => {
describe('if you use *', () => {
it('selects the first story in the store', () => {
const store = new StoryStore({ channel });
store.setSelectionSpecifier({ storySpecifier: '*', viewMode: 'story' });
addStoryToStore(store, 'a', '1', () => 0);
addStoryToStore(store, 'a', '2', () => 0);
addStoryToStore(store, 'b', '1', () => 0);
store.finishConfiguring();
expect(store.getSelection()).toEqual({ storyId: 'a--1', viewMode: 'story' });
});
it('takes into account sorting', () => {
const store = new StoryStore({ channel });
store.setSelectionSpecifier({ storySpecifier: '*', viewMode: 'story' });
addReverseSorting(store);
addStoryToStore(store, 'a', '1', () => 0);
addStoryToStore(store, 'a', '2', () => 0);
addStoryToStore(store, 'b', '1', () => 0);
store.finishConfiguring();
expect(store.getSelection()).toEqual({ storyId: 'b--1', viewMode: 'story' });
});
it('selects nothing if there are no stories', () => {
const store = new StoryStore({ channel });
store.setSelectionSpecifier({ storySpecifier: '*', viewMode: 'story' });
store.finishConfiguring();
expect(store.getSelection()).toEqual(undefined);
});
});
describe('if you use a component or group id', () => {
it('selects the first story for the component', () => {
const store = new StoryStore({ channel });
store.setSelectionSpecifier({ storySpecifier: 'b', viewMode: 'story' });
addStoryToStore(store, 'a', '1', () => 0);
addStoryToStore(store, 'a', '2', () => 0);
addStoryToStore(store, 'b', '1', () => 0);
store.finishConfiguring();
expect(store.getSelection()).toEqual({ storyId: 'b--1', viewMode: 'story' });
});
it('selects the first story for the group', () => {
const store = new StoryStore({ channel });
store.setSelectionSpecifier({ storySpecifier: 'g2', viewMode: 'story' });
addStoryToStore(store, 'g1/a', '1', () => 0);
addStoryToStore(store, 'g2/a', '1', () => 0);
addStoryToStore(store, 'g2/b', '1', () => 0);
store.finishConfiguring();
expect(store.getSelection()).toEqual({ storyId: 'g2-a--1', viewMode: 'story' });
});
it('selects nothing if the component or group does not exist', () => {
const store = new StoryStore({ channel });
store.setSelectionSpecifier({ storySpecifier: 'c', viewMode: 'story' });
addStoryToStore(store, 'a', '1', () => 0);
addStoryToStore(store, 'a', '2', () => 0);
addStoryToStore(store, 'b', '1', () => 0);
store.finishConfiguring();
expect(store.getSelection()).toEqual(undefined);
});
});
describe('if you use a storyId', () => {
it('selects a specific story', () => {
const store = new StoryStore({ channel });
store.setSelectionSpecifier({ storySpecifier: 'a--2', viewMode: 'story' });
addStoryToStore(store, 'a', '1', () => 0);
addStoryToStore(store, 'a', '2', () => 0);
addStoryToStore(store, 'b', '1', () => 0);
store.finishConfiguring();
expect(store.getSelection()).toEqual({ storyId: 'a--2', viewMode: 'story' });
});
it('selects nothing if you the story does not exist', () => {
const store = new StoryStore({ channel });
store.setSelectionSpecifier({ storySpecifier: 'a--3', viewMode: 'story' });
addStoryToStore(store, 'a', '1', () => 0);
addStoryToStore(store, 'a', '2', () => 0);
addStoryToStore(store, 'b', '1', () => 0);
store.finishConfiguring();
expect(store.getSelection()).toEqual(undefined);
});
});
describe('if you use no specifier', () => {
it('selects nothing', () => {
const store = new StoryStore({ channel });
addStoryToStore(store, 'a', '1', () => 0);
addStoryToStore(store, 'a', '2', () => 0);
addStoryToStore(store, 'b', '1', () => 0);
store.finishConfiguring();
expect(store.getSelection()).toEqual(undefined);
});
});
describe('HMR behaviour', () => {
it('retains successful selection', () => {
const store = new StoryStore({ channel });
store.setSelectionSpecifier({ storySpecifier: 'a--1', viewMode: 'story' });
addStoryToStore(store, 'a', '1', () => 0);
store.finishConfiguring();
expect(store.getSelection()).toEqual({ storyId: 'a--1', viewMode: 'story' });
store.startConfiguring();
store.removeStoryKind('a');
addStoryToStore(store, 'a', '1', () => 0);
store.finishConfiguring();
expect(store.getSelection()).toEqual({ storyId: 'a--1', viewMode: 'story' });
});
it('tries again with a specifier if it failed the first time', () => {
const store = new StoryStore({ channel });
store.setSelectionSpecifier({ storySpecifier: 'a--2', viewMode: 'story' });
addStoryToStore(store, 'a', '1', () => 0);
store.finishConfiguring();
expect(store.getSelection()).toEqual(undefined);
store.startConfiguring();
store.removeStoryKind('a');
addStoryToStore(store, 'a', '1', () => 0);
addStoryToStore(store, 'a', '2', () => 0);
store.finishConfiguring();
expect(store.getSelection()).toEqual({ storyId: 'a--2', viewMode: 'story' });
});
it('DOES NOT try again if the selection changed in the meantime', () => {
const store = new StoryStore({ channel });
store.setSelectionSpecifier({ storySpecifier: 'a--2', viewMode: 'story' });
addStoryToStore(store, 'a', '1', () => 0);
store.finishConfiguring();
expect(store.getSelection()).toEqual(undefined);
store.setSelection({ storyId: 'a--1', viewMode: 'story' });
expect(store.getSelection()).toEqual({ storyId: 'a--1', viewMode: 'story' });
store.startConfiguring();
store.removeStoryKind('a');
addStoryToStore(store, 'a', '1', () => 0);
addStoryToStore(store, 'a', '2', () => 0);
store.finishConfiguring();
expect(store.getSelection()).toEqual({ storyId: 'a--1', viewMode: 'story' });
});
});
});
describe('storySort', () => {
it('sorts stories using given function', () => {
const store = new StoryStore({ channel });
addReverseSorting(store);
addStoryToStore(store, 'a/a', '1', () => 0);
addStoryToStore(store, 'a/a', '2', () => 0);
addStoryToStore(store, 'a/b', '1', () => 0);
addStoryToStore(store, 'b/b1', '1', () => 0);
addStoryToStore(store, 'b/b10', '1', () => 0);
addStoryToStore(store, 'b/b9', '1', () => 0);
addStoryToStore(store, 'c', '1', () => 0);
const extracted = store.extract();
expect(Object.keys(extracted)).toEqual([
'c--1',
'b-b10--1',
'b-b9--1',
'b-b1--1',
'a-b--1',
'a-a--1',
'a-a--2',
]);
});
it('sorts stories alphabetically', () => {
const store = new StoryStore({ channel });
store.addGlobalMetadata({
decorators: [],
parameters: {
options: {
storySort: {
method: 'alphabetical',
},
},
},
});
addStoryToStore(store, 'a/b', '1', () => 0);
addStoryToStore(store, 'a/a', '2', () => 0);
addStoryToStore(store, 'a/a', '1', () => 0);
addStoryToStore(store, 'c', '1', () => 0);
addStoryToStore(store, 'b/b10', '1', () => 0);
addStoryToStore(store, 'b/b9', '1', () => 0);
addStoryToStore(store, 'b/b1', '1', () => 0);
const extracted = store.extract();
expect(Object.keys(extracted)).toEqual([
'a-a--2',
'a-a--1',
'a-b--1',
'b-b1--1',
'b-b9--1',
'b-b10--1',
'c--1',
]);
});
it('sorts stories in specified order or alphabetically', () => {
const store = new StoryStore({ channel });
store.addGlobalMetadata({
decorators: [],
parameters: {
options: {
storySort: {
method: 'alphabetical',
order: ['b', ['bc', 'ba', 'bb'], 'a', 'c'],
},
},
},
});
addStoryToStore(store, 'a/b', '1', () => 0);
addStoryToStore(store, 'a', '1', () => 0);
addStoryToStore(store, 'c', '1', () => 0);
addStoryToStore(store, 'b/bd', '1', () => 0);
addStoryToStore(store, 'b/bb', '1', () => 0);
addStoryToStore(store, 'b/ba', '1', () => 0);
addStoryToStore(store, 'b/bc', '1', () => 0);
addStoryToStore(store, 'b', '1', () => 0);
const extracted = store.extract();
expect(Object.keys(extracted)).toEqual([
'b--1',
'b-bc--1',
'b-ba--1',
'b-bb--1',
'b-bd--1',
'a--1',
'a-b--1',
'c--1',
]);
});
it('sorts stories in specified order or by configure order', () => {
const store = new StoryStore({ channel });
store.addGlobalMetadata({
decorators: [],
parameters: {
options: {
storySort: {
method: 'configure',
order: ['b', 'a', 'c'],
},
},
},
});
addStoryToStore(store, 'a/b', '1', () => 0);
addStoryToStore(store, 'a', '1', () => 0);
addStoryToStore(store, 'c', '1', () => 0);
addStoryToStore(store, 'b/bd', '1', () => 0);
addStoryToStore(store, 'b/bb', '1', () => 0);
addStoryToStore(store, 'b/ba', '1', () => 0);
addStoryToStore(store, 'b/bc', '1', () => 0);
addStoryToStore(store, 'b', '1', () => 0);
const extracted = store.extract();
expect(Object.keys(extracted)).toEqual([
'b--1',
'b-bd--1',
'b-bb--1',
'b-ba--1',
'b-bc--1',
'a--1',
'a-b--1',
'c--1',
]);
});
});
describe('configuration', () => {
it('does not allow addStory if not configuring, unless allowUsafe=true', () => {
const store = new StoryStore({ channel });
store.finishConfiguring();
expect(() => addStoryToStore(store, 'a', '1', () => 0)).toThrow(
'Cannot add a story when not configuring'
);
expect(() =>
store.addStory(
{
kind: 'a',
name: '1',
storyFn: () => 0,
parameters: {},
id: 'a--1',
},
{
applyDecorators: defaultDecorateStory,
allowUnsafe: true,
}
)
).not.toThrow();
});
it('does not allow remove if not configuring, unless allowUsafe=true', () => {
const store = new StoryStore({ channel });
addons.setChannel(channel);
addStoryToStore(store, 'a', '1', () => 0);
store.finishConfiguring();
expect(() => store.remove('a--1')).toThrow('Cannot remove a story when not configuring');
expect(() => store.remove('a--1', { allowUnsafe: true })).not.toThrow();
});
it('does not allow removeStoryKind if not configuring, unless allowUsafe=true', () => {
const store = new StoryStore({ channel });
addons.setChannel(channel);
addStoryToStore(store, 'a', '1', () => 0);
store.finishConfiguring();
expect(() => store.removeStoryKind('a')).toThrow('Cannot remove a kind when not configuring');
expect(() => store.removeStoryKind('a', { allowUnsafe: true })).not.toThrow();
});
it('waits for configuration to be over before emitting SET_STORIES', () => {
const onSetStories = jest.fn();
channel.on(Events.SET_STORIES, onSetStories);
const store = new StoryStore({ channel });
addStoryToStore(store, 'a', '1', () => 0);
expect(onSetStories).not.toHaveBeenCalled();
store.finishConfiguring();
expect(onSetStories).toHaveBeenCalledWith({
v: 2,
globals: {},
globalParameters: {},
kindParameters: { a: {} },
stories: {
'a--1': expect.objectContaining({
id: 'a--1',
}),
},
});
});
it('correctly emits globals with SET_STORIES', () => {
const onSetStories = jest.fn();
channel.on(Events.SET_STORIES, onSetStories);
const store = new StoryStore({ channel });
store.addGlobalMetadata({
decorators: [],
parameters: {
globalTypes: {
arg1: { defaultValue: 'arg1' },
},
},
});
addStoryToStore(store, 'a', '1', () => 0);
expect(onSetStories).not.toHaveBeenCalled();
store.finishConfiguring();
expect(onSetStories).toHaveBeenCalledWith({
v: 2,
globals: { arg1: 'arg1' },
globalParameters: {
// NOTE: Currently globalArg[Types] are emitted as parameters but this may not remain
globalTypes: {
arg1: { defaultValue: 'arg1' },
},
},
kindParameters: { a: {} },
stories: {
'a--1': expect.objectContaining({
id: 'a--1',
}),
},
});
});
it('emits an empty SET_STORIES if no stories were added during configuration', () => {
const onSetStories = jest.fn();
channel.on(Events.SET_STORIES, onSetStories);
const store = new StoryStore({ channel });
store.finishConfiguring();
expect(onSetStories).toHaveBeenCalledWith({
v: 2,
globals: {},
globalParameters: {},
kindParameters: {},
stories: {},
});
});
it('allows configuration as second time (HMR)', () => {
const onSetStories = jest.fn();
channel.on(Events.SET_STORIES, onSetStories);
const store = new StoryStore({ channel });
store.finishConfiguring();
onSetStories.mockClear();
store.startConfiguring();
addStoryToStore(store, 'a', '1', () => 0);
store.finishConfiguring();
expect(onSetStories).toHaveBeenCalledWith({
v: 2,
globals: {},
globalParameters: {},
kindParameters: { a: {} },
stories: {
'a--1': expect.objectContaining({
id: 'a--1',
}),
},
});
});
});
describe('HMR behaviour', () => {
it('emits the right things after removing a story', () => {
const onSetStories = jest.fn();
channel.on(Events.SET_STORIES, onSetStories);
const store = new StoryStore({ channel });
// For hooks
addons.setChannel(channel);
store.startConfiguring();
addStoryToStore(store, 'kind-1', 'story-1.1', () => 0);
addStoryToStore(store, 'kind-1', 'story-1.2', () => 0);
store.finishConfiguring();
onSetStories.mockClear();
store.startConfiguring();
store.remove(toId('kind-1', 'story-1.1'));
store.finishConfiguring();
expect(onSetStories).toHaveBeenCalledWith({
v: 2,
globals: {},
globalParameters: {},
kindParameters: { 'kind-1': {} },
stories: {
'kind-1--story-1-2': expect.objectContaining({
id: 'kind-1--story-1-2',
}),
},
});
expect(store.fromId(toId('kind-1', 'story-1.1'))).toBeFalsy();
expect(store.fromId(toId('kind-1', 'story-1.2'))).toBeTruthy();
});
it('emits the right things after removing a kind', () => {
const onSetStories = jest.fn();
channel.on(Events.SET_STORIES, onSetStories);
const store = new StoryStore({ channel });
// For hooks
addons.setChannel(channel);
store.startConfiguring();
addStoryToStore(store, 'kind-1', 'story-1.1', () => 0);
addStoryToStore(store, 'kind-1', 'story-1.2', () => 0);
addStoryToStore(store, 'kind-2', 'story-2.1', () => 0);
addStoryToStore(store, 'kind-2', 'story-2.2', () => 0);
store.finishConfiguring();
onSetStories.mockClear();
store.startConfiguring();
store.removeStoryKind('kind-1');
store.finishConfiguring();
expect(onSetStories).toHaveBeenCalledWith({
v: 2,
globals: {},
globalParameters: {},
kindParameters: { 'kind-1': {}, 'kind-2': {} },
stories: {
'kind-2--story-2-1': expect.objectContaining({
id: 'kind-2--story-2-1',
}),
'kind-2--story-2-2': expect.objectContaining({
id: 'kind-2--story-2-2',
}),
},
});
expect(store.fromId(toId('kind-1', 'story-1.1'))).toBeFalsy();
expect(store.fromId(toId('kind-2', 'story-2.1'))).toBeTruthy();
});
// eslint-disable-next-line jest/expect-expect
it('should not error even if you remove a kind that does not exist', () => {
const store = new StoryStore({ channel });
store.removeStoryKind('kind');
});
});
describe('CURRENT_STORY_WAS_SET', () => {
it('is emitted when configuration ends', () => {
const onCurrentStoryWasSet = jest.fn();
channel.on(Events.CURRENT_STORY_WAS_SET, onCurrentStoryWasSet);
const store = new StoryStore({ channel });
store.finishConfiguring();
expect(onCurrentStoryWasSet).toHaveBeenCalled();
});
it('is emitted when setSelection is called', () => {
const onCurrentStoryWasSet = jest.fn();
channel.on(Events.CURRENT_STORY_WAS_SET, onCurrentStoryWasSet);
const store = new StoryStore({ channel });
store.finishConfiguring();
onCurrentStoryWasSet.mockClear();
store.setSelection({ storyId: 'a--1', viewMode: 'story' });
expect(onCurrentStoryWasSet).toHaveBeenCalled();
});
});
});
| lib/client-api/src/story_store.test.ts | 1 | https://github.com/storybookjs/storybook/commit/962ab44d1155bfc8707695757726149be8713760 | [
0.002275224309414625,
0.0003056470595765859,
0.00016463646898046136,
0.00019184325356036425,
0.00031539914198219776
] |
{
"id": 4,
"code_window": [
" this._channel.on(Events.SET_CURRENT_STORY, ({ storyId, viewMode }) =>\n",
" this.setSelection({ storyId, viewMode })\n",
" );\n",
"\n",
" this._channel.on(Events.UPDATE_STORY_ARGS, (id: string, newArgs: Args) =>\n",
" this.updateStoryArgs(id, newArgs)\n",
" );\n",
"\n",
" this._channel.on(Events.UPDATE_GLOBALS, (newGlobals: Args) => this.updateGlobals(newGlobals));\n",
" }\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" this._channel.on(\n",
" Events.UPDATE_STORY_ARGS,\n",
" ({ storyId, updatedArgs }: { storyId: string; updatedArgs: Args }) =>\n",
" this.updateStoryArgs(storyId, updatedArgs)\n"
],
"file_path": "lib/client-api/src/story_store.ts",
"type": "replace",
"edit_start_line_idx": 157
} | import path from 'path';
import initStoryshots, { renderWithOptions } from '../dist';
initStoryshots({
framework: 'react',
configPath: path.join(__dirname, '..', '.storybook'),
test: renderWithOptions({}),
});
| addons/storyshots/storyshots-core/stories/storyshot.renderWithOptions.test.js | 0 | https://github.com/storybookjs/storybook/commit/962ab44d1155bfc8707695757726149be8713760 | [
0.00017079149256460369,
0.00017079149256460369,
0.00017079149256460369,
0.00017079149256460369,
0
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.