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": 4, "code_window": [ "import path from 'path'\n", "import chalk from 'chalk'\n", "import fs from 'fs-extra'\n", "import { ServerPlugin } from '.'\n", "import { resolveVue, cachedRead } from '../utils'\n", "import { URL } from 'url'\n", "import { resolveOptimizedModule, resolveNodeModuleFile } from '../resolver'\n", "\n", "const debug = require('debug')('vite:resolve')\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { resolveVue } from '../utils'\n" ], "file_path": "src/node/server/serverPluginModuleResolve.ts", "type": "replace", "edit_start_line_idx": 4 }
## Git Commit Message Convention > This is adapted from [Angular's commit convention](https://github.com/conventional-changelog/conventional-changelog/tree/master/packages/conventional-changelog-angular). #### TL;DR: Messages must be matched by the following regex: ``` js /^(revert: )?(feat|fix|docs|style|refactor|perf|test|workflow|build|ci|chore|types|wip): .{1,50}/ ``` #### Examples Appears under "Features" header, `dev` subheader: ``` feat(dev): add 'comments' option ``` Appears under "Bug Fixes" header, `dev` subheader, with a link to issue #28: ``` fix(dev): fix dev error close #28 ``` Appears under "Performance Improvements" header, and under "Breaking Changes" with the breaking change explanation: ``` perf(build): remove 'foo' option BREAKING CHANGE: The 'foo' option has been removed. ``` The following commit and commit `667ecc1` do not appear in the changelog if they are under the same release. If not, the revert commit appears under the "Reverts" header. ``` revert: feat(compiler): add 'comments' option This reverts commit 667ecc1654a317a13331b17617d973392f415f02. ``` ### Full Message Format A commit message consists of a **header**, **body** and **footer**. The header has a **type**, **scope** and **subject**: ``` <type>(<scope>): <subject> <BLANK LINE> <body> <BLANK LINE> <footer> ``` The **header** is mandatory and the **scope** of the header is optional. ### Revert If the commit reverts a previous commit, it should begin with `revert: `, followed by the header of the reverted commit. In the body, it should say: `This reverts commit <hash>.`, where the hash is the SHA of the commit being reverted. ### Type If the prefix is `feat`, `fix` or `perf`, it will appear in the changelog. However, if there is any [BREAKING CHANGE](#footer), the commit will always appear in the changelog. Other prefixes are up to your discretion. Suggested prefixes are `docs`, `chore`, `style`, `refactor`, and `test` for non-changelog related tasks. ### Scope The scope could be anything specifying the place of the commit change. For example `dev`, `build`, `workflow`, `cli` etc... ### Subject The subject contains a succinct description of the change: * use the imperative, present tense: "change" not "changed" nor "changes" * don't capitalize the first letter * no dot (.) at the end ### Body Just as in the **subject**, use the imperative, present tense: "change" not "changed" nor "changes". The body should include the motivation for the change and contrast this with previous behavior. ### Footer The footer should contain any information about **Breaking Changes** and is also the place to reference GitHub issues that this commit **Closes**. **Breaking Changes** should start with the word `BREAKING CHANGE:` with a space or two newlines. The rest of the commit message is then used for this.
.github/commit-convention.md
0
https://github.com/vitejs/vite/commit/49d50eebe86e18ea124d6223d258cc1dfe87a268
[ 0.00017516606021672487, 0.00017104065045714378, 0.00016685582522768527, 0.00017116953677032143, 0.00000267025984612701 ]
{ "id": 4, "code_window": [ "import path from 'path'\n", "import chalk from 'chalk'\n", "import fs from 'fs-extra'\n", "import { ServerPlugin } from '.'\n", "import { resolveVue, cachedRead } from '../utils'\n", "import { URL } from 'url'\n", "import { resolveOptimizedModule, resolveNodeModuleFile } from '../resolver'\n", "\n", "const debug = require('debug')('vite:resolve')\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { resolveVue } from '../utils'\n" ], "file_path": "src/node/server/serverPluginModuleResolve.ts", "type": "replace", "edit_start_line_idx": 4 }
{ "compilerOptions": { "jsx": "preserve", "baseUrl": "../", "paths": { "vite": ["dist/index.d.ts"] } } }
playground/tsconfig.json
0
https://github.com/vitejs/vite/commit/49d50eebe86e18ea124d6223d258cc1dfe87a268
[ 0.00017041734827216715, 0.00017041734827216715, 0.00017041734827216715, 0.00017041734827216715, 0 ]
{ "id": 5, "code_window": [ " moduleIdToFileMap.set(id, file)\n", " moduleFileToIdMap.set(file, ctx.path)\n", " debug(`(${type}) ${id} -> ${getDebugPath(root, file)}`)\n", " await cachedRead(ctx, file)\n", " return next()\n", " }\n", "\n", " // special handling for vue runtime in case it's not installed\n", " if (!vueResolved.isLocal && id in vueResolved) {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " await ctx.read(ctx, file)\n" ], "file_path": "src/node/server/serverPluginModuleResolve.ts", "type": "replace", "edit_start_line_idx": 37 }
import path from 'path' import fs from 'fs-extra' import { RequestListener, Server } from 'http' import { ServerOptions } from 'https' import Koa, { DefaultState, DefaultContext } from 'koa' import chokidar from 'chokidar' import { createResolver, InternalResolver } from '../resolver' import { moduleRewritePlugin } from './serverPluginModuleRewrite' import { moduleResolvePlugin } from './serverPluginModuleResolve' import { vuePlugin } from './serverPluginVue' import { hmrPlugin, HMRWatcher } from './serverPluginHmr' import { serveStaticPlugin } from './serverPluginServeStatic' import { jsonPlugin } from './serverPluginJson' import { cssPlugin } from './serverPluginCss' import { assetPathPlugin } from './serverPluginAssets' import { esbuildPlugin } from './serverPluginEsbuild' import { ServerConfig } from '../config' import { createServerTransformPlugin } from '../transform' import { serviceWorkerPlugin } from './serverPluginServiceWorker' import { htmlRewritePlugin } from './serverPluginHtml' import { proxyPlugin } from './serverPluginProxy' import { createCertificate } from '../utils/createCertificate' import { envPlugin } from './serverPluginEnv' export { rewriteImports } from './serverPluginModuleRewrite' import { sourceMapPlugin, SourceMap } from './serverPluginSourceMap' export type ServerPlugin = (ctx: ServerPluginContext) => void export interface ServerPluginContext { root: string app: Koa<State, Context> server: Server watcher: HMRWatcher resolver: InternalResolver config: ServerConfig & { __path?: string } } export interface State extends DefaultState {} export type Context = DefaultContext & ServerPluginContext & { map?: SourceMap | null } export function createServer(config: ServerConfig): Server { const { root = process.cwd(), configureServer = [], resolvers = [], alias = {}, transforms = [], vueCustomBlockTransforms = {}, optimizeDeps = {} } = config const app = new Koa<State, Context>() const server = resolveServer(config, app.callback()) const watcher = chokidar.watch(root, { ignored: [/\bnode_modules\b/, /\b\.git\b/] }) as HMRWatcher const resolver = createResolver(root, resolvers, alias) const context = { root, app, server, watcher, resolver, config } // attach server context to koa context app.use((ctx, next) => { Object.assign(ctx, context) return next() }) const resolvedPlugins = [ // rewrite and source map plugins take highest priority and should be run // after all other middlewares have finished sourceMapPlugin, moduleRewritePlugin, htmlRewritePlugin, // user plugins ...(Array.isArray(configureServer) ? configureServer : [configureServer]), envPlugin, moduleResolvePlugin, proxyPlugin, serviceWorkerPlugin, hmrPlugin, ...(transforms.length || Object.keys(vueCustomBlockTransforms).length ? [createServerTransformPlugin(transforms, vueCustomBlockTransforms)] : []), vuePlugin, cssPlugin, esbuildPlugin, jsonPlugin, assetPathPlugin, serveStaticPlugin ] resolvedPlugins.forEach((m) => m(context)) const listen = server.listen.bind(server) server.listen = (async (...args: any[]) => { if (optimizeDeps.auto !== false) { await require('../optimizer').optimizeDeps(config) } return listen(...args) }) as any return server } function resolveServer( { https = false, httpsOption = {} }: ServerConfig, requestListener: RequestListener ) { if (https) { return require('https').createServer( resolveHttpsConfig(httpsOption), requestListener ) } else { return require('http').createServer(requestListener) } } function resolveHttpsConfig(httpsOption: ServerOptions) { const { ca, cert, key, pfx } = httpsOption Object.assign(httpsOption, { ca: readFileIfExits(ca), cert: readFileIfExits(cert), key: readFileIfExits(key), pfx: readFileIfExits(pfx) }) if (!httpsOption.key || !httpsOption.cert) { httpsOption.cert = httpsOption.key = createCertificate() } return httpsOption } function readFileIfExits(value?: string | Buffer | any) { if (value && !Buffer.isBuffer(value)) { try { return fs.readFileSync(path.resolve(value as string)) } catch (e) { return value } } return value }
src/node/server/index.ts
1
https://github.com/vitejs/vite/commit/49d50eebe86e18ea124d6223d258cc1dfe87a268
[ 0.001382280606776476, 0.00025316496612504125, 0.0001634078216738999, 0.00017399806529283524, 0.0002920299593824893 ]
{ "id": 5, "code_window": [ " moduleIdToFileMap.set(id, file)\n", " moduleFileToIdMap.set(file, ctx.path)\n", " debug(`(${type}) ${id} -> ${getDebugPath(root, file)}`)\n", " await cachedRead(ctx, file)\n", " return next()\n", " }\n", "\n", " // special handling for vue runtime in case it's not installed\n", " if (!vueResolved.isLocal && id in vueResolved) {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " await ctx.read(ctx, file)\n" ], "file_path": "src/node/server/serverPluginModuleResolve.ts", "type": "replace", "edit_start_line_idx": 37 }
<h2>SFC Src Imports</h2> <div class="src-imports-script">{{ msg }}</div> <div class="src-imports-style">This should be light gray</div>
playground/src-import/template.html
0
https://github.com/vitejs/vite/commit/49d50eebe86e18ea124d6223d258cc1dfe87a268
[ 0.00017425332043785602, 0.00017425332043785602, 0.00017425332043785602, 0.00017425332043785602, 0 ]
{ "id": 5, "code_window": [ " moduleIdToFileMap.set(id, file)\n", " moduleFileToIdMap.set(file, ctx.path)\n", " debug(`(${type}) ${id} -> ${getDebugPath(root, file)}`)\n", " await cachedRead(ctx, file)\n", " return next()\n", " }\n", "\n", " // special handling for vue runtime in case it's not installed\n", " if (!vueResolved.isLocal && id in vueResolved) {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " await ctx.read(ctx, file)\n" ], "file_path": "src/node/server/serverPluginModuleResolve.ts", "type": "replace", "edit_start_line_idx": 37 }
.sfc-style-css-module-at-import { color: red; }
playground/css-@import/testCssModuleAtImportFromStyle.module.css
0
https://github.com/vitejs/vite/commit/49d50eebe86e18ea124d6223d258cc1dfe87a268
[ 0.00017407696577720344, 0.00017407696577720344, 0.00017407696577720344, 0.00017407696577720344, 0 ]
{ "id": 5, "code_window": [ " moduleIdToFileMap.set(id, file)\n", " moduleFileToIdMap.set(file, ctx.path)\n", " debug(`(${type}) ${id} -> ${getDebugPath(root, file)}`)\n", " await cachedRead(ctx, file)\n", " return next()\n", " }\n", "\n", " // special handling for vue runtime in case it's not installed\n", " if (!vueResolved.isLocal && id in vueResolved) {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " await ctx.read(ctx, file)\n" ], "file_path": "src/node/server/serverPluginModuleResolve.ts", "type": "replace", "edit_start_line_idx": 37 }
version: 2 defaults: &defaults docker: - image: vuejs/ci step_restore_cache: &restore_cache restore_cache: keys: - v1-dependencies-{{ checksum "yarn.lock" }}-1 - v1-dependencies- step_install_deps: &install_deps run: name: Install Dependencies command: yarn --frozen-lockfile step_save_cache: &save_cache save_cache: paths: - node_modules - ~/.cache/yarn key: v1-dependencies-{{ checksum "yarn.lock" }}-1 jobs: test: <<: *defaults steps: - checkout - *restore_cache - run: rm -rf ~/project/node_modules/esbuild/.install - *install_deps - *save_cache - run: yarn build - run: yarn test - run: yarn test-sw workflows: version: 2 ci: jobs: - test
.circleci/config.yml
0
https://github.com/vitejs/vite/commit/49d50eebe86e18ea124d6223d258cc1dfe87a268
[ 0.00017839577049016953, 0.00017475176719017327, 0.00016865019279066473, 0.00017536108498461545, 0.0000034882511954492657 ]
{ "id": 6, "code_window": [ "import fs from 'fs'\n", "import path from 'path'\n", "import { ServerPlugin } from '.'\n", "import { isStaticAsset, cachedRead } from '../utils'\n", "import chalk from 'chalk'\n", "\n", "const send = require('koa-send')\n", "const debug = require('debug')('vite:history')\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { isStaticAsset } from '../utils'\n" ], "file_path": "src/node/server/serverPluginServeStatic.ts", "type": "replace", "edit_start_line_idx": 3 }
import path from 'path' import fs from 'fs-extra' import { RequestListener, Server } from 'http' import { ServerOptions } from 'https' import Koa, { DefaultState, DefaultContext } from 'koa' import chokidar from 'chokidar' import { createResolver, InternalResolver } from '../resolver' import { moduleRewritePlugin } from './serverPluginModuleRewrite' import { moduleResolvePlugin } from './serverPluginModuleResolve' import { vuePlugin } from './serverPluginVue' import { hmrPlugin, HMRWatcher } from './serverPluginHmr' import { serveStaticPlugin } from './serverPluginServeStatic' import { jsonPlugin } from './serverPluginJson' import { cssPlugin } from './serverPluginCss' import { assetPathPlugin } from './serverPluginAssets' import { esbuildPlugin } from './serverPluginEsbuild' import { ServerConfig } from '../config' import { createServerTransformPlugin } from '../transform' import { serviceWorkerPlugin } from './serverPluginServiceWorker' import { htmlRewritePlugin } from './serverPluginHtml' import { proxyPlugin } from './serverPluginProxy' import { createCertificate } from '../utils/createCertificate' import { envPlugin } from './serverPluginEnv' export { rewriteImports } from './serverPluginModuleRewrite' import { sourceMapPlugin, SourceMap } from './serverPluginSourceMap' export type ServerPlugin = (ctx: ServerPluginContext) => void export interface ServerPluginContext { root: string app: Koa<State, Context> server: Server watcher: HMRWatcher resolver: InternalResolver config: ServerConfig & { __path?: string } } export interface State extends DefaultState {} export type Context = DefaultContext & ServerPluginContext & { map?: SourceMap | null } export function createServer(config: ServerConfig): Server { const { root = process.cwd(), configureServer = [], resolvers = [], alias = {}, transforms = [], vueCustomBlockTransforms = {}, optimizeDeps = {} } = config const app = new Koa<State, Context>() const server = resolveServer(config, app.callback()) const watcher = chokidar.watch(root, { ignored: [/\bnode_modules\b/, /\b\.git\b/] }) as HMRWatcher const resolver = createResolver(root, resolvers, alias) const context = { root, app, server, watcher, resolver, config } // attach server context to koa context app.use((ctx, next) => { Object.assign(ctx, context) return next() }) const resolvedPlugins = [ // rewrite and source map plugins take highest priority and should be run // after all other middlewares have finished sourceMapPlugin, moduleRewritePlugin, htmlRewritePlugin, // user plugins ...(Array.isArray(configureServer) ? configureServer : [configureServer]), envPlugin, moduleResolvePlugin, proxyPlugin, serviceWorkerPlugin, hmrPlugin, ...(transforms.length || Object.keys(vueCustomBlockTransforms).length ? [createServerTransformPlugin(transforms, vueCustomBlockTransforms)] : []), vuePlugin, cssPlugin, esbuildPlugin, jsonPlugin, assetPathPlugin, serveStaticPlugin ] resolvedPlugins.forEach((m) => m(context)) const listen = server.listen.bind(server) server.listen = (async (...args: any[]) => { if (optimizeDeps.auto !== false) { await require('../optimizer').optimizeDeps(config) } return listen(...args) }) as any return server } function resolveServer( { https = false, httpsOption = {} }: ServerConfig, requestListener: RequestListener ) { if (https) { return require('https').createServer( resolveHttpsConfig(httpsOption), requestListener ) } else { return require('http').createServer(requestListener) } } function resolveHttpsConfig(httpsOption: ServerOptions) { const { ca, cert, key, pfx } = httpsOption Object.assign(httpsOption, { ca: readFileIfExits(ca), cert: readFileIfExits(cert), key: readFileIfExits(key), pfx: readFileIfExits(pfx) }) if (!httpsOption.key || !httpsOption.cert) { httpsOption.cert = httpsOption.key = createCertificate() } return httpsOption } function readFileIfExits(value?: string | Buffer | any) { if (value && !Buffer.isBuffer(value)) { try { return fs.readFileSync(path.resolve(value as string)) } catch (e) { return value } } return value }
src/node/server/index.ts
1
https://github.com/vitejs/vite/commit/49d50eebe86e18ea124d6223d258cc1dfe87a268
[ 0.005608453880995512, 0.0006118147866800427, 0.00016386764764320105, 0.0001754268741933629, 0.001305022626183927 ]
{ "id": 6, "code_window": [ "import fs from 'fs'\n", "import path from 'path'\n", "import { ServerPlugin } from '.'\n", "import { isStaticAsset, cachedRead } from '../utils'\n", "import chalk from 'chalk'\n", "\n", "const send = require('koa-send')\n", "const debug = require('debug')('vite:history')\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { isStaticAsset } from '../utils'\n" ], "file_path": "src/node/server/serverPluginServeStatic.ts", "type": "replace", "edit_start_line_idx": 3 }
import slash from 'slash' import qs, { ParsedUrlQuery } from 'querystring' import resolve from 'resolve' import { supportedExts } from '../resolver' import { Context } from '../server' export const resolveFrom = (root: string, id: string) => resolve.sync(id, { basedir: root, extensions: supportedExts, // necessary to work with pnpm preserveSymlinks: false }) export const queryRE = /\?.*$/ export const hashRE = /#.*$/ export const cleanUrl = (url: string) => url.replace(hashRE, '').replace(queryRE, '') export const parseWithQuery = ( id: string ): { path: string query: ParsedUrlQuery } => { const queryMatch = id.match(queryRE) if (queryMatch) { return { path: slash(cleanUrl(id)), query: qs.parse(queryMatch[0].slice(1)) } } return { path: id, query: {} } } const externalRE = /^(https?:)?\/\// export const isExternalUrl = (url: string) => externalRE.test(url) const imageRE = /\.(png|jpe?g|gif|svg|ico|webp)(\?.*)?$/ const mediaRE = /\.(mp4|webm|ogg|mp3|wav|flac|aac)(\?.*)?$/ const fontsRE = /\.(woff2?|eot|ttf|otf)(\?.*)?$/i /** * Check if a file is a static asset that vite can process. */ export const isStaticAsset = (file: string) => { return imageRE.test(file) || mediaRE.test(file) || fontsRE.test(file) } /** * Check if a request is an import from js instead of a native resource request * i.e. differentiate * `import('/style.css')` * from * `<link rel="stylesheet" href="/style.css">` * * The ?import query is injected by serverPluginModuleRewrite. */ export const isImportRequest = (ctx: Context): boolean => { return ctx.query.import != null } export function parseNodeModuleId(id: string) { const parts = id.split('/') let scope = '', name = '', inPkgPath = '' if (id.startsWith('@')) scope = parts.shift()! name = parts.shift()! inPkgPath = parts.join('/') return { scope, name, inPkgPath } }
src/node/utils/pathUtils.ts
0
https://github.com/vitejs/vite/commit/49d50eebe86e18ea124d6223d258cc1dfe87a268
[ 0.006155807059258223, 0.0008455223869532347, 0.00016677455278113484, 0.00017165073950309306, 0.0018776098731905222 ]
{ "id": 6, "code_window": [ "import fs from 'fs'\n", "import path from 'path'\n", "import { ServerPlugin } from '.'\n", "import { isStaticAsset, cachedRead } from '../utils'\n", "import chalk from 'chalk'\n", "\n", "const send = require('koa-send')\n", "const debug = require('debug')('vite:history')\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { isStaticAsset } from '../utils'\n" ], "file_path": "src/node/server/serverPluginServeStatic.ts", "type": "replace", "edit_start_line_idx": 3 }
import { rewriteImports, ServerPlugin } from './index' import { debugHmr, ensureMapEntry, hmrClientPublicPath, importerMap } from './serverPluginHmr' import { init as initLexer } from 'es-module-lexer' import { cleanUrl, readBody, injectScriptToHtml } from '../utils' import LRUCache from 'lru-cache' import path from 'path' import slash from 'slash' import chalk from 'chalk' const debug = require('debug')('vite:rewrite') const rewriteHtmlPluginCache = new LRUCache({ max: 20 }) export const htmlRewritePlugin: ServerPlugin = ({ root, app, watcher, resolver, config }) => { const devInjectionCode = `\n<script type="module">\n` + // import hmr client first to establish connection `import "${hmrClientPublicPath}"\n` + // inject process.env.NODE_ENV // since some ESM builds expect these to be replaced by the bundler `window.process = { env: { NODE_ENV: ${JSON.stringify( config.mode || 'development' )} }}\n` + `</script>\n` const scriptRE = /(<script\b[^>]*>)([\s\S]*?)<\/script>/gm const srcRE = /\bsrc=(?:"([^"]+)"|'([^']+)'|([^'"\s]+)\b)/ async function rewriteHtml(importer: string, html: string) { await initLexer html = html!.replace(scriptRE, (matched, openTag, script) => { if (script) { return `${openTag}${rewriteImports( root, script, importer, resolver )}</script>` } else { const srcAttr = openTag.match(srcRE) if (srcAttr) { // register script as a import dep for hmr const importee = resolver.normalizePublicPath( cleanUrl(slash(path.resolve('/', srcAttr[1] || srcAttr[2]))) ) debugHmr(` ${importer} imports ${importee}`) ensureMapEntry(importerMap, importee).add(importer) } return matched } }) return injectScriptToHtml(html, devInjectionCode) } app.use(async (ctx, next) => { await next() if (ctx.status === 304) { return } if (ctx.response.is('html') && ctx.body) { const importer = ctx.path const html = await readBody(ctx.body) if (rewriteHtmlPluginCache.has(html)) { debug(`${ctx.path}: serving from cache`) ctx.body = rewriteHtmlPluginCache.get(html) } else { if (!html) return ctx.body = await rewriteHtml(importer, html) rewriteHtmlPluginCache.set(html, ctx.body) } return } }) watcher.on('change', (file) => { const path = resolver.fileToRequest(file) if (path.endsWith('.html')) { debug(`${path}: cache busted`) watcher.send({ type: 'full-reload', path, timestamp: Date.now() }) console.log(chalk.green(`[vite] `) + ` ${path} page reloaded.`) } }) }
src/node/server/serverPluginHtml.ts
0
https://github.com/vitejs/vite/commit/49d50eebe86e18ea124d6223d258cc1dfe87a268
[ 0.9945594668388367, 0.09107811748981476, 0.0001660270499996841, 0.00019633478950709105, 0.28570982813835144 ]
{ "id": 6, "code_window": [ "import fs from 'fs'\n", "import path from 'path'\n", "import { ServerPlugin } from '.'\n", "import { isStaticAsset, cachedRead } from '../utils'\n", "import chalk from 'chalk'\n", "\n", "const send = require('koa-send')\n", "const debug = require('debug')('vite:history')\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { isStaticAsset } from '../utils'\n" ], "file_path": "src/node/server/serverPluginServeStatic.ts", "type": "replace", "edit_start_line_idx": 3 }
import { defineComponent } from 'vue' export default defineComponent({ setup() { return { msg: 'hello from <script src="./script.ts">' } } })
playground/src-import/script.ts
0
https://github.com/vitejs/vite/commit/49d50eebe86e18ea124d6223d258cc1dfe87a268
[ 0.00017295603174716234, 0.00017295603174716234, 0.00017295603174716234, 0.00017295603174716234, 0 ]
{ "id": 7, "code_window": [ " filePath !== ctx.path &&\n", " fs.existsSync(filePath) &&\n", " fs.statSync(filePath).isFile()\n", " ) {\n", " await cachedRead(ctx, filePath)\n", " }\n", " }\n", " return next()\n", " })\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " await ctx.read(ctx, filePath)\n" ], "file_path": "src/node/server/serverPluginServeStatic.ts", "type": "replace", "edit_start_line_idx": 46 }
import path from 'path' import chalk from 'chalk' import fs from 'fs-extra' import { ServerPlugin } from '.' import { resolveVue, cachedRead } from '../utils' import { URL } from 'url' import { resolveOptimizedModule, resolveNodeModuleFile } from '../resolver' const debug = require('debug')('vite:resolve') export const moduleIdToFileMap = new Map() export const moduleFileToIdMap = new Map() export const moduleRE = /^\/@modules\// const getDebugPath = (root: string, p: string) => { const relative = path.relative(root, p) return relative.startsWith('..') ? p : relative } // plugin for resolving /@modules/:id requests. export const moduleResolvePlugin: ServerPlugin = ({ root, app, resolver }) => { const vueResolved = resolveVue(root) app.use(async (ctx, next) => { if (!moduleRE.test(ctx.path)) { return next() } // path maybe contain encode chars const id = decodeURIComponent(ctx.path.replace(moduleRE, '')) ctx.type = 'js' const serve = async (id: string, file: string, type: string) => { moduleIdToFileMap.set(id, file) moduleFileToIdMap.set(file, ctx.path) debug(`(${type}) ${id} -> ${getDebugPath(root, file)}`) await cachedRead(ctx, file) return next() } // special handling for vue runtime in case it's not installed if (!vueResolved.isLocal && id in vueResolved) { return serve(id, (vueResolved as any)[id], 'non-local vue') } // already resolved and cached const cachedPath = moduleIdToFileMap.get(id) if (cachedPath) { return serve(id, cachedPath, 'cached') } // resolve from vite optimized modules const optimized = resolveOptimizedModule(root, id) if (optimized) { return serve(id, optimized, 'optimized') } const referer = ctx.get('referer') let importer: string | undefined // this is a map file request from browser dev tool const isMapFile = ctx.path.endsWith('.map') if (referer) { importer = new URL(referer).pathname } else if (isMapFile) { // for some reason Chrome doesn't provide referer for source map requests. // do our best to reverse-infer the importer. importer = ctx.path.replace(/\.map$/, '') } const importerFilePath = importer ? resolver.requestToFile(importer) : root const nodeModulePath = resolveNodeModuleFile(importerFilePath, id) if (nodeModulePath) { return serve(id, nodeModulePath, 'node_modules') } if (isMapFile && importer) { // the resolveNodeModuleFile doesn't work with linked pkg // our last try: infer from the dir of importer const inferMapPath = path.join( path.dirname(importerFilePath), path.basename(ctx.path) ) if (fs.existsSync(inferMapPath)) { return serve(id, inferMapPath, 'map file in linked pkg') } } console.error( chalk.red( `[vite] Failed to resolve module import "${id}". ` + `(imported by ${importer || 'unknown'})` ) ) ctx.status = 404 }) }
src/node/server/serverPluginModuleResolve.ts
1
https://github.com/vitejs/vite/commit/49d50eebe86e18ea124d6223d258cc1dfe87a268
[ 0.0037372002843767405, 0.000996805028989911, 0.00017160440620500594, 0.0002886891888920218, 0.001242807717062533 ]
{ "id": 7, "code_window": [ " filePath !== ctx.path &&\n", " fs.existsSync(filePath) &&\n", " fs.statSync(filePath).isFile()\n", " ) {\n", " await cachedRead(ctx, filePath)\n", " }\n", " }\n", " return next()\n", " })\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " await ctx.read(ctx, filePath)\n" ], "file_path": "src/node/server/serverPluginServeStatic.ts", "type": "replace", "edit_start_line_idx": 46 }
import { createVNode, isVNode } from 'vue' if (import.meta.env.MODE === 'development') { console.log( `[vue tip] You are using an non-optimized version of Vue 3 JSX, ` + `which does not take advantage of Vue 3's runtime fast paths. An improved ` + `JSX transform will be provided at a later stage.` ) } const slice = Array.prototype.slice export function jsx(tag: any, props = null, children: any = null) { if (arguments.length > 3 || isVNode(children)) { children = slice.call(arguments, 2) } return createVNode(tag, props, children) }
src/client/vueJsxCompat.ts
0
https://github.com/vitejs/vite/commit/49d50eebe86e18ea124d6223d258cc1dfe87a268
[ 0.00017567419854458421, 0.00017245255003217608, 0.00016923090151976794, 0.00017245255003217608, 0.0000032216485124081373 ]
{ "id": 7, "code_window": [ " filePath !== ctx.path &&\n", " fs.existsSync(filePath) &&\n", " fs.statSync(filePath).isFile()\n", " ) {\n", " await cachedRead(ctx, filePath)\n", " }\n", " }\n", " return next()\n", " })\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " await ctx.read(ctx, filePath)\n" ], "file_path": "src/node/server/serverPluginServeStatic.ts", "type": "replace", "edit_start_line_idx": 46 }
.turquoise { color: rgb(255, 140, 0); }
playground/testCssModules.module.css
0
https://github.com/vitejs/vite/commit/49d50eebe86e18ea124d6223d258cc1dfe87a268
[ 0.00017276154540013522, 0.00017276154540013522, 0.00017276154540013522, 0.00017276154540013522, 0 ]
{ "id": 7, "code_window": [ " filePath !== ctx.path &&\n", " fs.existsSync(filePath) &&\n", " fs.statSync(filePath).isFile()\n", " ) {\n", " await cachedRead(ctx, filePath)\n", " }\n", " }\n", " return next()\n", " })\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " await ctx.read(ctx, filePath)\n" ], "file_path": "src/node/server/serverPluginServeStatic.ts", "type": "replace", "edit_start_line_idx": 46 }
export function Test(props: { count: 0 }) { return <div>Rendered from Preact TSX: count is {props.count}</div> }
playground/testTsx.tsx
0
https://github.com/vitejs/vite/commit/49d50eebe86e18ea124d6223d258cc1dfe87a268
[ 0.0001722927117953077, 0.0001722927117953077, 0.0001722927117953077, 0.0001722927117953077, 0 ]
{ "id": 8, "code_window": [ ") {\n", " const importer = ctx.path\n", " const importee = cleanUrl(resolveImport(root, importer, block.src!, resolver))\n", " const filePath = resolver.requestToFile(importee)\n", " await cachedRead(ctx, filePath)\n", " block.content = (ctx.body as Buffer).toString()\n", "\n", " // register HMR import relationship\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " await ctx.read(ctx, filePath)\n" ], "file_path": "src/node/server/serverPluginVue.ts", "type": "replace", "edit_start_line_idx": 331 }
import path from 'path' import fs from 'fs-extra' import { RequestListener, Server } from 'http' import { ServerOptions } from 'https' import Koa, { DefaultState, DefaultContext } from 'koa' import chokidar from 'chokidar' import { createResolver, InternalResolver } from '../resolver' import { moduleRewritePlugin } from './serverPluginModuleRewrite' import { moduleResolvePlugin } from './serverPluginModuleResolve' import { vuePlugin } from './serverPluginVue' import { hmrPlugin, HMRWatcher } from './serverPluginHmr' import { serveStaticPlugin } from './serverPluginServeStatic' import { jsonPlugin } from './serverPluginJson' import { cssPlugin } from './serverPluginCss' import { assetPathPlugin } from './serverPluginAssets' import { esbuildPlugin } from './serverPluginEsbuild' import { ServerConfig } from '../config' import { createServerTransformPlugin } from '../transform' import { serviceWorkerPlugin } from './serverPluginServiceWorker' import { htmlRewritePlugin } from './serverPluginHtml' import { proxyPlugin } from './serverPluginProxy' import { createCertificate } from '../utils/createCertificate' import { envPlugin } from './serverPluginEnv' export { rewriteImports } from './serverPluginModuleRewrite' import { sourceMapPlugin, SourceMap } from './serverPluginSourceMap' export type ServerPlugin = (ctx: ServerPluginContext) => void export interface ServerPluginContext { root: string app: Koa<State, Context> server: Server watcher: HMRWatcher resolver: InternalResolver config: ServerConfig & { __path?: string } } export interface State extends DefaultState {} export type Context = DefaultContext & ServerPluginContext & { map?: SourceMap | null } export function createServer(config: ServerConfig): Server { const { root = process.cwd(), configureServer = [], resolvers = [], alias = {}, transforms = [], vueCustomBlockTransforms = {}, optimizeDeps = {} } = config const app = new Koa<State, Context>() const server = resolveServer(config, app.callback()) const watcher = chokidar.watch(root, { ignored: [/\bnode_modules\b/, /\b\.git\b/] }) as HMRWatcher const resolver = createResolver(root, resolvers, alias) const context = { root, app, server, watcher, resolver, config } // attach server context to koa context app.use((ctx, next) => { Object.assign(ctx, context) return next() }) const resolvedPlugins = [ // rewrite and source map plugins take highest priority and should be run // after all other middlewares have finished sourceMapPlugin, moduleRewritePlugin, htmlRewritePlugin, // user plugins ...(Array.isArray(configureServer) ? configureServer : [configureServer]), envPlugin, moduleResolvePlugin, proxyPlugin, serviceWorkerPlugin, hmrPlugin, ...(transforms.length || Object.keys(vueCustomBlockTransforms).length ? [createServerTransformPlugin(transforms, vueCustomBlockTransforms)] : []), vuePlugin, cssPlugin, esbuildPlugin, jsonPlugin, assetPathPlugin, serveStaticPlugin ] resolvedPlugins.forEach((m) => m(context)) const listen = server.listen.bind(server) server.listen = (async (...args: any[]) => { if (optimizeDeps.auto !== false) { await require('../optimizer').optimizeDeps(config) } return listen(...args) }) as any return server } function resolveServer( { https = false, httpsOption = {} }: ServerConfig, requestListener: RequestListener ) { if (https) { return require('https').createServer( resolveHttpsConfig(httpsOption), requestListener ) } else { return require('http').createServer(requestListener) } } function resolveHttpsConfig(httpsOption: ServerOptions) { const { ca, cert, key, pfx } = httpsOption Object.assign(httpsOption, { ca: readFileIfExits(ca), cert: readFileIfExits(cert), key: readFileIfExits(key), pfx: readFileIfExits(pfx) }) if (!httpsOption.key || !httpsOption.cert) { httpsOption.cert = httpsOption.key = createCertificate() } return httpsOption } function readFileIfExits(value?: string | Buffer | any) { if (value && !Buffer.isBuffer(value)) { try { return fs.readFileSync(path.resolve(value as string)) } catch (e) { return value } } return value }
src/node/server/index.ts
1
https://github.com/vitejs/vite/commit/49d50eebe86e18ea124d6223d258cc1dfe87a268
[ 0.002408877480775118, 0.00039843254489824176, 0.000163553879247047, 0.00017522956477478147, 0.0006138004246167839 ]
{ "id": 8, "code_window": [ ") {\n", " const importer = ctx.path\n", " const importee = cleanUrl(resolveImport(root, importer, block.src!, resolver))\n", " const filePath = resolver.requestToFile(importee)\n", " await cachedRead(ctx, filePath)\n", " block.content = (ctx.body as Buffer).toString()\n", "\n", " // register HMR import relationship\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " await ctx.read(ctx, filePath)\n" ], "file_path": "src/node/server/serverPluginVue.ts", "type": "replace", "edit_start_line_idx": 331 }
import path from 'path' import fs from 'fs-extra' import chalk from 'chalk' import { Ora } from 'ora' import { resolveFrom } from '../utils' import { rollup as Rollup, RollupOutput, ExternalOption, Plugin, InputOptions } from 'rollup' import { createResolver, supportedExts, mainFields, InternalResolver } from '../resolver' import { createBuildResolvePlugin } from './buildPluginResolve' import { createBuildHtmlPlugin } from './buildPluginHtml' import { createBuildCssPlugin } from './buildPluginCss' import { createBuildAssetPlugin } from './buildPluginAsset' import { createEsbuildPlugin } from './buildPluginEsbuild' import { createReplacePlugin } from './buildPluginReplace' import { stopService } from '../esbuildService' import { BuildConfig } from '../config' import { createBuildJsTransformPlugin } from '../transform' import hash_sum from 'hash-sum' import { resolvePostcssOptions } from '../utils/cssUtils' export interface BuildResult { html: string assets: RollupOutput['output'] } const enum WriteType { JS, CSS, ASSET, HTML, SOURCE_MAP } const writeColors = { [WriteType.JS]: chalk.cyan, [WriteType.CSS]: chalk.magenta, [WriteType.ASSET]: chalk.green, [WriteType.HTML]: chalk.blue, [WriteType.SOURCE_MAP]: chalk.gray } const warningIgnoreList = [`CIRCULAR_DEPENDENCY`, `THIS_IS_UNDEFINED`] const dynamicImportWarningIgnoreList = [ `Unsupported expression`, `statically analyzed` ] export const onRollupWarning: ( spinner: Ora | undefined ) => InputOptions['onwarn'] = (spinner) => (warning, warn) => { if ( warning.plugin === 'rollup-plugin-dynamic-import-variables' && dynamicImportWarningIgnoreList.some((msg) => warning.message.includes(msg)) ) { return } if (!warningIgnoreList.includes(warning.code!)) { // ora would swallow the console.warn if we let it keep running // https://github.com/sindresorhus/ora/issues/90 if (spinner) { spinner.stop() } warn(warning) if (spinner) { spinner.start() } } } /** * Creates non-application specific plugins that are shared between the main * app and the dependencies. This is used by the `optimize` command to * pre-bundle dependencies. */ export async function createBaseRollupPlugins( root: string, resolver: InternalResolver, options: BuildConfig ): Promise<Plugin[]> { const { rollupInputOptions = {}, transforms = [], vueCustomBlockTransforms = {}, cssPreprocessOptions } = options const { nodeResolve } = require('@rollup/plugin-node-resolve') const dynamicImport = require('rollup-plugin-dynamic-import-variables') const { options: postcssOptions, plugins: postcssPlugins } = await resolvePostcssOptions(root) return [ // user plugins ...(rollupInputOptions.plugins || []), // vite:resolve createBuildResolvePlugin(root, resolver), // vite:esbuild await createEsbuildPlugin(options.minify === 'esbuild', options.jsx), // vue require('rollup-plugin-vue')({ ...options.rollupPluginVueOptions, transformAssetUrls: { includeAbsolute: true }, postcssOptions, postcssPlugins, preprocessStyles: true, preprocessOptions: { includePaths: ['node_modules'], ...cssPreprocessOptions }, preprocessCustomRequire: (id: string) => require(resolveFrom(root, id)), compilerOptions: options.vueCompilerOptions, cssModulesOptions: { generateScopedName: (local: string, filename: string) => `${local}_${hash_sum(filename)}`, ...(options.rollupPluginVueOptions && options.rollupPluginVueOptions.cssModulesOptions) }, customBlocks: Object.keys(vueCustomBlockTransforms) }), require('@rollup/plugin-json')({ preferConst: true, indent: ' ', compact: false, namedExports: true }), // user transforms ...(transforms.length || Object.keys(vueCustomBlockTransforms).length ? [createBuildJsTransformPlugin(transforms, vueCustomBlockTransforms)] : []), nodeResolve({ rootDir: root, extensions: supportedExts, preferBuiltins: false, dedupe: options.rollupDedupe || [], mainFields }), require('@rollup/plugin-commonjs')({ extensions: ['.js', '.cjs'] }), dynamicImport({ warnOnError: true, include: [/\.js$/], exclude: [/node_modules/] }) ].filter(Boolean) } /** * Bundles the app for production. * Returns a Promise containing the build result. */ export async function build(options: BuildConfig): Promise<BuildResult> { if (options.ssr) { return ssrBuild({ ...options, ssr: false // since ssrBuild calls build, this avoids an infinite loop. }) } const { root = process.cwd(), base = '/', outDir = path.resolve(root, 'dist'), assetsDir = '_assets', assetsInlineLimit = 4096, cssCodeSplit = true, alias = {}, resolvers = [], rollupInputOptions = {}, rollupOutputOptions = {}, emitIndex = true, emitAssets = true, write = true, minify = true, silent = false, sourcemap = false, shouldPreload = null, env = {}, mode = 'production', cssPreprocessOptions = {} } = options const isTest = process.env.NODE_ENV === 'test' process.env.NODE_ENV = mode const start = Date.now() let spinner: Ora | undefined const msg = 'Building for production...' if (!silent) { if (process.env.DEBUG || isTest) { console.log(msg) } else { spinner = require('ora')(msg + '\n').start() } } const indexPath = path.resolve(root, 'index.html') const publicBasePath = base.replace(/([^/])$/, '$1/') // ensure ending slash const resolvedAssetsPath = path.join(outDir, assetsDir) const resolver = createResolver(root, resolvers, alias) const { htmlPlugin, renderIndex } = await createBuildHtmlPlugin( root, indexPath, publicBasePath, assetsDir, assetsInlineLimit, resolver, shouldPreload ) const basePlugins = await createBaseRollupPlugins(root, resolver, options) // user env variables loaded from .env files. // only those prefixed with VITE_ are exposed. const userEnvReplacements = Object.keys(env).reduce((replacements, key) => { if (key.startsWith(`VITE_`)) { replacements[`import.meta.env.${key}`] = JSON.stringify(env[key]) } return replacements }, {} as Record<string, string>) // lazy require rollup so that we don't load it when only using the dev server // importing it just for the types const rollup = require('rollup').rollup as typeof Rollup const bundle = await rollup({ input: path.resolve(root, 'index.html'), preserveEntrySignatures: false, treeshake: { moduleSideEffects: 'no-external' }, onwarn: onRollupWarning(spinner), ...rollupInputOptions, plugins: [ ...basePlugins, // vite:html htmlPlugin, // we use a custom replacement plugin because @rollup/plugin-replace // performs replacements twice, once at transform and once at renderChunk // - which makes it impossible to exclude Vue templates from it since // Vue templates are compiled into js and included in chunks. createReplacePlugin( (id) => /\.(j|t)sx?$/.test(id), { ...userEnvReplacements, 'import.meta.env.BASE_URL': JSON.stringify(publicBasePath), 'import.meta.env.MODE': JSON.stringify(mode), 'import.meta.env.DEV': String(mode === 'development'), 'import.meta.env.PROD': String(mode === 'production'), 'process.env.NODE_ENV': JSON.stringify(mode), 'process.env.': `({}).`, 'import.meta.hot': `false` }, sourcemap ), // vite:css createBuildCssPlugin({ root, publicBase: publicBasePath, assetsDir, minify, inlineLimit: assetsInlineLimit, cssCodeSplit, preprocessOptions: cssPreprocessOptions }), // vite:asset createBuildAssetPlugin( root, publicBasePath, assetsDir, assetsInlineLimit ), // minify with terser // this is the default which has better compression, but slow // the user can opt-in to use esbuild which is much faster but results // in ~8-10% larger file size. minify && minify !== 'esbuild' ? require('rollup-plugin-terser').terser() : undefined ] }) const { output } = await bundle.generate({ format: 'es', sourcemap, entryFileNames: `[name].[hash].js`, chunkFileNames: `[name].[hash].js`, ...rollupOutputOptions }) spinner && spinner.stop() const cssFileName = output.find( (a) => a.type === 'asset' && a.fileName.endsWith('.css') )!.fileName const indexHtml = emitIndex ? renderIndex(output, cssFileName) : '' if (write) { const cwd = process.cwd() const writeFile = async ( filepath: string, content: string | Uint8Array, type: WriteType ) => { await fs.ensureDir(path.dirname(filepath)) await fs.writeFile(filepath, content) if (!silent) { console.log( `${chalk.gray(`[write]`)} ${writeColors[type]( path.relative(cwd, filepath) )} ${(content.length / 1024).toFixed(2)}kb, brotli: ${( require('brotli-size').sync(content) / 1024 ).toFixed(2)}kb` ) } } await fs.remove(outDir) await fs.ensureDir(outDir) // write js chunks and assets for (const chunk of output) { if (chunk.type === 'chunk') { // write chunk const filepath = path.join(resolvedAssetsPath, chunk.fileName) let code = chunk.code if (chunk.map) { code += `\n//# sourceMappingURL=${path.basename(filepath)}.map` } await writeFile(filepath, code, WriteType.JS) if (chunk.map) { await writeFile( filepath + '.map', chunk.map.toString(), WriteType.SOURCE_MAP ) } } else if (emitAssets) { // write asset const filepath = path.join(resolvedAssetsPath, chunk.fileName) await writeFile( filepath, chunk.source, chunk.fileName.endsWith('.css') ? WriteType.CSS : WriteType.ASSET ) } } // write html if (indexHtml && emitIndex) { await writeFile( path.join(outDir, 'index.html'), indexHtml, WriteType.HTML ) } // copy over /public if it exists if (emitAssets) { const publicDir = path.resolve(root, 'public') if (fs.existsSync(publicDir)) { for (const file of await fs.readdir(publicDir)) { await fs.copy(path.join(publicDir, file), path.resolve(outDir, file)) } } } } if (!silent) { console.log( `Build completed in ${((Date.now() - start) / 1000).toFixed(2)}s.\n` ) } // stop the esbuild service after each build stopService() return { assets: output, html: indexHtml } } /** * Bundles the app in SSR mode. * - All Vue dependencies are automatically externalized * - Imports to dependencies are compiled into require() calls * - Templates are compiled with SSR specific optimizations. */ export async function ssrBuild(options: BuildConfig): Promise<BuildResult> { const { rollupInputOptions, rollupOutputOptions, rollupPluginVueOptions } = options return build({ outDir: path.resolve(options.root || process.cwd(), 'dist-ssr'), assetsDir: '.', ...options, rollupPluginVueOptions: { ...rollupPluginVueOptions, target: 'node' }, rollupInputOptions: { ...rollupInputOptions, external: resolveExternal( rollupInputOptions && rollupInputOptions.external ) }, rollupOutputOptions: { ...rollupOutputOptions, format: 'cjs', exports: 'named', entryFileNames: '[name].js' }, emitIndex: false, emitAssets: false, cssCodeSplit: false, minify: false }) } function resolveExternal( userExternal: ExternalOption | undefined ): ExternalOption { const required = ['vue', /^@vue\//] if (!userExternal) { return required } if (Array.isArray(userExternal)) { return [...required, ...userExternal] } else if (typeof userExternal === 'function') { return (src, importer, isResolved) => { if (src === 'vue' || /^@vue\//.test(src)) { return true } return userExternal(src, importer, isResolved) } } else { return [...required, userExternal] } }
src/node/build/index.ts
0
https://github.com/vitejs/vite/commit/49d50eebe86e18ea124d6223d258cc1dfe87a268
[ 0.8891291618347168, 0.03853767737746239, 0.0001615194632904604, 0.0001740773004712537, 0.17946220934391022 ]
{ "id": 8, "code_window": [ ") {\n", " const importer = ctx.path\n", " const importee = cleanUrl(resolveImport(root, importer, block.src!, resolver))\n", " const filePath = resolver.requestToFile(importee)\n", " await cachedRead(ctx, filePath)\n", " block.content = (ctx.body as Buffer).toString()\n", "\n", " // register HMR import relationship\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " await ctx.read(ctx, filePath)\n" ], "file_path": "src/node/server/serverPluginVue.ts", "type": "replace", "edit_start_line_idx": 331 }
import { Plugin } from 'rollup' import { init, parse } from 'es-module-lexer' import { isCSSRequest } from '../utils/cssUtils' import MagicString from 'magic-string' import { isStaticAsset } from '../utils' import path from 'path' import { InternalResolver } from '../resolver' const isAsset = (id: string) => isCSSRequest(id) || isStaticAsset(id) export const depAssetExternalPlugin: Plugin = { name: 'vite:optimize-dep-assets-external', resolveId(id) { if (isAsset(id)) { return { id, external: true } } } } export const createDepAssetPlugin = (resolver: InternalResolver): Plugin => { return { name: 'vite:optimize-dep-assets', async transform(code, id) { if (id.endsWith('.js')) { await init const [imports] = parse(code) if (imports.length) { let s: MagicString | undefined for (let i = 0; i < imports.length; i++) { const { s: start, e: end, d: dynamicIndex } = imports[i] if (dynamicIndex === -1) { const importee = code.slice(start, end) if (isAsset(importee)) { // replace css/asset imports to deep imports to their original // location s = s || new MagicString(code) const deepPath = resolver.fileToRequest( path.resolve(path.dirname(id), importee) ) s.overwrite(start, end, deepPath) } } else { // ignore dynamic import } } if (s) { return s.toString() } } } return null } } }
src/node/optimizer/pluginAssets.ts
0
https://github.com/vitejs/vite/commit/49d50eebe86e18ea124d6223d258cc1dfe87a268
[ 0.9586392045021057, 0.19485479593276978, 0.00016738567501306534, 0.0001738692808430642, 0.35004666447639465 ]
{ "id": 8, "code_window": [ ") {\n", " const importer = ctx.path\n", " const importee = cleanUrl(resolveImport(root, importer, block.src!, resolver))\n", " const filePath = resolver.requestToFile(importee)\n", " await cachedRead(ctx, filePath)\n", " block.content = (ctx.body as Buffer).toString()\n", "\n", " // register HMR import relationship\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " await ctx.read(ctx, filePath)\n" ], "file_path": "src/node/server/serverPluginVue.ts", "type": "replace", "edit_start_line_idx": 331 }
semi: false singleQuote: true printWidth: 80 trailingComma: none
.prettierrc
0
https://github.com/vitejs/vite/commit/49d50eebe86e18ea124d6223d258cc1dfe87a268
[ 0.00017594426753930748, 0.00017594426753930748, 0.00017594426753930748, 0.00017594426753930748, 0 ]
{ "id": 0, "code_window": [ "type = \"docs\"\n", "aliases = [\"/reference/graph/\"]\n", "[menu.docs]\n", "name = \"Graph\"\n", "parent = \"panels\"\n", "weight = 1\n", "+++\n", "\n", "# Graph Panel\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "weight = 4\n" ], "file_path": "docs/sources/features/panels/graph.md", "type": "replace", "edit_start_line_idx": 8 }
+++ title = "Heatmap Panel" description = "Heatmap panel documentation" keywords = ["grafana", "heatmap", "panel", "documentation"] type = "docs" [menu.docs] name = "Heatmap" parent = "panels" weight = 3 +++ # Heatmap Panel ![](/img/docs/v43/heatmap_panel_cover.jpg) > New panel only available in Grafana v4.3+ The Heatmap panel allows you to view histograms over time. To fully understand and use this panel you need understand what Histograms are and how they are created. Read on below to for a quick introduction to the term Histogram. ## Histograms and buckets A histogram is a graphical representation of the distribution of numerical data. You group values into buckets (some times also called bins) and then count how many values fall into each bucket. Instead of graphing the actual values you then graph the buckets. Each bar represents a bucket and the bar height represents the frequency (i.e. count) of values that fell into that bucket's interval. Example Histogram: ![](/img/docs/v43/heatmap_histogram.png) The above histogram shows us that most value distribution of a couple of time series. We can easily see that most values land between 240-300 with a peak between 260-280. Histograms just look at value distributions over specific time range. So you cannot see any trend or changes in the distribution over time, this is where heatmaps become useful. ## Heatmap A Heatmap is like a histogram but over time where each time slice represents its own histogram. Instead of using bar height as a representation of frequency you use cells and color the cell proportional to the number of values in the bucket. Example: ![](/img/docs/v43/heatmap_histogram_over_time.png) Here we can clearly see what values are more common and how they trend over time. ## Data Options Data and bucket options can be found in the `Axes` tab. ### Data Formats Data format | Description ------------ | ------------- *Time series* | Grafana does the bucketing by going through all time series values. The bucket sizes and intervals will be determined using the Buckets options. *Time series buckets* | Each time series already represents a Y-Axis bucket. The time series name (alias) needs to be a numeric value representing the upper or lower interval for the bucket. Grafana does no bucketing so the bucket size options are hidden. ### Bucket bound When Data format is *Time series buckets* data source returns series with names representing bucket bound. But depending on data source, a bound may be *upper* or *lower*. This option allows to adjust a bound type. If *Auto* is set, a bound option will be chosen based on panels' data source type. ### Bucket Size The Bucket count and size options are used by Grafana to calculate how big each cell in the heatmap is. You can define the bucket size either by count (the first input box) or by specifying a size interval. For the Y-Axis the size interval is just a value but for the X-bucket you can specify a time range in the *Size* input, for example, the time range `1h`. This will make the cells 1h wide on the X-axis. ### Pre-bucketed data If you have a data that is already organized into buckets you can use the `Time series buckets` data format. This format requires that your metric query return regular time series and that each time series has a numeric name that represent the upper or lower bound of the interval. There are a number of data sources supporting histogram over time like Elasticsearch (by using a Histogram bucket aggregation) or Prometheus (with [histogram](https://prometheus.io/docs/concepts/metric_types/#histogram) metric type and *Format as* option set to Heatmap). But generally, any data source could be used if it meets the requirements: returns series with names representing bucket bound or returns series sorted by the bound in ascending order. With Elasticsearch you control the size of the buckets using the Histogram interval (Y-Axis) and the Date Histogram interval (X-axis). ![Elastic histogram](/img/docs/v43/elastic_histogram.png) With Prometheus you can only control X-axis by adjusting *Min step* and *Resolution* options. ![Prometheus histogram](/img/docs/v51/prometheus_histogram.png) ## Display Options In the heatmap *Display* tab you define how the cells are rendered and what color they are assigned. ### Color Mode and Spectrum {{< imgbox max-width="40%" img="/img/docs/v43/heatmap_scheme.png" caption="Color spectrum" >}} The color spectrum controls the mapping between value count (in each bucket) and the color assigned to each bucket. The left most color on the spectrum represents the minimum count and the color on the right most side represents the maximum count. Some color schemes are automatically inverted when using the light theme. You can also change the color mode to `Opacity`. In this case, the color will not change but the amount of opacity will change with the bucket count. ## Raw data vs aggregated If you use the heatmap with regular time series data (not pre-bucketed). Then it's important to keep in mind that your data is often already by aggregated by your time series backend. Most time series queries do not return raw sample data but include a group by time interval or maxDataPoints limit coupled with an aggregation function (usually average). This all depends on the time range of your query of course. But the important point is to know that the Histogram bucketing that Grafana performs may be done on already aggregated and averaged data. To get more accurate heatmaps it is better to do the bucketing during metric collection or store the data in Elasticsearch, or in the other data source which supports doing Histogram bucketing on the raw data. If you remove or lower the group by time (or raise maxDataPoints) in your query to return more data points your heatmap will be more accurate but this can also be very CPU and Memory taxing for your browser and could cause hangs and crashes if the number of data points becomes unreasonably large.
docs/sources/features/panels/heatmap.md
1
https://github.com/grafana/grafana/commit/64bf3b3c04c047824f6a2b00479f0d67bd0f31f4
[ 0.0006475473055616021, 0.00021007594477850944, 0.00016493092698510736, 0.00017195854161400348, 0.00012649904238060117 ]
{ "id": 0, "code_window": [ "type = \"docs\"\n", "aliases = [\"/reference/graph/\"]\n", "[menu.docs]\n", "name = \"Graph\"\n", "parent = \"panels\"\n", "weight = 1\n", "+++\n", "\n", "# Graph Panel\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "weight = 4\n" ], "file_path": "docs/sources/features/panels/graph.md", "type": "replace", "edit_start_line_idx": 8 }
import coreModule from 'app/core/core_module'; import _ from 'lodash'; export function elasticPipelineVariables() { return { templateUrl: 'public/app/plugins/datasource/elasticsearch/partials/pipeline_variables.html', controller: 'ElasticPipelineVariablesCtrl', restrict: 'E', scope: { onChange: '&', variables: '=', options: '=', }, }; } const newVariable = (index: any) => { return { name: 'var' + index, pipelineAgg: 'select metric', }; }; export class ElasticPipelineVariablesCtrl { /** @ngInject */ constructor($scope: any) { $scope.variables = $scope.variables || [newVariable(1)]; $scope.onChangeInternal = () => { $scope.onChange(); }; $scope.add = () => { $scope.variables.push(newVariable($scope.variables.length + 1)); $scope.onChange(); }; $scope.remove = (index: number) => { $scope.variables.splice(index, 1); $scope.onChange(); }; } } coreModule.directive('elasticPipelineVariables', elasticPipelineVariables); coreModule.controller('ElasticPipelineVariablesCtrl', ElasticPipelineVariablesCtrl);
public/app/plugins/datasource/elasticsearch/pipeline_variables.ts
0
https://github.com/grafana/grafana/commit/64bf3b3c04c047824f6a2b00479f0d67bd0f31f4
[ 0.0001758042344590649, 0.00017199075955431908, 0.00016753656382206827, 0.00017176666005980223, 0.000002792761506498209 ]
{ "id": 0, "code_window": [ "type = \"docs\"\n", "aliases = [\"/reference/graph/\"]\n", "[menu.docs]\n", "name = \"Graph\"\n", "parent = \"panels\"\n", "weight = 1\n", "+++\n", "\n", "# Graph Panel\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "weight = 4\n" ], "file_path": "docs/sources/features/panels/graph.md", "type": "replace", "edit_start_line_idx": 8 }
import React from 'react'; export enum IconSide { left = 'left', right = 'right', } type Props = { splitted: boolean; title: string; onClick: () => void; buttonClassName?: string; iconClassName?: string; iconSide?: IconSide; disabled?: boolean; }; function formatBtnTitle(title: string, iconSide?: string): string { return iconSide === IconSide.left ? '\xA0' + title : iconSide === IconSide.right ? title + '\xA0' : title; } export const ResponsiveButton = (props: Props) => { const defaultProps = { iconSide: IconSide.left, }; props = { ...defaultProps, ...props }; const { title, onClick, buttonClassName, iconClassName, splitted, iconSide, disabled } = props; return ( <button className={`btn navbar-button ${buttonClassName ? buttonClassName : ''}`} onClick={onClick} disabled={disabled || false} > {iconClassName && iconSide === IconSide.left ? <i className={`${iconClassName}`} /> : null} <span className="btn-title">{!splitted ? formatBtnTitle(title, iconSide) : ''}</span> {iconClassName && iconSide === IconSide.right ? <i className={`${iconClassName}`} /> : null} </button> ); };
public/app/features/explore/ResponsiveButton.tsx
0
https://github.com/grafana/grafana/commit/64bf3b3c04c047824f6a2b00479f0d67bd0f31f4
[ 0.00017845240654423833, 0.00017312905401922762, 0.00016814823902677745, 0.00017362606013193727, 0.000003369694695720682 ]
{ "id": 0, "code_window": [ "type = \"docs\"\n", "aliases = [\"/reference/graph/\"]\n", "[menu.docs]\n", "name = \"Graph\"\n", "parent = \"panels\"\n", "weight = 1\n", "+++\n", "\n", "# Graph Panel\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "weight = 4\n" ], "file_path": "docs/sources/features/panels/graph.md", "type": "replace", "edit_start_line_idx": 8 }
# go-colorable [![Godoc Reference](https://godoc.org/github.com/mattn/go-colorable?status.svg)](http://godoc.org/github.com/mattn/go-colorable) [![Build Status](https://travis-ci.org/mattn/go-colorable.svg?branch=master)](https://travis-ci.org/mattn/go-colorable) [![Coverage Status](https://coveralls.io/repos/github/mattn/go-colorable/badge.svg?branch=master)](https://coveralls.io/github/mattn/go-colorable?branch=master) [![Go Report Card](https://goreportcard.com/badge/mattn/go-colorable)](https://goreportcard.com/report/mattn/go-colorable) Colorable writer for windows. For example, most of logger packages doesn't show colors on windows. (I know we can do it with ansicon. But I don't want.) This package is possible to handle escape sequence for ansi color on windows. ## Too Bad! ![](https://raw.githubusercontent.com/mattn/go-colorable/gh-pages/bad.png) ## So Good! ![](https://raw.githubusercontent.com/mattn/go-colorable/gh-pages/good.png) ## Usage ```go logrus.SetFormatter(&logrus.TextFormatter{ForceColors: true}) logrus.SetOutput(colorable.NewColorableStdout()) logrus.Info("succeeded") logrus.Warn("not correct") logrus.Error("something error") logrus.Fatal("panic") ``` You can compile above code on non-windows OSs. ## Installation ``` $ go get github.com/mattn/go-colorable ``` # License MIT # Author Yasuhiro Matsumoto (a.k.a mattn)
vendor/github.com/mattn/go-colorable/README.md
0
https://github.com/grafana/grafana/commit/64bf3b3c04c047824f6a2b00479f0d67bd0f31f4
[ 0.00017441873205825686, 0.0001724214234855026, 0.00017069917521439493, 0.0001724514877423644, 0.0000012283367141208146 ]
{ "id": 1, "code_window": [ "[menu.docs]\n", "name = \"Heatmap\"\n", "parent = \"panels\"\n", "weight = 3\n", "+++\n", "\n", "# Heatmap Panel\n", "\n", "![](/img/docs/v43/heatmap_panel_cover.jpg)\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "weight = 4\n" ], "file_path": "docs/sources/features/panels/heatmap.md", "type": "replace", "edit_start_line_idx": 8 }
+++ title = "Heatmap Panel" description = "Heatmap panel documentation" keywords = ["grafana", "heatmap", "panel", "documentation"] type = "docs" [menu.docs] name = "Heatmap" parent = "panels" weight = 3 +++ # Heatmap Panel ![](/img/docs/v43/heatmap_panel_cover.jpg) > New panel only available in Grafana v4.3+ The Heatmap panel allows you to view histograms over time. To fully understand and use this panel you need understand what Histograms are and how they are created. Read on below to for a quick introduction to the term Histogram. ## Histograms and buckets A histogram is a graphical representation of the distribution of numerical data. You group values into buckets (some times also called bins) and then count how many values fall into each bucket. Instead of graphing the actual values you then graph the buckets. Each bar represents a bucket and the bar height represents the frequency (i.e. count) of values that fell into that bucket's interval. Example Histogram: ![](/img/docs/v43/heatmap_histogram.png) The above histogram shows us that most value distribution of a couple of time series. We can easily see that most values land between 240-300 with a peak between 260-280. Histograms just look at value distributions over specific time range. So you cannot see any trend or changes in the distribution over time, this is where heatmaps become useful. ## Heatmap A Heatmap is like a histogram but over time where each time slice represents its own histogram. Instead of using bar height as a representation of frequency you use cells and color the cell proportional to the number of values in the bucket. Example: ![](/img/docs/v43/heatmap_histogram_over_time.png) Here we can clearly see what values are more common and how they trend over time. ## Data Options Data and bucket options can be found in the `Axes` tab. ### Data Formats Data format | Description ------------ | ------------- *Time series* | Grafana does the bucketing by going through all time series values. The bucket sizes and intervals will be determined using the Buckets options. *Time series buckets* | Each time series already represents a Y-Axis bucket. The time series name (alias) needs to be a numeric value representing the upper or lower interval for the bucket. Grafana does no bucketing so the bucket size options are hidden. ### Bucket bound When Data format is *Time series buckets* data source returns series with names representing bucket bound. But depending on data source, a bound may be *upper* or *lower*. This option allows to adjust a bound type. If *Auto* is set, a bound option will be chosen based on panels' data source type. ### Bucket Size The Bucket count and size options are used by Grafana to calculate how big each cell in the heatmap is. You can define the bucket size either by count (the first input box) or by specifying a size interval. For the Y-Axis the size interval is just a value but for the X-bucket you can specify a time range in the *Size* input, for example, the time range `1h`. This will make the cells 1h wide on the X-axis. ### Pre-bucketed data If you have a data that is already organized into buckets you can use the `Time series buckets` data format. This format requires that your metric query return regular time series and that each time series has a numeric name that represent the upper or lower bound of the interval. There are a number of data sources supporting histogram over time like Elasticsearch (by using a Histogram bucket aggregation) or Prometheus (with [histogram](https://prometheus.io/docs/concepts/metric_types/#histogram) metric type and *Format as* option set to Heatmap). But generally, any data source could be used if it meets the requirements: returns series with names representing bucket bound or returns series sorted by the bound in ascending order. With Elasticsearch you control the size of the buckets using the Histogram interval (Y-Axis) and the Date Histogram interval (X-axis). ![Elastic histogram](/img/docs/v43/elastic_histogram.png) With Prometheus you can only control X-axis by adjusting *Min step* and *Resolution* options. ![Prometheus histogram](/img/docs/v51/prometheus_histogram.png) ## Display Options In the heatmap *Display* tab you define how the cells are rendered and what color they are assigned. ### Color Mode and Spectrum {{< imgbox max-width="40%" img="/img/docs/v43/heatmap_scheme.png" caption="Color spectrum" >}} The color spectrum controls the mapping between value count (in each bucket) and the color assigned to each bucket. The left most color on the spectrum represents the minimum count and the color on the right most side represents the maximum count. Some color schemes are automatically inverted when using the light theme. You can also change the color mode to `Opacity`. In this case, the color will not change but the amount of opacity will change with the bucket count. ## Raw data vs aggregated If you use the heatmap with regular time series data (not pre-bucketed). Then it's important to keep in mind that your data is often already by aggregated by your time series backend. Most time series queries do not return raw sample data but include a group by time interval or maxDataPoints limit coupled with an aggregation function (usually average). This all depends on the time range of your query of course. But the important point is to know that the Histogram bucketing that Grafana performs may be done on already aggregated and averaged data. To get more accurate heatmaps it is better to do the bucketing during metric collection or store the data in Elasticsearch, or in the other data source which supports doing Histogram bucketing on the raw data. If you remove or lower the group by time (or raise maxDataPoints) in your query to return more data points your heatmap will be more accurate but this can also be very CPU and Memory taxing for your browser and could cause hangs and crashes if the number of data points becomes unreasonably large.
docs/sources/features/panels/heatmap.md
1
https://github.com/grafana/grafana/commit/64bf3b3c04c047824f6a2b00479f0d67bd0f31f4
[ 0.4707864820957184, 0.03729569539427757, 0.00016617562505416572, 0.0006845091702416539, 0.12514916062355042 ]
{ "id": 1, "code_window": [ "[menu.docs]\n", "name = \"Heatmap\"\n", "parent = \"panels\"\n", "weight = 3\n", "+++\n", "\n", "# Heatmap Panel\n", "\n", "![](/img/docs/v43/heatmap_panel_cover.jpg)\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "weight = 4\n" ], "file_path": "docs/sources/features/panels/heatmap.md", "type": "replace", "edit_start_line_idx": 8 }
// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build s390x // +build linux // +build !gccgo #include "textflag.h" // // System calls for s390x, Linux // // Just jump to package syscall's implementation for all these functions. // The runtime may know about them. TEXT ·Syscall(SB),NOSPLIT,$0-56 BR syscall·Syscall(SB) TEXT ·Syscall6(SB),NOSPLIT,$0-80 BR syscall·Syscall6(SB) TEXT ·SyscallNoError(SB),NOSPLIT,$0-48 BL runtime·entersyscall(SB) MOVD a1+8(FP), R2 MOVD a2+16(FP), R3 MOVD a3+24(FP), R4 MOVD $0, R5 MOVD $0, R6 MOVD $0, R7 MOVD trap+0(FP), R1 // syscall entry SYSCALL MOVD R2, r1+32(FP) MOVD R3, r2+40(FP) BL runtime·exitsyscall(SB) RET TEXT ·RawSyscall(SB),NOSPLIT,$0-56 BR syscall·RawSyscall(SB) TEXT ·RawSyscall6(SB),NOSPLIT,$0-80 BR syscall·RawSyscall6(SB) TEXT ·RawSyscallNoError(SB),NOSPLIT,$0-48 MOVD a1+8(FP), R2 MOVD a2+16(FP), R3 MOVD a3+24(FP), R4 MOVD $0, R5 MOVD $0, R6 MOVD $0, R7 MOVD trap+0(FP), R1 // syscall entry SYSCALL MOVD R2, r1+32(FP) MOVD R3, r2+40(FP) RET
vendor/golang.org/x/sys/unix/asm_linux_s390x.s
0
https://github.com/grafana/grafana/commit/64bf3b3c04c047824f6a2b00479f0d67bd0f31f4
[ 0.00017814742750488222, 0.0001734027755446732, 0.0001662720023887232, 0.00017399544594809413, 0.0000035581147130869795 ]
{ "id": 1, "code_window": [ "[menu.docs]\n", "name = \"Heatmap\"\n", "parent = \"panels\"\n", "weight = 3\n", "+++\n", "\n", "# Heatmap Panel\n", "\n", "![](/img/docs/v43/heatmap_panel_cover.jpg)\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "weight = 4\n" ], "file_path": "docs/sources/features/panels/heatmap.md", "type": "replace", "edit_start_line_idx": 8 }
package ast import ( "errors" "fmt" "github.com/gobwas/glob/syntax/lexer" "unicode/utf8" ) type Lexer interface { Next() lexer.Token } type parseFn func(*Node, Lexer) (parseFn, *Node, error) func Parse(lexer Lexer) (*Node, error) { var parser parseFn root := NewNode(KindPattern, nil) var ( tree *Node err error ) for parser, tree = parserMain, root; parser != nil; { parser, tree, err = parser(tree, lexer) if err != nil { return nil, err } } return root, nil } func parserMain(tree *Node, lex Lexer) (parseFn, *Node, error) { for { token := lex.Next() switch token.Type { case lexer.EOF: return nil, tree, nil case lexer.Error: return nil, tree, errors.New(token.Raw) case lexer.Text: Insert(tree, NewNode(KindText, Text{token.Raw})) return parserMain, tree, nil case lexer.Any: Insert(tree, NewNode(KindAny, nil)) return parserMain, tree, nil case lexer.Super: Insert(tree, NewNode(KindSuper, nil)) return parserMain, tree, nil case lexer.Single: Insert(tree, NewNode(KindSingle, nil)) return parserMain, tree, nil case lexer.RangeOpen: return parserRange, tree, nil case lexer.TermsOpen: a := NewNode(KindAnyOf, nil) Insert(tree, a) p := NewNode(KindPattern, nil) Insert(a, p) return parserMain, p, nil case lexer.Separator: p := NewNode(KindPattern, nil) Insert(tree.Parent, p) return parserMain, p, nil case lexer.TermsClose: return parserMain, tree.Parent.Parent, nil default: return nil, tree, fmt.Errorf("unexpected token: %s", token) } } return nil, tree, fmt.Errorf("unknown error") } func parserRange(tree *Node, lex Lexer) (parseFn, *Node, error) { var ( not bool lo rune hi rune chars string ) for { token := lex.Next() switch token.Type { case lexer.EOF: return nil, tree, errors.New("unexpected end") case lexer.Error: return nil, tree, errors.New(token.Raw) case lexer.Not: not = true case lexer.RangeLo: r, w := utf8.DecodeRuneInString(token.Raw) if len(token.Raw) > w { return nil, tree, fmt.Errorf("unexpected length of lo character") } lo = r case lexer.RangeBetween: // case lexer.RangeHi: r, w := utf8.DecodeRuneInString(token.Raw) if len(token.Raw) > w { return nil, tree, fmt.Errorf("unexpected length of lo character") } hi = r if hi < lo { return nil, tree, fmt.Errorf("hi character '%s' should be greater than lo '%s'", string(hi), string(lo)) } case lexer.Text: chars = token.Raw case lexer.RangeClose: isRange := lo != 0 && hi != 0 isChars := chars != "" if isChars == isRange { return nil, tree, fmt.Errorf("could not parse range") } if isRange { Insert(tree, NewNode(KindRange, Range{ Lo: lo, Hi: hi, Not: not, })) } else { Insert(tree, NewNode(KindList, List{ Chars: chars, Not: not, })) } return parserMain, tree, nil } } }
vendor/github.com/gobwas/glob/syntax/ast/parser.go
0
https://github.com/grafana/grafana/commit/64bf3b3c04c047824f6a2b00479f0d67bd0f31f4
[ 0.00017583122826181352, 0.00017111931811086833, 0.00016796957061160356, 0.000170832994626835, 0.000002681917067093309 ]
{ "id": 1, "code_window": [ "[menu.docs]\n", "name = \"Heatmap\"\n", "parent = \"panels\"\n", "weight = 3\n", "+++\n", "\n", "# Heatmap Panel\n", "\n", "![](/img/docs/v43/heatmap_panel_cover.jpg)\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "weight = 4\n" ], "file_path": "docs/sources/features/panels/heatmap.md", "type": "replace", "edit_start_line_idx": 8 }
export const renderGeneratedFileBanner = (themeFile: string, templateFile: string) => `/*** * !!! THIS FILE WAS GENERATED AUTOMATICALLY !!! * * Do not modify this file! * - Edit ${themeFile} to regenerate * - Edit ${templateFile} to update template * * !!! THIS FILE WAS GENERATED AUTOMATICALLY !!! */ `;
packages/grafana-ui/src/utils/generatedFileBanner.ts
0
https://github.com/grafana/grafana/commit/64bf3b3c04c047824f6a2b00479f0d67bd0f31f4
[ 0.00020971264166291803, 0.00018797875964082778, 0.00016624489217065275, 0.00018797875964082778, 0.000021733874746132642 ]
{ "id": 2, "code_window": [ "aliases = [\"/reference/logs/\"]\n", "[menu.docs]\n", "name = \"Logs\"\n", "parent = \"panels\"\n", "weight = 2\n", "+++\n", "\n", "# Logs Panel\n", "\n", "<img class=\"screenshot\" src=\"/img/docs/v64/logs-panel.png\">\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "weight = 4\n" ], "file_path": "docs/sources/features/panels/logs.md", "type": "replace", "edit_start_line_idx": 8 }
+++ title = "Graph Panel" keywords = ["grafana", "graph panel", "documentation", "guide", "graph"] type = "docs" aliases = ["/reference/graph/"] [menu.docs] name = "Graph" parent = "panels" weight = 1 +++ # Graph Panel {{< docs-imagebox img="/img/docs/v45/graph_overview.png" class="docs-image--no-shadow" max-width="850px" >}} The main panel in Grafana is simply named Graph. It provides a very rich set of graphing options. 1. Clicking the title for a panel exposes a menu. The `edit` option opens additional configuration options for the panel. 2. Click to open color and axis selection. 3. Click to only show this series. Shift/Ctrl+Click to hide series. ## General {{< docs-imagebox img="/img/docs/v51/graph_general.png" max-width= "800px" >}} The general tab allows customization of a panel's appearance and menu options. ### Info - **Title** - The panel title of the dashboard, displayed at the top. - **Description** - The panel description, displayed on hover of info icon in the upper left corner of the panel. - **Transparent** - If checked, removes the solid background of the panel (default not checked). ### Repeat Repeat a panel for each value of a variable. Repeating panels are described in more detail [here]({{< relref "../../reference/templating.md#repeating-panels" >}}). ## Metrics The metrics tab defines what series data and sources to render. Each data source provides different options. ## Axes {{< docs-imagebox img="/img/docs/v51/graph_axes_grid_options.png" max-width= "800px" >}} The Axes tab controls the display of axes. ### Left Y/Right Y The **Left Y** and **Right Y** can be customized using: - **Unit** - The display unit for the Y value - **Scale** - The scale to use for the Y value, linear or logarithmic. (default linear) - **Y-Min** - The minimum Y value. (default auto) - **Y-Max** - The maximum Y value. (default auto) - **Decimals** - Controls how many decimals are displayed for Y value (default auto) - **Label** - The Y axis label (default "") Axes can also be hidden by unchecking the appropriate box from **Show**. ### X-Axis Axis can be hidden by unchecking **Show**. For **Mode** there are three options: - The default option is **Time** and means the x-axis represents time and that the data is grouped by time (for example, by hour or by minute). - The **Series** option means that the data is grouped by series and not by time. The y-axis still represents the value. {{< docs-imagebox img="/img/docs/v51/graph-x-axis-mode-series.png" max-width="800px">}} - The **Histogram** option converts the graph into a histogram. A Histogram is a kind of bar chart that groups numbers into ranges, often called buckets or bins. Taller bars show that more data falls in that range. Histograms and buckets are described in more detail [here](http://docs.grafana.org/features/panels/heatmap/#histograms-and-buckets). <img src="/img/docs/v43/heatmap_histogram.png" class="no-shadow"> ### Y-Axes - **Align** - Check to align left and right Y-axes by value (default unchecked/false) - **Level** - Available when *Align* is checked. Value to use for alignment of left and right Y-axes, starting from Y=0 (default 0) ## Legend {{< docs-imagebox img="/img/docs/v51/graph-legend.png" max-width= "800px" >}} ### Options - **Show** - Uncheck to hide the legend (default checked/true) - **Table** - Check to display legend in table (default unchecked/false) - **To the right** - Check to display legend to the right (default unchecked/false) - **Width** - Available when *To the right* is checked. Value to control the minimum width for the legend (default 0) ### Values Additional values can be shown along-side the legend names: - **Min** - Minimum of all values returned from metric query - **Max** - Maximum of all values returned from the metric query - **Avg** - Average of all values returned from metric query - **Current** - Last value returned from the metric query - **Total** - Sum of all values returned from metric query - **Decimals** - Controls how many decimals are displayed for legend values (and graph hover tooltips) The legend values are calculated client side by Grafana and depend on what type of aggregation or point consolidation your metric query is using. All the above legend values cannot be correct at the same time. For example if you plot a rate like requests/second, this is probably using average as aggregator, then the Total in the legend will not represent the total number of requests. It is just the sum of all data points received by Grafana. ### Hide series Hide series when all values of a series from a metric query are of a specific value: - **With only nulls** - Value=*null* (default unchecked) - **With only zeros** - Value=*zero* (default unchecked) ## Display styles {{< docs-imagebox img="/img/docs/v51/graph_display_styles.png" max-width= "800px" >}} Display styles control visual properties of the graph. ### Draw Options #### Draw Modes - **Bar** - Display values as a bar chart - **Lines** - Display values as a line graph - **Points** - Display points for values #### Mode Options - **Fill** - Amount of color fill for a series (default 1). 0 is none. - **Line Width** - The width of the line for a series (default 1). - **Staircase** - Draws adjacent points as staircase - **Points Radius** - Adjust the size of points when *Points* are selected as *Draw Mode*. - **Hidden Series** - Hide series by default in graph. #### Hover tooltip - **Mode** - Controls how many series to display in the tooltip when hover over a point in time, All series or single (default All series). - **Sort order** - Controls how series displayed in tooltip are sorted, None, Ascending or Descending (default None). - **Stacked value** - Available when *Stack* are checked and controls how stacked values are displayed in tooltip (default Individual). - Individual: the value for the series you hover over - Cumulative - sum of series below plus the series you hover over #### Stacking and Null value If there are multiple series, they can be displayed as a group. - **Stack** - Each series is stacked on top of another - **Percent** - Available when *Stack* are checked. Each series is drawn as a percentage of the total of all series - **Null value** - How null values are displayed ### Series overrides {{< docs-imagebox img="/img/docs/v51/graph_display_overrides.png" max-width= "800px" >}} The section allows a series to be rendered differently from the others. For example, one series can be given a thicker line width to make it stand out and/or be moved to the right Y-axis. #### Dashes Drawing Style There is an option under Series overrides to draw lines as dashes. Set Dashes to the value True to override the line draw setting for a specific series. ### Thresholds {{< docs-imagebox img="/img/docs/v51/graph_display_thresholds.png" max-width= "800px" >}} Thresholds allow you to add arbitrary lines or sections to the graph to make it easier to see when the graph crosses a particular threshold. ### Time Regions > Only available in Grafana v5.4 and above. {{< docs-imagebox img="/img/docs/v54/graph_time_regions.png" max-width= "800px" >}} Time regions allow you to highlight certain time regions of the graph to make it easier to see for example weekends, business hours and/or off work hours. ## Time Range {{< docs-imagebox img="/img/docs/v51/graph-time-range.png" max-width= "900px" >}} The time range tab allows you to override the dashboard time range and specify a panel specific time. Either through a relative from now time option or through a timeshift. Panel time overrides and timeshift are described in more detail [here]({{< relref "reference/timerange.md#panel-time-overrides-timeshift" >}}). ### Data link > Only available in Grafana v6.3+. Data link allows adding dynamic links to the visualization. Those links can link to either other dashboard or to an external URL. {{< docs-imagebox img="/img/docs/data_link.png" max-width= "800px" >}} Data link is defined by title, url and a setting whether or not it should be opened in a new window. **Title** is a human readable label for the link that will be displayed in the UI. The link itself is accessible in the graph's context menu when user **clicks on a single data point**: {{< docs-imagebox img="/img/docs/data_link_tooltip.png" max-width= "800px" >}} **URL** field allows the URL configuration for a given link. Apart from regular query params it also supports built-in variables and dashboard variables that you can choose from available suggestions: {{< docs-imagebox img="/img/docs/data_link_typeahead.png" max-width= "800px" >}} #### Built-in variables > These variables changed in 6.4 so if you have an older version of Grafana please use the version picker to select docs for an older version of Grafana. ``__url_time_range`` - current dashboard's time range (i.e. ``?from=now-6h&to=now``) ``__from`` - current dashboard's time range from value ``__to`` - current dashboard's time range to value #### Series variables Series specific variables are available under ``__series`` namespace: ``__series.name`` - series name to the URL ``__series.labels.<LABEL>`` - label's value to the URL. If your label contains dots use ``__series.labels["<LABEL>"]`` syntax #### Field variables Field specific variables are available under ``__field`` namespace: ``__field.name`` - field name to the URL #### Value variables Value specific variables are available under ``__value`` namespace: ``__value.time`` - value's timestamp (Unix ms epoch) to the URL (i.e. ``?time=1560268814105``) ``__value.raw`` - raw value ``__value.numeric`` - numeric representation of a value ``__value.text`` - text representation of a value ``__value.calc`` - calculation name if the value is result of calculation #### Template variables When linking to another dashboard that uses template variables, you can use ``var-myvar=${myvar}`` syntax (where ``myvar`` is a name of template variable) to use current dashboard's variable value. If you want to add all of the current dashboard's variables to the URL use ``__all_variables`` variable.
docs/sources/features/panels/graph.md
1
https://github.com/grafana/grafana/commit/64bf3b3c04c047824f6a2b00479f0d67bd0f31f4
[ 0.1178356260061264, 0.004727459512650967, 0.0001626816374482587, 0.00017182494048029184, 0.02262188494205475 ]
{ "id": 2, "code_window": [ "aliases = [\"/reference/logs/\"]\n", "[menu.docs]\n", "name = \"Logs\"\n", "parent = \"panels\"\n", "weight = 2\n", "+++\n", "\n", "# Logs Panel\n", "\n", "<img class=\"screenshot\" src=\"/img/docs/v64/logs-panel.png\">\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "weight = 4\n" ], "file_path": "docs/sources/features/panels/logs.md", "type": "replace", "edit_start_line_idx": 8 }
apiVersion: 1 datasources: - orgId: 1 name: prometheus type: prometheus isDefault: True access: proxy url: http://prometheus.example.com:9090 - name: Graphite type: graphite access: proxy url: http://localhost:8080 - orgId: 2 name: prometheus type: prometheus isDefault: True access: proxy url: http://prometheus.example.com:9090 - orgId: 2 name: Graphite type: graphite access: proxy url: http://localhost:8080
pkg/services/provisioning/datasources/testdata/multiple-org-default/config.yaml
0
https://github.com/grafana/grafana/commit/64bf3b3c04c047824f6a2b00479f0d67bd0f31f4
[ 0.0001794317940948531, 0.0001779706362867728, 0.00017550712800584733, 0.00017897301586344838, 0.0000017520103483548155 ]
{ "id": 2, "code_window": [ "aliases = [\"/reference/logs/\"]\n", "[menu.docs]\n", "name = \"Logs\"\n", "parent = \"panels\"\n", "weight = 2\n", "+++\n", "\n", "# Logs Panel\n", "\n", "<img class=\"screenshot\" src=\"/img/docs/v64/logs-panel.png\">\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "weight = 4\n" ], "file_path": "docs/sources/features/panels/logs.md", "type": "replace", "edit_start_line_idx": 8 }
// Libraries import { Observable, of, timer, merge, from } from 'rxjs'; import { flatten, map as lodashMap, isArray, isString } from 'lodash'; import { map, catchError, takeUntil, mapTo, share, finalize } from 'rxjs/operators'; // Utils & Services import { getBackendSrv } from 'app/core/services/backend_srv'; // Types import { DataSourceApi, DataQueryRequest, PanelData, DataQueryResponse, DataQueryResponseData, DataQueryError, LoadingState, dateMath, toDataFrame, DataFrame, guessFieldTypes, } from '@grafana/data'; import { ExpressionDatasourceID, expressionDatasource } from 'app/features/expressions/ExpressionDatasource'; type MapOfResponsePackets = { [str: string]: DataQueryResponse }; interface RunningQueryState { packets: { [key: string]: DataQueryResponse }; panelData: PanelData; } /* * This function should handle composing a PanelData from multiple responses */ export function processResponsePacket(packet: DataQueryResponse, state: RunningQueryState): RunningQueryState { const request = state.panelData.request; const packets: MapOfResponsePackets = { ...state.packets, }; packets[packet.key || 'A'] = packet; // Update the time range const range = { ...request.range }; const timeRange = isString(range.raw.from) ? { from: dateMath.parse(range.raw.from, false), to: dateMath.parse(range.raw.to, true), raw: range.raw, } : range; const combinedData = flatten( lodashMap(packets, (packet: DataQueryResponse) => { return packet.data; }) ); const panelData = { state: packet.state || LoadingState.Done, series: combinedData, request, timeRange, }; return { packets, panelData }; } /** * This function handles the excecution of requests & and processes the single or multiple response packets into * a combined PanelData response. * It will * * Merge multiple responses into a single DataFrame array based on the packet key * * Will emit a loading state if no response after 50ms * * Cancel any still runnning network requests on unsubscribe (using request.requestId) */ export function runRequest(datasource: DataSourceApi, request: DataQueryRequest): Observable<PanelData> { let state: RunningQueryState = { panelData: { state: LoadingState.Loading, series: [], request: request, timeRange: request.range, }, packets: {}, }; // Return early if there are no queries to run if (!request.targets.length) { request.endTime = Date.now(); state.panelData.state = LoadingState.Done; return of(state.panelData); } const dataObservable = callQueryMethod(datasource, request).pipe( // Transform response packets into PanelData with merged results map((packet: DataQueryResponse) => { if (!isArray(packet.data)) { throw new Error(`Expected response data to be array, got ${typeof packet.data}.`); } request.endTime = Date.now(); state = processResponsePacket(packet, state); return state.panelData; }), // handle errors catchError(err => of({ ...state.panelData, state: LoadingState.Error, error: processQueryError(err), }) ), // finalize is triggered when subscriber unsubscribes // This makes sure any still running network requests are cancelled finalize(cancelNetworkRequestsOnUnsubscribe(request)), // this makes it possible to share this observable in takeUntil share() ); // If 50ms without a response emit a loading state // mapTo will translate the timer event into state.panelData (which has state set to loading) // takeUntil will cancel the timer emit when first response packet is received on the dataObservable return merge( timer(200).pipe( mapTo(state.panelData), takeUntil(dataObservable) ), dataObservable ); } function cancelNetworkRequestsOnUnsubscribe(req: DataQueryRequest) { return () => { getBackendSrv().resolveCancelerIfExists(req.requestId); }; } export function callQueryMethod(datasource: DataSourceApi, request: DataQueryRequest) { // If any query has an expression, use the expression endpoint for (const target of request.targets) { if (target.datasource === ExpressionDatasourceID) { return expressionDatasource.query(request); } } // Otherwise it is a standard datasource request const returnVal = datasource.query(request); return from(returnVal); } export function processQueryError(err: any): DataQueryError { const error = (err || {}) as DataQueryError; if (!error.message) { if (typeof err === 'string' || err instanceof String) { return { message: err } as DataQueryError; } let message = 'Query error'; if (error.message) { message = error.message; } else if (error.data && error.data.message) { message = error.data.message; } else if (error.data && error.data.error) { message = error.data.error; } else if (error.status) { message = `Query error: ${error.status} ${error.statusText}`; } error.message = message; } return error; } /** * All panels will be passed tables that have our best guess at colum type set * * This is also used by PanelChrome for snapshot support */ export function getProcessedDataFrames(results?: DataQueryResponseData[]): DataFrame[] { if (!isArray(results)) { return []; } const dataFrames: DataFrame[] = []; for (const result of results) { const dataFrame = guessFieldTypes(toDataFrame(result)); // clear out any cached calcs for (const field of dataFrame.fields) { field.calcs = null; } dataFrames.push(dataFrame); } return dataFrames; } export function preProcessPanelData(data: PanelData, lastResult: PanelData): PanelData { const { series } = data; // for loading states with no data, use last result if (data.state === LoadingState.Loading && series.length === 0) { if (!lastResult) { lastResult = data; } return { ...lastResult, state: LoadingState.Loading }; } // Make sure the data frames are properly formatted return { ...data, series: getProcessedDataFrames(series), }; }
public/app/features/dashboard/state/runRequest.ts
0
https://github.com/grafana/grafana/commit/64bf3b3c04c047824f6a2b00479f0d67bd0f31f4
[ 0.0007551385788246989, 0.00022583756071981043, 0.00016667104500811547, 0.00017801548528950661, 0.00012801734555978328 ]
{ "id": 2, "code_window": [ "aliases = [\"/reference/logs/\"]\n", "[menu.docs]\n", "name = \"Logs\"\n", "parent = \"panels\"\n", "weight = 2\n", "+++\n", "\n", "# Logs Panel\n", "\n", "<img class=\"screenshot\" src=\"/img/docs/v64/logs-panel.png\">\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "weight = 4\n" ], "file_path": "docs/sources/features/panels/logs.md", "type": "replace", "edit_start_line_idx": 8 }
import UrlBuilder from './url_builder'; describe('AzureMonitorUrlBuilder', () => { describe('when metric definition is Microsoft.Sql/servers/databases', () => { it('should build the getMetricNames url in the longer format', () => { const url = UrlBuilder.buildAzureMonitorGetMetricNamesUrl( '', 'sub1', 'rg', 'Microsoft.Sql/servers/databases', 'rn1/rn2', 'default', '2017-05-01-preview' ); expect(url).toBe( '/sub1/resourceGroups/rg/providers/Microsoft.Sql/servers/rn1/databases/rn2/' + 'providers/microsoft.insights/metricdefinitions?api-version=2017-05-01-preview&metricnamespace=default' ); }); }); describe('when metric definition is Microsoft.Sql/servers', () => { it('should build the getMetricNames url in the shorter format', () => { const url = UrlBuilder.buildAzureMonitorGetMetricNamesUrl( '', 'sub1', 'rg', 'Microsoft.Sql/servers', 'rn', 'default', '2017-05-01-preview' ); expect(url).toBe( '/sub1/resourceGroups/rg/providers/Microsoft.Sql/servers/rn/' + 'providers/microsoft.insights/metricdefinitions?api-version=2017-05-01-preview&metricnamespace=default' ); }); }); describe('when metric definition is Microsoft.Storage/storageAccounts/blobServices', () => { it('should build the getMetricNames url in the longer format', () => { const url = UrlBuilder.buildAzureMonitorGetMetricNamesUrl( '', 'sub1', 'rg', 'Microsoft.Storage/storageAccounts/blobServices', 'rn1/default', 'default', '2017-05-01-preview' ); expect(url).toBe( '/sub1/resourceGroups/rg/providers/Microsoft.Storage/storageAccounts/rn1/blobServices/default/' + 'providers/microsoft.insights/metricdefinitions?api-version=2017-05-01-preview&metricnamespace=default' ); }); }); describe('when metric definition is Microsoft.Storage/storageAccounts/fileServices', () => { it('should build the getMetricNames url in the longer format', () => { const url = UrlBuilder.buildAzureMonitorGetMetricNamesUrl( '', 'sub1', 'rg', 'Microsoft.Storage/storageAccounts/fileServices', 'rn1/default', 'default', '2017-05-01-preview' ); expect(url).toBe( '/sub1/resourceGroups/rg/providers/Microsoft.Storage/storageAccounts/rn1/fileServices/default/' + 'providers/microsoft.insights/metricdefinitions?api-version=2017-05-01-preview&metricnamespace=default' ); }); }); describe('when metric definition is Microsoft.Storage/storageAccounts/tableServices', () => { it('should build the getMetricNames url in the longer format', () => { const url = UrlBuilder.buildAzureMonitorGetMetricNamesUrl( '', 'sub1', 'rg', 'Microsoft.Storage/storageAccounts/tableServices', 'rn1/default', 'default', '2017-05-01-preview' ); expect(url).toBe( '/sub1/resourceGroups/rg/providers/Microsoft.Storage/storageAccounts/rn1/tableServices/default/' + 'providers/microsoft.insights/metricdefinitions?api-version=2017-05-01-preview&metricnamespace=default' ); }); }); describe('when metric definition is Microsoft.Storage/storageAccounts/queueServices', () => { it('should build the getMetricNames url in the longer format', () => { const url = UrlBuilder.buildAzureMonitorGetMetricNamesUrl( '', 'sub1', 'rg', 'Microsoft.Storage/storageAccounts/queueServices', 'rn1/default', 'default', '2017-05-01-preview' ); expect(url).toBe( '/sub1/resourceGroups/rg/providers/Microsoft.Storage/storageAccounts/rn1/queueServices/default/' + 'providers/microsoft.insights/metricdefinitions?api-version=2017-05-01-preview&metricnamespace=default' ); }); }); });
public/app/plugins/datasource/grafana-azure-monitor-datasource/azure_monitor/url_builder.test.ts
0
https://github.com/grafana/grafana/commit/64bf3b3c04c047824f6a2b00479f0d67bd0f31f4
[ 0.0001791189715731889, 0.0001757283607730642, 0.00017175257380586118, 0.00017546096933074296, 0.0000020007191778859124 ]
{ "id": 3, "code_window": [ "aliases = [\"/reference/singlestat/\"]\n", "[menu.docs]\n", "name = \"Singlestat\"\n", "parent = \"panels\"\n", "weight = 2\n", "+++\n", "\n", "\n", "# Singlestat Panel\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "weight = 4\n" ], "file_path": "docs/sources/features/panels/singlestat.md", "type": "replace", "edit_start_line_idx": 8 }
+++ title = "Logs Panel" keywords = ["grafana", "dashboard", "documentation", "panels", "logs panel"] type = "docs" aliases = ["/reference/logs/"] [menu.docs] name = "Logs" parent = "panels" weight = 2 +++ # Logs Panel <img class="screenshot" src="/img/docs/v64/logs-panel.png"> > Logs panel is only available in Grafana v6.4+ The logs panel shows log lines from datasources that support logs, e.g., Elastic, Influx, and Loki. Typically you would use this panel next to a graph panel to display the log output of a related process. ## Querying Data The logs panel will show the result of queries that are specified in the **Queries** tab. The results of multiple queries will be merged and sorted by time. Note that you can scroll inside the panel in case the datasource returns more lines than can be displayed at any one time. ### Query Options To limit the number of lines rendered, you can use the queries-wide **Max data points** setting. If it is not set, the datasource will usually enforce a limit. ## Visualization Options ### Columns 1. **Time**: Show/hide the time column. This is the timestamp associated with the log line as reported from the datasource. 2. **Order**: Set to **Ascending** to show the oldest log lines first. <div class="clearfix"></div>
docs/sources/features/panels/logs.md
1
https://github.com/grafana/grafana/commit/64bf3b3c04c047824f6a2b00479f0d67bd0f31f4
[ 0.03750208392739296, 0.009543219581246376, 0.00016844045603647828, 0.00025117865880019963, 0.016142193228006363 ]
{ "id": 3, "code_window": [ "aliases = [\"/reference/singlestat/\"]\n", "[menu.docs]\n", "name = \"Singlestat\"\n", "parent = \"panels\"\n", "weight = 2\n", "+++\n", "\n", "\n", "# Singlestat Panel\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "weight = 4\n" ], "file_path": "docs/sources/features/panels/singlestat.md", "type": "replace", "edit_start_line_idx": 8 }
// 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. // Code generated by the FlatBuffers compiler. DO NOT EDIT. package flatbuf import ( flatbuffers "github.com/google/flatbuffers/go" ) /// Time type. The physical storage type depends on the unit /// - SECOND and MILLISECOND: 32 bits /// - MICROSECOND and NANOSECOND: 64 bits type Time struct { _tab flatbuffers.Table } func GetRootAsTime(buf []byte, offset flatbuffers.UOffsetT) *Time { n := flatbuffers.GetUOffsetT(buf[offset:]) x := &Time{} x.Init(buf, n+offset) return x } func (rcv *Time) Init(buf []byte, i flatbuffers.UOffsetT) { rcv._tab.Bytes = buf rcv._tab.Pos = i } func (rcv *Time) Table() flatbuffers.Table { return rcv._tab } func (rcv *Time) Unit() TimeUnit { o := flatbuffers.UOffsetT(rcv._tab.Offset(4)) if o != 0 { return rcv._tab.GetInt16(o + rcv._tab.Pos) } return 1 } func (rcv *Time) MutateUnit(n TimeUnit) bool { return rcv._tab.MutateInt16Slot(4, n) } func (rcv *Time) BitWidth() int32 { o := flatbuffers.UOffsetT(rcv._tab.Offset(6)) if o != 0 { return rcv._tab.GetInt32(o + rcv._tab.Pos) } return 32 } func (rcv *Time) MutateBitWidth(n int32) bool { return rcv._tab.MutateInt32Slot(6, n) } func TimeStart(builder *flatbuffers.Builder) { builder.StartObject(2) } func TimeAddUnit(builder *flatbuffers.Builder, unit int16) { builder.PrependInt16Slot(0, unit, 1) } func TimeAddBitWidth(builder *flatbuffers.Builder, bitWidth int32) { builder.PrependInt32Slot(1, bitWidth, 32) } func TimeEnd(builder *flatbuffers.Builder) flatbuffers.UOffsetT { return builder.EndObject() }
vendor/github.com/apache/arrow/go/arrow/internal/flatbuf/Time.go
0
https://github.com/grafana/grafana/commit/64bf3b3c04c047824f6a2b00479f0d67bd0f31f4
[ 0.00018030045612249523, 0.00017344435036648065, 0.0001686368341324851, 0.00017369858687743545, 0.000003995312454208033 ]
{ "id": 3, "code_window": [ "aliases = [\"/reference/singlestat/\"]\n", "[menu.docs]\n", "name = \"Singlestat\"\n", "parent = \"panels\"\n", "weight = 2\n", "+++\n", "\n", "\n", "# Singlestat Panel\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "weight = 4\n" ], "file_path": "docs/sources/features/panels/singlestat.md", "type": "replace", "edit_start_line_idx": 8 }
import _ from 'lodash'; import { isVersionGtOrEq } from 'app/core/utils/version'; import { InterpolateFunction } from '@grafana/data'; const index: any = {}; export interface FuncDef { name: any; category?: string; params?: any; defaultParams?: any; shortName?: any; fake?: boolean; version?: string; description?: string; } function addFuncDef(funcDef: FuncDef) { funcDef.params = funcDef.params || []; funcDef.defaultParams = funcDef.defaultParams || []; index[funcDef.name] = funcDef; if (funcDef.shortName) { index[funcDef.shortName] = funcDef; } } const optionalSeriesRefArgs = [{ name: 'other', type: 'value_or_series', optional: true, multiple: true }]; addFuncDef({ name: 'scaleToSeconds', category: 'Transform', params: [{ name: 'seconds', type: 'int' }], defaultParams: [1], }); addFuncDef({ name: 'perSecond', category: 'Transform', params: [{ name: 'max value', type: 'int', optional: true }], defaultParams: [], }); addFuncDef({ name: 'holtWintersForecast', category: 'Calculate', }); addFuncDef({ name: 'holtWintersConfidenceBands', category: 'Calculate', params: [{ name: 'delta', type: 'int' }], defaultParams: [3], }); addFuncDef({ name: 'holtWintersAberration', category: 'Calculate', params: [{ name: 'delta', type: 'int' }], defaultParams: [3], }); addFuncDef({ name: 'nPercentile', category: 'Calculate', params: [{ name: 'Nth percentile', type: 'int' }], defaultParams: [95], }); addFuncDef({ name: 'diffSeries', params: optionalSeriesRefArgs, defaultParams: ['#A'], category: 'Combine', }); addFuncDef({ name: 'stddevSeries', params: optionalSeriesRefArgs, defaultParams: [''], category: 'Combine', }); addFuncDef({ name: 'divideSeries', params: optionalSeriesRefArgs, defaultParams: ['#A'], category: 'Combine', }); addFuncDef({ name: 'multiplySeries', params: optionalSeriesRefArgs, defaultParams: ['#A'], category: 'Combine', }); addFuncDef({ name: 'asPercent', params: optionalSeriesRefArgs, defaultParams: ['#A'], category: 'Combine', }); addFuncDef({ name: 'group', params: optionalSeriesRefArgs, defaultParams: ['#A', '#B'], category: 'Combine', }); addFuncDef({ name: 'sumSeries', shortName: 'sum', category: 'Combine', params: optionalSeriesRefArgs, defaultParams: [''], }); addFuncDef({ name: 'averageSeries', shortName: 'avg', category: 'Combine', params: optionalSeriesRefArgs, defaultParams: [''], }); addFuncDef({ name: 'rangeOfSeries', category: 'Combine', }); addFuncDef({ name: 'percentileOfSeries', category: 'Combine', params: [{ name: 'n', type: 'int' }, { name: 'interpolate', type: 'boolean', options: ['true', 'false'] }], defaultParams: [95, 'false'], }); addFuncDef({ name: 'sumSeriesWithWildcards', category: 'Combine', params: [{ name: 'node', type: 'int', multiple: true }], defaultParams: [3], }); addFuncDef({ name: 'maxSeries', shortName: 'max', category: 'Combine', }); addFuncDef({ name: 'minSeries', shortName: 'min', category: 'Combine', }); addFuncDef({ name: 'averageSeriesWithWildcards', category: 'Combine', params: [{ name: 'node', type: 'int', multiple: true }], defaultParams: [3], }); addFuncDef({ name: 'alias', category: 'Alias', params: [{ name: 'alias', type: 'string' }], defaultParams: ['alias'], }); addFuncDef({ name: 'aliasSub', category: 'Alias', params: [{ name: 'search', type: 'string' }, { name: 'replace', type: 'string' }], defaultParams: ['', '\\1'], }); addFuncDef({ name: 'consolidateBy', category: 'Special', params: [ { name: 'function', type: 'string', options: ['sum', 'average', 'min', 'max'], }, ], defaultParams: ['max'], }); addFuncDef({ name: 'cumulative', category: 'Special', params: [], defaultParams: [], }); addFuncDef({ name: 'groupByNode', category: 'Combine', params: [ { name: 'node', type: 'int', options: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12], }, { name: 'function', type: 'string', options: ['sum', 'avg', 'maxSeries'], }, ], defaultParams: [3, 'sum'], }); addFuncDef({ name: 'aliasByNode', category: 'Alias', params: [ { name: 'node', type: 'int', options: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12], multiple: true, }, ], defaultParams: [3], }); addFuncDef({ name: 'substr', category: 'Special', params: [ { name: 'start', type: 'int', options: [-6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12], }, { name: 'stop', type: 'int', options: [-6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12], }, ], defaultParams: [0, 0], }); addFuncDef({ name: 'sortByName', category: 'Sorting', params: [ { name: 'natural', type: 'boolean', options: ['true', 'false'], optional: true, }, ], defaultParams: ['false'], }); addFuncDef({ name: 'sortByMaxima', category: 'Sorting', }); addFuncDef({ name: 'sortByMinima', category: 'Sorting', }); addFuncDef({ name: 'sortByTotal', category: 'Sorting', }); addFuncDef({ name: 'aliasByMetric', category: 'Alias', }); addFuncDef({ name: 'randomWalk', fake: true, category: 'Special', params: [{ name: 'name', type: 'string' }], defaultParams: ['randomWalk'], }); addFuncDef({ name: 'countSeries', category: 'Combine', }); addFuncDef({ name: 'constantLine', category: 'Special', params: [{ name: 'value', type: 'int' }], defaultParams: [10], }); addFuncDef({ name: 'cactiStyle', category: 'Special', }); addFuncDef({ name: 'keepLastValue', category: 'Transform', params: [{ name: 'n', type: 'int' }], defaultParams: [100], }); addFuncDef({ name: 'changed', category: 'Special', params: [], defaultParams: [], }); addFuncDef({ name: 'scale', category: 'Transform', params: [{ name: 'factor', type: 'int' }], defaultParams: [1], }); addFuncDef({ name: 'offset', category: 'Transform', params: [{ name: 'amount', type: 'int' }], defaultParams: [10], }); addFuncDef({ name: 'transformNull', category: 'Transform', params: [{ name: 'amount', type: 'int' }], defaultParams: [0], }); addFuncDef({ name: 'integral', category: 'Transform', }); addFuncDef({ name: 'derivative', category: 'Transform', }); addFuncDef({ name: 'nonNegativeDerivative', category: 'Transform', params: [{ name: 'max value or 0', type: 'int', optional: true }], defaultParams: [''], }); addFuncDef({ name: 'timeShift', category: 'Transform', params: [ { name: 'amount', type: 'select', options: ['1h', '6h', '12h', '1d', '2d', '7d', '14d', '30d'], }, ], defaultParams: ['1d'], }); addFuncDef({ name: 'timeStack', category: 'Transform', params: [ { name: 'timeShiftUnit', type: 'select', options: ['1h', '6h', '12h', '1d', '2d', '7d', '14d', '30d'], }, { name: 'timeShiftStart', type: 'int' }, { name: 'timeShiftEnd', type: 'int' }, ], defaultParams: ['1d', 0, 7], }); addFuncDef({ name: 'summarize', category: 'Transform', params: [ { name: 'interval', type: 'string' }, { name: 'func', type: 'select', options: ['sum', 'avg', 'min', 'max', 'last'], }, { name: 'alignToFrom', type: 'boolean', optional: true, options: ['false', 'true'], }, ], defaultParams: ['1h', 'sum', 'false'], }); addFuncDef({ name: 'smartSummarize', category: 'Transform', params: [ { name: 'interval', type: 'string' }, { name: 'func', type: 'select', options: ['sum', 'avg', 'min', 'max', 'last'], }, ], defaultParams: ['1h', 'sum'], }); addFuncDef({ name: 'absolute', category: 'Transform', }); addFuncDef({ name: 'hitcount', category: 'Transform', params: [{ name: 'interval', type: 'string' }], defaultParams: ['10s'], }); addFuncDef({ name: 'log', category: 'Transform', params: [{ name: 'base', type: 'int' }], defaultParams: ['10'], }); addFuncDef({ name: 'averageAbove', category: 'Filter Series', params: [{ name: 'n', type: 'int' }], defaultParams: [25], }); addFuncDef({ name: 'averageBelow', category: 'Filter Series', params: [{ name: 'n', type: 'int' }], defaultParams: [25], }); addFuncDef({ name: 'currentAbove', category: 'Filter Series', params: [{ name: 'n', type: 'int' }], defaultParams: [25], }); addFuncDef({ name: 'currentBelow', category: 'Filter Series', params: [{ name: 'n', type: 'int' }], defaultParams: [25], }); addFuncDef({ name: 'maximumAbove', category: 'Filter Series', params: [{ name: 'value', type: 'int' }], defaultParams: [0], }); addFuncDef({ name: 'maximumBelow', category: 'Filter Series', params: [{ name: 'value', type: 'int' }], defaultParams: [0], }); addFuncDef({ name: 'minimumAbove', category: 'Filter Series', params: [{ name: 'value', type: 'int' }], defaultParams: [0], }); addFuncDef({ name: 'minimumBelow', category: 'Filter Series', params: [{ name: 'value', type: 'int' }], defaultParams: [0], }); addFuncDef({ name: 'limit', category: 'Filter Series', params: [{ name: 'n', type: 'int' }], defaultParams: [5], }); addFuncDef({ name: 'mostDeviant', category: 'Filter Series', params: [{ name: 'n', type: 'int' }], defaultParams: [10], }); addFuncDef({ name: 'exclude', category: 'Filter Series', params: [{ name: 'exclude', type: 'string' }], defaultParams: ['exclude'], }); addFuncDef({ name: 'highestCurrent', category: 'Filter Series', params: [{ name: 'count', type: 'int' }], defaultParams: [5], }); addFuncDef({ name: 'highestMax', category: 'Filter Series', params: [{ name: 'count', type: 'int' }], defaultParams: [5], }); addFuncDef({ name: 'lowestCurrent', category: 'Filter Series', params: [{ name: 'count', type: 'int' }], defaultParams: [5], }); addFuncDef({ name: 'movingAverage', category: 'Calculate', params: [ { name: 'windowSize', type: 'int_or_interval', options: ['5', '7', '10', '5min', '10min', '30min', '1hour'], }, ], defaultParams: [10], }); addFuncDef({ name: 'movingMedian', category: 'Calculate', params: [ { name: 'windowSize', type: 'int_or_interval', options: ['5', '7', '10', '5min', '10min', '30min', '1hour'], }, ], defaultParams: ['5'], }); addFuncDef({ name: 'stdev', category: 'Calculate', params: [{ name: 'n', type: 'int' }, { name: 'tolerance', type: 'int' }], defaultParams: [5, 0.1], }); addFuncDef({ name: 'highestAverage', category: 'Filter Series', params: [{ name: 'count', type: 'int' }], defaultParams: [5], }); addFuncDef({ name: 'lowestAverage', category: 'Filter Series', params: [{ name: 'count', type: 'int' }], defaultParams: [5], }); addFuncDef({ name: 'removeAbovePercentile', category: 'Filter Data', params: [{ name: 'n', type: 'int' }], defaultParams: [5], }); addFuncDef({ name: 'removeAboveValue', category: 'Filter Data', params: [{ name: 'n', type: 'int' }], defaultParams: [5], }); addFuncDef({ name: 'removeBelowPercentile', category: 'Filter Data', params: [{ name: 'n', type: 'int' }], defaultParams: [5], }); addFuncDef({ name: 'removeBelowValue', category: 'Filter Data', params: [{ name: 'n', type: 'int' }], defaultParams: [5], }); addFuncDef({ name: 'useSeriesAbove', category: 'Filter Series', params: [{ name: 'value', type: 'int' }, { name: 'search', type: 'string' }, { name: 'replace', type: 'string' }], defaultParams: [0, 'search', 'replace'], }); //////////////////// // Graphite 1.0.x // //////////////////// addFuncDef({ name: 'aggregateLine', category: 'Calculate', params: [ { name: 'func', type: 'select', options: ['sum', 'avg', 'min', 'max', 'last'], }, ], defaultParams: ['avg'], version: '1.0', }); addFuncDef({ name: 'averageOutsidePercentile', category: 'Filter Series', params: [{ name: 'n', type: 'int' }], defaultParams: [95], version: '1.0', }); addFuncDef({ name: 'delay', category: 'Transform', params: [{ name: 'steps', type: 'int' }], defaultParams: [1], version: '1.0', }); addFuncDef({ name: 'exponentialMovingAverage', category: 'Calculate', params: [ { name: 'windowSize', type: 'int_or_interval', options: ['5', '7', '10', '5min', '10min', '30min', '1hour'], }, ], defaultParams: [10], version: '1.0', }); addFuncDef({ name: 'fallbackSeries', category: 'Special', params: [{ name: 'fallback', type: 'string' }], defaultParams: ['constantLine(0)'], version: '1.0', }); addFuncDef({ name: 'grep', category: 'Filter Series', params: [{ name: 'grep', type: 'string' }], defaultParams: ['grep'], version: '1.0', }); addFuncDef({ name: 'groupByNodes', category: 'Combine', params: [ { name: 'function', type: 'string', options: ['sum', 'avg', 'maxSeries'], }, { name: 'node', type: 'int', options: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12], multiple: true, }, ], defaultParams: ['sum', 3], version: '1.0', }); addFuncDef({ name: 'integralByInterval', category: 'Transform', params: [ { name: 'intervalUnit', type: 'select', options: ['1h', '6h', '12h', '1d', '2d', '7d', '14d', '30d'], }, ], defaultParams: ['1d'], version: '1.0', }); addFuncDef({ name: 'interpolate', category: 'Transform', params: [{ name: 'limit', type: 'int', optional: true }], defaultParams: [], version: '1.0', }); addFuncDef({ name: 'invert', category: 'Transform', version: '1.0', }); addFuncDef({ name: 'isNonNull', category: 'Combine', version: '1.0', }); addFuncDef({ name: 'linearRegression', category: 'Calculate', params: [ { name: 'startSourceAt', type: 'select', options: ['-1h', '-6h', '-12h', '-1d', '-2d', '-7d', '-14d', '-30d'], optional: true, }, { name: 'endSourceAt', type: 'select', options: ['-1h', '-6h', '-12h', '-1d', '-2d', '-7d', '-14d', '-30d'], optional: true, }, ], defaultParams: [], version: '1.0', }); addFuncDef({ name: 'mapSeries', shortName: 'map', params: [{ name: 'node', type: 'int' }], defaultParams: [3], category: 'Combine', version: '1.0', }); addFuncDef({ name: 'movingMin', category: 'Calculate', params: [ { name: 'windowSize', type: 'int_or_interval', options: ['5', '7', '10', '5min', '10min', '30min', '1hour'], }, ], defaultParams: [10], version: '1.0', }); addFuncDef({ name: 'movingMax', category: 'Calculate', params: [ { name: 'windowSize', type: 'int_or_interval', options: ['5', '7', '10', '5min', '10min', '30min', '1hour'], }, ], defaultParams: [10], version: '1.0', }); addFuncDef({ name: 'movingSum', category: 'Calculate', params: [ { name: 'windowSize', type: 'int_or_interval', options: ['5', '7', '10', '5min', '10min', '30min', '1hour'], }, ], defaultParams: [10], version: '1.0', }); addFuncDef({ name: 'multiplySeriesWithWildcards', category: 'Combine', params: [ { name: 'position', type: 'int', options: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12], multiple: true, }, ], defaultParams: [2], version: '1.0', }); addFuncDef({ name: 'offsetToZero', category: 'Transform', version: '1.0', }); addFuncDef({ name: 'pow', category: 'Transform', params: [{ name: 'factor', type: 'int' }], defaultParams: [10], version: '1.0', }); addFuncDef({ name: 'powSeries', category: 'Transform', params: optionalSeriesRefArgs, defaultParams: [''], version: '1.0', }); addFuncDef({ name: 'reduceSeries', shortName: 'reduce', params: [ { name: 'function', type: 'string', options: ['asPercent', 'diffSeries', 'divideSeries'], }, { name: 'reduceNode', type: 'int', options: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13], }, { name: 'reduceMatchers', type: 'string', multiple: true }, ], defaultParams: ['asPercent', 2, 'used_bytes'], category: 'Combine', version: '1.0', }); addFuncDef({ name: 'removeBetweenPercentile', category: 'Filter Series', params: [{ name: 'n', type: 'int' }], defaultParams: [95], version: '1.0', }); addFuncDef({ name: 'removeEmptySeries', category: 'Filter Series', version: '1.0', }); addFuncDef({ name: 'squareRoot', category: 'Transform', version: '1.0', }); addFuncDef({ name: 'timeSlice', category: 'Transform', params: [ { name: 'startSliceAt', type: 'select', options: ['-1h', '-6h', '-12h', '-1d', '-2d', '-7d', '-14d', '-30d'], }, { name: 'endSliceAt', type: 'select', options: ['-1h', '-6h', '-12h', '-1d', '-2d', '-7d', '-14d', '-30d'], optional: true, }, ], defaultParams: ['-1h'], version: '1.0', }); addFuncDef({ name: 'weightedAverage', category: 'Combine', params: [ { name: 'other', type: 'value_or_series', optional: true }, { name: 'node', type: 'int', options: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12], }, ], defaultParams: ['#A', 4], version: '1.0', }); addFuncDef({ name: 'seriesByTag', category: 'Special', params: [{ name: 'tagExpression', type: 'string', multiple: true }], version: '1.1', }); addFuncDef({ name: 'groupByTags', category: 'Combine', params: [ { name: 'function', type: 'string', options: ['sum', 'avg', 'maxSeries'], }, { name: 'tag', type: 'string', multiple: true }, ], defaultParams: ['sum', 'tag'], version: '1.1', }); addFuncDef({ name: 'aliasByTags', category: 'Alias', params: [{ name: 'tag', type: 'string', multiple: true }], defaultParams: ['tag'], version: '1.1', }); function isVersionRelatedFunction(obj: { version: string }, graphiteVersion: string) { return !obj.version || isVersionGtOrEq(graphiteVersion, obj.version); } export class FuncInstance { def: any; params: any; text: any; added: boolean; constructor(funcDef: any, options: { withDefaultParams: any }) { this.def = funcDef; this.params = []; if (options && options.withDefaultParams) { this.params = funcDef.defaultParams.slice(0); } this.updateText(); } render(metricExp: string, replaceVariables: InterpolateFunction): string { const str = this.def.name + '('; const parameters = _.map(this.params, (value, index) => { let paramType; if (index < this.def.params.length) { paramType = this.def.params[index].type; } else if (_.get(_.last(this.def.params), 'multiple')) { paramType = _.get(_.last(this.def.params), 'type'); } // param types that should never be quoted if (_.includes(['value_or_series', 'boolean', 'int', 'float', 'node'], paramType)) { return value; } const valueInterpolated = _.isString(value) ? replaceVariables(value) : value; // param types that might be quoted // To quote variables correctly we need to interpolate it to check if it contains a numeric or string value if (_.includes(['int_or_interval', 'node_or_tag'], paramType) && _.isFinite(+valueInterpolated)) { return _.toString(value); } return "'" + value + "'"; }); // don't send any blank parameters to graphite while (parameters[parameters.length - 1] === '') { parameters.pop(); } if (metricExp) { parameters.unshift(metricExp); } return str + parameters.join(', ') + ')'; } _hasMultipleParamsInString(strValue: any, index: number) { if (strValue.indexOf(',') === -1) { return false; } if (this.def.params[index + 1] && this.def.params[index + 1].optional) { return true; } if (index + 1 >= this.def.params.length && _.get(_.last(this.def.params), 'multiple')) { return true; } return false; } updateParam(strValue: any, index: any) { // handle optional parameters // if string contains ',' and next param is optional, split and update both if (this._hasMultipleParamsInString(strValue, index)) { _.each(strValue.split(','), (partVal, idx) => { this.updateParam(partVal.trim(), index + idx); }); return; } if (strValue === '' && (index >= this.def.params.length || this.def.params[index].optional)) { this.params.splice(index, 1); } else { this.params[index] = strValue; } this.updateText(); } updateText() { if (this.params.length === 0) { this.text = this.def.name + '()'; return; } let text = this.def.name + '('; text += this.params.join(', '); text += ')'; this.text = text; } } function createFuncInstance(funcDef: any, options?: { withDefaultParams: any }, idx?: any) { if (_.isString(funcDef)) { funcDef = getFuncDef(funcDef, idx); } return new FuncInstance(funcDef, options); } function getFuncDef(name: string, idx?: any) { if (!(idx || index)[name]) { throw { message: 'Method not found ' + name }; } return (idx || index)[name]; } function getFuncDefs(graphiteVersion: string, idx?: any) { const funcs: any = {}; _.forEach(idx || index, funcDef => { if (isVersionRelatedFunction(funcDef, graphiteVersion)) { funcs[funcDef.name] = _.assign({}, funcDef, { params: _.filter(funcDef.params, param => { return isVersionRelatedFunction(param, graphiteVersion); }), }); } }); return funcs; } // parse response from graphite /functions endpoint into internal format function parseFuncDefs(rawDefs: any) { const funcDefs: any = {}; _.forEach(rawDefs || {}, (funcDef, funcName) => { // skip graphite graph functions if (funcDef.group === 'Graph') { return; } let description = funcDef.description; if (description) { // tidy up some pydoc syntax that rst2html can't handle description = description .replace(/:py:func:`(.+)( <[^>]*>)?`/g, '``$1``') .replace(/.. seealso:: /g, 'See also: ') .replace(/.. code-block *:: *none/g, '.. code-block::'); } const func: FuncDef = { name: funcDef.name, description, category: funcDef.group, params: [], defaultParams: [], fake: false, }; // get rid of the first "seriesList" param if (/^seriesLists?$/.test(_.get(funcDef, 'params[0].type', ''))) { // handle functions that accept multiple seriesLists // we leave the param in place but mark it optional, so users can add more series if they wish if (funcDef.params[0].multiple) { funcDef.params[0].required = false; // otherwise chop off the first param, it'll be handled separately } else { funcDef.params.shift(); } // tag function as fake } else { func.fake = true; } _.forEach(funcDef.params, rawParam => { const param: any = { name: rawParam.name, type: 'string', optional: !rawParam.required, multiple: !!rawParam.multiple, options: undefined, }; if (rawParam.default !== undefined) { func.defaultParams.push(_.toString(rawParam.default)); } else if (rawParam.suggestions) { func.defaultParams.push(_.toString(rawParam.suggestions[0])); } else { func.defaultParams.push(''); } if (rawParam.type === 'boolean') { param.type = 'boolean'; param.options = ['true', 'false']; } else if (rawParam.type === 'integer') { param.type = 'int'; } else if (rawParam.type === 'float') { param.type = 'float'; } else if (rawParam.type === 'node') { param.type = 'node'; param.options = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12']; } else if (rawParam.type === 'nodeOrTag') { param.type = 'node_or_tag'; param.options = ['name', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12']; } else if (rawParam.type === 'intOrInterval') { param.type = 'int_or_interval'; } else if (rawParam.type === 'seriesList') { param.type = 'value_or_series'; } if (rawParam.options) { param.options = _.map(rawParam.options, _.toString); } else if (rawParam.suggestions) { param.options = _.map(rawParam.suggestions, _.toString); } func.params.push(param); }); funcDefs[funcName] = func; }); return funcDefs; } export default { createFuncInstance: createFuncInstance, getFuncDef: getFuncDef, getFuncDefs: getFuncDefs, parseFuncDefs: parseFuncDefs, };
public/app/plugins/datasource/graphite/gfunc.ts
0
https://github.com/grafana/grafana/commit/64bf3b3c04c047824f6a2b00479f0d67bd0f31f4
[ 0.00018031919898930937, 0.00017544561706017703, 0.0001661930582486093, 0.0001758728176355362, 0.0000026941356736642774 ]
{ "id": 3, "code_window": [ "aliases = [\"/reference/singlestat/\"]\n", "[menu.docs]\n", "name = \"Singlestat\"\n", "parent = \"panels\"\n", "weight = 2\n", "+++\n", "\n", "\n", "# Singlestat Panel\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "weight = 4\n" ], "file_path": "docs/sources/features/panels/singlestat.md", "type": "replace", "edit_start_line_idx": 8 }
// Copyright 2018 The Prometheus Authors // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package prometheus import ( "errors" "fmt" "strings" "unicode/utf8" "github.com/prometheus/common/model" ) // Labels represents a collection of label name -> value mappings. This type is // commonly used with the With(Labels) and GetMetricWith(Labels) methods of // metric vector Collectors, e.g.: // myVec.With(Labels{"code": "404", "method": "GET"}).Add(42) // // The other use-case is the specification of constant label pairs in Opts or to // create a Desc. type Labels map[string]string // reservedLabelPrefix is a prefix which is not legal in user-supplied // label names. const reservedLabelPrefix = "__" var errInconsistentCardinality = errors.New("inconsistent label cardinality") func makeInconsistentCardinalityError(fqName string, labels, labelValues []string) error { return fmt.Errorf( "%s: %q has %d variable labels named %q but %d values %q were provided", errInconsistentCardinality, fqName, len(labels), labels, len(labelValues), labelValues, ) } func validateValuesInLabels(labels Labels, expectedNumberOfValues int) error { if len(labels) != expectedNumberOfValues { return fmt.Errorf( "%s: expected %d label values but got %d in %#v", errInconsistentCardinality, expectedNumberOfValues, len(labels), labels, ) } for name, val := range labels { if !utf8.ValidString(val) { return fmt.Errorf("label %s: value %q is not valid UTF-8", name, val) } } return nil } func validateLabelValues(vals []string, expectedNumberOfValues int) error { if len(vals) != expectedNumberOfValues { return fmt.Errorf( "%s: expected %d label values but got %d in %#v", errInconsistentCardinality, expectedNumberOfValues, len(vals), vals, ) } for _, val := range vals { if !utf8.ValidString(val) { return fmt.Errorf("label value %q is not valid UTF-8", val) } } return nil } func checkLabelName(l string) bool { return model.LabelName(l).IsValid() && !strings.HasPrefix(l, reservedLabelPrefix) }
vendor/github.com/prometheus/client_golang/prometheus/labels.go
0
https://github.com/grafana/grafana/commit/64bf3b3c04c047824f6a2b00479f0d67bd0f31f4
[ 0.00017827113333623856, 0.00017100881086662412, 0.00016032918938435614, 0.00017306755762547255, 0.000005270623660180718 ]
{ "id": 4, "code_window": [ "aliases = [\"/reference/table/\"]\n", "[menu.docs]\n", "name = \"Table\"\n", "parent = \"panels\"\n", "weight = 2\n", "+++\n", "\n", "\n", "# Table Panel\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "weight = 4\n" ], "file_path": "docs/sources/features/panels/table_panel.md", "type": "replace", "edit_start_line_idx": 8 }
+++ title = "Graph Panel" keywords = ["grafana", "graph panel", "documentation", "guide", "graph"] type = "docs" aliases = ["/reference/graph/"] [menu.docs] name = "Graph" parent = "panels" weight = 1 +++ # Graph Panel {{< docs-imagebox img="/img/docs/v45/graph_overview.png" class="docs-image--no-shadow" max-width="850px" >}} The main panel in Grafana is simply named Graph. It provides a very rich set of graphing options. 1. Clicking the title for a panel exposes a menu. The `edit` option opens additional configuration options for the panel. 2. Click to open color and axis selection. 3. Click to only show this series. Shift/Ctrl+Click to hide series. ## General {{< docs-imagebox img="/img/docs/v51/graph_general.png" max-width= "800px" >}} The general tab allows customization of a panel's appearance and menu options. ### Info - **Title** - The panel title of the dashboard, displayed at the top. - **Description** - The panel description, displayed on hover of info icon in the upper left corner of the panel. - **Transparent** - If checked, removes the solid background of the panel (default not checked). ### Repeat Repeat a panel for each value of a variable. Repeating panels are described in more detail [here]({{< relref "../../reference/templating.md#repeating-panels" >}}). ## Metrics The metrics tab defines what series data and sources to render. Each data source provides different options. ## Axes {{< docs-imagebox img="/img/docs/v51/graph_axes_grid_options.png" max-width= "800px" >}} The Axes tab controls the display of axes. ### Left Y/Right Y The **Left Y** and **Right Y** can be customized using: - **Unit** - The display unit for the Y value - **Scale** - The scale to use for the Y value, linear or logarithmic. (default linear) - **Y-Min** - The minimum Y value. (default auto) - **Y-Max** - The maximum Y value. (default auto) - **Decimals** - Controls how many decimals are displayed for Y value (default auto) - **Label** - The Y axis label (default "") Axes can also be hidden by unchecking the appropriate box from **Show**. ### X-Axis Axis can be hidden by unchecking **Show**. For **Mode** there are three options: - The default option is **Time** and means the x-axis represents time and that the data is grouped by time (for example, by hour or by minute). - The **Series** option means that the data is grouped by series and not by time. The y-axis still represents the value. {{< docs-imagebox img="/img/docs/v51/graph-x-axis-mode-series.png" max-width="800px">}} - The **Histogram** option converts the graph into a histogram. A Histogram is a kind of bar chart that groups numbers into ranges, often called buckets or bins. Taller bars show that more data falls in that range. Histograms and buckets are described in more detail [here](http://docs.grafana.org/features/panels/heatmap/#histograms-and-buckets). <img src="/img/docs/v43/heatmap_histogram.png" class="no-shadow"> ### Y-Axes - **Align** - Check to align left and right Y-axes by value (default unchecked/false) - **Level** - Available when *Align* is checked. Value to use for alignment of left and right Y-axes, starting from Y=0 (default 0) ## Legend {{< docs-imagebox img="/img/docs/v51/graph-legend.png" max-width= "800px" >}} ### Options - **Show** - Uncheck to hide the legend (default checked/true) - **Table** - Check to display legend in table (default unchecked/false) - **To the right** - Check to display legend to the right (default unchecked/false) - **Width** - Available when *To the right* is checked. Value to control the minimum width for the legend (default 0) ### Values Additional values can be shown along-side the legend names: - **Min** - Minimum of all values returned from metric query - **Max** - Maximum of all values returned from the metric query - **Avg** - Average of all values returned from metric query - **Current** - Last value returned from the metric query - **Total** - Sum of all values returned from metric query - **Decimals** - Controls how many decimals are displayed for legend values (and graph hover tooltips) The legend values are calculated client side by Grafana and depend on what type of aggregation or point consolidation your metric query is using. All the above legend values cannot be correct at the same time. For example if you plot a rate like requests/second, this is probably using average as aggregator, then the Total in the legend will not represent the total number of requests. It is just the sum of all data points received by Grafana. ### Hide series Hide series when all values of a series from a metric query are of a specific value: - **With only nulls** - Value=*null* (default unchecked) - **With only zeros** - Value=*zero* (default unchecked) ## Display styles {{< docs-imagebox img="/img/docs/v51/graph_display_styles.png" max-width= "800px" >}} Display styles control visual properties of the graph. ### Draw Options #### Draw Modes - **Bar** - Display values as a bar chart - **Lines** - Display values as a line graph - **Points** - Display points for values #### Mode Options - **Fill** - Amount of color fill for a series (default 1). 0 is none. - **Line Width** - The width of the line for a series (default 1). - **Staircase** - Draws adjacent points as staircase - **Points Radius** - Adjust the size of points when *Points* are selected as *Draw Mode*. - **Hidden Series** - Hide series by default in graph. #### Hover tooltip - **Mode** - Controls how many series to display in the tooltip when hover over a point in time, All series or single (default All series). - **Sort order** - Controls how series displayed in tooltip are sorted, None, Ascending or Descending (default None). - **Stacked value** - Available when *Stack* are checked and controls how stacked values are displayed in tooltip (default Individual). - Individual: the value for the series you hover over - Cumulative - sum of series below plus the series you hover over #### Stacking and Null value If there are multiple series, they can be displayed as a group. - **Stack** - Each series is stacked on top of another - **Percent** - Available when *Stack* are checked. Each series is drawn as a percentage of the total of all series - **Null value** - How null values are displayed ### Series overrides {{< docs-imagebox img="/img/docs/v51/graph_display_overrides.png" max-width= "800px" >}} The section allows a series to be rendered differently from the others. For example, one series can be given a thicker line width to make it stand out and/or be moved to the right Y-axis. #### Dashes Drawing Style There is an option under Series overrides to draw lines as dashes. Set Dashes to the value True to override the line draw setting for a specific series. ### Thresholds {{< docs-imagebox img="/img/docs/v51/graph_display_thresholds.png" max-width= "800px" >}} Thresholds allow you to add arbitrary lines or sections to the graph to make it easier to see when the graph crosses a particular threshold. ### Time Regions > Only available in Grafana v5.4 and above. {{< docs-imagebox img="/img/docs/v54/graph_time_regions.png" max-width= "800px" >}} Time regions allow you to highlight certain time regions of the graph to make it easier to see for example weekends, business hours and/or off work hours. ## Time Range {{< docs-imagebox img="/img/docs/v51/graph-time-range.png" max-width= "900px" >}} The time range tab allows you to override the dashboard time range and specify a panel specific time. Either through a relative from now time option or through a timeshift. Panel time overrides and timeshift are described in more detail [here]({{< relref "reference/timerange.md#panel-time-overrides-timeshift" >}}). ### Data link > Only available in Grafana v6.3+. Data link allows adding dynamic links to the visualization. Those links can link to either other dashboard or to an external URL. {{< docs-imagebox img="/img/docs/data_link.png" max-width= "800px" >}} Data link is defined by title, url and a setting whether or not it should be opened in a new window. **Title** is a human readable label for the link that will be displayed in the UI. The link itself is accessible in the graph's context menu when user **clicks on a single data point**: {{< docs-imagebox img="/img/docs/data_link_tooltip.png" max-width= "800px" >}} **URL** field allows the URL configuration for a given link. Apart from regular query params it also supports built-in variables and dashboard variables that you can choose from available suggestions: {{< docs-imagebox img="/img/docs/data_link_typeahead.png" max-width= "800px" >}} #### Built-in variables > These variables changed in 6.4 so if you have an older version of Grafana please use the version picker to select docs for an older version of Grafana. ``__url_time_range`` - current dashboard's time range (i.e. ``?from=now-6h&to=now``) ``__from`` - current dashboard's time range from value ``__to`` - current dashboard's time range to value #### Series variables Series specific variables are available under ``__series`` namespace: ``__series.name`` - series name to the URL ``__series.labels.<LABEL>`` - label's value to the URL. If your label contains dots use ``__series.labels["<LABEL>"]`` syntax #### Field variables Field specific variables are available under ``__field`` namespace: ``__field.name`` - field name to the URL #### Value variables Value specific variables are available under ``__value`` namespace: ``__value.time`` - value's timestamp (Unix ms epoch) to the URL (i.e. ``?time=1560268814105``) ``__value.raw`` - raw value ``__value.numeric`` - numeric representation of a value ``__value.text`` - text representation of a value ``__value.calc`` - calculation name if the value is result of calculation #### Template variables When linking to another dashboard that uses template variables, you can use ``var-myvar=${myvar}`` syntax (where ``myvar`` is a name of template variable) to use current dashboard's variable value. If you want to add all of the current dashboard's variables to the URL use ``__all_variables`` variable.
docs/sources/features/panels/graph.md
1
https://github.com/grafana/grafana/commit/64bf3b3c04c047824f6a2b00479f0d67bd0f31f4
[ 0.011689257808029652, 0.0006425020401366055, 0.00016486694221384823, 0.00017006072448566556, 0.002211842453107238 ]
{ "id": 4, "code_window": [ "aliases = [\"/reference/table/\"]\n", "[menu.docs]\n", "name = \"Table\"\n", "parent = \"panels\"\n", "weight = 2\n", "+++\n", "\n", "\n", "# Table Panel\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "weight = 4\n" ], "file_path": "docs/sources/features/panels/table_panel.md", "type": "replace", "edit_start_line_idx": 8 }
package models import ( "context" "errors" ) // Typed errors var ( ErrUserTokenNotFound = errors.New("user token not found") ) // UserToken represents a user token type UserToken struct { Id int64 UserId int64 AuthToken string PrevAuthToken string UserAgent string ClientIp string AuthTokenSeen bool SeenAt int64 RotatedAt int64 CreatedAt int64 UpdatedAt int64 UnhashedToken string } type RevokeAuthTokenCmd struct { AuthTokenId int64 `json:"authTokenId"` } // UserTokenService are used for generating and validating user tokens type UserTokenService interface { CreateToken(ctx context.Context, userId int64, clientIP, userAgent string) (*UserToken, error) LookupToken(ctx context.Context, unhashedToken string) (*UserToken, error) TryRotateToken(ctx context.Context, token *UserToken, clientIP, userAgent string) (bool, error) RevokeToken(ctx context.Context, token *UserToken) error RevokeAllUserTokens(ctx context.Context, userId int64) error ActiveTokenCount(ctx context.Context) (int64, error) GetUserToken(ctx context.Context, userId, userTokenId int64) (*UserToken, error) GetUserTokens(ctx context.Context, userId int64) ([]*UserToken, error) }
pkg/models/user_token.go
0
https://github.com/grafana/grafana/commit/64bf3b3c04c047824f6a2b00479f0d67bd0f31f4
[ 0.0001731301163090393, 0.00017126579768955708, 0.00016930029960349202, 0.00017141617718152702, 0.0000013993314951221691 ]
{ "id": 4, "code_window": [ "aliases = [\"/reference/table/\"]\n", "[menu.docs]\n", "name = \"Table\"\n", "parent = \"panels\"\n", "weight = 2\n", "+++\n", "\n", "\n", "# Table Panel\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "weight = 4\n" ], "file_path": "docs/sources/features/panels/table_panel.md", "type": "replace", "edit_start_line_idx": 8 }
package gtime import ( "regexp" "strconv" "time" ) var dateUnitPattern = regexp.MustCompile(`(\d+)([wdy])`) // ParseInterval parses an interval with support for all units that Grafana uses. func ParseInterval(interval string) (time.Duration, error) { result := dateUnitPattern.FindSubmatch([]byte(interval)) if len(result) != 3 { return time.ParseDuration(interval) } num, _ := strconv.Atoi(string(result[1])) period := string(result[2]) if period == `d` { return time.Hour * 24 * time.Duration(num), nil } if period == `w` { return time.Hour * 24 * 7 * time.Duration(num), nil } return time.Hour * 24 * 7 * 365 * time.Duration(num), nil }
pkg/components/gtime/gtime.go
0
https://github.com/grafana/grafana/commit/64bf3b3c04c047824f6a2b00479f0d67bd0f31f4
[ 0.00018041326256934553, 0.00017513780039735138, 0.00017080208635888994, 0.00017466793360654265, 0.0000034364202292636037 ]
{ "id": 4, "code_window": [ "aliases = [\"/reference/table/\"]\n", "[menu.docs]\n", "name = \"Table\"\n", "parent = \"panels\"\n", "weight = 2\n", "+++\n", "\n", "\n", "# Table Panel\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "weight = 4\n" ], "file_path": "docs/sources/features/panels/table_panel.md", "type": "replace", "edit_start_line_idx": 8 }
// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. // Package ec2 provides the client and types for making API // requests to Amazon Elastic Compute Cloud. // // Amazon Elastic Compute Cloud (Amazon EC2) provides secure and resizable computing // capacity in the AWS cloud. Using Amazon EC2 eliminates the need to invest // in hardware up front, so you can develop and deploy applications faster. // // To learn more, see the following resources: // // * Amazon EC2: AmazonEC2 product page (http://aws.amazon.com/ec2), Amazon // EC2 documentation (http://aws.amazon.com/documentation/ec2) // // * Amazon EBS: Amazon EBS product page (http://aws.amazon.com/ebs), Amazon // EBS documentation (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/AmazonEBS.html) // // * Amazon VPC: Amazon VPC product page (http://aws.amazon.com/vpc), Amazon // VPC documentation (http://aws.amazon.com/documentation/vpc) // // * AWS VPN: AWS VPN product page (http://aws.amazon.com/vpn), AWS VPN documentation // (http://aws.amazon.com/documentation/vpn) // // See https://docs.aws.amazon.com/goto/WebAPI/ec2-2016-11-15 for more information on this service. // // See ec2 package documentation for more information. // https://docs.aws.amazon.com/sdk-for-go/api/service/ec2/ // // Using the Client // // To contact Amazon Elastic Compute Cloud with the SDK use the New function to create // a new service client. With that client you can make API requests to the service. // These clients are safe to use concurrently. // // See the SDK's documentation for more information on how to use the SDK. // https://docs.aws.amazon.com/sdk-for-go/api/ // // See aws.Config documentation for more information on configuring SDK clients. // https://docs.aws.amazon.com/sdk-for-go/api/aws/#Config // // See the Amazon Elastic Compute Cloud client EC2 for more // information on creating client for this service. // https://docs.aws.amazon.com/sdk-for-go/api/service/ec2/#New package ec2
vendor/github.com/aws/aws-sdk-go/service/ec2/doc.go
0
https://github.com/grafana/grafana/commit/64bf3b3c04c047824f6a2b00479f0d67bd0f31f4
[ 0.00017509725876152515, 0.0001721647277008742, 0.000169550214195624, 0.00017121429846156389, 0.000002130319217030774 ]
{ "id": 0, "code_window": [ "var a: 123;\n", "var a: 123.0;\n", "var a: 0x7B;\n", "var a: 123;\n", "var a: 123;\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace" ], "after_edit": [ "var a: 0b1111011;\n", "var a: 0o173;" ], "file_path": "packages/babel/test/fixtures/generation/flow/number-literal-types/expected.js", "type": "replace", "edit_start_line_idx": 3 }
import { types as tt } from "../tokentype"; import { Parser } from "../state"; var pp = Parser.prototype; pp.flowParseTypeInitialiser = function (tok) { var oldInType = this.inType; this.inType = true; this.expect(tok || tt.colon); var type = this.flowParseType(); this.inType = oldInType; return type; }; pp.flowParseDeclareClass = function (node) { this.next(); this.flowParseInterfaceish(node, true); return this.finishNode(node, "DeclareClass"); }; pp.flowParseDeclareFunction = function (node) { this.next(); var id = node.id = this.parseIdent(); var typeNode = this.startNode(); var typeContainer = this.startNode(); if (this.isRelational("<")) { typeNode.typeParameters = this.flowParseTypeParameterDeclaration(); } else { typeNode.typeParameters = null; } this.expect(tt.parenL); var tmp = this.flowParseFunctionTypeParams(); typeNode.params = tmp.params; typeNode.rest = tmp.rest; this.expect(tt.parenR); typeNode.returnType = this.flowParseTypeInitialiser(); typeContainer.typeAnnotation = this.finishNode(typeNode, "FunctionTypeAnnotation"); id.typeAnnotation = this.finishNode(typeContainer, "TypeAnnotation"); this.finishNode(id, id.type); this.semicolon(); return this.finishNode(node, "DeclareFunction"); }; pp.flowParseDeclare = function (node) { if (this.type === tt._class) { return this.flowParseDeclareClass(node); } else if (this.type === tt._function) { return this.flowParseDeclareFunction(node); } else if (this.type === tt._var) { return this.flowParseDeclareVariable(node); } else if (this.isContextual("module")) { return this.flowParseDeclareModule(node); } else { this.unexpected(); } }; pp.flowParseDeclareVariable = function (node) { this.next(); node.id = this.flowParseTypeAnnotatableIdentifier(); this.semicolon(); return this.finishNode(node, "DeclareVariable"); }; pp.flowParseDeclareModule = function (node) { this.next(); if (this.type === tt.string) { node.id = this.parseExprAtom(); } else { node.id = this.parseIdent(); } var bodyNode = node.body = this.startNode(); var body = bodyNode.body = []; this.expect(tt.braceL); while (this.type !== tt.braceR) { var node2 = this.startNode(); // todo: declare check this.next(); body.push(this.flowParseDeclare(node2)); } this.expect(tt.braceR); this.finishNode(bodyNode, "BlockStatement"); return this.finishNode(node, "DeclareModule"); }; // Interfaces pp.flowParseInterfaceish = function (node, allowStatic) { node.id = this.parseIdent(); if (this.isRelational("<")) { node.typeParameters = this.flowParseTypeParameterDeclaration(); } else { node.typeParameters = null; } node.extends = []; if (this.eat(tt._extends)) { do { node.extends.push(this.flowParseInterfaceExtends()); } while(this.eat(tt.comma)); } node.body = this.flowParseObjectType(allowStatic); }; pp.flowParseInterfaceExtends = function () { var node = this.startNode(); node.id = this.parseIdent(); if (this.isRelational("<")) { node.typeParameters = this.flowParseTypeParameterInstantiation(); } else { node.typeParameters = null; } return this.finishNode(node, "InterfaceExtends"); }; pp.flowParseInterface = function (node) { this.flowParseInterfaceish(node, false); return this.finishNode(node, "InterfaceDeclaration"); }; // Type aliases pp.flowParseTypeAlias = function (node) { node.id = this.parseIdent(); if (this.isRelational("<")) { node.typeParameters = this.flowParseTypeParameterDeclaration(); } else { node.typeParameters = null; } node.right = this.flowParseTypeInitialiser(tt.eq); this.semicolon(); return this.finishNode(node, "TypeAlias"); }; // Type annotations pp.flowParseTypeParameterDeclaration = function () { var node = this.startNode(); node.params = []; this.expectRelational("<"); while (!this.isRelational(">")) { node.params.push(this.flowParseTypeAnnotatableIdentifier()); if (!this.isRelational(">")) { this.expect(tt.comma); } } this.expectRelational(">"); return this.finishNode(node, "TypeParameterDeclaration"); }; pp.flowParseTypeParameterInstantiation = function () { var node = this.startNode(), oldInType = this.inType; node.params = []; this.inType = true; this.expectRelational("<"); while (!this.isRelational(">")) { node.params.push(this.flowParseType()); if (!this.isRelational(">")) { this.expect(tt.comma); } } this.expectRelational(">"); this.inType = oldInType; return this.finishNode(node, "TypeParameterInstantiation"); }; pp.flowParseObjectPropertyKey = function () { return (this.type === tt.num || this.type === tt.string) ? this.parseExprAtom() : this.parseIdent(true); }; pp.flowParseObjectTypeIndexer = function (node, isStatic) { node.static = isStatic; this.expect(tt.bracketL); node.id = this.flowParseObjectPropertyKey(); node.key = this.flowParseTypeInitialiser(); this.expect(tt.bracketR); node.value = this.flowParseTypeInitialiser(); this.flowObjectTypeSemicolon(); return this.finishNode(node, "ObjectTypeIndexer"); }; pp.flowParseObjectTypeMethodish = function (node) { node.params = []; node.rest = null; node.typeParameters = null; if (this.isRelational("<")) { node.typeParameters = this.flowParseTypeParameterDeclaration(); } this.expect(tt.parenL); while (this.type === tt.name) { node.params.push(this.flowParseFunctionTypeParam()); if (this.type !== tt.parenR) { this.expect(tt.comma); } } if (this.eat(tt.ellipsis)) { node.rest = this.flowParseFunctionTypeParam(); } this.expect(tt.parenR); node.returnType = this.flowParseTypeInitialiser(); return this.finishNode(node, "FunctionTypeAnnotation"); }; pp.flowParseObjectTypeMethod = function (startPos, startLoc, isStatic, key) { var node = this.startNodeAt(startPos, startLoc); node.value = this.flowParseObjectTypeMethodish(this.startNodeAt(startPos, startLoc)); node.static = isStatic; node.key = key; node.optional = false; this.flowObjectTypeSemicolon(); return this.finishNode(node, "ObjectTypeProperty"); }; pp.flowParseObjectTypeCallProperty = function (node, isStatic) { var valueNode = this.startNode(); node.static = isStatic; node.value = this.flowParseObjectTypeMethodish(valueNode); this.flowObjectTypeSemicolon(); return this.finishNode(node, "ObjectTypeCallProperty"); }; pp.flowParseObjectType = function (allowStatic) { var nodeStart = this.startNode(); var node; var optional = false; var propertyKey; var isStatic; nodeStart.callProperties = []; nodeStart.properties = []; nodeStart.indexers = []; this.expect(tt.braceL); while (this.type !== tt.braceR) { var startPos = this.start, startLoc = this.startLoc; node = this.startNode(); if (allowStatic && this.isContextual("static")) { this.next(); isStatic = true; } if (this.type === tt.bracketL) { nodeStart.indexers.push(this.flowParseObjectTypeIndexer(node, isStatic)); } else if (this.type === tt.parenL || this.isRelational("<")) { nodeStart.callProperties.push(this.flowParseObjectTypeCallProperty(node, allowStatic)); } else { if (isStatic && this.type === tt.colon) { propertyKey = this.parseIdent(); } else { propertyKey = this.flowParseObjectPropertyKey(); } if (this.isRelational("<") || this.type === tt.parenL) { // This is a method property nodeStart.properties.push(this.flowParseObjectTypeMethod(startPos, startLoc, isStatic, propertyKey)); } else { if (this.eat(tt.question)) { optional = true; } node.key = propertyKey; node.value = this.flowParseTypeInitialiser(); node.optional = optional; node.static = isStatic; this.flowObjectTypeSemicolon(); nodeStart.properties.push(this.finishNode(node, "ObjectTypeProperty")); } } } this.expect(tt.braceR); return this.finishNode(nodeStart, "ObjectTypeAnnotation"); }; pp.flowObjectTypeSemicolon = function () { if (!this.eat(tt.semi) && !this.eat(tt.comma) && this.type !== tt.braceR) { this.unexpected(); } }; pp.flowParseGenericType = function (startPos, startLoc, id) { var node = this.startNodeAt(startPos, startLoc); node.typeParameters = null; node.id = id; while (this.eat(tt.dot)) { var node2 = this.startNodeAt(startPos, startLoc); node2.qualification = node.id; node2.id = this.parseIdent(); node.id = this.finishNode(node2, "QualifiedTypeIdentifier"); } if (this.isRelational("<")) { node.typeParameters = this.flowParseTypeParameterInstantiation(); } return this.finishNode(node, "GenericTypeAnnotation"); }; pp.flowParseTypeofType = function () { var node = this.startNode(); this.expect(tt._typeof); node.argument = this.flowParsePrimaryType(); return this.finishNode(node, "TypeofTypeAnnotation"); }; pp.flowParseTupleType = function () { var node = this.startNode(); node.types = []; this.expect(tt.bracketL); // We allow trailing commas while (this.pos < this.input.length && this.type !== tt.bracketR) { node.types.push(this.flowParseType()); if (this.type === tt.bracketR) break; this.expect(tt.comma); } this.expect(tt.bracketR); return this.finishNode(node, "TupleTypeAnnotation"); }; pp.flowParseFunctionTypeParam = function () { var optional = false; var node = this.startNode(); node.name = this.parseIdent(); if (this.eat(tt.question)) { optional = true; } node.optional = optional; node.typeAnnotation = this.flowParseTypeInitialiser(); return this.finishNode(node, "FunctionTypeParam"); }; pp.flowParseFunctionTypeParams = function () { var ret = { params: [], rest: null }; while (this.type === tt.name) { ret.params.push(this.flowParseFunctionTypeParam()); if (this.type !== tt.parenR) { this.expect(tt.comma); } } if (this.eat(tt.ellipsis)) { ret.rest = this.flowParseFunctionTypeParam(); } return ret; }; pp.flowIdentToTypeAnnotation = function (startPos, startLoc, node, id) { switch (id.name) { case "any": return this.finishNode(node, "AnyTypeAnnotation"); case "void": return this.finishNode(node, "VoidTypeAnnotation"); case "bool": case "boolean": return this.finishNode(node, "BooleanTypeAnnotation"); case "mixed": return this.finishNode(node, "MixedTypeAnnotation"); case "number": return this.finishNode(node, "NumberTypeAnnotation"); case "string": return this.finishNode(node, "StringTypeAnnotation"); default: return this.flowParseGenericType(startPos, startLoc, id); } }; // The parsing of types roughly parallels the parsing of expressions, and // primary types are kind of like primary expressions...they're the // primitives with which other types are constructed. pp.flowParsePrimaryType = function () { var startPos = this.start, startLoc = this.startLoc; var node = this.startNode(); var tmp; var type; var isGroupedType = false; switch (this.type) { case tt.name: return this.flowIdentToTypeAnnotation(startPos, startLoc, node, this.parseIdent()); case tt.braceL: return this.flowParseObjectType(); case tt.bracketL: return this.flowParseTupleType(); case tt.relational: if (this.value === "<") { node.typeParameters = this.flowParseTypeParameterDeclaration(); this.expect(tt.parenL); tmp = this.flowParseFunctionTypeParams(); node.params = tmp.params; node.rest = tmp.rest; this.expect(tt.parenR); this.expect(tt.arrow); node.returnType = this.flowParseType(); return this.finishNode(node, "FunctionTypeAnnotation"); } case tt.parenL: this.next(); // Check to see if this is actually a grouped type if (this.type !== tt.parenR && this.type !== tt.ellipsis) { if (this.type === tt.name) { var token = this.lookahead().type; isGroupedType = token !== tt.question && token !== tt.colon; } else { isGroupedType = true; } } if (isGroupedType) { type = this.flowParseType(); this.expect(tt.parenR); // If we see a => next then someone was probably confused about // function types, so we can provide a better error message if (this.eat(tt.arrow)) { this.raise(node, "Unexpected token =>. It looks like " + "you are trying to write a function type, but you ended up " + "writing a grouped type followed by an =>, which is a syntax " + "error. Remember, function type parameters are named so function " + "types look like (name1: type1, name2: type2) => returnType. You " + "probably wrote (type1) => returnType" ); } return type; } tmp = this.flowParseFunctionTypeParams(); node.params = tmp.params; node.rest = tmp.rest; this.expect(tt.parenR); this.expect(tt.arrow); node.returnType = this.flowParseType(); node.typeParameters = null; return this.finishNode(node, "FunctionTypeAnnotation"); case tt.string: node.value = this.value; node.raw = this.input.slice(this.start, this.end); this.next(); return this.finishNode(node, "StringLiteralTypeAnnotation"); case tt.num: node.value = this.value; node.raw = this.input.slice(this.start, this.end); this.next(); return this.finishNode(node, "NumberLiteralTypeAnnotation"); default: if (this.type.keyword === "typeof") { return this.flowParseTypeofType(); } } this.unexpected(); }; pp.flowParsePostfixType = function () { var node = this.startNode(); var type = node.elementType = this.flowParsePrimaryType(); if (this.type === tt.bracketL) { this.expect(tt.bracketL); this.expect(tt.bracketR); return this.finishNode(node, "ArrayTypeAnnotation"); } else { return type; } }; pp.flowParsePrefixType = function () { var node = this.startNode(); if (this.eat(tt.question)) { node.typeAnnotation = this.flowParsePrefixType(); return this.finishNode(node, "NullableTypeAnnotation"); } else { return this.flowParsePostfixType(); } }; pp.flowParseIntersectionType = function () { var node = this.startNode(); var type = this.flowParsePrefixType(); node.types = [type]; while (this.eat(tt.bitwiseAND)) { node.types.push(this.flowParsePrefixType()); } return node.types.length === 1 ? type : this.finishNode(node, "IntersectionTypeAnnotation"); }; pp.flowParseUnionType = function () { var node = this.startNode(); var type = this.flowParseIntersectionType(); node.types = [type]; while (this.eat(tt.bitwiseOR)) { node.types.push(this.flowParseIntersectionType()); } return node.types.length === 1 ? type : this.finishNode(node, "UnionTypeAnnotation"); }; pp.flowParseType = function () { var oldInType = this.inType; this.inType = true; var type = this.flowParseUnionType(); this.inType = oldInType; return type; }; pp.flowParseTypeAnnotation = function () { var node = this.startNode(); node.typeAnnotation = this.flowParseTypeInitialiser(); return this.finishNode(node, "TypeAnnotation"); }; pp.flowParseTypeAnnotatableIdentifier = function (requireTypeAnnotation, canBeOptionalParam) { var ident = this.parseIdent(); var isOptionalParam = false; if (canBeOptionalParam && this.eat(tt.question)) { this.expect(tt.question); isOptionalParam = true; } if (requireTypeAnnotation || this.type === tt.colon) { ident.typeAnnotation = this.flowParseTypeAnnotation(); this.finishNode(ident, ident.type); } if (isOptionalParam) { ident.optional = true; this.finishNode(ident, ident.type); } return ident; }; export default function (instance) { // function name(): string {} instance.extend("parseFunctionBody", function (inner) { return function (node, allowExpression) { if (this.type === tt.colon && !allowExpression) { // if allowExpression is true then we're parsing an arrow function and if // there's a return type then it's been handled elsewhere node.returnType = this.flowParseTypeAnnotation(); } return inner.call(this, node, allowExpression); }; }); instance.extend("parseStatement", function (inner) { return function (declaration, topLevel) { // strict mode handling of `interface` since it's a reserved word if (this.strict && this.type === tt.name && this.value === "interface") { var node = this.startNode(); this.next(); return this.flowParseInterface(node); } else { return inner.call(this, declaration, topLevel); } }; }); instance.extend("parseExpressionStatement", function (inner) { return function (node, expr) { if (expr.type === "Identifier") { if (expr.name === "declare") { if (this.type === tt._class || this.type === tt.name || this.type === tt._function || this.type === tt._var) { return this.flowParseDeclare(node); } } else if (this.type === tt.name) { if (expr.name === "interface") { return this.flowParseInterface(node); } else if (expr.name === "type") { return this.flowParseTypeAlias(node); } } } return inner.call(this, node, expr); }; }); instance.extend("shouldParseExportDeclaration", function (inner) { return function () { return this.isContextual("type") || inner.call(this); }; }); instance.extend("parseParenItem", function () { return function (node, startLoc, startPos, forceArrow?) { if (this.type === tt.colon) { var typeCastNode = this.startNodeAt(startLoc, startPos); typeCastNode.expression = node; typeCastNode.typeAnnotation = this.flowParseTypeAnnotation(); if (forceArrow && this.type !== tt.arrow) { this.unexpected(); } if (this.eat(tt.arrow)) { // ((lol): number => {}); var func = this.parseArrowExpression(this.startNodeAt(startLoc, startPos), [node]); func.returnType = typeCastNode.typeAnnotation; return func; } else { return this.finishNode(typeCastNode, "TypeCastExpression"); } } else { return node; } }; }); instance.extend("parseClassId", function (inner) { return function (node, isStatement) { inner.call(this, node, isStatement); if (this.isRelational("<")) { node.typeParameters = this.flowParseTypeParameterDeclaration(); } }; }); // don't consider `void` to be a keyword as then it'll use the void token type // and set startExpr instance.extend("isKeyword", function (inner) { return function (name) { if (this.inType && name === "void") { return false; } else { return inner.call(this, name); } }; }); instance.extend("readToken", function (inner) { return function (code) { if (this.inType && (code === 62 || code === 60)) { return this.finishOp(tt.relational, 1); } else { return inner.call(this, code); } }; }); instance.extend("jsx_readToken", function (inner) { return function () { if (!this.inType) return inner.call(this); }; }); function typeCastToParameter(node) { node.expression.typeAnnotation = node.typeAnnotation; return node.expression; } instance.extend("toAssignableList", function (inner) { return function (exprList, isBinding) { for (var i = 0; i < exprList.length; i++) { var expr = exprList[i]; if (expr && expr.type === "TypeCastExpression") { exprList[i] = typeCastToParameter(expr); } } return inner.call(this, exprList, isBinding); }; }); instance.extend("toReferencedList", function () { return function (exprList) { for (var i = 0; i < exprList.length; i++) { var expr = exprList[i]; if (expr && expr._exprListItem && expr.type === "TypeCastExpression") { this.raise(expr.start, "Unexpected type cast"); } } return exprList; }; }); instance.extend("parseExprListItem", function (inner) { return function (allowEmpty, refShorthandDefaultPos) { var container = this.startNode(); var node = inner.call(this, allowEmpty, refShorthandDefaultPos); if (this.type === tt.colon) { container._exprListItem = true; container.expression = node; container.typeAnnotation = this.flowParseTypeAnnotation(); return this.finishNode(container, "TypeCastExpression"); } else { return node; } }; }); instance.extend("parseClassProperty", function (inner) { return function (node) { if (this.type === tt.colon) { node.typeAnnotation = this.flowParseTypeAnnotation(); } return inner.call(this, node); }; }); instance.extend("isClassProperty", function (inner) { return function () { return this.type === tt.colon || inner.call(this); }; }); instance.extend("parseClassMethod", function () { return function (classBody, method, isGenerator, isAsync) { var typeParameters; if (this.isRelational("<")) { typeParameters = this.flowParseTypeParameterDeclaration(); } method.value = this.parseMethod(isGenerator, isAsync); method.value.typeParameters = typeParameters; classBody.body.push(this.finishNode(method, "MethodDefinition")); }; }); instance.extend("parseClassSuper", function (inner) { return function (node, isStatement) { inner.call(this, node, isStatement); if (node.superClass && this.isRelational("<")) { node.superTypeParameters = this.flowParseTypeParameterInstantiation(); } if (this.isContextual("implements")) { this.next(); var implemented = node.implements = []; do { let node = this.startNode(); node.id = this.parseIdent(); if (this.isRelational("<")) { node.typeParameters = this.flowParseTypeParameterInstantiation(); } else { node.typeParameters = null; } implemented.push(this.finishNode(node, "ClassImplements")); } while(this.eat(tt.comma)) } }; }); instance.extend("parseObjPropValue", function (inner) { return function (prop) { var typeParameters; if (this.isRelational("<")) { typeParameters = this.flowParseTypeParameterDeclaration(); if (this.type !== tt.parenL) this.unexpected(); } inner.apply(this, arguments); prop.value.typeParameters = typeParameters; }; }); instance.extend("parseAssignableListItemTypes", function () { return function (param) { if (this.eat(tt.question)) { param.optional = true; } if (this.type === tt.colon) { param.typeAnnotation = this.flowParseTypeAnnotation(); } this.finishNode(param, param.type); return param; }; }); instance.extend("parseImportSpecifiers", function (inner) { return function (node) { node.importKind = "value"; var kind = (this.type === tt._typeof ? "typeof" : (this.isContextual("type") ? "type" : null)); if (kind) { var lh = this.lookahead(); if ((lh.type === tt.name && lh.value !== "from") || lh.type === tt.braceL || lh.type === tt.star) { this.next(); node.importKind = kind; } } inner.call(this, node); }; }); // function foo<T>() {} instance.extend("parseFunctionParams", function (inner) { return function (node) { if (this.isRelational("<")) { node.typeParameters = this.flowParseTypeParameterDeclaration(); } inner.call(this, node); }; }); // var foo: string = bar instance.extend("parseVarHead", function (inner) { return function (decl) { inner.call(this, decl); if (this.type === tt.colon) { decl.id.typeAnnotation = this.flowParseTypeAnnotation(); this.finishNode(decl.id, decl.id.type); } }; }); // var foo = (async (): number => {}); instance.extend("parseAsyncArrowFromCallExpression", function (inner) { return function (node, call) { if (this.type === tt.colon) { node.returnType = this.flowParseTypeAnnotation(); } return inner.call(this, node, call); }; }); instance.extend("parseParenAndDistinguishExpression", function (inner) { return function (startPos, startLoc, canBeArrow, isAsync) { startPos = startPos || this.start; startLoc = startLoc || this.startLoc; if (this.lookahead().type === tt.parenR) { // var foo = (): number => {}; this.expect(tt.parenL); this.expect(tt.parenR); let node = this.startNodeAt(startPos, startLoc); if (this.type === tt.colon) node.returnType = this.flowParseTypeAnnotation(); this.expect(tt.arrow); return this.parseArrowExpression(node, [], isAsync); } else { // var foo = (foo): number => {}; let node = inner.call(this, startPos, startLoc, canBeArrow, isAsync); var state = this.getState(); if (this.type === tt.colon) { try { return this.parseParenItem(node, startPos, startLoc, true); } catch (err) { if (err instanceof SyntaxError) { this.setState(state); return node; } else { throw err; } } } else { return node; } } }; }); }
packages/babylon/src/plugins/flow.js
1
https://github.com/babel/babel/commit/30be1317e6b3d83e7a22328ca4baf37b218470da
[ 0.00022207583242561668, 0.00017105085134971887, 0.0001644602743908763, 0.0001704856549622491, 0.0000059919580053247046 ]
{ "id": 0, "code_window": [ "var a: 123;\n", "var a: 123.0;\n", "var a: 0x7B;\n", "var a: 123;\n", "var a: 123;\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace" ], "after_edit": [ "var a: 0b1111011;\n", "var a: 0o173;" ], "file_path": "packages/babel/test/fixtures/generation/flow/number-literal-types/expected.js", "type": "replace", "edit_start_line_idx": 3 }
function test() { // Leading if statement if (cond) {print("hello") } // Trailing if-block statement }
packages/babel/test/fixtures/generation/comments/if-line-comment/actual.js
0
https://github.com/babel/babel/commit/30be1317e6b3d83e7a22328ca4baf37b218470da
[ 0.0001716407568892464, 0.0001716407568892464, 0.0001716407568892464, 0.0001716407568892464, 0 ]
{ "id": 0, "code_window": [ "var a: 123;\n", "var a: 123.0;\n", "var a: 0x7B;\n", "var a: 123;\n", "var a: 123;\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace" ], "after_edit": [ "var a: 0b1111011;\n", "var a: 0o173;" ], "file_path": "packages/babel/test/fixtures/generation/flow/number-literal-types/expected.js", "type": "replace", "edit_start_line_idx": 3 }
var Whateva = React.createClass({ displayName: "Whatever", render: function render() { return null; } }); var Bar = React.createClass({ "displayName": "Ba", render: function render() { return null; } });
packages/babel/test/fixtures/transformation/react/display-name-if-missing/actual.js
0
https://github.com/babel/babel/commit/30be1317e6b3d83e7a22328ca4baf37b218470da
[ 0.00017309511895291507, 0.00017235992709174752, 0.00017162472067866474, 0.00017235992709174752, 7.351991371251643e-7 ]
{ "id": 0, "code_window": [ "var a: 123;\n", "var a: 123.0;\n", "var a: 0x7B;\n", "var a: 123;\n", "var a: 123;\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace" ], "after_edit": [ "var a: 0b1111011;\n", "var a: 0o173;" ], "file_path": "packages/babel/test/fixtures/generation/flow/number-literal-types/expected.js", "type": "replace", "edit_start_line_idx": 3 }
"use strict"; true; blah();
packages/babel/test/fixtures/transformation/minification.remove-console/expression-top-level/expected.js
0
https://github.com/babel/babel/commit/30be1317e6b3d83e7a22328ca4baf37b218470da
[ 0.00017455282795708627, 0.00017455282795708627, 0.00017455282795708627, 0.00017455282795708627, 0 ]
{ "id": 1, "code_window": [ " return this.finishNode(node, \"FunctionTypeAnnotation\");\n", "\n", " case tt.string:\n", " node.value = this.value;\n", " node.raw = this.input.slice(this.start, this.end);\n", " this.next();\n", " return this.finishNode(node, \"StringLiteralTypeAnnotation\");\n", "\n", " case tt.num:\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " node.rawValue = node.value = this.value;\n" ], "file_path": "packages/babylon/src/plugins/flow.js", "type": "replace", "edit_start_line_idx": 490 }
import { types as tt } from "../tokentype"; import { Parser } from "../state"; var pp = Parser.prototype; pp.flowParseTypeInitialiser = function (tok) { var oldInType = this.inType; this.inType = true; this.expect(tok || tt.colon); var type = this.flowParseType(); this.inType = oldInType; return type; }; pp.flowParseDeclareClass = function (node) { this.next(); this.flowParseInterfaceish(node, true); return this.finishNode(node, "DeclareClass"); }; pp.flowParseDeclareFunction = function (node) { this.next(); var id = node.id = this.parseIdent(); var typeNode = this.startNode(); var typeContainer = this.startNode(); if (this.isRelational("<")) { typeNode.typeParameters = this.flowParseTypeParameterDeclaration(); } else { typeNode.typeParameters = null; } this.expect(tt.parenL); var tmp = this.flowParseFunctionTypeParams(); typeNode.params = tmp.params; typeNode.rest = tmp.rest; this.expect(tt.parenR); typeNode.returnType = this.flowParseTypeInitialiser(); typeContainer.typeAnnotation = this.finishNode(typeNode, "FunctionTypeAnnotation"); id.typeAnnotation = this.finishNode(typeContainer, "TypeAnnotation"); this.finishNode(id, id.type); this.semicolon(); return this.finishNode(node, "DeclareFunction"); }; pp.flowParseDeclare = function (node) { if (this.type === tt._class) { return this.flowParseDeclareClass(node); } else if (this.type === tt._function) { return this.flowParseDeclareFunction(node); } else if (this.type === tt._var) { return this.flowParseDeclareVariable(node); } else if (this.isContextual("module")) { return this.flowParseDeclareModule(node); } else { this.unexpected(); } }; pp.flowParseDeclareVariable = function (node) { this.next(); node.id = this.flowParseTypeAnnotatableIdentifier(); this.semicolon(); return this.finishNode(node, "DeclareVariable"); }; pp.flowParseDeclareModule = function (node) { this.next(); if (this.type === tt.string) { node.id = this.parseExprAtom(); } else { node.id = this.parseIdent(); } var bodyNode = node.body = this.startNode(); var body = bodyNode.body = []; this.expect(tt.braceL); while (this.type !== tt.braceR) { var node2 = this.startNode(); // todo: declare check this.next(); body.push(this.flowParseDeclare(node2)); } this.expect(tt.braceR); this.finishNode(bodyNode, "BlockStatement"); return this.finishNode(node, "DeclareModule"); }; // Interfaces pp.flowParseInterfaceish = function (node, allowStatic) { node.id = this.parseIdent(); if (this.isRelational("<")) { node.typeParameters = this.flowParseTypeParameterDeclaration(); } else { node.typeParameters = null; } node.extends = []; if (this.eat(tt._extends)) { do { node.extends.push(this.flowParseInterfaceExtends()); } while(this.eat(tt.comma)); } node.body = this.flowParseObjectType(allowStatic); }; pp.flowParseInterfaceExtends = function () { var node = this.startNode(); node.id = this.parseIdent(); if (this.isRelational("<")) { node.typeParameters = this.flowParseTypeParameterInstantiation(); } else { node.typeParameters = null; } return this.finishNode(node, "InterfaceExtends"); }; pp.flowParseInterface = function (node) { this.flowParseInterfaceish(node, false); return this.finishNode(node, "InterfaceDeclaration"); }; // Type aliases pp.flowParseTypeAlias = function (node) { node.id = this.parseIdent(); if (this.isRelational("<")) { node.typeParameters = this.flowParseTypeParameterDeclaration(); } else { node.typeParameters = null; } node.right = this.flowParseTypeInitialiser(tt.eq); this.semicolon(); return this.finishNode(node, "TypeAlias"); }; // Type annotations pp.flowParseTypeParameterDeclaration = function () { var node = this.startNode(); node.params = []; this.expectRelational("<"); while (!this.isRelational(">")) { node.params.push(this.flowParseTypeAnnotatableIdentifier()); if (!this.isRelational(">")) { this.expect(tt.comma); } } this.expectRelational(">"); return this.finishNode(node, "TypeParameterDeclaration"); }; pp.flowParseTypeParameterInstantiation = function () { var node = this.startNode(), oldInType = this.inType; node.params = []; this.inType = true; this.expectRelational("<"); while (!this.isRelational(">")) { node.params.push(this.flowParseType()); if (!this.isRelational(">")) { this.expect(tt.comma); } } this.expectRelational(">"); this.inType = oldInType; return this.finishNode(node, "TypeParameterInstantiation"); }; pp.flowParseObjectPropertyKey = function () { return (this.type === tt.num || this.type === tt.string) ? this.parseExprAtom() : this.parseIdent(true); }; pp.flowParseObjectTypeIndexer = function (node, isStatic) { node.static = isStatic; this.expect(tt.bracketL); node.id = this.flowParseObjectPropertyKey(); node.key = this.flowParseTypeInitialiser(); this.expect(tt.bracketR); node.value = this.flowParseTypeInitialiser(); this.flowObjectTypeSemicolon(); return this.finishNode(node, "ObjectTypeIndexer"); }; pp.flowParseObjectTypeMethodish = function (node) { node.params = []; node.rest = null; node.typeParameters = null; if (this.isRelational("<")) { node.typeParameters = this.flowParseTypeParameterDeclaration(); } this.expect(tt.parenL); while (this.type === tt.name) { node.params.push(this.flowParseFunctionTypeParam()); if (this.type !== tt.parenR) { this.expect(tt.comma); } } if (this.eat(tt.ellipsis)) { node.rest = this.flowParseFunctionTypeParam(); } this.expect(tt.parenR); node.returnType = this.flowParseTypeInitialiser(); return this.finishNode(node, "FunctionTypeAnnotation"); }; pp.flowParseObjectTypeMethod = function (startPos, startLoc, isStatic, key) { var node = this.startNodeAt(startPos, startLoc); node.value = this.flowParseObjectTypeMethodish(this.startNodeAt(startPos, startLoc)); node.static = isStatic; node.key = key; node.optional = false; this.flowObjectTypeSemicolon(); return this.finishNode(node, "ObjectTypeProperty"); }; pp.flowParseObjectTypeCallProperty = function (node, isStatic) { var valueNode = this.startNode(); node.static = isStatic; node.value = this.flowParseObjectTypeMethodish(valueNode); this.flowObjectTypeSemicolon(); return this.finishNode(node, "ObjectTypeCallProperty"); }; pp.flowParseObjectType = function (allowStatic) { var nodeStart = this.startNode(); var node; var optional = false; var propertyKey; var isStatic; nodeStart.callProperties = []; nodeStart.properties = []; nodeStart.indexers = []; this.expect(tt.braceL); while (this.type !== tt.braceR) { var startPos = this.start, startLoc = this.startLoc; node = this.startNode(); if (allowStatic && this.isContextual("static")) { this.next(); isStatic = true; } if (this.type === tt.bracketL) { nodeStart.indexers.push(this.flowParseObjectTypeIndexer(node, isStatic)); } else if (this.type === tt.parenL || this.isRelational("<")) { nodeStart.callProperties.push(this.flowParseObjectTypeCallProperty(node, allowStatic)); } else { if (isStatic && this.type === tt.colon) { propertyKey = this.parseIdent(); } else { propertyKey = this.flowParseObjectPropertyKey(); } if (this.isRelational("<") || this.type === tt.parenL) { // This is a method property nodeStart.properties.push(this.flowParseObjectTypeMethod(startPos, startLoc, isStatic, propertyKey)); } else { if (this.eat(tt.question)) { optional = true; } node.key = propertyKey; node.value = this.flowParseTypeInitialiser(); node.optional = optional; node.static = isStatic; this.flowObjectTypeSemicolon(); nodeStart.properties.push(this.finishNode(node, "ObjectTypeProperty")); } } } this.expect(tt.braceR); return this.finishNode(nodeStart, "ObjectTypeAnnotation"); }; pp.flowObjectTypeSemicolon = function () { if (!this.eat(tt.semi) && !this.eat(tt.comma) && this.type !== tt.braceR) { this.unexpected(); } }; pp.flowParseGenericType = function (startPos, startLoc, id) { var node = this.startNodeAt(startPos, startLoc); node.typeParameters = null; node.id = id; while (this.eat(tt.dot)) { var node2 = this.startNodeAt(startPos, startLoc); node2.qualification = node.id; node2.id = this.parseIdent(); node.id = this.finishNode(node2, "QualifiedTypeIdentifier"); } if (this.isRelational("<")) { node.typeParameters = this.flowParseTypeParameterInstantiation(); } return this.finishNode(node, "GenericTypeAnnotation"); }; pp.flowParseTypeofType = function () { var node = this.startNode(); this.expect(tt._typeof); node.argument = this.flowParsePrimaryType(); return this.finishNode(node, "TypeofTypeAnnotation"); }; pp.flowParseTupleType = function () { var node = this.startNode(); node.types = []; this.expect(tt.bracketL); // We allow trailing commas while (this.pos < this.input.length && this.type !== tt.bracketR) { node.types.push(this.flowParseType()); if (this.type === tt.bracketR) break; this.expect(tt.comma); } this.expect(tt.bracketR); return this.finishNode(node, "TupleTypeAnnotation"); }; pp.flowParseFunctionTypeParam = function () { var optional = false; var node = this.startNode(); node.name = this.parseIdent(); if (this.eat(tt.question)) { optional = true; } node.optional = optional; node.typeAnnotation = this.flowParseTypeInitialiser(); return this.finishNode(node, "FunctionTypeParam"); }; pp.flowParseFunctionTypeParams = function () { var ret = { params: [], rest: null }; while (this.type === tt.name) { ret.params.push(this.flowParseFunctionTypeParam()); if (this.type !== tt.parenR) { this.expect(tt.comma); } } if (this.eat(tt.ellipsis)) { ret.rest = this.flowParseFunctionTypeParam(); } return ret; }; pp.flowIdentToTypeAnnotation = function (startPos, startLoc, node, id) { switch (id.name) { case "any": return this.finishNode(node, "AnyTypeAnnotation"); case "void": return this.finishNode(node, "VoidTypeAnnotation"); case "bool": case "boolean": return this.finishNode(node, "BooleanTypeAnnotation"); case "mixed": return this.finishNode(node, "MixedTypeAnnotation"); case "number": return this.finishNode(node, "NumberTypeAnnotation"); case "string": return this.finishNode(node, "StringTypeAnnotation"); default: return this.flowParseGenericType(startPos, startLoc, id); } }; // The parsing of types roughly parallels the parsing of expressions, and // primary types are kind of like primary expressions...they're the // primitives with which other types are constructed. pp.flowParsePrimaryType = function () { var startPos = this.start, startLoc = this.startLoc; var node = this.startNode(); var tmp; var type; var isGroupedType = false; switch (this.type) { case tt.name: return this.flowIdentToTypeAnnotation(startPos, startLoc, node, this.parseIdent()); case tt.braceL: return this.flowParseObjectType(); case tt.bracketL: return this.flowParseTupleType(); case tt.relational: if (this.value === "<") { node.typeParameters = this.flowParseTypeParameterDeclaration(); this.expect(tt.parenL); tmp = this.flowParseFunctionTypeParams(); node.params = tmp.params; node.rest = tmp.rest; this.expect(tt.parenR); this.expect(tt.arrow); node.returnType = this.flowParseType(); return this.finishNode(node, "FunctionTypeAnnotation"); } case tt.parenL: this.next(); // Check to see if this is actually a grouped type if (this.type !== tt.parenR && this.type !== tt.ellipsis) { if (this.type === tt.name) { var token = this.lookahead().type; isGroupedType = token !== tt.question && token !== tt.colon; } else { isGroupedType = true; } } if (isGroupedType) { type = this.flowParseType(); this.expect(tt.parenR); // If we see a => next then someone was probably confused about // function types, so we can provide a better error message if (this.eat(tt.arrow)) { this.raise(node, "Unexpected token =>. It looks like " + "you are trying to write a function type, but you ended up " + "writing a grouped type followed by an =>, which is a syntax " + "error. Remember, function type parameters are named so function " + "types look like (name1: type1, name2: type2) => returnType. You " + "probably wrote (type1) => returnType" ); } return type; } tmp = this.flowParseFunctionTypeParams(); node.params = tmp.params; node.rest = tmp.rest; this.expect(tt.parenR); this.expect(tt.arrow); node.returnType = this.flowParseType(); node.typeParameters = null; return this.finishNode(node, "FunctionTypeAnnotation"); case tt.string: node.value = this.value; node.raw = this.input.slice(this.start, this.end); this.next(); return this.finishNode(node, "StringLiteralTypeAnnotation"); case tt.num: node.value = this.value; node.raw = this.input.slice(this.start, this.end); this.next(); return this.finishNode(node, "NumberLiteralTypeAnnotation"); default: if (this.type.keyword === "typeof") { return this.flowParseTypeofType(); } } this.unexpected(); }; pp.flowParsePostfixType = function () { var node = this.startNode(); var type = node.elementType = this.flowParsePrimaryType(); if (this.type === tt.bracketL) { this.expect(tt.bracketL); this.expect(tt.bracketR); return this.finishNode(node, "ArrayTypeAnnotation"); } else { return type; } }; pp.flowParsePrefixType = function () { var node = this.startNode(); if (this.eat(tt.question)) { node.typeAnnotation = this.flowParsePrefixType(); return this.finishNode(node, "NullableTypeAnnotation"); } else { return this.flowParsePostfixType(); } }; pp.flowParseIntersectionType = function () { var node = this.startNode(); var type = this.flowParsePrefixType(); node.types = [type]; while (this.eat(tt.bitwiseAND)) { node.types.push(this.flowParsePrefixType()); } return node.types.length === 1 ? type : this.finishNode(node, "IntersectionTypeAnnotation"); }; pp.flowParseUnionType = function () { var node = this.startNode(); var type = this.flowParseIntersectionType(); node.types = [type]; while (this.eat(tt.bitwiseOR)) { node.types.push(this.flowParseIntersectionType()); } return node.types.length === 1 ? type : this.finishNode(node, "UnionTypeAnnotation"); }; pp.flowParseType = function () { var oldInType = this.inType; this.inType = true; var type = this.flowParseUnionType(); this.inType = oldInType; return type; }; pp.flowParseTypeAnnotation = function () { var node = this.startNode(); node.typeAnnotation = this.flowParseTypeInitialiser(); return this.finishNode(node, "TypeAnnotation"); }; pp.flowParseTypeAnnotatableIdentifier = function (requireTypeAnnotation, canBeOptionalParam) { var ident = this.parseIdent(); var isOptionalParam = false; if (canBeOptionalParam && this.eat(tt.question)) { this.expect(tt.question); isOptionalParam = true; } if (requireTypeAnnotation || this.type === tt.colon) { ident.typeAnnotation = this.flowParseTypeAnnotation(); this.finishNode(ident, ident.type); } if (isOptionalParam) { ident.optional = true; this.finishNode(ident, ident.type); } return ident; }; export default function (instance) { // function name(): string {} instance.extend("parseFunctionBody", function (inner) { return function (node, allowExpression) { if (this.type === tt.colon && !allowExpression) { // if allowExpression is true then we're parsing an arrow function and if // there's a return type then it's been handled elsewhere node.returnType = this.flowParseTypeAnnotation(); } return inner.call(this, node, allowExpression); }; }); instance.extend("parseStatement", function (inner) { return function (declaration, topLevel) { // strict mode handling of `interface` since it's a reserved word if (this.strict && this.type === tt.name && this.value === "interface") { var node = this.startNode(); this.next(); return this.flowParseInterface(node); } else { return inner.call(this, declaration, topLevel); } }; }); instance.extend("parseExpressionStatement", function (inner) { return function (node, expr) { if (expr.type === "Identifier") { if (expr.name === "declare") { if (this.type === tt._class || this.type === tt.name || this.type === tt._function || this.type === tt._var) { return this.flowParseDeclare(node); } } else if (this.type === tt.name) { if (expr.name === "interface") { return this.flowParseInterface(node); } else if (expr.name === "type") { return this.flowParseTypeAlias(node); } } } return inner.call(this, node, expr); }; }); instance.extend("shouldParseExportDeclaration", function (inner) { return function () { return this.isContextual("type") || inner.call(this); }; }); instance.extend("parseParenItem", function () { return function (node, startLoc, startPos, forceArrow?) { if (this.type === tt.colon) { var typeCastNode = this.startNodeAt(startLoc, startPos); typeCastNode.expression = node; typeCastNode.typeAnnotation = this.flowParseTypeAnnotation(); if (forceArrow && this.type !== tt.arrow) { this.unexpected(); } if (this.eat(tt.arrow)) { // ((lol): number => {}); var func = this.parseArrowExpression(this.startNodeAt(startLoc, startPos), [node]); func.returnType = typeCastNode.typeAnnotation; return func; } else { return this.finishNode(typeCastNode, "TypeCastExpression"); } } else { return node; } }; }); instance.extend("parseClassId", function (inner) { return function (node, isStatement) { inner.call(this, node, isStatement); if (this.isRelational("<")) { node.typeParameters = this.flowParseTypeParameterDeclaration(); } }; }); // don't consider `void` to be a keyword as then it'll use the void token type // and set startExpr instance.extend("isKeyword", function (inner) { return function (name) { if (this.inType && name === "void") { return false; } else { return inner.call(this, name); } }; }); instance.extend("readToken", function (inner) { return function (code) { if (this.inType && (code === 62 || code === 60)) { return this.finishOp(tt.relational, 1); } else { return inner.call(this, code); } }; }); instance.extend("jsx_readToken", function (inner) { return function () { if (!this.inType) return inner.call(this); }; }); function typeCastToParameter(node) { node.expression.typeAnnotation = node.typeAnnotation; return node.expression; } instance.extend("toAssignableList", function (inner) { return function (exprList, isBinding) { for (var i = 0; i < exprList.length; i++) { var expr = exprList[i]; if (expr && expr.type === "TypeCastExpression") { exprList[i] = typeCastToParameter(expr); } } return inner.call(this, exprList, isBinding); }; }); instance.extend("toReferencedList", function () { return function (exprList) { for (var i = 0; i < exprList.length; i++) { var expr = exprList[i]; if (expr && expr._exprListItem && expr.type === "TypeCastExpression") { this.raise(expr.start, "Unexpected type cast"); } } return exprList; }; }); instance.extend("parseExprListItem", function (inner) { return function (allowEmpty, refShorthandDefaultPos) { var container = this.startNode(); var node = inner.call(this, allowEmpty, refShorthandDefaultPos); if (this.type === tt.colon) { container._exprListItem = true; container.expression = node; container.typeAnnotation = this.flowParseTypeAnnotation(); return this.finishNode(container, "TypeCastExpression"); } else { return node; } }; }); instance.extend("parseClassProperty", function (inner) { return function (node) { if (this.type === tt.colon) { node.typeAnnotation = this.flowParseTypeAnnotation(); } return inner.call(this, node); }; }); instance.extend("isClassProperty", function (inner) { return function () { return this.type === tt.colon || inner.call(this); }; }); instance.extend("parseClassMethod", function () { return function (classBody, method, isGenerator, isAsync) { var typeParameters; if (this.isRelational("<")) { typeParameters = this.flowParseTypeParameterDeclaration(); } method.value = this.parseMethod(isGenerator, isAsync); method.value.typeParameters = typeParameters; classBody.body.push(this.finishNode(method, "MethodDefinition")); }; }); instance.extend("parseClassSuper", function (inner) { return function (node, isStatement) { inner.call(this, node, isStatement); if (node.superClass && this.isRelational("<")) { node.superTypeParameters = this.flowParseTypeParameterInstantiation(); } if (this.isContextual("implements")) { this.next(); var implemented = node.implements = []; do { let node = this.startNode(); node.id = this.parseIdent(); if (this.isRelational("<")) { node.typeParameters = this.flowParseTypeParameterInstantiation(); } else { node.typeParameters = null; } implemented.push(this.finishNode(node, "ClassImplements")); } while(this.eat(tt.comma)) } }; }); instance.extend("parseObjPropValue", function (inner) { return function (prop) { var typeParameters; if (this.isRelational("<")) { typeParameters = this.flowParseTypeParameterDeclaration(); if (this.type !== tt.parenL) this.unexpected(); } inner.apply(this, arguments); prop.value.typeParameters = typeParameters; }; }); instance.extend("parseAssignableListItemTypes", function () { return function (param) { if (this.eat(tt.question)) { param.optional = true; } if (this.type === tt.colon) { param.typeAnnotation = this.flowParseTypeAnnotation(); } this.finishNode(param, param.type); return param; }; }); instance.extend("parseImportSpecifiers", function (inner) { return function (node) { node.importKind = "value"; var kind = (this.type === tt._typeof ? "typeof" : (this.isContextual("type") ? "type" : null)); if (kind) { var lh = this.lookahead(); if ((lh.type === tt.name && lh.value !== "from") || lh.type === tt.braceL || lh.type === tt.star) { this.next(); node.importKind = kind; } } inner.call(this, node); }; }); // function foo<T>() {} instance.extend("parseFunctionParams", function (inner) { return function (node) { if (this.isRelational("<")) { node.typeParameters = this.flowParseTypeParameterDeclaration(); } inner.call(this, node); }; }); // var foo: string = bar instance.extend("parseVarHead", function (inner) { return function (decl) { inner.call(this, decl); if (this.type === tt.colon) { decl.id.typeAnnotation = this.flowParseTypeAnnotation(); this.finishNode(decl.id, decl.id.type); } }; }); // var foo = (async (): number => {}); instance.extend("parseAsyncArrowFromCallExpression", function (inner) { return function (node, call) { if (this.type === tt.colon) { node.returnType = this.flowParseTypeAnnotation(); } return inner.call(this, node, call); }; }); instance.extend("parseParenAndDistinguishExpression", function (inner) { return function (startPos, startLoc, canBeArrow, isAsync) { startPos = startPos || this.start; startLoc = startLoc || this.startLoc; if (this.lookahead().type === tt.parenR) { // var foo = (): number => {}; this.expect(tt.parenL); this.expect(tt.parenR); let node = this.startNodeAt(startPos, startLoc); if (this.type === tt.colon) node.returnType = this.flowParseTypeAnnotation(); this.expect(tt.arrow); return this.parseArrowExpression(node, [], isAsync); } else { // var foo = (foo): number => {}; let node = inner.call(this, startPos, startLoc, canBeArrow, isAsync); var state = this.getState(); if (this.type === tt.colon) { try { return this.parseParenItem(node, startPos, startLoc, true); } catch (err) { if (err instanceof SyntaxError) { this.setState(state); return node; } else { throw err; } } } else { return node; } } }; }); }
packages/babylon/src/plugins/flow.js
1
https://github.com/babel/babel/commit/30be1317e6b3d83e7a22328ca4baf37b218470da
[ 0.9317079186439514, 0.012881782837212086, 0.00016461168706882745, 0.0006404421292245388, 0.0969892367720604 ]
{ "id": 1, "code_window": [ " return this.finishNode(node, \"FunctionTypeAnnotation\");\n", "\n", " case tt.string:\n", " node.value = this.value;\n", " node.raw = this.input.slice(this.start, this.end);\n", " this.next();\n", " return this.finishNode(node, \"StringLiteralTypeAnnotation\");\n", "\n", " case tt.num:\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " node.rawValue = node.value = this.value;\n" ], "file_path": "packages/babylon/src/plugins/flow.js", "type": "replace", "edit_start_line_idx": 490 }
class Foo extends Bar { bar = "foo"; constructor() { super(); } }
packages/babel/test/fixtures/transformation/es7.class-properties/super-statement/actual.js
0
https://github.com/babel/babel/commit/30be1317e6b3d83e7a22328ca4baf37b218470da
[ 0.00017056739307008684, 0.00017056739307008684, 0.00017056739307008684, 0.00017056739307008684, 0 ]
{ "id": 1, "code_window": [ " return this.finishNode(node, \"FunctionTypeAnnotation\");\n", "\n", " case tt.string:\n", " node.value = this.value;\n", " node.raw = this.input.slice(this.start, this.end);\n", " this.next();\n", " return this.finishNode(node, \"StringLiteralTypeAnnotation\");\n", "\n", " case tt.num:\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " node.rawValue = node.value = this.value;\n" ], "file_path": "packages/babylon/src/plugins/flow.js", "type": "replace", "edit_start_line_idx": 490 }
import detectIndent from "detect-indent"; import Whitespace from "./whitespace"; import NodePrinter from "./node/printer"; import repeating from "repeating"; import SourceMap from "./source-map"; import Position from "./position"; import * as messages from "../messages"; import Buffer from "./buffer"; import extend from "lodash/object/extend"; import each from "lodash/collection/each"; import n from "./node"; import * as t from "../types"; /** * Babel's code generator, turns an ast into code, maintaining sourcemaps, * user preferences, and valid output. */ class CodeGenerator { constructor(ast, opts, code) { opts = opts || {}; this.comments = ast.comments || []; this.tokens = ast.tokens || []; this.format = CodeGenerator.normalizeOptions(code, opts, this.tokens); this.opts = opts; this.ast = ast; this.whitespace = new Whitespace(this.tokens); this.position = new Position; this.map = new SourceMap(this.position, opts, code); this.buffer = new Buffer(this.position, this.format); } /** * Normalize generator options, setting defaults. * * - Detects code indentation. * - If `opts.compact = "auto"` and the code is over 100KB, `compact` will be set to `true`. */ static normalizeOptions(code, opts, tokens) { var style = " "; if (code) { var indent = detectIndent(code).indent; if (indent && indent !== " ") style = indent; } var format = { shouldPrintComment: opts.shouldPrintComment, retainLines: opts.retainLines, comments: opts.comments == null || opts.comments, compact: opts.compact, quotes: CodeGenerator.findCommonStringDelimiter(code, tokens), indent: { adjustMultilineComment: true, style: style, base: 0 } }; if (format.compact === "auto") { format.compact = code.length > 100000; // 100KB if (format.compact) { console.error("[BABEL] " + messages.get("codeGeneratorDeopt", opts.filename, "100KB")); } } if (format.compact) { format.indent.adjustMultilineComment = false; } return format; } /** * Determine if input code uses more single or double quotes. */ static findCommonStringDelimiter(code, tokens) { var occurences = { single: 0, double: 0 }; var checked = 0; for (var i = 0; i < tokens.length; i++) { var token = tokens[i]; if (token.type.label !== "string") continue; var raw = code.slice(token.start, token.end); if (raw[0] === "'") { occurences.single++; } else { occurences.double++; } checked++; if (checked >= 3) break; } if (occurences.single > occurences.double) { return "single"; } else { return "double"; } } /** * All node generators. */ static generators = { templateLiterals: require("./generators/template-literals"), comprehensions: require("./generators/comprehensions"), expressions: require("./generators/expressions"), statements: require("./generators/statements"), classes: require("./generators/classes"), methods: require("./generators/methods"), modules: require("./generators/modules"), types: require("./generators/types"), flow: require("./generators/flow"), base: require("./generators/base"), jsx: require("./generators/jsx") }; /** * Generate code and sourcemap from ast. * * Appends comments that weren't attached to any node to the end of the generated output. */ generate() { var ast = this.ast; this.print(ast); if (ast.comments) { var comments = []; for (var comment of (ast.comments: Array)) { if (!comment._displayed) comments.push(comment); } this._printComments(comments); } return { map: this.map.get(), code: this.buffer.get() }; } /** * Build NodePrinter. */ buildPrint(parent) { return new NodePrinter(this, parent); } /** * [Please add a description.] */ catchUp(node, parent, leftParenPrinted) { // catch up to this nodes newline if we're behind if (node.loc && this.format.retainLines && this.buffer.buf) { var needsParens = false; if (!leftParenPrinted && parent && this.position.line < node.loc.start.line && t.isTerminatorless(parent)) { needsParens = true; this._push("("); } while (this.position.line < node.loc.start.line) { this._push("\n"); } return needsParens; } return false; } /** * [Please add a description.] */ _printNewline(leading, node, parent, opts) { if (!opts.statement && !n.isUserWhitespacable(node, parent)) { return; } var lines = 0; if (node.start != null && !node._ignoreUserWhitespace) { // user node if (leading) { lines = this.whitespace.getNewlinesBefore(node); } else { lines = this.whitespace.getNewlinesAfter(node); } } else { // generated node if (!leading) lines++; // always include at least a single line after if (opts.addNewlines) lines += opts.addNewlines(leading, node) || 0; var needs = n.needsWhitespaceAfter; if (leading) needs = n.needsWhitespaceBefore; if (needs(node, parent)) lines++; // generated nodes can't add starting file whitespace if (!this.buffer.buf) lines = 0; } this.newline(lines); } /** * [Please add a description.] */ print(node, parent, opts = {}) { if (!node) return; if (parent && parent._compact) { node._compact = true; } var oldConcise = this.format.concise; if (node._compact) { this.format.concise = true; } if (this[node.type]) { var needsNoLineTermParens = n.needsParensNoLineTerminator(node, parent); var needsParens = needsNoLineTermParens || n.needsParens(node, parent); if (needsParens) this.push("("); if (needsNoLineTermParens) this.indent(); this.printLeadingComments(node, parent); var needsParensFromCatchup = this.catchUp(node, parent, needsParens); this._printNewline(true, node, parent, opts); if (opts.before) opts.before(); this.map.mark(node, "start"); this[node.type](node, this.buildPrint(node), parent); if (needsNoLineTermParens) { this.newline(); this.dedent(); } if (needsParens || needsParensFromCatchup) this.push(")"); this.map.mark(node, "end"); if (opts.after) opts.after(); this.format.concise = oldConcise; this._printNewline(false, node, parent, opts); this.printTrailingComments(node, parent); } else { throw new ReferenceError(`unknown node of type ${JSON.stringify(node.type)} with constructor ${JSON.stringify(node && node.constructor.name)}`); } } /** * [Please add a description.] */ printJoin(print, nodes, opts = {}) { if (!nodes || !nodes.length) return; var len = nodes.length; if (opts.indent) this.indent(); var printOpts = { statement: opts.statement, addNewlines: opts.addNewlines, after: () => { if (opts.iterator) { opts.iterator(node, i); } if (opts.separator && i < len - 1) { this.push(opts.separator); } } }; for (var i = 0; i < nodes.length; i++) { var node = nodes[i]; print.plain(node, printOpts); } if (opts.indent) this.dedent(); } /** * [Please add a description.] */ printAndIndentOnComments(print, node) { var indent = !!node.leadingComments; if (indent) this.indent(); print.plain(node); if (indent) this.dedent(); } /** * [Please add a description.] */ printBlock(print, node) { if (t.isEmptyStatement(node)) { this.semicolon(); } else { this.push(" "); print.plain(node); } } /** * [Please add a description.] */ generateComment(comment) { var val = comment.value; if (comment.type === "CommentLine") { val = `//${val}`; } else { val = `/*${val}*/`; } return val; } /** * [Please add a description.] */ printTrailingComments(node, parent) { this._printComments(this.getComments("trailingComments", node, parent)); } /** * [Please add a description.] */ printLeadingComments(node, parent) { this._printComments(this.getComments("leadingComments", node, parent)); } /** * [Please add a description.] */ getComments(key, node, parent) { if (t.isExpressionStatement(parent)) { return []; } var comments = []; var nodes = [node]; if (t.isExpressionStatement(node)) { nodes.push(node.argument); } for (let node of (nodes: Array)) { comments = comments.concat(this._getComments(key, node)); } return comments; } /** * [Please add a description.] */ _getComments(key, node) { return (node && node[key]) || []; } /** * [Please add a description.] */ shouldPrintComment(comment) { if (this.format.shouldPrintComment) { return this.format.shouldPrintComment(comment.value); } else { if (comment.value.indexOf("@license") >= 0 || comment.value.indexOf("@preserve") >= 0) { return true; } else { return this.format.comments; } } } /** * [Please add a description.] */ _printComments(comments) { if (!comments || !comments.length) return; for (var comment of (comments: Array)) { if (!this.shouldPrintComment(comment)) continue; if (comment._displayed) continue; comment._displayed = true; this.catchUp(comment); // whitespace before this.newline(this.whitespace.getNewlinesBefore(comment)); var column = this.position.column; var val = this.generateComment(comment); if (column && !this.isLast(["\n", " ", "[", "{"])) { this._push(" "); column++; } // if (comment.type === "CommentBlock" && this.format.indent.adjustMultilineComment) { var offset = comment.loc && comment.loc.start.column; if (offset) { var newlineRegex = new RegExp("\\n\\s{1," + offset + "}", "g"); val = val.replace(newlineRegex, "\n"); } var indent = Math.max(this.indentSize(), column); val = val.replace(/\n/g, `\n${repeating(" ", indent)}`); } if (column === 0) { val = this.getIndent() + val; } // force a newline for line comments when retainLines is set in case the next printed node // doesn't catch up if ((this.format.compact || this.format.retainLines) && comment.type === "CommentLine") { val += "\n"; } // this._push(val); // whitespace after this.newline(this.whitespace.getNewlinesAfter(comment)); } } } /** * [Please add a description.] */ each(Buffer.prototype, function (fn, key) { CodeGenerator.prototype[key] = function () { return fn.apply(this.buffer, arguments); }; }); /** * [Please add a description.] */ each(CodeGenerator.generators, function (generator) { extend(CodeGenerator.prototype, generator); }); /** * [Please add a description.] */ module.exports = function (ast, opts, code) { var gen = new CodeGenerator(ast, opts, code); return gen.generate(); }; module.exports.CodeGenerator = CodeGenerator;
packages/babel/src/generation/index.js
0
https://github.com/babel/babel/commit/30be1317e6b3d83e7a22328ca4baf37b218470da
[ 0.005251532886177301, 0.0003683444519992918, 0.00016422427142970264, 0.00017387507250532508, 0.0007493854500353336 ]
{ "id": 1, "code_window": [ " return this.finishNode(node, \"FunctionTypeAnnotation\");\n", "\n", " case tt.string:\n", " node.value = this.value;\n", " node.raw = this.input.slice(this.start, this.end);\n", " this.next();\n", " return this.finishNode(node, \"StringLiteralTypeAnnotation\");\n", "\n", " case tt.num:\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " node.rawValue = node.value = this.value;\n" ], "file_path": "packages/babylon/src/plugins/flow.js", "type": "replace", "edit_start_line_idx": 490 }
class Tripler { triple(n) { return n * 3; } } assert.equal(new Tripler().triple(2), 6);
packages/babel/test/fixtures/esnext/es6-classes/method-declaration-with-arguments.js
0
https://github.com/babel/babel/commit/30be1317e6b3d83e7a22328ca4baf37b218470da
[ 0.00017377114272676408, 0.00017377114272676408, 0.00017377114272676408, 0.00017377114272676408, 0 ]
{ "id": 2, "code_window": [ " return this.finishNode(node, \"StringLiteralTypeAnnotation\");\n", "\n", " case tt.num:\n", " node.value = this.value;\n", " node.raw = this.input.slice(this.start, this.end);\n", " this.next();\n", " return this.finishNode(node, \"NumberLiteralTypeAnnotation\");\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " node.rawValue = node.value = this.value;\n" ], "file_path": "packages/babylon/src/plugins/flow.js", "type": "replace", "edit_start_line_idx": 496 }
var a: 123; var a: 123.0; var a: 0x7B; var a: 123; var a: 123;
packages/babel/test/fixtures/generation/flow/number-literal-types/expected.js
1
https://github.com/babel/babel/commit/30be1317e6b3d83e7a22328ca4baf37b218470da
[ 0.0001738250139169395, 0.0001738250139169395, 0.0001738250139169395, 0.0001738250139169395, 0 ]
{ "id": 2, "code_window": [ " return this.finishNode(node, \"StringLiteralTypeAnnotation\");\n", "\n", " case tt.num:\n", " node.value = this.value;\n", " node.raw = this.input.slice(this.start, this.end);\n", " this.next();\n", " return this.finishNode(node, \"NumberLiteralTypeAnnotation\");\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " node.rawValue = node.value = this.value;\n" ], "file_path": "packages/babylon/src/plugins/flow.js", "type": "replace", "edit_start_line_idx": 496 }
function foo(x=5, y=6) { return [x, y]; } assert.deepEqual(foo(undefined, null), [5, null]);
packages/babel/test/fixtures/esnext/es6-default-parameters/null-vs-undefined.js
0
https://github.com/babel/babel/commit/30be1317e6b3d83e7a22328ca4baf37b218470da
[ 0.00017406583356205374, 0.00017406583356205374, 0.00017406583356205374, 0.00017406583356205374, 0 ]
{ "id": 2, "code_window": [ " return this.finishNode(node, \"StringLiteralTypeAnnotation\");\n", "\n", " case tt.num:\n", " node.value = this.value;\n", " node.raw = this.input.slice(this.start, this.end);\n", " this.next();\n", " return this.finishNode(node, \"NumberLiteralTypeAnnotation\");\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " node.rawValue = node.value = this.value;\n" ], "file_path": "packages/babylon/src/plugins/flow.js", "type": "replace", "edit_start_line_idx": 496 }
System.register([], function (_export) { "use strict"; var test, a, b, d; return { setters: [], execute: function () { test = 2; _export("test", test); _export("test", test = 5); _export("test", test += 1); (function () { var test = 2; test = 3; test++; })(); a = 2; _export("a", a); _export("a", a = 3); b = 2; _export("c", b); _export("c", b = 3); d = 3; _export("e", d); _export("f", d); _export("f", _export("e", d = 4)); } }; });
packages/babel/test/fixtures/transformation/es6.modules-system/remap/expected.js
0
https://github.com/babel/babel/commit/30be1317e6b3d83e7a22328ca4baf37b218470da
[ 0.00017629843205213547, 0.00017470688908360898, 0.00017384623060934246, 0.0001744937471812591, 8.567622558075527e-7 ]
{ "id": 2, "code_window": [ " return this.finishNode(node, \"StringLiteralTypeAnnotation\");\n", "\n", " case tt.num:\n", " node.value = this.value;\n", " node.raw = this.input.slice(this.start, this.end);\n", " this.next();\n", " return this.finishNode(node, \"NumberLiteralTypeAnnotation\");\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " node.rawValue = node.value = this.value;\n" ], "file_path": "packages/babylon/src/plugins/flow.js", "type": "replace", "edit_start_line_idx": 496 }
{ "optional": ["es6.spec.templateLiterals"] }
packages/babel/test/fixtures/transformation/es6.spec.template-literals/options.json
0
https://github.com/babel/babel/commit/30be1317e6b3d83e7a22328ca4baf37b218470da
[ 0.00017175666289404035, 0.00017175666289404035, 0.00017175666289404035, 0.00017175666289404035, 0 ]
{ "id": 0, "code_window": [ "\tm.Query = query\n", "\trExp, _ := regexp.Compile(sExpr)\n", "\tvar macroError error\n", "\n", "\tsql = replaceAllStringSubmatchFunc(rExp, sql, func(groups []string) string {\n", "\t\tres, err := m.evaluateMacro(groups[1], strings.Split(groups[2], \",\"))\n", "\t\tif err != nil && macroError == nil {\n", "\t\t\tmacroError = err\n", "\t\t\treturn \"macro_error()\"\n", "\t\t}\n", "\t\treturn res\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\targs := strings.Split(groups[2], \",\")\n", "\t\tfor i, arg := range args {\n", "\t\t\targs[i] = strings.Trim(arg, \" \")\n", "\t\t}\n", "\t\tres, err := m.evaluateMacro(groups[1], args)\n" ], "file_path": "pkg/tsdb/postgres/macros.go", "type": "replace", "edit_start_line_idx": 32 }
package postgres import ( "fmt" "regexp" "strconv" "strings" "time" "github.com/grafana/grafana/pkg/tsdb" ) //const rsString = `(?:"([^"]*)")`; const rsIdentifier = `([_a-zA-Z0-9]+)` const sExpr = `\$` + rsIdentifier + `\(([^\)]*)\)` type PostgresMacroEngine struct { TimeRange *tsdb.TimeRange Query *tsdb.Query } func NewPostgresMacroEngine() tsdb.SqlMacroEngine { return &PostgresMacroEngine{} } func (m *PostgresMacroEngine) Interpolate(query *tsdb.Query, timeRange *tsdb.TimeRange, sql string) (string, error) { m.TimeRange = timeRange m.Query = query rExp, _ := regexp.Compile(sExpr) var macroError error sql = replaceAllStringSubmatchFunc(rExp, sql, func(groups []string) string { res, err := m.evaluateMacro(groups[1], strings.Split(groups[2], ",")) if err != nil && macroError == nil { macroError = err return "macro_error()" } return res }) if macroError != nil { return "", macroError } return sql, nil } func replaceAllStringSubmatchFunc(re *regexp.Regexp, str string, repl func([]string) string) string { result := "" lastIndex := 0 for _, v := range re.FindAllSubmatchIndex([]byte(str), -1) { groups := []string{} for i := 0; i < len(v); i += 2 { groups = append(groups, str[v[i]:v[i+1]]) } result += str[lastIndex:v[0]] + repl(groups) lastIndex = v[1] } return result + str[lastIndex:] } func (m *PostgresMacroEngine) evaluateMacro(name string, args []string) (string, error) { switch name { case "__time": if len(args) == 0 { return "", fmt.Errorf("missing time column argument for macro %v", name) } return fmt.Sprintf("%s AS \"time\"", args[0]), nil case "__timeEpoch": if len(args) == 0 { return "", fmt.Errorf("missing time column argument for macro %v", name) } return fmt.Sprintf("extract(epoch from %s) as \"time\"", args[0]), nil case "__timeFilter": // dont use to_timestamp in this macro for redshift compatibility #9566 if len(args) == 0 { return "", fmt.Errorf("missing time column argument for macro %v", name) } return fmt.Sprintf("extract(epoch from %s) BETWEEN %d AND %d", args[0], uint64(m.TimeRange.GetFromAsMsEpoch()/1000), uint64(m.TimeRange.GetToAsMsEpoch()/1000)), nil case "__timeFrom": return fmt.Sprintf("to_timestamp(%d)", uint64(m.TimeRange.GetFromAsMsEpoch()/1000)), nil case "__timeTo": return fmt.Sprintf("to_timestamp(%d)", uint64(m.TimeRange.GetToAsMsEpoch()/1000)), nil case "__timeGroup": if len(args) < 2 { return "", fmt.Errorf("macro %v needs time column and interval and optional fill value", name) } interval, err := time.ParseDuration(strings.Trim(args[1], `' `)) if err != nil { return "", fmt.Errorf("error parsing interval %v", args[1]) } if len(args) == 3 { m.Query.Model.Set("fill", true) m.Query.Model.Set("fillInterval", interval.Seconds()) if strings.Trim(args[2], " ") == "NULL" { m.Query.Model.Set("fillNull", true) } else { floatVal, err := strconv.ParseFloat(args[2], 64) if err != nil { return "", fmt.Errorf("error parsing fill value %v", args[2]) } m.Query.Model.Set("fillValue", floatVal) } } return fmt.Sprintf("(extract(epoch from %s)/%v)::bigint*%v AS time", args[0], interval.Seconds(), interval.Seconds()), nil case "__unixEpochFilter": if len(args) == 0 { return "", fmt.Errorf("missing time column argument for macro %v", name) } return fmt.Sprintf("%s >= %d AND %s <= %d", args[0], uint64(m.TimeRange.GetFromAsMsEpoch()/1000), args[0], uint64(m.TimeRange.GetToAsMsEpoch()/1000)), nil case "__unixEpochFrom": return fmt.Sprintf("%d", uint64(m.TimeRange.GetFromAsMsEpoch()/1000)), nil case "__unixEpochTo": return fmt.Sprintf("%d", uint64(m.TimeRange.GetToAsMsEpoch()/1000)), nil default: return "", fmt.Errorf("Unknown macro %v", name) } }
pkg/tsdb/postgres/macros.go
1
https://github.com/grafana/grafana/commit/f1ba9137c07d9d9c5d420585993b12ce750f0454
[ 0.998204231262207, 0.1022580936551094, 0.00016764970496296883, 0.0002703182981349528, 0.269713431596756 ]
{ "id": 0, "code_window": [ "\tm.Query = query\n", "\trExp, _ := regexp.Compile(sExpr)\n", "\tvar macroError error\n", "\n", "\tsql = replaceAllStringSubmatchFunc(rExp, sql, func(groups []string) string {\n", "\t\tres, err := m.evaluateMacro(groups[1], strings.Split(groups[2], \",\"))\n", "\t\tif err != nil && macroError == nil {\n", "\t\t\tmacroError = err\n", "\t\t\treturn \"macro_error()\"\n", "\t\t}\n", "\t\treturn res\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\targs := strings.Split(groups[2], \",\")\n", "\t\tfor i, arg := range args {\n", "\t\t\targs[i] = strings.Trim(arg, \" \")\n", "\t\t}\n", "\t\tres, err := m.evaluateMacro(groups[1], args)\n" ], "file_path": "pkg/tsdb/postgres/macros.go", "type": "replace", "edit_start_line_idx": 32 }
<div class="gf-form-group"> <div class="gf-form-inline"> <div class="gf-form"> <span class="gf-form-label width-10">Mode</span> <div class="gf-form-select-wrapper max-width-10"> <select class="gf-form-input" ng-model="ctrl.panel.mode" ng-options="f for f in ctrl.modes" ng-change="ctrl.refresh()"></select> </div> </div> <div class="gf-form" ng-show="ctrl.panel.mode === 'recently viewed'"> <span class="gf-form-label"> <i class="grafana-tip fa fa-question-circle ng-scope" bs-tooltip="'WARNING: This list will be cleared when clearing browser cache'" data-original-title="" title=""></i> </span> </div> </div> <div class="gf-form-inline" ng-if="ctrl.panel.mode === 'search'"> <div class="gf-form"> <span class="gf-form-label width-10">Search options</span> <span class="gf-form-label">Query</span> <input type="text" class="gf-form-input" placeholder="title query" ng-model="ctrl.panel.query" ng-change="ctrl.refresh()" ng-model-onblur> </div> <div class="gf-form"> <span class="gf-form-label">Tags</span> <bootstrap-tagsinput ng-model="ctrl.panel.tags" tagclass="label label-tag" placeholder="add tags" on-tags-updated="ctrl.refresh()"> </bootstrap-tagsinput> </div> </div> <div class="gf-form-inline"> <div class="gf-form"> <span class="gf-form-label width-10">Limit number to</span> <input class="gf-form-input" type="number" ng-model="ctrl.panel.limit" ng-model-onblur ng-change="ctrl.refresh()"> </div> </div> </div>
public/app/plugins/panel/gettingstarted/editor.html
0
https://github.com/grafana/grafana/commit/f1ba9137c07d9d9c5d420585993b12ce750f0454
[ 0.00017094904615078121, 0.00016729568596929312, 0.0001636707311263308, 0.0001685141760390252, 0.0000027093462904304033 ]
{ "id": 0, "code_window": [ "\tm.Query = query\n", "\trExp, _ := regexp.Compile(sExpr)\n", "\tvar macroError error\n", "\n", "\tsql = replaceAllStringSubmatchFunc(rExp, sql, func(groups []string) string {\n", "\t\tres, err := m.evaluateMacro(groups[1], strings.Split(groups[2], \",\"))\n", "\t\tif err != nil && macroError == nil {\n", "\t\t\tmacroError = err\n", "\t\t\treturn \"macro_error()\"\n", "\t\t}\n", "\t\treturn res\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\targs := strings.Split(groups[2], \",\")\n", "\t\tfor i, arg := range args {\n", "\t\t\targs[i] = strings.Trim(arg, \" \")\n", "\t\t}\n", "\t\tres, err := m.evaluateMacro(groups[1], args)\n" ], "file_path": "pkg/tsdb/postgres/macros.go", "type": "replace", "edit_start_line_idx": 32 }
package reporting import ( "fmt" "io" "strings" ) type Printer struct { out io.Writer prefix string } func (self *Printer) Println(message string, values ...interface{}) { formatted := self.format(message, values...) + newline self.out.Write([]byte(formatted)) } func (self *Printer) Print(message string, values ...interface{}) { formatted := self.format(message, values...) self.out.Write([]byte(formatted)) } func (self *Printer) Insert(text string) { self.out.Write([]byte(text)) } func (self *Printer) format(message string, values ...interface{}) string { var formatted string if len(values) == 0 { formatted = self.prefix + message } else { formatted = self.prefix + fmt.Sprintf(message, values...) } indented := strings.Replace(formatted, newline, newline+self.prefix, -1) return strings.TrimRight(indented, space) } func (self *Printer) Indent() { self.prefix += pad } func (self *Printer) Dedent() { if len(self.prefix) >= padLength { self.prefix = self.prefix[:len(self.prefix)-padLength] } } func NewPrinter(out io.Writer) *Printer { self := new(Printer) self.out = out return self } const space = " " const pad = space + space const padLength = len(pad)
vendor/github.com/smartystreets/goconvey/convey/reporting/printer.go
0
https://github.com/grafana/grafana/commit/f1ba9137c07d9d9c5d420585993b12ce750f0454
[ 0.00017451471649110317, 0.00016730302013456821, 0.0001620794937480241, 0.00016675284132361412, 0.000004262575203028973 ]
{ "id": 0, "code_window": [ "\tm.Query = query\n", "\trExp, _ := regexp.Compile(sExpr)\n", "\tvar macroError error\n", "\n", "\tsql = replaceAllStringSubmatchFunc(rExp, sql, func(groups []string) string {\n", "\t\tres, err := m.evaluateMacro(groups[1], strings.Split(groups[2], \",\"))\n", "\t\tif err != nil && macroError == nil {\n", "\t\t\tmacroError = err\n", "\t\t\treturn \"macro_error()\"\n", "\t\t}\n", "\t\treturn res\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\targs := strings.Split(groups[2], \",\")\n", "\t\tfor i, arg := range args {\n", "\t\t\targs[i] = strings.Trim(arg, \" \")\n", "\t\t}\n", "\t\tres, err := m.evaluateMacro(groups[1], args)\n" ], "file_path": "pkg/tsdb/postgres/macros.go", "type": "replace", "edit_start_line_idx": 32 }
.navbar-buttons--zoom { display: none; } .navbar-page-btn { max-width: 200px; } .gf-timepicker-nav-btn { max-width: 120px; } .navbar-buttons--actions { display: none; } // Media queries // --------------------- @include media-breakpoint-down(xs) { input[type='text'], input[type='number'], textarea { font-size: 16px; } } @include media-breakpoint-up(sm) { .navbar-page-btn { max-width: 250px; } .gf-timepicker-nav-btn { max-width: 200px; } } @include media-breakpoint-up(md) { .navbar-buttons--actions { display: flex; } .navbar-page-btn { max-width: 325px; } .gf-timepicker-nav-btn { max-width: 240px; } } @include media-breakpoint-up(lg) { .navbar-buttons--zoom { display: flex; } .navbar-page-btn { max-width: 450px; } .gf-timepicker-nav-btn { max-width: none; } } @include media-breakpoint-up(xl) { .navbar-page-btn { max-width: 600px; } }
public/sass/_old_responsive.scss
0
https://github.com/grafana/grafana/commit/f1ba9137c07d9d9c5d420585993b12ce750f0454
[ 0.00017528167518321425, 0.00017286707588937134, 0.00016995535406749696, 0.0001734782854327932, 0.00000176272521912324 ]
{ "id": 1, "code_window": [ "\t\tif len(args) < 2 {\n", "\t\t\treturn \"\", fmt.Errorf(\"macro %v needs time column and interval and optional fill value\", name)\n", "\t\t}\n", "\t\tinterval, err := time.ParseDuration(strings.Trim(args[1], `' `))\n", "\t\tif err != nil {\n", "\t\t\treturn \"\", fmt.Errorf(\"error parsing interval %v\", args[1])\n", "\t\t}\n", "\t\tif len(args) == 3 {\n", "\t\t\tm.Query.Model.Set(\"fill\", true)\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tinterval, err := time.ParseDuration(strings.Trim(args[1], `'`))\n" ], "file_path": "pkg/tsdb/postgres/macros.go", "type": "replace", "edit_start_line_idx": 90 }
package postgres import ( "fmt" "regexp" "strconv" "strings" "time" "github.com/grafana/grafana/pkg/tsdb" ) //const rsString = `(?:"([^"]*)")`; const rsIdentifier = `([_a-zA-Z0-9]+)` const sExpr = `\$` + rsIdentifier + `\(([^\)]*)\)` type PostgresMacroEngine struct { TimeRange *tsdb.TimeRange Query *tsdb.Query } func NewPostgresMacroEngine() tsdb.SqlMacroEngine { return &PostgresMacroEngine{} } func (m *PostgresMacroEngine) Interpolate(query *tsdb.Query, timeRange *tsdb.TimeRange, sql string) (string, error) { m.TimeRange = timeRange m.Query = query rExp, _ := regexp.Compile(sExpr) var macroError error sql = replaceAllStringSubmatchFunc(rExp, sql, func(groups []string) string { res, err := m.evaluateMacro(groups[1], strings.Split(groups[2], ",")) if err != nil && macroError == nil { macroError = err return "macro_error()" } return res }) if macroError != nil { return "", macroError } return sql, nil } func replaceAllStringSubmatchFunc(re *regexp.Regexp, str string, repl func([]string) string) string { result := "" lastIndex := 0 for _, v := range re.FindAllSubmatchIndex([]byte(str), -1) { groups := []string{} for i := 0; i < len(v); i += 2 { groups = append(groups, str[v[i]:v[i+1]]) } result += str[lastIndex:v[0]] + repl(groups) lastIndex = v[1] } return result + str[lastIndex:] } func (m *PostgresMacroEngine) evaluateMacro(name string, args []string) (string, error) { switch name { case "__time": if len(args) == 0 { return "", fmt.Errorf("missing time column argument for macro %v", name) } return fmt.Sprintf("%s AS \"time\"", args[0]), nil case "__timeEpoch": if len(args) == 0 { return "", fmt.Errorf("missing time column argument for macro %v", name) } return fmt.Sprintf("extract(epoch from %s) as \"time\"", args[0]), nil case "__timeFilter": // dont use to_timestamp in this macro for redshift compatibility #9566 if len(args) == 0 { return "", fmt.Errorf("missing time column argument for macro %v", name) } return fmt.Sprintf("extract(epoch from %s) BETWEEN %d AND %d", args[0], uint64(m.TimeRange.GetFromAsMsEpoch()/1000), uint64(m.TimeRange.GetToAsMsEpoch()/1000)), nil case "__timeFrom": return fmt.Sprintf("to_timestamp(%d)", uint64(m.TimeRange.GetFromAsMsEpoch()/1000)), nil case "__timeTo": return fmt.Sprintf("to_timestamp(%d)", uint64(m.TimeRange.GetToAsMsEpoch()/1000)), nil case "__timeGroup": if len(args) < 2 { return "", fmt.Errorf("macro %v needs time column and interval and optional fill value", name) } interval, err := time.ParseDuration(strings.Trim(args[1], `' `)) if err != nil { return "", fmt.Errorf("error parsing interval %v", args[1]) } if len(args) == 3 { m.Query.Model.Set("fill", true) m.Query.Model.Set("fillInterval", interval.Seconds()) if strings.Trim(args[2], " ") == "NULL" { m.Query.Model.Set("fillNull", true) } else { floatVal, err := strconv.ParseFloat(args[2], 64) if err != nil { return "", fmt.Errorf("error parsing fill value %v", args[2]) } m.Query.Model.Set("fillValue", floatVal) } } return fmt.Sprintf("(extract(epoch from %s)/%v)::bigint*%v AS time", args[0], interval.Seconds(), interval.Seconds()), nil case "__unixEpochFilter": if len(args) == 0 { return "", fmt.Errorf("missing time column argument for macro %v", name) } return fmt.Sprintf("%s >= %d AND %s <= %d", args[0], uint64(m.TimeRange.GetFromAsMsEpoch()/1000), args[0], uint64(m.TimeRange.GetToAsMsEpoch()/1000)), nil case "__unixEpochFrom": return fmt.Sprintf("%d", uint64(m.TimeRange.GetFromAsMsEpoch()/1000)), nil case "__unixEpochTo": return fmt.Sprintf("%d", uint64(m.TimeRange.GetToAsMsEpoch()/1000)), nil default: return "", fmt.Errorf("Unknown macro %v", name) } }
pkg/tsdb/postgres/macros.go
1
https://github.com/grafana/grafana/commit/f1ba9137c07d9d9c5d420585993b12ce750f0454
[ 0.9957236051559448, 0.22974126040935516, 0.00016619605594314635, 0.004135682247579098, 0.40326550602912903 ]
{ "id": 1, "code_window": [ "\t\tif len(args) < 2 {\n", "\t\t\treturn \"\", fmt.Errorf(\"macro %v needs time column and interval and optional fill value\", name)\n", "\t\t}\n", "\t\tinterval, err := time.ParseDuration(strings.Trim(args[1], `' `))\n", "\t\tif err != nil {\n", "\t\t\treturn \"\", fmt.Errorf(\"error parsing interval %v\", args[1])\n", "\t\t}\n", "\t\tif len(args) == 3 {\n", "\t\t\tm.Query.Model.Set(\"fill\", true)\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tinterval, err := time.ParseDuration(strings.Trim(args[1], `'`))\n" ], "file_path": "pkg/tsdb/postgres/macros.go", "type": "replace", "edit_start_line_idx": 90 }
package assertions import "fmt" // ShouldPanic receives a void, niladic function and expects to recover a panic. func ShouldPanic(actual interface{}, expected ...interface{}) (message string) { if fail := need(0, expected); fail != success { return fail } action, _ := actual.(func()) if action == nil { message = shouldUseVoidNiladicFunction return } defer func() { recovered := recover() if recovered == nil { message = shouldHavePanicked } else { message = success } }() action() return } // ShouldNotPanic receives a void, niladic function and expects to execute the function without any panic. func ShouldNotPanic(actual interface{}, expected ...interface{}) (message string) { if fail := need(0, expected); fail != success { return fail } action, _ := actual.(func()) if action == nil { message = shouldUseVoidNiladicFunction return } defer func() { recovered := recover() if recovered != nil { message = fmt.Sprintf(shouldNotHavePanicked, recovered) } else { message = success } }() action() return } // ShouldPanicWith receives a void, niladic function and expects to recover a panic with the second argument as the content. func ShouldPanicWith(actual interface{}, expected ...interface{}) (message string) { if fail := need(1, expected); fail != success { return fail } action, _ := actual.(func()) if action == nil { message = shouldUseVoidNiladicFunction return } defer func() { recovered := recover() if recovered == nil { message = shouldHavePanicked } else { if equal := ShouldEqual(recovered, expected[0]); equal != success { message = serializer.serialize(expected[0], recovered, fmt.Sprintf(shouldHavePanickedWith, expected[0], recovered)) } else { message = success } } }() action() return } // ShouldNotPanicWith receives a void, niladic function and expects to recover a panic whose content differs from the second argument. func ShouldNotPanicWith(actual interface{}, expected ...interface{}) (message string) { if fail := need(1, expected); fail != success { return fail } action, _ := actual.(func()) if action == nil { message = shouldUseVoidNiladicFunction return } defer func() { recovered := recover() if recovered == nil { message = success } else { if equal := ShouldEqual(recovered, expected[0]); equal == success { message = fmt.Sprintf(shouldNotHavePanickedWith, expected[0]) } else { message = success } } }() action() return }
vendor/github.com/smartystreets/assertions/panic.go
0
https://github.com/grafana/grafana/commit/f1ba9137c07d9d9c5d420585993b12ce750f0454
[ 0.00019986076222267002, 0.00017314428987447172, 0.00016401473840232939, 0.00017099844990298152, 0.000008577925655117724 ]
{ "id": 1, "code_window": [ "\t\tif len(args) < 2 {\n", "\t\t\treturn \"\", fmt.Errorf(\"macro %v needs time column and interval and optional fill value\", name)\n", "\t\t}\n", "\t\tinterval, err := time.ParseDuration(strings.Trim(args[1], `' `))\n", "\t\tif err != nil {\n", "\t\t\treturn \"\", fmt.Errorf(\"error parsing interval %v\", args[1])\n", "\t\t}\n", "\t\tif len(args) == 3 {\n", "\t\t\tm.Query.Model.Set(\"fill\", true)\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tinterval, err := time.ParseDuration(strings.Trim(args[1], `'`))\n" ], "file_path": "pkg/tsdb/postgres/macros.go", "type": "replace", "edit_start_line_idx": 90 }
package ec2rolecreds import ( "bufio" "encoding/json" "fmt" "path" "strings" "time" "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/aws/client" "github.com/aws/aws-sdk-go/aws/credentials" "github.com/aws/aws-sdk-go/aws/ec2metadata" ) // ProviderName provides a name of EC2Role provider const ProviderName = "EC2RoleProvider" // A EC2RoleProvider retrieves credentials from the EC2 service, and keeps track if // those credentials are expired. // // Example how to configure the EC2RoleProvider with custom http Client, Endpoint // or ExpiryWindow // // p := &ec2rolecreds.EC2RoleProvider{ // // Pass in a custom timeout to be used when requesting // // IAM EC2 Role credentials. // Client: ec2metadata.New(sess, aws.Config{ // HTTPClient: &http.Client{Timeout: 10 * time.Second}, // }), // // // Do not use early expiry of credentials. If a non zero value is // // specified the credentials will be expired early // ExpiryWindow: 0, // } type EC2RoleProvider struct { credentials.Expiry // Required EC2Metadata client to use when connecting to EC2 metadata service. Client *ec2metadata.EC2Metadata // ExpiryWindow will allow the credentials to trigger refreshing prior to // the credentials actually expiring. This is beneficial so race conditions // with expiring credentials do not cause request to fail unexpectedly // due to ExpiredTokenException exceptions. // // So a ExpiryWindow of 10s would cause calls to IsExpired() to return true // 10 seconds before the credentials are actually expired. // // If ExpiryWindow is 0 or less it will be ignored. ExpiryWindow time.Duration } // NewCredentials returns a pointer to a new Credentials object wrapping // the EC2RoleProvider. Takes a ConfigProvider to create a EC2Metadata client. // The ConfigProvider is satisfied by the session.Session type. func NewCredentials(c client.ConfigProvider, options ...func(*EC2RoleProvider)) *credentials.Credentials { p := &EC2RoleProvider{ Client: ec2metadata.New(c), } for _, option := range options { option(p) } return credentials.NewCredentials(p) } // NewCredentialsWithClient returns a pointer to a new Credentials object wrapping // the EC2RoleProvider. Takes a EC2Metadata client to use when connecting to EC2 // metadata service. func NewCredentialsWithClient(client *ec2metadata.EC2Metadata, options ...func(*EC2RoleProvider)) *credentials.Credentials { p := &EC2RoleProvider{ Client: client, } for _, option := range options { option(p) } return credentials.NewCredentials(p) } // Retrieve retrieves credentials from the EC2 service. // Error will be returned if the request fails, or unable to extract // the desired credentials. func (m *EC2RoleProvider) Retrieve() (credentials.Value, error) { credsList, err := requestCredList(m.Client) if err != nil { return credentials.Value{ProviderName: ProviderName}, err } if len(credsList) == 0 { return credentials.Value{ProviderName: ProviderName}, awserr.New("EmptyEC2RoleList", "empty EC2 Role list", nil) } credsName := credsList[0] roleCreds, err := requestCred(m.Client, credsName) if err != nil { return credentials.Value{ProviderName: ProviderName}, err } m.SetExpiration(roleCreds.Expiration, m.ExpiryWindow) return credentials.Value{ AccessKeyID: roleCreds.AccessKeyID, SecretAccessKey: roleCreds.SecretAccessKey, SessionToken: roleCreds.Token, ProviderName: ProviderName, }, nil } // A ec2RoleCredRespBody provides the shape for unmarshaling credential // request responses. type ec2RoleCredRespBody struct { // Success State Expiration time.Time AccessKeyID string SecretAccessKey string Token string // Error state Code string Message string } const iamSecurityCredsPath = "/iam/security-credentials" // requestCredList requests a list of credentials from the EC2 service. // If there are no credentials, or there is an error making or receiving the request func requestCredList(client *ec2metadata.EC2Metadata) ([]string, error) { resp, err := client.GetMetadata(iamSecurityCredsPath) if err != nil { return nil, awserr.New("EC2RoleRequestError", "no EC2 instance role found", err) } credsList := []string{} s := bufio.NewScanner(strings.NewReader(resp)) for s.Scan() { credsList = append(credsList, s.Text()) } if err := s.Err(); err != nil { return nil, awserr.New("SerializationError", "failed to read EC2 instance role from metadata service", err) } return credsList, nil } // requestCred requests the credentials for a specific credentials from the EC2 service. // // If the credentials cannot be found, or there is an error reading the response // and error will be returned. func requestCred(client *ec2metadata.EC2Metadata, credsName string) (ec2RoleCredRespBody, error) { resp, err := client.GetMetadata(path.Join(iamSecurityCredsPath, credsName)) if err != nil { return ec2RoleCredRespBody{}, awserr.New("EC2RoleRequestError", fmt.Sprintf("failed to get %s EC2 instance role credentials", credsName), err) } respCreds := ec2RoleCredRespBody{} if err := json.NewDecoder(strings.NewReader(resp)).Decode(&respCreds); err != nil { return ec2RoleCredRespBody{}, awserr.New("SerializationError", fmt.Sprintf("failed to decode %s EC2 instance role credentials", credsName), err) } if respCreds.Code != "Success" { // If an error code was returned something failed requesting the role. return ec2RoleCredRespBody{}, awserr.New(respCreds.Code, respCreds.Message, nil) } return respCreds, nil }
vendor/github.com/aws/aws-sdk-go/aws/credentials/ec2rolecreds/ec2_role_provider.go
0
https://github.com/grafana/grafana/commit/f1ba9137c07d9d9c5d420585993b12ce750f0454
[ 0.0002994581591337919, 0.0001805917709134519, 0.00016507520922459662, 0.00016727257752791047, 0.00003266078056185506 ]
{ "id": 1, "code_window": [ "\t\tif len(args) < 2 {\n", "\t\t\treturn \"\", fmt.Errorf(\"macro %v needs time column and interval and optional fill value\", name)\n", "\t\t}\n", "\t\tinterval, err := time.ParseDuration(strings.Trim(args[1], `' `))\n", "\t\tif err != nil {\n", "\t\t\treturn \"\", fmt.Errorf(\"error parsing interval %v\", args[1])\n", "\t\t}\n", "\t\tif len(args) == 3 {\n", "\t\t\tm.Query.Model.Set(\"fill\", true)\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tinterval, err := time.ParseDuration(strings.Trim(args[1], `'`))\n" ], "file_path": "pkg/tsdb/postgres/macros.go", "type": "replace", "edit_start_line_idx": 90 }
/* * * Copyright 2017 gRPC authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ // Package keepalive defines configurable parameters for point-to-point healthcheck. package keepalive import ( "time" ) // ClientParameters is used to set keepalive parameters on the client-side. // These configure how the client will actively probe to notice when a connection is broken // and send pings so intermediaries will be aware of the liveness of the connection. // Make sure these parameters are set in coordination with the keepalive policy on the server, // as incompatible settings can result in closing of connection. type ClientParameters struct { // After a duration of this time if the client doesn't see any activity it pings the server to see if the transport is still alive. Time time.Duration // The current default value is infinity. // After having pinged for keepalive check, the client waits for a duration of Timeout and if no activity is seen even after that // the connection is closed. Timeout time.Duration // The current default value is 20 seconds. // If true, client runs keepalive checks even with no active RPCs. PermitWithoutStream bool // false by default. } // ServerParameters is used to set keepalive and max-age parameters on the server-side. type ServerParameters struct { // MaxConnectionIdle is a duration for the amount of time after which an idle connection would be closed by sending a GoAway. // Idleness duration is defined since the most recent time the number of outstanding RPCs became zero or the connection establishment. MaxConnectionIdle time.Duration // The current default value is infinity. // MaxConnectionAge is a duration for the maximum amount of time a connection may exist before it will be closed by sending a GoAway. // A random jitter of +/-10% will be added to MaxConnectionAge to spread out connection storms. MaxConnectionAge time.Duration // The current default value is infinity. // MaxConnectinoAgeGrace is an additive period after MaxConnectionAge after which the connection will be forcibly closed. MaxConnectionAgeGrace time.Duration // The current default value is infinity. // After a duration of this time if the server doesn't see any activity it pings the client to see if the transport is still alive. Time time.Duration // The current default value is 2 hours. // After having pinged for keepalive check, the server waits for a duration of Timeout and if no activity is seen even after that // the connection is closed. Timeout time.Duration // The current default value is 20 seconds. } // EnforcementPolicy is used to set keepalive enforcement policy on the server-side. // Server will close connection with a client that violates this policy. type EnforcementPolicy struct { // MinTime is the minimum amount of time a client should wait before sending a keepalive ping. MinTime time.Duration // The current default value is 5 minutes. // If true, server expects keepalive pings even when there are no active streams(RPCs). PermitWithoutStream bool // false by default. }
vendor/google.golang.org/grpc/keepalive/keepalive.go
0
https://github.com/grafana/grafana/commit/f1ba9137c07d9d9c5d420585993b12ce750f0454
[ 0.004050271585583687, 0.0007306005572900176, 0.00016378953296225518, 0.00017263343033846468, 0.0013553154421970248 ]
{ "id": 2, "code_window": [ "\t\t}\n", "\t\tif len(args) == 3 {\n", "\t\t\tm.Query.Model.Set(\"fill\", true)\n", "\t\t\tm.Query.Model.Set(\"fillInterval\", interval.Seconds())\n", "\t\t\tif strings.Trim(args[2], \" \") == \"NULL\" {\n", "\t\t\t\tm.Query.Model.Set(\"fillNull\", true)\n", "\t\t\t} else {\n", "\t\t\t\tfloatVal, err := strconv.ParseFloat(args[2], 64)\n", "\t\t\t\tif err != nil {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tif args[2] == \"NULL\" {\n" ], "file_path": "pkg/tsdb/postgres/macros.go", "type": "replace", "edit_start_line_idx": 97 }
package postgres import ( "fmt" "regexp" "strconv" "strings" "time" "github.com/grafana/grafana/pkg/tsdb" ) //const rsString = `(?:"([^"]*)")`; const rsIdentifier = `([_a-zA-Z0-9]+)` const sExpr = `\$` + rsIdentifier + `\(([^\)]*)\)` type PostgresMacroEngine struct { TimeRange *tsdb.TimeRange Query *tsdb.Query } func NewPostgresMacroEngine() tsdb.SqlMacroEngine { return &PostgresMacroEngine{} } func (m *PostgresMacroEngine) Interpolate(query *tsdb.Query, timeRange *tsdb.TimeRange, sql string) (string, error) { m.TimeRange = timeRange m.Query = query rExp, _ := regexp.Compile(sExpr) var macroError error sql = replaceAllStringSubmatchFunc(rExp, sql, func(groups []string) string { res, err := m.evaluateMacro(groups[1], strings.Split(groups[2], ",")) if err != nil && macroError == nil { macroError = err return "macro_error()" } return res }) if macroError != nil { return "", macroError } return sql, nil } func replaceAllStringSubmatchFunc(re *regexp.Regexp, str string, repl func([]string) string) string { result := "" lastIndex := 0 for _, v := range re.FindAllSubmatchIndex([]byte(str), -1) { groups := []string{} for i := 0; i < len(v); i += 2 { groups = append(groups, str[v[i]:v[i+1]]) } result += str[lastIndex:v[0]] + repl(groups) lastIndex = v[1] } return result + str[lastIndex:] } func (m *PostgresMacroEngine) evaluateMacro(name string, args []string) (string, error) { switch name { case "__time": if len(args) == 0 { return "", fmt.Errorf("missing time column argument for macro %v", name) } return fmt.Sprintf("%s AS \"time\"", args[0]), nil case "__timeEpoch": if len(args) == 0 { return "", fmt.Errorf("missing time column argument for macro %v", name) } return fmt.Sprintf("extract(epoch from %s) as \"time\"", args[0]), nil case "__timeFilter": // dont use to_timestamp in this macro for redshift compatibility #9566 if len(args) == 0 { return "", fmt.Errorf("missing time column argument for macro %v", name) } return fmt.Sprintf("extract(epoch from %s) BETWEEN %d AND %d", args[0], uint64(m.TimeRange.GetFromAsMsEpoch()/1000), uint64(m.TimeRange.GetToAsMsEpoch()/1000)), nil case "__timeFrom": return fmt.Sprintf("to_timestamp(%d)", uint64(m.TimeRange.GetFromAsMsEpoch()/1000)), nil case "__timeTo": return fmt.Sprintf("to_timestamp(%d)", uint64(m.TimeRange.GetToAsMsEpoch()/1000)), nil case "__timeGroup": if len(args) < 2 { return "", fmt.Errorf("macro %v needs time column and interval and optional fill value", name) } interval, err := time.ParseDuration(strings.Trim(args[1], `' `)) if err != nil { return "", fmt.Errorf("error parsing interval %v", args[1]) } if len(args) == 3 { m.Query.Model.Set("fill", true) m.Query.Model.Set("fillInterval", interval.Seconds()) if strings.Trim(args[2], " ") == "NULL" { m.Query.Model.Set("fillNull", true) } else { floatVal, err := strconv.ParseFloat(args[2], 64) if err != nil { return "", fmt.Errorf("error parsing fill value %v", args[2]) } m.Query.Model.Set("fillValue", floatVal) } } return fmt.Sprintf("(extract(epoch from %s)/%v)::bigint*%v AS time", args[0], interval.Seconds(), interval.Seconds()), nil case "__unixEpochFilter": if len(args) == 0 { return "", fmt.Errorf("missing time column argument for macro %v", name) } return fmt.Sprintf("%s >= %d AND %s <= %d", args[0], uint64(m.TimeRange.GetFromAsMsEpoch()/1000), args[0], uint64(m.TimeRange.GetToAsMsEpoch()/1000)), nil case "__unixEpochFrom": return fmt.Sprintf("%d", uint64(m.TimeRange.GetFromAsMsEpoch()/1000)), nil case "__unixEpochTo": return fmt.Sprintf("%d", uint64(m.TimeRange.GetToAsMsEpoch()/1000)), nil default: return "", fmt.Errorf("Unknown macro %v", name) } }
pkg/tsdb/postgres/macros.go
1
https://github.com/grafana/grafana/commit/f1ba9137c07d9d9c5d420585993b12ce750f0454
[ 0.9958891272544861, 0.149637833237648, 0.00016857896116562188, 0.0001810142712201923, 0.34994077682495117 ]
{ "id": 2, "code_window": [ "\t\t}\n", "\t\tif len(args) == 3 {\n", "\t\t\tm.Query.Model.Set(\"fill\", true)\n", "\t\t\tm.Query.Model.Set(\"fillInterval\", interval.Seconds())\n", "\t\t\tif strings.Trim(args[2], \" \") == \"NULL\" {\n", "\t\t\t\tm.Query.Model.Set(\"fillNull\", true)\n", "\t\t\t} else {\n", "\t\t\t\tfloatVal, err := strconv.ParseFloat(args[2], 64)\n", "\t\t\t\tif err != nil {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tif args[2] == \"NULL\" {\n" ], "file_path": "pkg/tsdb/postgres/macros.go", "type": "replace", "edit_start_line_idx": 97 }
package dashboards import ( "strings" "time" "github.com/grafana/grafana/pkg/bus" "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/services/guardian" "github.com/grafana/grafana/pkg/util" ) // DashboardService service for operating on dashboards type DashboardService interface { SaveDashboard(dto *SaveDashboardDTO) (*models.Dashboard, error) } // DashboardProvisioningService service for operating on provisioned dashboards type DashboardProvisioningService interface { SaveProvisionedDashboard(dto *SaveDashboardDTO, provisioning *models.DashboardProvisioning) (*models.Dashboard, error) SaveFolderForProvisionedDashboards(*SaveDashboardDTO) (*models.Dashboard, error) GetProvisionedDashboardData(name string) ([]*models.DashboardProvisioning, error) } // NewService factory for creating a new dashboard service var NewService = func() DashboardService { return &dashboardServiceImpl{} } // NewProvisioningService factory for creating a new dashboard provisioning service var NewProvisioningService = func() DashboardProvisioningService { return &dashboardServiceImpl{} } type SaveDashboardDTO struct { OrgId int64 UpdatedAt time.Time User *models.SignedInUser Message string Overwrite bool Dashboard *models.Dashboard } type dashboardServiceImpl struct { orgId int64 user *models.SignedInUser } func (dr *dashboardServiceImpl) GetProvisionedDashboardData(name string) ([]*models.DashboardProvisioning, error) { cmd := &models.GetProvisionedDashboardDataQuery{Name: name} err := bus.Dispatch(cmd) if err != nil { return nil, err } return cmd.Result, nil } func (dr *dashboardServiceImpl) buildSaveDashboardCommand(dto *SaveDashboardDTO, validateAlerts bool) (*models.SaveDashboardCommand, error) { dash := dto.Dashboard dash.Title = strings.TrimSpace(dash.Title) dash.Data.Set("title", dash.Title) dash.SetUid(strings.TrimSpace(dash.Uid)) if dash.Title == "" { return nil, models.ErrDashboardTitleEmpty } if dash.IsFolder && dash.FolderId > 0 { return nil, models.ErrDashboardFolderCannotHaveParent } if dash.IsFolder && strings.ToLower(dash.Title) == strings.ToLower(models.RootFolderName) { return nil, models.ErrDashboardFolderNameExists } if !util.IsValidShortUid(dash.Uid) { return nil, models.ErrDashboardInvalidUid } else if len(dash.Uid) > 40 { return nil, models.ErrDashboardUidToLong } if validateAlerts { validateAlertsCmd := models.ValidateDashboardAlertsCommand{ OrgId: dto.OrgId, Dashboard: dash, } if err := bus.Dispatch(&validateAlertsCmd); err != nil { return nil, models.ErrDashboardContainsInvalidAlertData } } validateBeforeSaveCmd := models.ValidateDashboardBeforeSaveCommand{ OrgId: dto.OrgId, Dashboard: dash, Overwrite: dto.Overwrite, } if err := bus.Dispatch(&validateBeforeSaveCmd); err != nil { return nil, err } guard := guardian.New(dash.GetDashboardIdForSavePermissionCheck(), dto.OrgId, dto.User) if canSave, err := guard.CanSave(); err != nil || !canSave { if err != nil { return nil, err } return nil, models.ErrDashboardUpdateAccessDenied } cmd := &models.SaveDashboardCommand{ Dashboard: dash.Data, Message: dto.Message, OrgId: dto.OrgId, Overwrite: dto.Overwrite, UserId: dto.User.UserId, FolderId: dash.FolderId, IsFolder: dash.IsFolder, PluginId: dash.PluginId, } if !dto.UpdatedAt.IsZero() { cmd.UpdatedAt = dto.UpdatedAt } return cmd, nil } func (dr *dashboardServiceImpl) updateAlerting(cmd *models.SaveDashboardCommand, dto *SaveDashboardDTO) error { alertCmd := models.UpdateDashboardAlertsCommand{ OrgId: dto.OrgId, UserId: dto.User.UserId, Dashboard: cmd.Result, } if err := bus.Dispatch(&alertCmd); err != nil { return models.ErrDashboardFailedToUpdateAlertData } return nil } func (dr *dashboardServiceImpl) SaveProvisionedDashboard(dto *SaveDashboardDTO, provisioning *models.DashboardProvisioning) (*models.Dashboard, error) { dto.User = &models.SignedInUser{ UserId: 0, OrgRole: models.ROLE_ADMIN, } cmd, err := dr.buildSaveDashboardCommand(dto, true) if err != nil { return nil, err } saveCmd := &models.SaveProvisionedDashboardCommand{ DashboardCmd: cmd, DashboardProvisioning: provisioning, } // dashboard err = bus.Dispatch(saveCmd) if err != nil { return nil, err } //alerts err = dr.updateAlerting(cmd, dto) if err != nil { return nil, err } return cmd.Result, nil } func (dr *dashboardServiceImpl) SaveFolderForProvisionedDashboards(dto *SaveDashboardDTO) (*models.Dashboard, error) { dto.User = &models.SignedInUser{ UserId: 0, OrgRole: models.ROLE_ADMIN, } cmd, err := dr.buildSaveDashboardCommand(dto, false) if err != nil { return nil, err } err = bus.Dispatch(cmd) if err != nil { return nil, err } err = dr.updateAlerting(cmd, dto) if err != nil { return nil, err } return cmd.Result, nil } func (dr *dashboardServiceImpl) SaveDashboard(dto *SaveDashboardDTO) (*models.Dashboard, error) { cmd, err := dr.buildSaveDashboardCommand(dto, true) if err != nil { return nil, err } err = bus.Dispatch(cmd) if err != nil { return nil, err } err = dr.updateAlerting(cmd, dto) if err != nil { return nil, err } return cmd.Result, nil } type FakeDashboardService struct { SaveDashboardResult *models.Dashboard SaveDashboardError error SavedDashboards []*SaveDashboardDTO } func (s *FakeDashboardService) SaveDashboard(dto *SaveDashboardDTO) (*models.Dashboard, error) { s.SavedDashboards = append(s.SavedDashboards, dto) if s.SaveDashboardResult == nil && s.SaveDashboardError == nil { s.SaveDashboardResult = dto.Dashboard } return s.SaveDashboardResult, s.SaveDashboardError } func MockDashboardService(mock *FakeDashboardService) { NewService = func() DashboardService { return mock } }
pkg/services/dashboards/dashboard_service.go
0
https://github.com/grafana/grafana/commit/f1ba9137c07d9d9c5d420585993b12ce750f0454
[ 0.00019359138968866318, 0.00017001171363517642, 0.00016037627938203514, 0.0001683709560893476, 0.000007998643013706896 ]
{ "id": 2, "code_window": [ "\t\t}\n", "\t\tif len(args) == 3 {\n", "\t\t\tm.Query.Model.Set(\"fill\", true)\n", "\t\t\tm.Query.Model.Set(\"fillInterval\", interval.Seconds())\n", "\t\t\tif strings.Trim(args[2], \" \") == \"NULL\" {\n", "\t\t\t\tm.Query.Model.Set(\"fillNull\", true)\n", "\t\t\t} else {\n", "\t\t\t\tfloatVal, err := strconv.ParseFloat(args[2], 64)\n", "\t\t\t\tif err != nil {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tif args[2] == \"NULL\" {\n" ], "file_path": "pkg/tsdb/postgres/macros.go", "type": "replace", "edit_start_line_idx": 97 }
// Copyright 2015 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build !go1.7 package ctxhttp // import "golang.org/x/net/context/ctxhttp" import ( "io" "net/http" "net/url" "strings" "golang.org/x/net/context" ) func nop() {} var ( testHookContextDoneBeforeHeaders = nop testHookDoReturned = nop testHookDidBodyClose = nop ) // Do sends an HTTP request with the provided http.Client and returns an HTTP response. // If the client is nil, http.DefaultClient is used. // If the context is canceled or times out, ctx.Err() will be returned. func Do(ctx context.Context, client *http.Client, req *http.Request) (*http.Response, error) { if client == nil { client = http.DefaultClient } // TODO(djd): Respect any existing value of req.Cancel. cancel := make(chan struct{}) req.Cancel = cancel type responseAndError struct { resp *http.Response err error } result := make(chan responseAndError, 1) // Make local copies of test hooks closed over by goroutines below. // Prevents data races in tests. testHookDoReturned := testHookDoReturned testHookDidBodyClose := testHookDidBodyClose go func() { resp, err := client.Do(req) testHookDoReturned() result <- responseAndError{resp, err} }() var resp *http.Response select { case <-ctx.Done(): testHookContextDoneBeforeHeaders() close(cancel) // Clean up after the goroutine calling client.Do: go func() { if r := <-result; r.resp != nil { testHookDidBodyClose() r.resp.Body.Close() } }() return nil, ctx.Err() case r := <-result: var err error resp, err = r.resp, r.err if err != nil { return resp, err } } c := make(chan struct{}) go func() { select { case <-ctx.Done(): close(cancel) case <-c: // The response's Body is closed. } }() resp.Body = &notifyingReader{resp.Body, c} return resp, nil } // Get issues a GET request via the Do function. func Get(ctx context.Context, client *http.Client, url string) (*http.Response, error) { req, err := http.NewRequest("GET", url, nil) if err != nil { return nil, err } return Do(ctx, client, req) } // Head issues a HEAD request via the Do function. func Head(ctx context.Context, client *http.Client, url string) (*http.Response, error) { req, err := http.NewRequest("HEAD", url, nil) if err != nil { return nil, err } return Do(ctx, client, req) } // Post issues a POST request via the Do function. func Post(ctx context.Context, client *http.Client, url string, bodyType string, body io.Reader) (*http.Response, error) { req, err := http.NewRequest("POST", url, body) if err != nil { return nil, err } req.Header.Set("Content-Type", bodyType) return Do(ctx, client, req) } // PostForm issues a POST request via the Do function. func PostForm(ctx context.Context, client *http.Client, url string, data url.Values) (*http.Response, error) { return Post(ctx, client, url, "application/x-www-form-urlencoded", strings.NewReader(data.Encode())) } // notifyingReader is an io.ReadCloser that closes the notify channel after // Close is called or a Read fails on the underlying ReadCloser. type notifyingReader struct { io.ReadCloser notify chan<- struct{} } func (r *notifyingReader) Read(p []byte) (int, error) { n, err := r.ReadCloser.Read(p) if err != nil && r.notify != nil { close(r.notify) r.notify = nil } return n, err } func (r *notifyingReader) Close() error { err := r.ReadCloser.Close() if r.notify != nil { close(r.notify) r.notify = nil } return err }
vendor/golang.org/x/net/context/ctxhttp/ctxhttp_pre17.go
0
https://github.com/grafana/grafana/commit/f1ba9137c07d9d9c5d420585993b12ce750f0454
[ 0.0002831908059306443, 0.0001772866671672091, 0.0001605285215191543, 0.000170844592503272, 0.00002858726293197833 ]
{ "id": 2, "code_window": [ "\t\t}\n", "\t\tif len(args) == 3 {\n", "\t\t\tm.Query.Model.Set(\"fill\", true)\n", "\t\t\tm.Query.Model.Set(\"fillInterval\", interval.Seconds())\n", "\t\t\tif strings.Trim(args[2], \" \") == \"NULL\" {\n", "\t\t\t\tm.Query.Model.Set(\"fillNull\", true)\n", "\t\t\t} else {\n", "\t\t\t\tfloatVal, err := strconv.ParseFloat(args[2], 64)\n", "\t\t\t\tif err != nil {\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tif args[2] == \"NULL\" {\n" ], "file_path": "pkg/tsdb/postgres/macros.go", "type": "replace", "edit_start_line_idx": 97 }
.dashboard-container { padding: $dashboard-padding; width: 100%; min-height: 100%; } .template-variable { color: $variable; } div.flot-text { color: $text-color !important; } .panel { height: 100%; &--solo { .panel-container { border: none; z-index: $zindex-sidemenu + 1; } } } .panel-height-helper { display: block; height: 100%; } .panel-container { background-color: $panel-bg; border: $panel-border; position: relative; border-radius: 3px; height: 100%; &.panel-transparent { background-color: transparent; border: none; } } .panel-content { padding: $panel-padding; height: calc(100% - 27px); position: relative; overflow: hidden; } .panel-title-container { min-height: 9px; cursor: move; word-wrap: break-word; display: block; } .panel-title { border: 0px; font-weight: $font-weight-semi-bold; position: relative; width: 100%; display: block; padding-bottom: 2px; } .panel-title-text { cursor: pointer; font-weight: $font-weight-semi-bold; &:hover { color: $link-hover-color; } } .panel-menu-container { width: 1px; height: 19px; display: inline-block; } .panel-menu-toggle { color: $text-color-weak; cursor: pointer; padding: 3px 5px; visibility: hidden; opacity: 0; position: absolute; width: 16px; height: 16px; left: 1px; top: 4px; &:hover { color: $link-hover-color; } } .panel-loading { position: absolute; top: -3px; right: 0px; z-index: 800; font-size: $font-size-sm; color: $text-color-weak; } .panel-header { text-align: center; &:hover { transition: background-color 0.1s ease-in-out; background-color: $panel-header-hover-bg; } } .panel-menu { top: 25px; left: -100px; } .panel-info-corner-inner { width: 0; height: 0; position: absolute; left: 0; bottom: 0; } @mixin panel-corner-color($corner-bg) { .panel-info-corner-inner { border-left: 27px solid $corner-bg; border-right: none; border-bottom: 27px solid transparent; } } .panel-info-corner { color: $text-muted; cursor: pointer; position: absolute; display: none; left: 0; width: 27px; height: 27px; top: 0; z-index: 1; .fa { position: relative; top: -4px; left: -6px; font-size: 75%; z-index: 1; } &--info { display: block; @include panel-corner-color(lighten($panel-bg, 4%)); .fa:before { content: '\f129'; } } &--links { display: block; @include panel-corner-color(lighten($panel-bg, 4%)); .fa { left: -5px; } .fa:before { content: '\f08e'; } } &--error { display: block; color: $text-color; @include panel-corner-color($popover-error-bg); .fa:before { content: '\f12a'; } } } .panel-hover-highlight { .panel-menu-toggle { visibility: visible; transition: opacity 0.1s ease-in 0.2s; opacity: 1; } } .panel-time-info { font-weight: bold; float: right; margin-right: 15px; color: $blue; font-size: 85%; position: absolute; top: 4px; right: 0; } .dashboard-header { font-family: $headings-font-family; font-size: $font-size-h3; text-align: center; overflow: hidden; position: relative; top: -10px; span { display: inline-block; @include brand-bottom-border(); padding: 0.5rem 0.5rem 0.2rem 0.5rem; } } .panel-full-edit { margin: $dashboard-padding (-$dashboard-padding) 0 (-$dashboard-padding); }
public/sass/pages/_dashboard.scss
0
https://github.com/grafana/grafana/commit/f1ba9137c07d9d9c5d420585993b12ce750f0454
[ 0.0001788600638974458, 0.00017402936646249145, 0.00016866979422047734, 0.00017312302952632308, 0.0000026566860924504 ]
{ "id": 3, "code_window": [ "\n", "\t\t\tSo(sql, ShouldEqual, \"GROUP BY (extract(epoch from time_column)/300)::bigint*300 AS time\")\n", "\t\t})\n", "\n", "\t\tConvey(\"interpolate __timeTo function\", func() {\n", "\t\t\tsql, err := engine.Interpolate(query, timeRange, \"select $__timeTo(time_column)\")\n", "\t\t\tSo(err, ShouldBeNil)\n", "\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tConvey(\"interpolate __timeGroup function with spaces between args\", func() {\n", "\n", "\t\t\tsql, err := engine.Interpolate(query, timeRange, \"GROUP BY $__timeGroup(time_column , '5m')\")\n", "\t\t\tSo(err, ShouldBeNil)\n", "\n", "\t\t\tSo(sql, ShouldEqual, \"GROUP BY (extract(epoch from time_column)/300)::bigint*300 AS time\")\n", "\t\t})\n", "\n" ], "file_path": "pkg/tsdb/postgres/macros_test.go", "type": "add", "edit_start_line_idx": 51 }
package postgres import ( "testing" "github.com/grafana/grafana/pkg/tsdb" . "github.com/smartystreets/goconvey/convey" ) func TestMacroEngine(t *testing.T) { Convey("MacroEngine", t, func() { engine := &PostgresMacroEngine{} query := &tsdb.Query{} timeRange := &tsdb.TimeRange{From: "5m", To: "now"} Convey("interpolate __time function", func() { sql, err := engine.Interpolate(query, timeRange, "select $__time(time_column)") So(err, ShouldBeNil) So(sql, ShouldEqual, "select time_column AS \"time\"") }) Convey("interpolate __time function wrapped in aggregation", func() { sql, err := engine.Interpolate(query, timeRange, "select min($__time(time_column))") So(err, ShouldBeNil) So(sql, ShouldEqual, "select min(time_column AS \"time\")") }) Convey("interpolate __timeFilter function", func() { sql, err := engine.Interpolate(query, timeRange, "WHERE $__timeFilter(time_column)") So(err, ShouldBeNil) So(sql, ShouldEqual, "WHERE extract(epoch from time_column) BETWEEN 18446744066914186738 AND 18446744066914187038") }) Convey("interpolate __timeFrom function", func() { sql, err := engine.Interpolate(query, timeRange, "select $__timeFrom(time_column)") So(err, ShouldBeNil) So(sql, ShouldEqual, "select to_timestamp(18446744066914186738)") }) Convey("interpolate __timeGroup function", func() { sql, err := engine.Interpolate(query, timeRange, "GROUP BY $__timeGroup(time_column,'5m')") So(err, ShouldBeNil) So(sql, ShouldEqual, "GROUP BY (extract(epoch from time_column)/300)::bigint*300 AS time") }) Convey("interpolate __timeTo function", func() { sql, err := engine.Interpolate(query, timeRange, "select $__timeTo(time_column)") So(err, ShouldBeNil) So(sql, ShouldEqual, "select to_timestamp(18446744066914187038)") }) Convey("interpolate __unixEpochFilter function", func() { sql, err := engine.Interpolate(query, timeRange, "select $__unixEpochFilter(18446744066914186738)") So(err, ShouldBeNil) So(sql, ShouldEqual, "select 18446744066914186738 >= 18446744066914186738 AND 18446744066914186738 <= 18446744066914187038") }) Convey("interpolate __unixEpochFrom function", func() { sql, err := engine.Interpolate(query, timeRange, "select $__unixEpochFrom()") So(err, ShouldBeNil) So(sql, ShouldEqual, "select 18446744066914186738") }) Convey("interpolate __unixEpochTo function", func() { sql, err := engine.Interpolate(query, timeRange, "select $__unixEpochTo()") So(err, ShouldBeNil) So(sql, ShouldEqual, "select 18446744066914187038") }) }) }
pkg/tsdb/postgres/macros_test.go
1
https://github.com/grafana/grafana/commit/f1ba9137c07d9d9c5d420585993b12ce750f0454
[ 0.993304431438446, 0.4984196126461029, 0.00017104636935982853, 0.48987117409706116, 0.4540882110595703 ]
{ "id": 3, "code_window": [ "\n", "\t\t\tSo(sql, ShouldEqual, \"GROUP BY (extract(epoch from time_column)/300)::bigint*300 AS time\")\n", "\t\t})\n", "\n", "\t\tConvey(\"interpolate __timeTo function\", func() {\n", "\t\t\tsql, err := engine.Interpolate(query, timeRange, \"select $__timeTo(time_column)\")\n", "\t\t\tSo(err, ShouldBeNil)\n", "\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tConvey(\"interpolate __timeGroup function with spaces between args\", func() {\n", "\n", "\t\t\tsql, err := engine.Interpolate(query, timeRange, \"GROUP BY $__timeGroup(time_column , '5m')\")\n", "\t\t\tSo(err, ShouldBeNil)\n", "\n", "\t\t\tSo(sql, ShouldEqual, \"GROUP BY (extract(epoch from time_column)/300)::bigint*300 AS time\")\n", "\t\t})\n", "\n" ], "file_path": "pkg/tsdb/postgres/macros_test.go", "type": "add", "edit_start_line_idx": 51 }
import _ from 'lodash'; import appEvents from 'app/core/app_events'; import { coreModule, JsonExplorer } from 'app/core/core'; const template = ` <div class="query-troubleshooter" ng-if="ctrl.isOpen"> <div class="query-troubleshooter__header"> <a class="pointer" ng-click="ctrl.toggleMocking()">Mock Response</a> <a class="pointer" ng-click="ctrl.toggleExpand()" ng-hide="ctrl.allNodesExpanded"> <i class="fa fa-plus-square-o"></i> Expand All </a> <a class="pointer" ng-click="ctrl.toggleExpand()" ng-show="ctrl.allNodesExpanded"> <i class="fa fa-minus-square-o"></i> Collapse All </a> <a class="pointer" clipboard-button="ctrl.getClipboardText()"><i class="fa fa-clipboard"></i> Copy to Clipboard</a> </div> <div class="query-troubleshooter__body" ng-hide="ctrl.isMocking"> <i class="fa fa-spinner fa-spin" ng-show="ctrl.isLoading"></i> <div class="query-troubleshooter-json"></div> </div> <div class="query-troubleshooter__body" ng-show="ctrl.isMocking"> <div class="gf-form p-l-1 gf-form--v-stretch"> <textarea class="gf-form-input" style="width: 95%" rows="10" ng-model="ctrl.mockedResponse" placeholder="JSON"></textarea> </div> </div> </div> `; export class QueryTroubleshooterCtrl { isOpen: any; isLoading: boolean; showResponse: boolean; panelCtrl: any; renderJsonExplorer: (data) => void; onRequestErrorEventListener: any; onRequestResponseEventListener: any; hasError: boolean; allNodesExpanded: boolean; isMocking: boolean; mockedResponse: string; jsonExplorer: JsonExplorer; /** @ngInject **/ constructor($scope, private $timeout) { this.onRequestErrorEventListener = this.onRequestError.bind(this); this.onRequestResponseEventListener = this.onRequestResponse.bind(this); appEvents.on('ds-request-response', this.onRequestResponseEventListener); appEvents.on('ds-request-error', this.onRequestErrorEventListener); $scope.$on('$destroy', this.removeEventsListeners.bind(this)); $scope.$watch('ctrl.isOpen', this.stateChanged.bind(this)); } removeEventsListeners() { appEvents.off('ds-request-response', this.onRequestResponseEventListener); appEvents.off('ds-request-error', this.onRequestErrorEventListener); } toggleMocking() { this.isMocking = !this.isMocking; } onRequestError(err) { // ignore if closed if (!this.isOpen) { return; } this.isOpen = true; this.hasError = true; this.onRequestResponse(err); } stateChanged() { if (this.isOpen) { this.panelCtrl.refresh(); this.isLoading = true; } } getClipboardText(): string { if (this.jsonExplorer) { return JSON.stringify(this.jsonExplorer.json, null, 2); } return ''; } handleMocking(data) { var mockedData; try { mockedData = JSON.parse(this.mockedResponse); } catch (err) { appEvents.emit('alert-error', ['Failed to parse mocked response']); return; } data.data = mockedData; } onRequestResponse(data) { // ignore if closed if (!this.isOpen) { return; } if (this.isMocking) { this.handleMocking(data); return; } this.isLoading = false; data = _.cloneDeep(data); if (data.headers) { delete data.headers; } if (data.config) { data.request = data.config; delete data.config; delete data.request.transformRequest; delete data.request.transformResponse; delete data.request.paramSerializer; delete data.request.jsonpCallbackParam; delete data.request.headers; delete data.request.requestId; delete data.request.inspect; delete data.request.retry; delete data.request.timeout; } if (data.data) { data.response = data.data; if (data.status === 200) { // if we are in error state, assume we automatically opened // and auto close it again if (this.hasError) { this.hasError = false; this.isOpen = false; } } delete data.data; delete data.status; delete data.statusText; delete data.$$config; } this.$timeout(_.partial(this.renderJsonExplorer, data)); } toggleExpand(depth) { if (this.jsonExplorer) { this.allNodesExpanded = !this.allNodesExpanded; this.jsonExplorer.openAtDepth(this.allNodesExpanded ? 20 : 1); } } } export function queryTroubleshooter() { return { restrict: 'E', template: template, controller: QueryTroubleshooterCtrl, bindToController: true, controllerAs: 'ctrl', scope: { panelCtrl: '=', isOpen: '=', }, link: function(scope, elem, attrs, ctrl) { ctrl.renderJsonExplorer = function(data) { var jsonElem = elem.find('.query-troubleshooter-json'); ctrl.jsonExplorer = new JsonExplorer(data, 3, { animateOpen: true, }); const html = ctrl.jsonExplorer.render(true); jsonElem.html(html); }; }, }; } coreModule.directive('queryTroubleshooter', queryTroubleshooter);
public/app/features/panel/query_troubleshooter.ts
0
https://github.com/grafana/grafana/commit/f1ba9137c07d9d9c5d420585993b12ce750f0454
[ 0.00017986241437029094, 0.00017418916104361415, 0.00016639776004012674, 0.00017428837600164115, 0.000003458878609308158 ]
{ "id": 3, "code_window": [ "\n", "\t\t\tSo(sql, ShouldEqual, \"GROUP BY (extract(epoch from time_column)/300)::bigint*300 AS time\")\n", "\t\t})\n", "\n", "\t\tConvey(\"interpolate __timeTo function\", func() {\n", "\t\t\tsql, err := engine.Interpolate(query, timeRange, \"select $__timeTo(time_column)\")\n", "\t\t\tSo(err, ShouldBeNil)\n", "\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tConvey(\"interpolate __timeGroup function with spaces between args\", func() {\n", "\n", "\t\t\tsql, err := engine.Interpolate(query, timeRange, \"GROUP BY $__timeGroup(time_column , '5m')\")\n", "\t\t\tSo(err, ShouldBeNil)\n", "\n", "\t\t\tSo(sql, ShouldEqual, \"GROUP BY (extract(epoch from time_column)/300)::bigint*300 AS time\")\n", "\t\t})\n", "\n" ], "file_path": "pkg/tsdb/postgres/macros_test.go", "type": "add", "edit_start_line_idx": 51 }
import _ from 'lodash'; import { GRID_COLUMN_COUNT, GRID_CELL_HEIGHT, GRID_CELL_VMARGIN, DEFAULT_ROW_HEIGHT, MIN_PANEL_HEIGHT, DEFAULT_PANEL_SPAN, } from 'app/core/constants'; import { PanelModel } from './panel_model'; import { DashboardModel } from './dashboard_model'; export class DashboardMigrator { dashboard: DashboardModel; constructor(dashboardModel: DashboardModel) { this.dashboard = dashboardModel; } updateSchema(old) { var i, j, k, n; var oldVersion = this.dashboard.schemaVersion; var panelUpgrades = []; this.dashboard.schemaVersion = 16; if (oldVersion === this.dashboard.schemaVersion) { return; } // version 2 schema changes if (oldVersion < 2) { if (old.services) { if (old.services.filter) { this.dashboard.time = old.services.filter.time; this.dashboard.templating.list = old.services.filter.list || []; } } panelUpgrades.push(function(panel) { // rename panel type if (panel.type === 'graphite') { panel.type = 'graph'; } if (panel.type !== 'graph') { return; } if (_.isBoolean(panel.legend)) { panel.legend = { show: panel.legend }; } if (panel.grid) { if (panel.grid.min) { panel.grid.leftMin = panel.grid.min; delete panel.grid.min; } if (panel.grid.max) { panel.grid.leftMax = panel.grid.max; delete panel.grid.max; } } if (panel.y_format) { if (!panel.y_formats) { panel.y_formats = []; } panel.y_formats[0] = panel.y_format; delete panel.y_format; } if (panel.y2_format) { if (!panel.y_formats) { panel.y_formats = []; } panel.y_formats[1] = panel.y2_format; delete panel.y2_format; } }); } // schema version 3 changes if (oldVersion < 3) { // ensure panel ids var maxId = this.dashboard.getNextPanelId(); panelUpgrades.push(function(panel) { if (!panel.id) { panel.id = maxId; maxId += 1; } }); } // schema version 4 changes if (oldVersion < 4) { // move aliasYAxis changes panelUpgrades.push(function(panel) { if (panel.type !== 'graph') { return; } _.each(panel.aliasYAxis, function(value, key) { panel.seriesOverrides = [{ alias: key, yaxis: value }]; }); delete panel.aliasYAxis; }); } if (oldVersion < 6) { // move pulldowns to new schema var annotations = _.find(old.pulldowns, { type: 'annotations' }); if (annotations) { this.dashboard.annotations = { list: annotations.annotations || [], }; } // update template variables for (i = 0; i < this.dashboard.templating.list.length; i++) { var variable = this.dashboard.templating.list[i]; if (variable.datasource === void 0) { variable.datasource = null; } if (variable.type === 'filter') { variable.type = 'query'; } if (variable.type === void 0) { variable.type = 'query'; } if (variable.allFormat === void 0) { variable.allFormat = 'glob'; } } } if (oldVersion < 7) { if (old.nav && old.nav.length) { this.dashboard.timepicker = old.nav[0]; } // ensure query refIds panelUpgrades.push(function(panel) { _.each( panel.targets, function(target) { if (!target.refId) { target.refId = this.dashboard.getNextQueryLetter(panel); } }.bind(this) ); }); } if (oldVersion < 8) { panelUpgrades.push(function(panel) { _.each(panel.targets, function(target) { // update old influxdb query schema if (target.fields && target.tags && target.groupBy) { if (target.rawQuery) { delete target.fields; delete target.fill; } else { target.select = _.map(target.fields, function(field) { var parts = []; parts.push({ type: 'field', params: [field.name] }); parts.push({ type: field.func, params: [] }); if (field.mathExpr) { parts.push({ type: 'math', params: [field.mathExpr] }); } if (field.asExpr) { parts.push({ type: 'alias', params: [field.asExpr] }); } return parts; }); delete target.fields; _.each(target.groupBy, function(part) { if (part.type === 'time' && part.interval) { part.params = [part.interval]; delete part.interval; } if (part.type === 'tag' && part.key) { part.params = [part.key]; delete part.key; } }); if (target.fill) { target.groupBy.push({ type: 'fill', params: [target.fill] }); delete target.fill; } } } }); }); } // schema version 9 changes if (oldVersion < 9) { // move aliasYAxis changes panelUpgrades.push(function(panel) { if (panel.type !== 'singlestat' && panel.thresholds !== '') { return; } if (panel.thresholds) { var k = panel.thresholds.split(','); if (k.length >= 3) { k.shift(); panel.thresholds = k.join(','); } } }); } // schema version 10 changes if (oldVersion < 10) { // move aliasYAxis changes panelUpgrades.push(function(panel) { if (panel.type !== 'table') { return; } _.each(panel.styles, function(style) { if (style.thresholds && style.thresholds.length >= 3) { var k = style.thresholds; k.shift(); style.thresholds = k; } }); }); } if (oldVersion < 12) { // update template variables _.each(this.dashboard.templating.list, function(templateVariable) { if (templateVariable.refresh) { templateVariable.refresh = 1; } if (!templateVariable.refresh) { templateVariable.refresh = 0; } if (templateVariable.hideVariable) { templateVariable.hide = 2; } else if (templateVariable.hideLabel) { templateVariable.hide = 1; } }); } if (oldVersion < 12) { // update graph yaxes changes panelUpgrades.push(function(panel) { if (panel.type !== 'graph') { return; } if (!panel.grid) { return; } if (!panel.yaxes) { panel.yaxes = [ { show: panel['y-axis'], min: panel.grid.leftMin, max: panel.grid.leftMax, logBase: panel.grid.leftLogBase, format: panel.y_formats[0], label: panel.leftYAxisLabel, }, { show: panel['y-axis'], min: panel.grid.rightMin, max: panel.grid.rightMax, logBase: panel.grid.rightLogBase, format: panel.y_formats[1], label: panel.rightYAxisLabel, }, ]; panel.xaxis = { show: panel['x-axis'], }; delete panel.grid.leftMin; delete panel.grid.leftMax; delete panel.grid.leftLogBase; delete panel.grid.rightMin; delete panel.grid.rightMax; delete panel.grid.rightLogBase; delete panel.y_formats; delete panel.leftYAxisLabel; delete panel.rightYAxisLabel; delete panel['y-axis']; delete panel['x-axis']; } }); } if (oldVersion < 13) { // update graph yaxes changes panelUpgrades.push(function(panel) { if (panel.type !== 'graph') { return; } if (!panel.grid) { return; } panel.thresholds = []; var t1: any = {}, t2: any = {}; if (panel.grid.threshold1 !== null) { t1.value = panel.grid.threshold1; if (panel.grid.thresholdLine) { t1.line = true; t1.lineColor = panel.grid.threshold1Color; t1.colorMode = 'custom'; } else { t1.fill = true; t1.fillColor = panel.grid.threshold1Color; t1.colorMode = 'custom'; } } if (panel.grid.threshold2 !== null) { t2.value = panel.grid.threshold2; if (panel.grid.thresholdLine) { t2.line = true; t2.lineColor = panel.grid.threshold2Color; t2.colorMode = 'custom'; } else { t2.fill = true; t2.fillColor = panel.grid.threshold2Color; t2.colorMode = 'custom'; } } if (_.isNumber(t1.value)) { if (_.isNumber(t2.value)) { if (t1.value > t2.value) { t1.op = t2.op = 'lt'; panel.thresholds.push(t1); panel.thresholds.push(t2); } else { t1.op = t2.op = 'gt'; panel.thresholds.push(t1); panel.thresholds.push(t2); } } else { t1.op = 'gt'; panel.thresholds.push(t1); } } delete panel.grid.threshold1; delete panel.grid.threshold1Color; delete panel.grid.threshold2; delete panel.grid.threshold2Color; delete panel.grid.thresholdLine; }); } if (oldVersion < 14) { this.dashboard.graphTooltip = old.sharedCrosshair ? 1 : 0; } if (oldVersion < 16) { this.upgradeToGridLayout(old); } if (panelUpgrades.length === 0) { return; } for (j = 0; j < this.dashboard.panels.length; j++) { for (k = 0; k < panelUpgrades.length; k++) { panelUpgrades[k].call(this, this.dashboard.panels[j]); if (this.dashboard.panels[j].panels) { for (n = 0; n < this.dashboard.panels[j].panels.length; n++) { panelUpgrades[k].call(this, this.dashboard.panels[j].panels[n]); } } } } } upgradeToGridLayout(old) { let yPos = 0; let widthFactor = GRID_COLUMN_COUNT / 12; const maxPanelId = _.max( _.flattenDeep( _.map(old.rows, row => { return _.map(row.panels, 'id'); }) ) ); let nextRowId = maxPanelId + 1; if (!old.rows) { return; } // Add special "row" panels if even one row is collapsed, repeated or has visible title const showRows = _.some(old.rows, row => row.collapse || row.showTitle || row.repeat); for (let row of old.rows) { if (row.repeatIteration) { continue; } let height: any = row.height || DEFAULT_ROW_HEIGHT; const rowGridHeight = getGridHeight(height); let rowPanel: any = {}; let rowPanelModel: PanelModel; if (showRows) { // add special row panel rowPanel.id = nextRowId; rowPanel.type = 'row'; rowPanel.title = row.title; rowPanel.collapsed = row.collapse; rowPanel.repeat = row.repeat; rowPanel.panels = []; rowPanel.gridPos = { x: 0, y: yPos, w: GRID_COLUMN_COUNT, h: rowGridHeight, }; rowPanelModel = new PanelModel(rowPanel); nextRowId++; yPos++; } let rowArea = new RowArea(rowGridHeight, GRID_COLUMN_COUNT, yPos); for (let panel of row.panels) { panel.span = panel.span || DEFAULT_PANEL_SPAN; if (panel.minSpan) { panel.minSpan = Math.min(GRID_COLUMN_COUNT, GRID_COLUMN_COUNT / 12 * panel.minSpan); } const panelWidth = Math.floor(panel.span) * widthFactor; const panelHeight = panel.height ? getGridHeight(panel.height) : rowGridHeight; let panelPos = rowArea.getPanelPosition(panelHeight, panelWidth); yPos = rowArea.yPos; panel.gridPos = { x: panelPos.x, y: yPos + panelPos.y, w: panelWidth, h: panelHeight, }; rowArea.addPanel(panel.gridPos); delete panel.span; if (rowPanelModel && rowPanel.collapsed) { rowPanelModel.panels.push(panel); } else { this.dashboard.panels.push(new PanelModel(panel)); } } if (rowPanelModel) { this.dashboard.panels.push(rowPanelModel); } if (!(rowPanelModel && rowPanel.collapsed)) { yPos += rowGridHeight; } } } } function getGridHeight(height) { if (_.isString(height)) { height = parseInt(height.replace('px', ''), 10); } if (height < MIN_PANEL_HEIGHT) { height = MIN_PANEL_HEIGHT; } const gridHeight = Math.ceil(height / (GRID_CELL_HEIGHT + GRID_CELL_VMARGIN)); return gridHeight; } /** * RowArea represents dashboard row filled by panels * area is an array of numbers represented filled column's cells like * ----------------------- * |******** **** * |******** **** * |******** * ----------------------- * 33333333 2222 00000 ... */ class RowArea { area: number[]; yPos: number; height: number; constructor(height, width = GRID_COLUMN_COUNT, rowYPos = 0) { this.area = new Array(width).fill(0); this.yPos = rowYPos; this.height = height; } reset() { this.area.fill(0); } /** * Update area after adding the panel. */ addPanel(gridPos) { for (let i = gridPos.x; i < gridPos.x + gridPos.w; i++) { if (!this.area[i] || gridPos.y + gridPos.h - this.yPos > this.area[i]) { this.area[i] = gridPos.y + gridPos.h - this.yPos; } } return this.area; } /** * Calculate position for the new panel in the row. */ getPanelPosition(panelHeight, panelWidth, callOnce = false) { let startPlace, endPlace; let place; for (let i = this.area.length - 1; i >= 0; i--) { if (this.height - this.area[i] > 0) { if (endPlace === undefined) { endPlace = i; } else { if (i < this.area.length - 1 && this.area[i] <= this.area[i + 1]) { startPlace = i; } else { break; } } } else { break; } } if (startPlace !== undefined && endPlace !== undefined && endPlace - startPlace >= panelWidth - 1) { const yPos = _.max(this.area.slice(startPlace)); place = { x: startPlace, y: yPos, }; } else if (!callOnce) { // wrap to next row this.yPos += this.height; this.reset(); return this.getPanelPosition(panelHeight, panelWidth, true); } else { return null; } return place; } }
public/app/features/dashboard/dashboard_migration.ts
0
https://github.com/grafana/grafana/commit/f1ba9137c07d9d9c5d420585993b12ce750f0454
[ 0.00023518470698036253, 0.0001759860897436738, 0.00016521141515113413, 0.0001760995073709637, 0.00000876308240549406 ]
{ "id": 3, "code_window": [ "\n", "\t\t\tSo(sql, ShouldEqual, \"GROUP BY (extract(epoch from time_column)/300)::bigint*300 AS time\")\n", "\t\t})\n", "\n", "\t\tConvey(\"interpolate __timeTo function\", func() {\n", "\t\t\tsql, err := engine.Interpolate(query, timeRange, \"select $__timeTo(time_column)\")\n", "\t\t\tSo(err, ShouldBeNil)\n", "\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tConvey(\"interpolate __timeGroup function with spaces between args\", func() {\n", "\n", "\t\t\tsql, err := engine.Interpolate(query, timeRange, \"GROUP BY $__timeGroup(time_column , '5m')\")\n", "\t\t\tSo(err, ShouldBeNil)\n", "\n", "\t\t\tSo(sql, ShouldEqual, \"GROUP BY (extract(epoch from time_column)/300)::bigint*300 AS time\")\n", "\t\t})\n", "\n" ], "file_path": "pkg/tsdb/postgres/macros_test.go", "type": "add", "edit_start_line_idx": 51 }
// Package pq is a pure Go Postgres driver for the database/sql package. // +build darwin dragonfly freebsd linux nacl netbsd openbsd solaris rumprun package pq import ( "os" "os/user" ) func userCurrent() (string, error) { u, err := user.Current() if err == nil { return u.Username, nil } name := os.Getenv("USER") if name != "" { return name, nil } return "", ErrCouldNotDetectUsername }
vendor/github.com/lib/pq/user_posix.go
0
https://github.com/grafana/grafana/commit/f1ba9137c07d9d9c5d420585993b12ce750f0454
[ 0.00017416065384168178, 0.00017188485071528703, 0.00017052153998520225, 0.00017097235831897706, 0.0000016197261629713466 ]
{ "id": 0, "code_window": [ "import { $Fetch } from 'ohmyfetch'\n", "import { Nuxt } from '../dist'\n", "\n", "declare global {\n", " // eslint-disable-next-line no-var\n", " var $fetch: $Fetch\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "keep" ], "after_edit": [ " // eslint-disable-next-line no-var\n", " var $fetch: $Fetch\n" ], "file_path": "packages/app/types/shims.d.ts", "type": "replace", "edit_start_line_idx": 5 }
declare global { namespace NodeJS { interface Global { __timing__: any $config: any } } } // type export required to turn this into a module for TS augmentation purposes export type A = {}
packages/nitro/src/runtime/types.d.ts
1
https://github.com/nuxt/nuxt/commit/b53d8a77ffe1bdd69ae8dcc41da9d37a867329cc
[ 0.0010515287285670638, 0.0006110169924795628, 0.00017050528549589217, 0.0006110169924795628, 0.0004405117069836706 ]
{ "id": 0, "code_window": [ "import { $Fetch } from 'ohmyfetch'\n", "import { Nuxt } from '../dist'\n", "\n", "declare global {\n", " // eslint-disable-next-line no-var\n", " var $fetch: $Fetch\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "keep" ], "after_edit": [ " // eslint-disable-next-line no-var\n", " var $fetch: $Fetch\n" ], "file_path": "packages/app/types/shims.d.ts", "type": "replace", "edit_start_line_idx": 5 }
# Azure Static Web Apps > How to deploy Nuxt to Azure Static Web Apps with Nuxt Nitro. - Support for serverless SSR build - Auto-detected when deploying - Minimal configuration required ## Setup Azure Static Web Apps are designed to be deployed continuously in a [GitHub Actions workflow](https://docs.microsoft.com/en-us/azure/static-web-apps/github-actions-workflow). By default, Nitro will detect this deployment environment and enable the `azure` preset. ## Deploy from CI/CD via GitHub Actions When you link your GitHub repository to Azure Static Web Apps, a workflow file is added to the repository. Find the build configuration section in this workflow and update the build configuration: ```yml{}[.github/workflows/azure-static-web-apps-<RANDOM_NAME>.yml] ###### Repository/Build Configurations ###### app_location: '/' api_location: '.output/server' output_location: '.output/public' ###### End of Repository/Build Configurations ###### ``` **Note** Pending an update in the [Azure Static Web Apps workflow](https://github.com/Azure/static-web-apps-deploy), you will also need to run the following in your root directory: ```bash mkdir -p .output/server touch .output/server/.gitkeep git add -f .output/server/.gitkeep ``` That's it! Now Azure Static Web Apps will automatically deploy your Nitro-powered Nuxt application on push.
docs/content/6.deployment/platforms/azure.md
0
https://github.com/nuxt/nuxt/commit/b53d8a77ffe1bdd69ae8dcc41da9d37a867329cc
[ 0.000263011286733672, 0.0001908142294269055, 0.00016595378110650927, 0.00016714591765776277, 0.0000416859365941491 ]
{ "id": 0, "code_window": [ "import { $Fetch } from 'ohmyfetch'\n", "import { Nuxt } from '../dist'\n", "\n", "declare global {\n", " // eslint-disable-next-line no-var\n", " var $fetch: $Fetch\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "keep" ], "after_edit": [ " // eslint-disable-next-line no-var\n", " var $fetch: $Fetch\n" ], "file_path": "packages/app/types/shims.d.ts", "type": "replace", "edit_start_line_idx": 5 }
# Server Middleware Nuxt will automatically read in any files in the `~/server/middleware` to create server middleware for your project. These files will be run on every request, unlike [API routes](./api) that are mapped to their own routes. This is typically so you can add a common header to all responses, log responses or modify the incoming request object for use later on in the request chain. Each file should export a default function that will handle a request. ```js export default async (req, res) => { req.someValue = true } ``` There is nothing different about the `req`/`res` objects, so typing them is straightforward. ```ts import type { IncomingMessage, ServerResponse } from 'http' export default async (req: IncomingMessage, res: ServerResponse) => { req.someValue = true } ```
docs/content/3.server/3.middleware.md
0
https://github.com/nuxt/nuxt/commit/b53d8a77ffe1bdd69ae8dcc41da9d37a867329cc
[ 0.0002632187388371676, 0.00020293657144065946, 0.00016983466048259288, 0.00017575630045030266, 0.00004269443161319941 ]
{ "id": 0, "code_window": [ "import { $Fetch } from 'ohmyfetch'\n", "import { Nuxt } from '../dist'\n", "\n", "declare global {\n", " // eslint-disable-next-line no-var\n", " var $fetch: $Fetch\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "keep" ], "after_edit": [ " // eslint-disable-next-line no-var\n", " var $fetch: $Fetch\n" ], "file_path": "packages/app/types/shims.d.ts", "type": "replace", "edit_start_line_idx": 5 }
import { NitroPreset } from '../context' export const node: NitroPreset = { entry: '{{ _internal.runtimeDir }}/entries/node', externals: true }
packages/nitro/src/presets/node.ts
0
https://github.com/nuxt/nuxt/commit/b53d8a77ffe1bdd69ae8dcc41da9d37a867329cc
[ 0.00016765370673965663, 0.00016765370673965663, 0.00016765370673965663, 0.00016765370673965663, 0 ]
{ "id": 1, "code_window": [ "\n", " namespace NodeJS {\n", " interface Global {\n", " $fetch: $Fetch\n", " }\n", " interface Process {\n", " browser: boolean\n", " client: boolean\n", " mode: 'spa' | 'universal'\n", " server: boolean\n", " static: boolean\n", " }\n", " }\n" ], "labels": [ "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep" ], "after_edit": [ " namespace NodeJS {\n", " interface Global {\n", " $fetch: $Fetch\n" ], "file_path": "packages/app/types/shims.d.ts", "type": "replace", "edit_start_line_idx": 8 }
import Vue from 'vue' import { $Fetch } from 'ohmyfetch' import { Nuxt } from '../dist' declare global { // eslint-disable-next-line no-var var $fetch: $Fetch namespace NodeJS { interface Global { $fetch: $Fetch } interface Process { browser: boolean client: boolean mode: 'spa' | 'universal' server: boolean static: boolean } } interface Window { __NUXT__?: Record<string, any> } } declare module '*.vue' { export default Vue } declare module 'vue' { interface App { $nuxt: Nuxt } } export {}
packages/app/types/shims.d.ts
1
https://github.com/nuxt/nuxt/commit/b53d8a77ffe1bdd69ae8dcc41da9d37a867329cc
[ 0.03899674117565155, 0.014629673212766647, 0.00016891314589884132, 0.009676520712673664, 0.016067825257778168 ]
{ "id": 1, "code_window": [ "\n", " namespace NodeJS {\n", " interface Global {\n", " $fetch: $Fetch\n", " }\n", " interface Process {\n", " browser: boolean\n", " client: boolean\n", " mode: 'spa' | 'universal'\n", " server: boolean\n", " static: boolean\n", " }\n", " }\n" ], "labels": [ "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep" ], "after_edit": [ " namespace NodeJS {\n", " interface Global {\n", " $fetch: $Fetch\n" ], "file_path": "packages/app/types/shims.d.ts", "type": "replace", "edit_start_line_idx": 8 }
import { withDocus } from 'docus' export default withDocus({ rootDir: __dirname })
docs/src/docus/nuxt.config.ts
0
https://github.com/nuxt/nuxt/commit/b53d8a77ffe1bdd69ae8dcc41da9d37a867329cc
[ 0.00017557942192070186, 0.00017557942192070186, 0.00017557942192070186, 0.00017557942192070186, 0 ]
{ "id": 1, "code_window": [ "\n", " namespace NodeJS {\n", " interface Global {\n", " $fetch: $Fetch\n", " }\n", " interface Process {\n", " browser: boolean\n", " client: boolean\n", " mode: 'spa' | 'universal'\n", " server: boolean\n", " static: boolean\n", " }\n", " }\n" ], "labels": [ "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep" ], "after_edit": [ " namespace NodeJS {\n", " interface Global {\n", " $fetch: $Fetch\n" ], "file_path": "packages/app/types/shims.d.ts", "type": "replace", "edit_start_line_idx": 8 }
import _renderToString from 'vue-server-renderer/basic' export function renderToString (component, context) { return new Promise((resolve, reject) => { _renderToString(component, context, (err, result) => { if (err) { return reject(err) } return resolve(result) }) }) }
packages/nitro/src/runtime/app/vue2.basic.ts
0
https://github.com/nuxt/nuxt/commit/b53d8a77ffe1bdd69ae8dcc41da9d37a867329cc
[ 0.00017185905016958714, 0.0001715408288873732, 0.00017122260760515928, 0.0001715408288873732, 3.182212822139263e-7 ]
{ "id": 1, "code_window": [ "\n", " namespace NodeJS {\n", " interface Global {\n", " $fetch: $Fetch\n", " }\n", " interface Process {\n", " browser: boolean\n", " client: boolean\n", " mode: 'spa' | 'universal'\n", " server: boolean\n", " static: boolean\n", " }\n", " }\n" ], "labels": [ "keep", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "replace", "keep" ], "after_edit": [ " namespace NodeJS {\n", " interface Global {\n", " $fetch: $Fetch\n" ], "file_path": "packages/app/types/shims.d.ts", "type": "replace", "edit_start_line_idx": 8 }
import { resolve } from 'upath' import globby, { GlobbyOptions } from 'globby' import type { Plugin } from 'rollup' const PLUGIN_NAME = 'dynamic-require' const HELPER_DYNAMIC = `\0${PLUGIN_NAME}.js` const DYNAMIC_REQUIRE_RE = /require\("\.\/" ?\+/g interface Options { dir: string inline: boolean globbyOptions: GlobbyOptions outDir?: string prefix?: string } interface Chunk { id: string src: string name: string meta?: { id?: string ids?: string[] moduleIds?: string[] } } interface TemplateContext { chunks: Chunk[] } export function dynamicRequire ({ dir, globbyOptions, inline }: Options): Plugin { return { name: PLUGIN_NAME, transform (code: string, _id: string) { return { code: code.replace(DYNAMIC_REQUIRE_RE, `require('${HELPER_DYNAMIC}')(`), map: null } }, resolveId (id: string) { return id === HELPER_DYNAMIC ? id : null }, // TODO: Async chunk loading over netwrok! // renderDynamicImport () { // return { // left: 'fetch(', right: ')' // } // }, async load (_id: string) { if (_id !== HELPER_DYNAMIC) { return null } // Scan chunks const files = await globby('**/*.js', { cwd: dir, absolute: false, ...globbyOptions }) const chunks = files.map(id => ({ id, src: resolve(dir, id).replace(/\\/g, '/'), name: '_' + id.replace(/[^a-zA-Z0-9_]/g, '_'), meta: getWebpackChunkMeta(resolve(dir, id)) })) return inline ? TMPL_INLINE({ chunks }) : TMPL_LAZY({ chunks }) }, renderChunk (code) { if (inline) { return { map: null, code } } return { map: null, code: code.replace( /Promise.resolve\(\).then\(function \(\) \{ return require\('([^']*)' \/\* webpackChunk \*\/\); \}\).then\(function \(n\) \{ return n.([_a-zA-Z0-9]*); \}\)/g, "require('$1').$2") } } } } function getWebpackChunkMeta (src: string) { const chunk = require(src) || {} const { id, ids, modules } = chunk return { id, ids, moduleIds: Object.keys(modules) } } function TMPL_INLINE ({ chunks }: TemplateContext) { return `${chunks.map(i => `import ${i.name} from '${i.src}'`).join('\n')} const dynamicChunks = { ${chunks.map(i => ` ['${i.id}']: ${i.name}`).join(',\n')} }; export default function dynamicRequire(id) { return dynamicChunks[id]; };` } function TMPL_LAZY ({ chunks }: TemplateContext) { return ` function dynamicWebpackModule(id, getChunk) { return function (module, exports, require) { const r = getChunk() if (r instanceof Promise) { module.exports = r.then(r => { const realModule = { exports: {}, require }; r.modules[id](realModule, realModule.exports, realModule.require); return realModule.exports; }); } else { r.modules[id](module, exports, require); } }; }; function webpackChunk (meta, getChunk) { const chunk = { ...meta, modules: {} }; for (const id of meta.moduleIds) { chunk.modules[id] = dynamicWebpackModule(id, getChunk); }; return chunk; }; const dynamicChunks = { ${chunks.map(i => ` ['${i.id}']: () => webpackChunk(${JSON.stringify(i.meta)}, () => import('${i.src}' /* webpackChunk */))`).join(',\n')} }; export default function dynamicRequire(id) { return dynamicChunks[id](); };` }
packages/nitro/src/rollup/plugins/dynamic-require.ts
0
https://github.com/nuxt/nuxt/commit/b53d8a77ffe1bdd69ae8dcc41da9d37a867329cc
[ 0.000173931461176835, 0.00017070819740183651, 0.00016441935440525413, 0.00017101327830459923, 0.0000021556181764026405 ]
{ "id": 2, "code_window": [ " }\n", "\n", " interface Window {\n", " __NUXT__?: Record<string, any>\n", " }\n" ], "labels": [ "keep", "replace", "replace", "replace", "keep" ], "after_edit": [ " interface Process {\n", " browser: boolean\n", " client: boolean\n", " mode: 'spa' | 'universal'\n", " server: boolean\n", " static: boolean\n" ], "file_path": "packages/app/types/shims.d.ts", "type": "replace", "edit_start_line_idx": 20 }
import Vue from 'vue' import { $Fetch } from 'ohmyfetch' import { Nuxt } from '../dist' declare global { // eslint-disable-next-line no-var var $fetch: $Fetch namespace NodeJS { interface Global { $fetch: $Fetch } interface Process { browser: boolean client: boolean mode: 'spa' | 'universal' server: boolean static: boolean } } interface Window { __NUXT__?: Record<string, any> } } declare module '*.vue' { export default Vue } declare module 'vue' { interface App { $nuxt: Nuxt } } export {}
packages/app/types/shims.d.ts
1
https://github.com/nuxt/nuxt/commit/b53d8a77ffe1bdd69ae8dcc41da9d37a867329cc
[ 0.9844955801963806, 0.2465025931596756, 0.00017191789811477065, 0.0006714325863867998, 0.4260806143283844 ]
{ "id": 2, "code_window": [ " }\n", "\n", " interface Window {\n", " __NUXT__?: Record<string, any>\n", " }\n" ], "labels": [ "keep", "replace", "replace", "replace", "keep" ], "after_edit": [ " interface Process {\n", " browser: boolean\n", " client: boolean\n", " mode: 'spa' | 'universal'\n", " server: boolean\n", " static: boolean\n" ], "file_path": "packages/app/types/shims.d.ts", "type": "replace", "edit_start_line_idx": 20 }
{ "name": "@nuxt/component-discovery", "version": "0.2.0", "repository": "nuxt/framework", "license": "MIT", "types": "./dist/module.d.ts", "files": [ "dist", "module.js" ], "scripts": { "prepack": "unbuild" }, "dependencies": { "@nuxt/kit": "^0.6.4", "globby": "^11.0.4", "scule": "^0.2.1", "ufo": "^0.7.7", "upath": "^2.0.1" }, "devDependencies": { "unbuild": "^0.3.1" }, "peerDependencies": { "vue": "3.1.3" } }
packages/components/package.json
0
https://github.com/nuxt/nuxt/commit/b53d8a77ffe1bdd69ae8dcc41da9d37a867329cc
[ 0.00017257353465538472, 0.00017157381807919592, 0.00017047407163772732, 0.00017167381884064525, 8.600146657045116e-7 ]
{ "id": 2, "code_window": [ " }\n", "\n", " interface Window {\n", " __NUXT__?: Record<string, any>\n", " }\n" ], "labels": [ "keep", "replace", "replace", "replace", "keep" ], "after_edit": [ " interface Process {\n", " browser: boolean\n", " client: boolean\n", " mode: 'spa' | 'universal'\n", " server: boolean\n", " static: boolean\n" ], "file_path": "packages/app/types/shims.d.ts", "type": "replace", "edit_start_line_idx": 20 }
<template> <div> Welcome to Nuxt Layouts 👋 <NuxtLink to="/manual"> Manual layout </NuxtLink> <NuxtLink to="/same"> Same layout </NuxtLink> </div> </template> <script> import { defineNuxtComponent } from '@nuxt/app' export default defineNuxtComponent({ layout: 'custom' }) </script>
examples/with-layouts/pages/index.vue
0
https://github.com/nuxt/nuxt/commit/b53d8a77ffe1bdd69ae8dcc41da9d37a867329cc
[ 0.00031541375210508704, 0.0002212700346717611, 0.0001688922056928277, 0.000179504175321199, 0.00006671047594863921 ]
{ "id": 2, "code_window": [ " }\n", "\n", " interface Window {\n", " __NUXT__?: Record<string, any>\n", " }\n" ], "labels": [ "keep", "replace", "replace", "replace", "keep" ], "after_edit": [ " interface Process {\n", " browser: boolean\n", " client: boolean\n", " mode: 'spa' | 'universal'\n", " server: boolean\n", " static: boolean\n" ], "file_path": "packages/app/types/shims.d.ts", "type": "replace", "edit_start_line_idx": 20 }
# Change Log All notable changes to this project will be documented in this file. See [Conventional Commits](https://conventionalcommits.org) for commit guidelines. # [0.8.0](https://github.com/nuxt/framework/compare/[email protected]@0.8.0) (2021-06-24) ### Bug Fixes * use nitro plugin with explicit mjs extension ([1ed3387](https://github.com/nuxt/framework/commit/1ed33872433bc0d4d370fa8a9b35833793ee4bdb)) * **nitro:** update nitro internal hook name ([#218](https://github.com/nuxt/framework/issues/218)) ([77e489a](https://github.com/nuxt/framework/commit/77e489aae37ce1bc8ad12e20b7a4dc3d6f1085a7)) ### Features * components discovery ([#243](https://github.com/nuxt/framework/issues/243)) ([a0f81cd](https://github.com/nuxt/framework/commit/a0f81cd1fbdfae8d8eabc8e015b7635bdaa93575)) ## [0.7.4](https://github.com/nuxt/framework/compare/[email protected]@0.7.4) (2021-06-16) ### Bug Fixes * **nuxt3:** add support for custom templates ([#225](https://github.com/nuxt/framework/issues/225)) ([5c67408](https://github.com/nuxt/framework/commit/5c6740819199d68ed64cb6afdc800df9fe0e1d4d)) * add nitro client plugin ($fetch support) ([#223](https://github.com/nuxt/framework/issues/223)) ([e2d5a2f](https://github.com/nuxt/framework/commit/e2d5a2f4b3f27d1454321ab22958ef3941a02978)), closes [#213](https://github.com/nuxt/framework/issues/213) ## [0.7.3](https://github.com/nuxt/framework/compare/[email protected]@0.7.3) (2021-06-04) **Note:** Version bump only for package nuxt3 ## [0.7.2](https://github.com/nuxt/framework/compare/[email protected]@0.7.2) (2021-06-04) **Note:** Version bump only for package nuxt3 ## [0.7.1](https://github.com/nuxt/framework/compare/[email protected]@0.7.1) (2021-05-24) **Note:** Version bump only for package nuxt3 # [0.7.0](https://github.com/nuxt/framework/compare/[email protected]@0.7.0) (2021-05-20) ### Features * optional pages and refactor nuxt3 ([#142](https://github.com/nuxt/framework/issues/142)) ([6b62d45](https://github.com/nuxt/framework/commit/6b62d456d7fe8c9dd92803a30dcebf0d481f65c7)) * update vite implementation ([#130](https://github.com/nuxt/framework/issues/130)) ([9732d63](https://github.com/nuxt/framework/commit/9732d63c74b394706150ef35cc06c65d3fb185ad)) ## [0.6.3](https://github.com/nuxt/framework/compare/[email protected]@0.6.3) (2021-04-28) **Note:** Version bump only for package nuxt3 ## [0.6.2](https://github.com/nuxt/framework/compare/[email protected]@0.6.2) (2021-04-28) **Note:** Version bump only for package nuxt3 ## [0.6.1](https://github.com/nuxt/framework/compare/[email protected]@0.6.1) (2021-04-23) **Note:** Version bump only for package nuxt3 # [0.6.0](https://github.com/nuxt/framework/compare/[email protected]@0.6.0) (2021-04-23) ### Bug Fixes * **nuxt3:** binary proxy for cli ([7ee7a7a](https://github.com/nuxt/framework/commit/7ee7a7a7b58f31d27c61b43b43ef621cc83a2939)) ### Features * **nitro:** allow extending nitro context ([bef9f82](https://github.com/nuxt/framework/commit/bef9f82a8dd8ac916c9e9f82eafca7e916782500)) ## [0.5.1](https://github.com/nuxt/framework/compare/[email protected]@0.5.1) (2021-04-17) **Note:** Version bump only for package nuxt3 # [0.5.0](https://github.com/nuxt/framework/compare/[email protected]@0.5.0) (2021-04-16) ### Features * improve dev experience ([#89](https://github.com/nuxt/framework/issues/89)) ([e224818](https://github.com/nuxt/framework/commit/e224818395cd366f2a338ce3da4aaae993f641b7)) # [0.4.0](https://github.com/nuxt/framework/compare/[email protected]@0.4.0) (2021-04-12) ### Features * add hook signatures and basic typings ([#79](https://github.com/nuxt/framework/issues/79)) ([dacde63](https://github.com/nuxt/framework/commit/dacde630634700172ccd54a1e4f1d0469b28bd30)) # [0.3.0](https://github.com/nuxt/framework/compare/[email protected]@0.3.0) (2021-04-09) ### Features * initial version of nu cli ([#54](https://github.com/nuxt/framework/issues/54)) ([a030c62](https://github.com/nuxt/framework/commit/a030c62d29ba871f94a7152c7d5fa36d4de1d3b6)) ## [0.2.6](https://github.com/nuxt/framework/compare/[email protected]@0.2.6) (2021-04-08) **Note:** Version bump only for package nuxt3 ## [0.2.5](https://github.com/nuxt/framework/compare/[email protected]@0.2.5) (2021-04-06) **Note:** Version bump only for package nuxt3 ## [0.2.4](https://github.com/nuxt/framework/compare/[email protected]@0.2.4) (2021-04-06) **Note:** Version bump only for package nuxt3 ## [0.2.3](https://github.com/nuxt/framework/compare/[email protected]@0.2.3) (2021-04-04) **Note:** Version bump only for package nuxt3 ## [0.2.2](https://github.com/nuxt/framework/compare/[email protected]@0.2.2) (2021-04-04) ### Bug Fixes * **nitro:** resolve alias for serverMiddleware ([c864c5a](https://github.com/nuxt/framework/commit/c864c5a30cfc38362e35ee4c7015b589d445edee)) ## [0.2.1](https://github.com/nuxt/framework/compare/[email protected]@0.2.1) (2021-04-04) ### Bug Fixes * **nuxt3:** install nuxt-cli by default ([3e794a3](https://github.com/nuxt/framework/commit/3e794a36f2b1aa9fd729f7556741c47930a30b64)) # 0.2.0 (2021-04-04) ### Bug Fixes * **app:** provide appDir via meta export ([94d3697](https://github.com/nuxt/framework/commit/94d36976c79ff549a8d510795e7d47c5e32b8f96)) * webpack compilation ([#41](https://github.com/nuxt/framework/issues/41)) ([2c1eb87](https://github.com/nuxt/framework/commit/2c1eb8767180fc04b91fb409976b4fe1e0c3047d)) * **app:** improve composables ([#183](https://github.com/nuxt/framework/issues/183)) ([451fc29](https://github.com/nuxt/framework/commit/451fc29b60683bf37f4b311cbbca10f12da6e508)) * **webpack:** types in webpack and await compiler close ([#176](https://github.com/nuxt/framework/issues/176)) ([2c9854d](https://github.com/nuxt/framework/commit/2c9854dfe347e35046819102dee2ed8420cbd324)) * import Builder not as default ([daaa8ed](https://github.com/nuxt/framework/commit/daaa8eda8cf48f4f9da70946a77a39b2208cec25)) * include nitro.client plugin for global $fetch ([23f6578](https://github.com/nuxt/framework/commit/23f6578c88f05d148efdaa08a13d865b12d92255)) * remove runtimeChunk options (HMR push of undefined error) ([7309ef3](https://github.com/nuxt/framework/commit/7309ef303a928295ca04a6ad4cfab3ccb4891f6e)) * update nitro preset for dev ([040e14f](https://github.com/nuxt/framework/commit/040e14f2b6b93f47a3e1c7cd2ae821cdfab3c53c)) * **types:** type definitions errors ([#172](https://github.com/nuxt/framework/issues/172)) ([52d28c0](https://github.com/nuxt/framework/commit/52d28c041a0dbf46dd0cb5492835b0d1fbd7436b)) * allow resolving relative `package.json` in vite mode ([abb21f3](https://github.com/nuxt/framework/commit/abb21f30cacb232f717c9cd20e6c2aac295cf5a2)), closes [#146](https://github.com/nuxt/framework/issues/146) * don't display 404 page if no pages/ ([d63b283](https://github.com/nuxt/framework/commit/d63b28303ece59df69f79def167aea97bc7ed5e4)) * init nitro before module container (closes [#165](https://github.com/nuxt/framework/issues/165)) ([270bbbc](https://github.com/nuxt/framework/commit/270bbbc47ef0b9a95042feebac3cc1ecb3f44683)) * polyfill $fetch on globalThis ([a1ac066](https://github.com/nuxt/framework/commit/a1ac066cb51fa99861d52799a11ff4bb1780316c)) * remove use of html-webpack-plugin ([c89166f](https://github.com/nuxt/framework/commit/c89166f8f998d8d156b69ca43f06aaff225afd88)) * replace ~build with nuxt/build ([52592a5](https://github.com/nuxt/framework/commit/52592a5d64ec0fc654fd9081f6abd1785672573c)) * **build:** style not work in vue ([dab1a83](https://github.com/nuxt/framework/commit/dab1a831a68760b1a092c26b8c778730b75273f4)) * **build:** use last hash file name in client manifest ([#123](https://github.com/nuxt/framework/issues/123)) ([8e320f8](https://github.com/nuxt/framework/commit/8e320f80aa346efa6085b9b66327b5bd8b8e3e38)) * **builder:** empty buildDir only once by build ([7b3244a](https://github.com/nuxt/framework/commit/7b3244a567524a47cd566741b62b67d7d66453c1)) * **builder:** empty dir before generate ([8a1cb84](https://github.com/nuxt/framework/commit/8a1cb845187540ea41acecd75369d95047ba5014)) * **renderer:** missing nomodule on legacy modules ([d171823](https://github.com/nuxt/framework/commit/d1718230edc7a2385d504abb0d3c61e44ea9968d)) * **router:** generate empty array ([#133](https://github.com/nuxt/framework/issues/133)) ([0b31d93](https://github.com/nuxt/framework/commit/0b31d93892e6ef955dad08edd12ea747a48e56c7)), closes [#129](https://github.com/nuxt/framework/issues/129) * **ssr:** update ssr/client manifect after webpack v5 beta.30 ([#48](https://github.com/nuxt/framework/issues/48)) ([db050fd](https://github.com/nuxt/framework/commit/db050fd0a2049ccac64f6fed2848f3b46ef47162)) * **vite:** include deps from nuxt3 package ([694a6b5](https://github.com/nuxt/framework/commit/694a6b5635e17448fb5f55c7523369f7b8cd5884)) * **webpack:** remove hmr chunks from client manifest ([64ca193](https://github.com/nuxt/framework/commit/64ca193ac9b636607f2fb16f37a8b78a14627922)) * remove NuxtChild refs ([#113](https://github.com/nuxt/framework/issues/113)) ([ba0fae7](https://github.com/nuxt/framework/commit/ba0fae74a741dbcaafafdf3e4b8592672a94593a)) * **webpack:** DeprecationWarning DEP_WEBPACK_COMPILATION_ASSETS ([#57](https://github.com/nuxt/framework/issues/57)) ([20c2375](https://github.com/nuxt/framework/commit/20c2375e74537d85073dbf93c8785a37aefad72d)) * **webpack:** use modern target for esbuild ([ae32ca4](https://github.com/nuxt/framework/commit/ae32ca42fa1785ee801939e812b477c741a2837f)) * **webpack5:** plugins/vue/server DeprecationWarning ([8936fe7](https://github.com/nuxt/framework/commit/8936fe77ebfca9ee22d620cc08b4bd47167f495c)) * RouterLink import ([00e13c3](https://github.com/nuxt/framework/commit/00e13c3e41275caf21496a2e9c2c8667ca68fd65)) ### Features * `@nuxt/kit` and new config schema ([#34](https://github.com/nuxt/framework/issues/34)) ([46f771a](https://github.com/nuxt/framework/commit/46f771a98b6226e19e9df3511e31b4ec2da6abda)) * add `nuxt-head` component ([#166](https://github.com/nuxt/framework/issues/166)) ([545bfe4](https://github.com/nuxt/framework/commit/545bfe4f9e1dab086e03eb2cdad151b754cb90ba)) * add asyncData and improve reactivity ([#174](https://github.com/nuxt/framework/issues/174)) ([5248c61](https://github.com/nuxt/framework/commit/5248c61ed0c65d5da7c0e49eb8f50aba208af8b6)) * add support for `useHead` ([#122](https://github.com/nuxt/framework/issues/122)) ([3f99bb7](https://github.com/nuxt/framework/commit/3f99bb7878a3df176b8115004acae7b90182c6d2)) * add vue-app types ([#12](https://github.com/nuxt/framework/issues/12)) ([a74b48c](https://github.com/nuxt/framework/commit/a74b48c648d2dc55adc5d47989ffdca8941e0483)) * create `nu` cli ([c9347e3](https://github.com/nuxt/framework/commit/c9347e3f5b68664007710c32e30be34bde08836b)) * improve app, fetch and support vuex5 ([5a7f516](https://github.com/nuxt/framework/commit/5a7f5164f0b4f6d3b8a2fca526f194545f6796a6)) * improve typing of config ([2122838](https://github.com/nuxt/framework/commit/212283837b248ee203f0b0459c37f2b1121a5784)) * initial support for vite bundler ([#127](https://github.com/nuxt/framework/issues/127)) ([9be2826](https://github.com/nuxt/framework/commit/9be282623cf69270fc4f28ec599c0844fa3bfaea)) * initial work for pages routing ([#113](https://github.com/nuxt/framework/issues/113)) ([a6f9fb4](https://github.com/nuxt/framework/commit/a6f9fb4c7ac4d4b90b88f5341acad9120a2fa1ee)) * migrate to nitro ([faabd1a](https://github.com/nuxt/framework/commit/faabd1ab54b4dc0af1f1ab0dfdf98206f92c7f0c)) * module utils and improvements ([#38](https://github.com/nuxt/framework/issues/38)) ([b3f3dc9](https://github.com/nuxt/framework/commit/b3f3dc94f3ef0790eea114d605b6f320dbf3f1d2)) * preliminary vue-app types ([426cf1b](https://github.com/nuxt/framework/commit/426cf1b3de893db6c6430a874a9fd57a7db3b4a2)) * prepare for npm publish ([47c738c](https://github.com/nuxt/framework/commit/47c738cd9d5d1f86f7b5671479019166408bd034)) * rewrite webpack config ([#30](https://github.com/nuxt/framework/issues/30)) ([d6ed1df](https://github.com/nuxt/framework/commit/d6ed1dfc2c3ed7bdfa7481d3e4974b12701b3fc6)) * rollup build, basic typescript support and typescript app ([e7dd27f](https://github.com/nuxt/framework/commit/e7dd27fa2a5a165d87f277188515ea8024999e3b)) * support auto import of plugins ([#169](https://github.com/nuxt/framework/issues/169)) ([bece3b8](https://github.com/nuxt/framework/commit/bece3b85abb579d0b4d42a92ee85ba2480ec3c3d)) * support document.html ([0947613](https://github.com/nuxt/framework/commit/09476134eeeb12c025618919ab9a795a680a9b30)) * typed nuxt (1) ([38e72f8](https://github.com/nuxt/framework/commit/38e72f86c2b5e891d4c86e4801cd42eb136f9cea)) * use express instead of connect ([c0e565c](https://github.com/nuxt/framework/commit/c0e565cbe7d6beecb4df760ac893c915ff67693e)) * use sigma ([#95](https://github.com/nuxt/framework/issues/95)) ([0091dba](https://github.com/nuxt/framework/commit/0091dba181e46abc617d5faf8a8c4c1338755082)) * useAsyncData ([#142](https://github.com/nuxt/framework/issues/142)) ([a870746](https://github.com/nuxt/framework/commit/a8707469f875f9426ef41d8162e6b5acda7a3fc3)), closes [#141](https://github.com/nuxt/framework/issues/141) * **style:** add style loaders ([#50](https://github.com/nuxt/framework/issues/50)) ([232d329](https://github.com/nuxt/framework/commit/232d3298b443581dc193f3b1e7dd8f4260443720)) * **webpack:** replace optimize-css-assets-webpack-plugin with css-minimizer-webpack-plugin ([2ee8628](https://github.com/nuxt/framework/commit/2ee86286ad530b6192f10c68d409caf480933caa))
packages/nuxt3/CHANGELOG.md
0
https://github.com/nuxt/nuxt/commit/b53d8a77ffe1bdd69ae8dcc41da9d37a867329cc
[ 0.0020388374105095863, 0.0004364752385299653, 0.00016177486395463347, 0.0001671574282227084, 0.0005626418278552592 ]
{ "id": 3, "code_window": [ " }\n", "}\n", "\n", "declare module '*.vue' {\n" ], "labels": [ "add", "keep", "keep", "keep" ], "after_edit": [ " }\n", "\n", " interface Window {\n", " __NUXT__?: Record<string, any>\n", " }\n" ], "file_path": "packages/app/types/shims.d.ts", "type": "add", "edit_start_line_idx": 24 }
import Vue from 'vue' import { $Fetch } from 'ohmyfetch' import { Nuxt } from '../dist' declare global { // eslint-disable-next-line no-var var $fetch: $Fetch namespace NodeJS { interface Global { $fetch: $Fetch } interface Process { browser: boolean client: boolean mode: 'spa' | 'universal' server: boolean static: boolean } } interface Window { __NUXT__?: Record<string, any> } } declare module '*.vue' { export default Vue } declare module 'vue' { interface App { $nuxt: Nuxt } } export {}
packages/app/types/shims.d.ts
1
https://github.com/nuxt/nuxt/commit/b53d8a77ffe1bdd69ae8dcc41da9d37a867329cc
[ 0.6165862679481506, 0.15697601437568665, 0.00016801024321466684, 0.005574893206357956, 0.265390008687973 ]
{ "id": 3, "code_window": [ " }\n", "}\n", "\n", "declare module '*.vue' {\n" ], "labels": [ "add", "keep", "keep", "keep" ], "after_edit": [ " }\n", "\n", " interface Window {\n", " __NUXT__?: Record<string, any>\n", " }\n" ], "file_path": "packages/app/types/shims.d.ts", "type": "add", "edit_start_line_idx": 24 }
import { resolve } from 'path' import { testNitroBuild, setupTest, testNitroBehavior } from './_utils' describe('nitro:preset:lambda', () => { const ctx = setupTest() testNitroBuild(ctx, 'lambda') testNitroBehavior(ctx, async () => { const { handler } = await import(resolve(ctx.outDir, 'server/index.js')) return async ({ url: rawRelativeUrl, headers, method, body }) => { // creating new URL object to parse query easier const url = new URL(`https://example.com${rawRelativeUrl}`) const queryStringParameters = Object.fromEntries(url.searchParams.entries()) const event = { path: url.pathname, headers: headers || {}, method: method || 'GET', queryStringParameters, body: body || '' } const res = await handler(event) return { data: res.body } } }) })
test/presets/lambda.test.ts
0
https://github.com/nuxt/nuxt/commit/b53d8a77ffe1bdd69ae8dcc41da9d37a867329cc
[ 0.00016943304217420518, 0.00016826142382342368, 0.00016697966202627867, 0.00016837155271787196, 0.0000010046112493000692 ]
{ "id": 3, "code_window": [ " }\n", "}\n", "\n", "declare module '*.vue' {\n" ], "labels": [ "add", "keep", "keep", "keep" ], "after_edit": [ " }\n", "\n", " interface Window {\n", " __NUXT__?: Record<string, any>\n", " }\n" ], "file_path": "packages/app/types/shims.d.ts", "type": "add", "edit_start_line_idx": 24 }
import { dirname, join, relative, resolve } from 'upath' import { InputOptions, OutputOptions } from 'rollup' import defu from 'defu' import { terser } from 'rollup-plugin-terser' import commonjs from '@rollup/plugin-commonjs' import nodeResolve from '@rollup/plugin-node-resolve' import alias from '@rollup/plugin-alias' import json from '@rollup/plugin-json' import replace from '@rollup/plugin-replace' import virtual from '@rollup/plugin-virtual' import inject from '@rollup/plugin-inject' import analyze from 'rollup-plugin-analyzer' import * as unenv from 'unenv' import type { Preset } from 'unenv' import { NitroContext } from '../context' import { resolvePath, MODULE_DIR } from '../utils' import { dynamicRequire } from './plugins/dynamic-require' import { externals } from './plugins/externals' import { timing } from './plugins/timing' // import { autoMock } from './plugins/automock' import { staticAssets, dirnames } from './plugins/static' import { assets } from './plugins/assets' import { middleware } from './plugins/middleware' import { esbuild } from './plugins/esbuild' import { raw } from './plugins/raw' import { storage } from './plugins/storage' export type RollupConfig = InputOptions & { output: OutputOptions } export const getRollupConfig = (nitroContext: NitroContext) => { const extensions: string[] = ['.ts', '.mjs', '.js', '.json', '.node'] const nodePreset = nitroContext.node === false ? unenv.nodeless : unenv.node const builtinPreset: Preset = { alias: { // General debug: 'unenv/runtime/npm/debug', consola: 'unenv/runtime/npm/consola', // Vue 2 encoding: 'unenv/runtime/mock/proxy', he: 'unenv/runtime/mock/proxy', resolve: 'unenv/runtime/mock/proxy', 'source-map': 'unenv/runtime/mock/proxy', 'lodash.template': 'unenv/runtime/mock/proxy', 'serialize-javascript': 'unenv/runtime/mock/proxy', // Vue 3 'estree-walker': 'unenv/runtime/mock/proxy', '@babel/parser': 'unenv/runtime/mock/proxy', '@vue/compiler-core': 'unenv/runtime/mock/proxy', '@vue/compiler-dom': 'unenv/runtime/mock/proxy', '@vue/compiler-ssr': 'unenv/runtime/mock/proxy' } } const env = unenv.env(nodePreset, builtinPreset, nitroContext.env) delete env.alias['node-fetch'] // FIX ME if (nitroContext.sourceMap) { env.polyfill.push('source-map-support/register') } const buildServerDir = join(nitroContext._nuxt.buildDir, 'dist/server') const runtimeAppDir = join(nitroContext._internal.runtimeDir, 'app') const rollupConfig: RollupConfig = { input: resolvePath(nitroContext, nitroContext.entry), output: { dir: nitroContext.output.serverDir, entryFileNames: 'index.js', chunkFileNames (chunkInfo) { let prefix = '' const modules = Object.keys(chunkInfo.modules) const lastModule = modules[modules.length - 1] if (lastModule.startsWith(buildServerDir)) { prefix = join('app', relative(buildServerDir, dirname(lastModule))) } else if (lastModule.startsWith(runtimeAppDir)) { prefix = 'app' } else if (lastModule.startsWith(nitroContext._nuxt.buildDir)) { prefix = 'nuxt' } else if (lastModule.startsWith(nitroContext._internal.runtimeDir)) { prefix = 'nitro' } else if (!prefix && nitroContext.middleware.find(m => lastModule.startsWith(m.handle as string))) { prefix = 'middleware' } else if (lastModule.includes('assets')) { prefix = 'assets' } return join('chunks', prefix, '[name].js') }, inlineDynamicImports: nitroContext.inlineDynamicImports, format: 'cjs', exports: 'auto', intro: '', outro: '', preferConst: true, sourcemap: nitroContext.sourceMap, sourcemapExcludeSources: true, sourcemapPathTransform (relativePath, sourcemapPath) { return resolve(dirname(sourcemapPath), relativePath) } }, external: env.external, // https://github.com/rollup/rollup/pull/4021#issuecomment-809985618 // https://github.com/nuxt/framework/issues/160 makeAbsoluteExternalsRelative: false, plugins: [], onwarn (warning, rollupWarn) { if ( !['CIRCULAR_DEPENDENCY', 'EVAL'].includes(warning.code) && !warning.message.includes('Unsupported source map comment') ) { rollupWarn(warning) } } } if (nitroContext.timing) { rollupConfig.plugins.push(timing()) } // Raw asset loader rollupConfig.plugins.push(raw()) // https://github.com/rollup/plugins/tree/master/packages/replace rollupConfig.plugins.push(replace({ // @ts-ignore https://github.com/rollup/plugins/pull/810 preventAssignment: true, values: { 'process.env.NODE_ENV': nitroContext._nuxt.dev ? '"development"' : '"production"', 'typeof window': '"undefined"', 'global.': 'globalThis.', 'process.server': 'true', 'process.client': 'false', 'process.env.ROUTER_BASE': JSON.stringify(nitroContext._nuxt.routerBase), 'process.env.PUBLIC_PATH': JSON.stringify(nitroContext._nuxt.publicPath), 'process.env.NUXT_STATIC_BASE': JSON.stringify(nitroContext._nuxt.staticAssets.base), 'process.env.NUXT_STATIC_VERSION': JSON.stringify(nitroContext._nuxt.staticAssets.version), 'process.env.NUXT_FULL_STATIC': nitroContext._nuxt.fullStatic as unknown as string, 'process.env.NITRO_PRESET': JSON.stringify(nitroContext.preset), 'process.env.RUNTIME_CONFIG': JSON.stringify(nitroContext._nuxt.runtimeConfig), 'process.env.DEBUG': JSON.stringify(nitroContext._nuxt.dev) } })) // ESBuild rollupConfig.plugins.push(esbuild({ target: 'es2019', sourceMap: true })) // Dynamic Require Support rollupConfig.plugins.push(dynamicRequire({ dir: resolve(nitroContext._nuxt.buildDir, 'dist/server'), inline: nitroContext.node === false || nitroContext.inlineDynamicImports, globbyOptions: { ignore: [ 'server.js' ] } })) // Assets rollupConfig.plugins.push(assets(nitroContext.assets)) // Static // TODO: use assets plugin if (nitroContext.serveStatic) { rollupConfig.plugins.push(dirnames()) rollupConfig.plugins.push(staticAssets(nitroContext)) } // Storage rollupConfig.plugins.push(storage(nitroContext.storage)) // Middleware rollupConfig.plugins.push(middleware(() => { const _middleware = [ ...nitroContext.scannedMiddleware, ...nitroContext.middleware ] if (nitroContext.serveStatic) { _middleware.unshift({ route: '/', handle: '#nitro/server/static' }) } return _middleware })) // Polyfill rollupConfig.plugins.push(virtual({ '#polyfill': env.polyfill.map(p => `import '${p}';`).join('\n') })) // https://github.com/rollup/plugins/tree/master/packages/alias const renderer = nitroContext.renderer || (nitroContext._nuxt.majorVersion === 3 ? 'vue3' : 'vue2') const vue2ServerRenderer = 'vue-server-renderer/' + (nitroContext._nuxt.dev ? 'build.dev.js' : 'build.prod.js') rollupConfig.plugins.push(alias({ entries: { '#nitro': nitroContext._internal.runtimeDir, '#nitro-renderer': require.resolve(resolve(nitroContext._internal.runtimeDir, 'app', renderer)), '#config': require.resolve(resolve(nitroContext._internal.runtimeDir, 'app/config')), '#nitro-vue-renderer': vue2ServerRenderer, '#build': nitroContext._nuxt.buildDir, '~': nitroContext._nuxt.srcDir, '@/': nitroContext._nuxt.srcDir, '~~': nitroContext._nuxt.rootDir, '@@/': nitroContext._nuxt.rootDir, ...env.alias } })) const moduleDirectories = [ resolve(nitroContext._nuxt.rootDir, 'node_modules'), resolve(MODULE_DIR, 'node_modules'), resolve(MODULE_DIR, '../node_modules'), 'node_modules' ] // Externals Plugin if (nitroContext.externals) { rollupConfig.plugins.push(externals(defu(nitroContext.externals as any, { outDir: nitroContext.output.serverDir, moduleDirectories, external: [ ...(nitroContext._nuxt.dev ? [nitroContext._nuxt.buildDir] : []) ], inline: [ '#', '~', '@/', '~~', '@@/', 'virtual:', nitroContext._internal.runtimeDir, nitroContext._nuxt.srcDir, nitroContext._nuxt.rootDir, nitroContext._nuxt.serverDir, ...nitroContext.middleware.map(m => m.handle), ...(nitroContext._nuxt.dev ? [] : ['vue', '@vue/', '@nuxt/']) ], traceOptions: { base: '/', processCwd: nitroContext._nuxt.rootDir } }))) } // https://github.com/rollup/plugins/tree/master/packages/node-resolve rollupConfig.plugins.push(nodeResolve({ extensions, preferBuiltins: true, rootDir: nitroContext._nuxt.rootDir, moduleDirectories, mainFields: ['main'] // Force resolve CJS (@vue/runtime-core ssrUtils) })) // Automatically mock unresolved externals // rollupConfig.plugins.push(autoMock()) // https://github.com/rollup/plugins/tree/master/packages/commonjs rollupConfig.plugins.push(commonjs({ requireReturnsDefault: 'auto' })) // https://github.com/rollup/plugins/tree/master/packages/json rollupConfig.plugins.push(json()) // https://github.com/rollup/plugins/tree/master/packages/inject rollupConfig.plugins.push(inject(env.inject)) if (nitroContext.analyze) { // https://github.com/doesdev/rollup-plugin-analyzer rollupConfig.plugins.push(analyze()) } // https://github.com/TrySound/rollup-plugin-terser // https://github.com/terser/terser#minify-nitroContext if (nitroContext.minify) { rollupConfig.plugins.push(terser({ mangle: { keep_fnames: true, keep_classnames: true }, format: { comments: false } })) } return rollupConfig }
packages/nitro/src/rollup/config.ts
0
https://github.com/nuxt/nuxt/commit/b53d8a77ffe1bdd69ae8dcc41da9d37a867329cc
[ 0.0006137769087217748, 0.0002138874988304451, 0.00016544015670660883, 0.00016912836872506887, 0.00010284427116857842 ]
{ "id": 3, "code_window": [ " }\n", "}\n", "\n", "declare module '*.vue' {\n" ], "labels": [ "add", "keep", "keep", "keep" ], "after_edit": [ " }\n", "\n", " interface Window {\n", " __NUXT__?: Record<string, any>\n", " }\n" ], "file_path": "packages/app/types/shims.d.ts", "type": "add", "edit_start_line_idx": 24 }
# Contribution Nuxt is a community project - and so we love contributions of all kinds! ❤️ There are a range of different ways you might be able to contribute to the Nuxt ecosystem. ## Create a module If you've built something with Nuxt that's cool, why not [extract it into a module](/modules/kit), so it can be shared with others? We have [many awesome modules already](https://modules.nuxtjs.org/) but there's always room for more. If you need help while building it, feel free to [check in with us](/community/getting-help). ## Improve our documentation Documentation is one of the most important parts of Nuxt. We aim to be an intuitive framework - and a big part of that is making sure that both the developer experience and the docs are perfect. 👌 If you spot an area where we can improve documentation or error messages, please do open a PR - even if it's just to fix a typo! ## Triage issues and help out in discussions Check out [our issues board](https://github.com/nuxt/framework/issues) and [discussions](https://github.com/nuxt/framework/discussions). Helping other users, sharing workarounds, creating reproductions or even just poking into a bug a little bit and sharing your findings - it all makes a huge difference. ## Fixing a bug or adding a feature Before you fix a bug or add a feature, ensure there's an issue that describes it. Particularly for new features, this is a great opportunity for the project leads to give feedback before starting work on it. ### Setup your dev environment 1. [Fork](https://help.github.com/articles/fork-a-repo/) the [Nuxt3 repository](https://github.com/nuxt/framework) to your own GitHub account and then [clone](https://help.github.com/articles/cloning-a-repository/) it to your local device. 2. Run `yarn` to install the dependencies. > If you are adding a dependency, please use `yarn add`. The `yarn.lock` file is the source of truth for all Nuxt dependencies. 3. Check out a branch where you can work and commit your changes: ``` git checkout -b my-new-branch ``` ### Examples While working on your PR you will likely want to check if your changes are working correctly. To do so you can modify the example app in `playground/`, and run it with `yarn play`. Make sure not to commit it to your branch, but it could be helpful to add some example code to your PR description. This can help reviewers and other Nuxt users understand the feature you've built in-depth. ### Testing Every new feature should have a corresponding unit test (if possible). The `test` folder in this repository is currently a work in progress, but do your best to create a new test following the example of what's already there. Before creating a PR or marking it as ready-to-review, make sure that all tests are passing by running `yarn test` locally. ### Linting As you might have noticed already, we use ESLint to enforce a code standard. Please run `yarn lint` before committing your changes to verify that the code style is correct. If not, you can use `yarn lint --fix` to fix most of the style changes. If there are still errors left, you must correct them manually. ### Documentation If you are adding a new feature, or refactoring or changing the behavior of Nuxt in any other manner, you'll likely want to document the changes. Please include any changes to the docs in the same PR. You don't have to write documentation up on the first commit (but please do so as soon as your pull request is mature enough). ### Final checklist When submitting your PR, there is a simple template that you have to fill out. Please tick all appropriate "answers" in the checklists. Particularly, make sure your PR title adheres to [Conventional Commits guidelines](https://www.conventionalcommits.org/en/v1.0.0/), and do link the related issue (feature request or bug report) in the issue description.
docs/content/99.community/3.contribution.md
0
https://github.com/nuxt/nuxt/commit/b53d8a77ffe1bdd69ae8dcc41da9d37a867329cc
[ 0.0001719559368211776, 0.0001695376995485276, 0.0001659295812714845, 0.00016978170606307685, 0.0000018936509604827734 ]
{ "id": 4, "code_window": [ "}\n", "\n", "declare module '*.vue' {\n", " export default Vue\n", "}\n", "\n", "declare module 'vue' {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " export default Vue\n" ], "file_path": "packages/app/types/shims.d.ts", "type": "replace", "edit_start_line_idx": 27 }
import Vue from 'vue' import { $Fetch } from 'ohmyfetch' import { Nuxt } from '../dist' declare global { // eslint-disable-next-line no-var var $fetch: $Fetch namespace NodeJS { interface Global { $fetch: $Fetch } interface Process { browser: boolean client: boolean mode: 'spa' | 'universal' server: boolean static: boolean } } interface Window { __NUXT__?: Record<string, any> } } declare module '*.vue' { export default Vue } declare module 'vue' { interface App { $nuxt: Nuxt } } export {}
packages/app/types/shims.d.ts
1
https://github.com/nuxt/nuxt/commit/b53d8a77ffe1bdd69ae8dcc41da9d37a867329cc
[ 0.988621175289154, 0.2507815659046173, 0.0001722013985272497, 0.0071664536371827126, 0.4260283410549164 ]
{ "id": 4, "code_window": [ "}\n", "\n", "declare module '*.vue' {\n", " export default Vue\n", "}\n", "\n", "declare module 'vue' {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " export default Vue\n" ], "file_path": "packages/app/types/shims.d.ts", "type": "replace", "edit_start_line_idx": 27 }
<template> <div> 404 | Page Not Found </div> </template>
packages/pages/src/runtime/404.vue
0
https://github.com/nuxt/nuxt/commit/b53d8a77ffe1bdd69ae8dcc41da9d37a867329cc
[ 0.0001755897974362597, 0.0001755897974362597, 0.0001755897974362597, 0.0001755897974362597, 0 ]
{ "id": 4, "code_window": [ "}\n", "\n", "declare module '*.vue' {\n", " export default Vue\n", "}\n", "\n", "declare module 'vue' {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " export default Vue\n" ], "file_path": "packages/app/types/shims.d.ts", "type": "replace", "edit_start_line_idx": 27 }
import { join, relative, resolve } from 'upath' import { existsSync, readJSONSync } from 'fs-extra' import consola from 'consola' import globby from 'globby' import { writeFile } from '../utils' import { NitroPreset, NitroContext } from '../context' export const firebase: NitroPreset = { entry: '{{ _internal.runtimeDir }}/entries/firebase', hooks: { async 'nitro:compiled' (ctx: NitroContext) { await writeRoutes(ctx) } } } async function writeRoutes ({ output: { publicDir, serverDir }, _nuxt: { rootDir } }: NitroContext) { if (!existsSync(join(rootDir, 'firebase.json'))) { const firebase = { functions: { source: relative(rootDir, serverDir) }, hosting: [ { site: '<your_project_id>', public: relative(rootDir, publicDir), cleanUrls: true, rewrites: [ { source: '**', function: 'server' } ] } ] } await writeFile(resolve(rootDir, 'firebase.json'), JSON.stringify(firebase)) } const jsons = await globby(`${serverDir}/node_modules/**/package.json`) const prefixLength = `${serverDir}/node_modules/`.length const suffixLength = '/package.json'.length const dependencies = jsons.reduce((obj, packageJson) => { const dirname = packageJson.slice(prefixLength, -suffixLength) if (!dirname.includes('node_modules')) { obj[dirname] = require(packageJson).version } return obj }, {} as Record<string, string>) let nodeVersion = '12' try { const currentNodeVersion = readJSONSync(join(rootDir, 'package.json')).engines.node if (['12', '10'].includes(currentNodeVersion)) { nodeVersion = currentNodeVersion } } catch {} await writeFile( resolve(serverDir, 'package.json'), JSON.stringify( { private: true, main: './index.js', dependencies, devDependencies: { 'firebase-functions-test': 'latest', 'firebase-admin': require('firebase-admin/package.json').version, 'firebase-functions': require('firebase-functions/package.json') .version }, engines: { node: nodeVersion } }, null, 2 ) ) consola.success('Ready to run `firebase deploy`') }
packages/nitro/src/presets/firebase.ts
0
https://github.com/nuxt/nuxt/commit/b53d8a77ffe1bdd69ae8dcc41da9d37a867329cc
[ 0.00018114082922693342, 0.00017376168398186564, 0.00017169967759400606, 0.00017285563808400184, 0.0000028843980999226915 ]
{ "id": 4, "code_window": [ "}\n", "\n", "declare module '*.vue' {\n", " export default Vue\n", "}\n", "\n", "declare module 'vue' {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " export default Vue\n" ], "file_path": "packages/app/types/shims.d.ts", "type": "replace", "edit_start_line_idx": 27 }
import { defineNuxtConfig } from '@nuxt/kit' export default defineNuxtConfig({ })
examples/hello-world/nuxt.config.ts
0
https://github.com/nuxt/nuxt/commit/b53d8a77ffe1bdd69ae8dcc41da9d37a867329cc
[ 0.00017824767564889044, 0.00017824767564889044, 0.00017824767564889044, 0.00017824767564889044, 0 ]
{ "id": 5, "code_window": [ "}\n", "\n", "declare module 'vue' {\n", " interface App {\n", " $nuxt: Nuxt\n", " }\n", "}\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "keep" ], "after_edit": [ " interface App {\n", " $nuxt: Nuxt\n", " }\n" ], "file_path": "packages/app/types/shims.d.ts", "type": "replace", "edit_start_line_idx": 31 }
declare module 'vue' { export interface GlobalComponents { <%= components.map(c => { return ` '${c.pascalName}': typeof import('${c.filePath}')['${c.export}']` }).join(',\n') %> } }
packages/components/src/runtime/components.tmpl.d.ts
1
https://github.com/nuxt/nuxt/commit/b53d8a77ffe1bdd69ae8dcc41da9d37a867329cc
[ 0.00727670406922698, 0.00727670406922698, 0.00727670406922698, 0.00727670406922698, 0 ]
{ "id": 5, "code_window": [ "}\n", "\n", "declare module 'vue' {\n", " interface App {\n", " $nuxt: Nuxt\n", " }\n", "}\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "keep" ], "after_edit": [ " interface App {\n", " $nuxt: Nuxt\n", " }\n" ], "file_path": "packages/app/types/shims.d.ts", "type": "replace", "edit_start_line_idx": 31 }
import { defineNuxtConfig } from '@nuxt/kit' export default defineNuxtConfig({ vite: process.env.NODE_ENV === 'development', modules: [ '~/modules/windicss', '~/modules/content' ] })
docs/src/v3/nuxt.config.ts
0
https://github.com/nuxt/nuxt/commit/b53d8a77ffe1bdd69ae8dcc41da9d37a867329cc
[ 0.0004179336247034371, 0.0004179336247034371, 0.0004179336247034371, 0.0004179336247034371, 0 ]
{ "id": 5, "code_window": [ "}\n", "\n", "declare module 'vue' {\n", " interface App {\n", " $nuxt: Nuxt\n", " }\n", "}\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "keep" ], "after_edit": [ " interface App {\n", " $nuxt: Nuxt\n", " }\n" ], "file_path": "packages/app/types/shims.d.ts", "type": "replace", "edit_start_line_idx": 31 }
import { resolve } from 'path' import { requireModule } from '../utils/cjs' export async function invoke (args) { process.env.NODE_ENV = process.env.NODE_ENV || 'production' const rootDir = resolve(args._[0] || '.') const { loadNuxt, buildNuxt } = requireModule('@nuxt/kit', rootDir) const nuxt = await loadNuxt({ rootDir }) await buildNuxt(nuxt) } export const meta = { usage: 'nu build [rootDir]', description: 'Build nuxt for production deployment' }
packages/cli/src/commands/build.ts
0
https://github.com/nuxt/nuxt/commit/b53d8a77ffe1bdd69ae8dcc41da9d37a867329cc
[ 0.0033066184259951115, 0.00314820627681911, 0.0029897941276431084, 0.00314820627681911, 0.00015841214917600155 ]
{ "id": 5, "code_window": [ "}\n", "\n", "declare module 'vue' {\n", " interface App {\n", " $nuxt: Nuxt\n", " }\n", "}\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "keep" ], "after_edit": [ " interface App {\n", " $nuxt: Nuxt\n", " }\n" ], "file_path": "packages/app/types/shims.d.ts", "type": "replace", "edit_start_line_idx": 31 }
# Change Log All notable changes to this project will be documented in this file. See [Conventional Commits](https://conventionalcommits.org) for commit guidelines. # [0.3.0](https://github.com/nuxt/framework/compare/@nuxt/[email protected]...@nuxt/[email protected]) (2021-06-24) ### Features * **app:** `defineNuxtPlugin` + legacy plugin handling ([#237](https://github.com/nuxt/framework/issues/237)) ([f843568](https://github.com/nuxt/framework/commit/f8435681d4e487ef2446956f557888401dd99d04)) * **pages:** add catchall support (`[...id].vue`) ([#254](https://github.com/nuxt/framework/issues/254)) ([1518a2a](https://github.com/nuxt/framework/commit/1518a2a070ea4cbdf6f61a87b2c2caac9e7ba3d1)) ## [0.2.3](https://github.com/nuxt/framework/compare/@nuxt/[email protected]...@nuxt/[email protected]) (2021-06-16) **Note:** Version bump only for package @nuxt/pages ## [0.2.2](https://github.com/nuxt/framework/compare/@nuxt/[email protected]...@nuxt/[email protected]) (2021-06-04) **Note:** Version bump only for package @nuxt/pages ## [0.2.1](https://github.com/nuxt/framework/compare/@nuxt/[email protected]...@nuxt/[email protected]) (2021-05-24) **Note:** Version bump only for package @nuxt/pages # 0.2.0 (2021-05-20) ### Features * optional pages and refactor nuxt3 ([#142](https://github.com/nuxt/framework/issues/142)) ([6b62d45](https://github.com/nuxt/framework/commit/6b62d456d7fe8c9dd92803a30dcebf0d481f65c7))
packages/pages/CHANGELOG.md
0
https://github.com/nuxt/nuxt/commit/b53d8a77ffe1bdd69ae8dcc41da9d37a867329cc
[ 0.9103373885154724, 0.18220701813697815, 0.00016544802929274738, 0.00016830526874400675, 0.36406517028808594 ]
{ "id": 6, "code_window": [ "}\n", "\n", "export {}" ], "labels": [ "keep", "replace", "replace" ], "after_edit": [], "file_path": "packages/app/types/shims.d.ts", "type": "replace", "edit_start_line_idx": 35 }
declare global { namespace NodeJS { interface Global { __timing__: any $config: any } } } // type export required to turn this into a module for TS augmentation purposes export type A = {}
packages/nitro/src/runtime/types.d.ts
1
https://github.com/nuxt/nuxt/commit/b53d8a77ffe1bdd69ae8dcc41da9d37a867329cc
[ 0.0011078238021582365, 0.000994834117591381, 0.0008818443748168647, 0.000994834117591381, 0.00011298971367068589 ]
{ "id": 6, "code_window": [ "}\n", "\n", "export {}" ], "labels": [ "keep", "replace", "replace" ], "after_edit": [], "file_path": "packages/app/types/shims.d.ts", "type": "replace", "edit_start_line_idx": 35 }
{ "name": "@nuxt/app", "version": "0.5.0", "repository": "nuxt/framework", "license": "MIT", "exports": { ".": "./dist", "./meta": "./meta.js", "./dist/*": "./dist/*" }, "main": "./dist", "module": "./dist", "types": "./types/index.d.ts", "files": [ "dist", "types", "meta.js" ], "scripts": { "prepack": "unbuild" }, "dependencies": { "@vueuse/head": "^0.6.0", "hookable": "^4.4.1", "ohmyfetch": "^0.2.0", "vue": "^3.1.3", "vue-router": "^4.0.10", "vuex5": "^0.5.0-testing.3" }, "devDependencies": { "unbuild": "^0.3.1" } }
packages/app/package.json
0
https://github.com/nuxt/nuxt/commit/b53d8a77ffe1bdd69ae8dcc41da9d37a867329cc
[ 0.00019747571786865592, 0.00017766978999134153, 0.00016574344772379845, 0.00017373001901432872, 0.000013128748832968995 ]
{ "id": 6, "code_window": [ "}\n", "\n", "export {}" ], "labels": [ "keep", "replace", "replace" ], "after_edit": [], "file_path": "packages/app/types/shims.d.ts", "type": "replace", "edit_start_line_idx": 35 }
# Azure Functions > How to deploy Nuxt to Azure Functions with Nuxt Nitro. - Support for serverless SSR build - No configuration required - Static assets served from Azure Function ## Setup ```js [nuxt.config.js] export default { nitro: { preset: 'azure_functions' } } ``` ## Local preview Install [Azure Functions Core Tools](https://docs.microsoft.com/en-us/azure/azure-functions/functions-run-local) if you want to test locally. You can invoke a development environment from the serverless directory. ```bash NITRO_PRESET=azure_functions yarn build cd .output func start ``` You can now visit http://localhost:7071/ in your browser and browse your site running locally on Azure Functions. ## Deploy from your local machine To deploy, just run the following command: ```bash # To publish the bundled zip file az functionapp deployment source config-zip -g <resource-group> -n <app-name> --src dist/deploy.zip # Alternatively you can publish from source cd dist && func azure functionapp publish --javascript <app-name> ``` ## Deploy from CI/CD via GitHub Actions First, obtain your Azure Functions Publish Profile and add it as a secret to your GitHub repository settings following [these instructions](https://github.com/Azure/functions-action#using-publish-profile-as-deployment-credential-recommended). Then create the following file as a workflow: ```yml{}[.github/workflows/azure.yml] name: azure on: push: branches: - main pull_request: branches: - main jobs: deploy: runs-on: ${{ matrix.os }} strategy: matrix: os: [ ubuntu-latest ] node: [ 12 ] steps: - uses: actions/setup-node@v2 with: node-version: ${{ matrix.node }} - name: Checkout uses: actions/checkout@master - name: Get yarn cache directory path id: yarn-cache-dir-path run: echo "::set-output name=dir::$(yarn cache dir)" - uses: actions/cache@v2 id: yarn-cache with: path: ${{ steps.yarn-cache-dir-path.outputs.dir }} key: ${{ runner.os }}-yarn-${{ hashFiles('**/yarn.lock') }} restore-keys: | ${{ runner.os }}-yarn-azure - name: Install Dependencies if: steps.cache.outputs.cache-hit != 'true' run: yarn - name: Build run: npm run build env: NITRO_PRESET: azure - name: 'Deploy to Azure Functions' uses: Azure/functions-action@v1 with: app-name: <your-app-name> package: .output/deploy.zip publish-profile: ${{ secrets.AZURE_FUNCTIONAPP_PUBLISH_PROFILE }} ``` ## Optimizing Azure Functions Consider [turning on immutable packages](https://docs.microsoft.com/en-us/azure/app-service/deploy-run-package) to support running your app from the zipfile. This can speed up cold starts. ## Demo A live demo is available on https://nuxt-nitro.azurewebsites.net/
docs/content/6.deployment/platforms/azure-functions.md
0
https://github.com/nuxt/nuxt/commit/b53d8a77ffe1bdd69ae8dcc41da9d37a867329cc
[ 0.00019258174870628864, 0.00017261062748730183, 0.00016611225146334618, 0.0001685648167040199, 0.000007749699761916418 ]
{ "id": 6, "code_window": [ "}\n", "\n", "export {}" ], "labels": [ "keep", "replace", "replace" ], "after_edit": [], "file_path": "packages/app/types/shims.d.ts", "type": "replace", "edit_start_line_idx": 35 }
import { defineNuxtConfig } from '@nuxt/kit' export default defineNuxtConfig({})
test/fixtures/basic/nuxt.config.ts
0
https://github.com/nuxt/nuxt/commit/b53d8a77ffe1bdd69ae8dcc41da9d37a867329cc
[ 0.0003482302709016949, 0.0003482302709016949, 0.0003482302709016949, 0.0003482302709016949, 0 ]
{ "id": 7, "code_window": [ " return ` '${c.pascalName}': typeof import('${c.filePath}')['${c.export}']`\n", "}).join(',\\n') %>\n", " }\n", "}\n" ], "labels": [ "keep", "keep", "keep", "add" ], "after_edit": [ "\n", "// export required to turn this into a module for TS augmentation purposes\n", "export { }" ], "file_path": "packages/components/src/runtime/components.tmpl.d.ts", "type": "add", "edit_start_line_idx": 7 }
declare global { namespace NodeJS { interface Global { __timing__: any $config: any } } } // type export required to turn this into a module for TS augmentation purposes export type A = {}
packages/nitro/src/runtime/types.d.ts
1
https://github.com/nuxt/nuxt/commit/b53d8a77ffe1bdd69ae8dcc41da9d37a867329cc
[ 0.000718652387149632, 0.00046050178934819996, 0.00020235120609868318, 0.00046050178934819996, 0.000258150597801432 ]
{ "id": 7, "code_window": [ " return ` '${c.pascalName}': typeof import('${c.filePath}')['${c.export}']`\n", "}).join(',\\n') %>\n", " }\n", "}\n" ], "labels": [ "keep", "keep", "keep", "add" ], "after_edit": [ "\n", "// export required to turn this into a module for TS augmentation purposes\n", "export { }" ], "file_path": "packages/components/src/runtime/components.tmpl.d.ts", "type": "add", "edit_start_line_idx": 7 }
<template> <div> 404 | Page Not Found </div> </template>
packages/pages/src/runtime/404.vue
0
https://github.com/nuxt/nuxt/commit/b53d8a77ffe1bdd69ae8dcc41da9d37a867329cc
[ 0.00017313803255092353, 0.00017313803255092353, 0.00017313803255092353, 0.00017313803255092353, 0 ]
{ "id": 7, "code_window": [ " return ` '${c.pascalName}': typeof import('${c.filePath}')['${c.export}']`\n", "}).join(',\\n') %>\n", " }\n", "}\n" ], "labels": [ "keep", "keep", "keep", "add" ], "after_edit": [ "\n", "// export required to turn this into a module for TS augmentation purposes\n", "export { }" ], "file_path": "packages/components/src/runtime/components.tmpl.d.ts", "type": "add", "edit_start_line_idx": 7 }
import { dirname, join, relative, resolve } from 'upath' import { InputOptions, OutputOptions } from 'rollup' import defu from 'defu' import { terser } from 'rollup-plugin-terser' import commonjs from '@rollup/plugin-commonjs' import nodeResolve from '@rollup/plugin-node-resolve' import alias from '@rollup/plugin-alias' import json from '@rollup/plugin-json' import replace from '@rollup/plugin-replace' import virtual from '@rollup/plugin-virtual' import inject from '@rollup/plugin-inject' import analyze from 'rollup-plugin-analyzer' import * as unenv from 'unenv' import type { Preset } from 'unenv' import { NitroContext } from '../context' import { resolvePath, MODULE_DIR } from '../utils' import { dynamicRequire } from './plugins/dynamic-require' import { externals } from './plugins/externals' import { timing } from './plugins/timing' // import { autoMock } from './plugins/automock' import { staticAssets, dirnames } from './plugins/static' import { assets } from './plugins/assets' import { middleware } from './plugins/middleware' import { esbuild } from './plugins/esbuild' import { raw } from './plugins/raw' import { storage } from './plugins/storage' export type RollupConfig = InputOptions & { output: OutputOptions } export const getRollupConfig = (nitroContext: NitroContext) => { const extensions: string[] = ['.ts', '.mjs', '.js', '.json', '.node'] const nodePreset = nitroContext.node === false ? unenv.nodeless : unenv.node const builtinPreset: Preset = { alias: { // General debug: 'unenv/runtime/npm/debug', consola: 'unenv/runtime/npm/consola', // Vue 2 encoding: 'unenv/runtime/mock/proxy', he: 'unenv/runtime/mock/proxy', resolve: 'unenv/runtime/mock/proxy', 'source-map': 'unenv/runtime/mock/proxy', 'lodash.template': 'unenv/runtime/mock/proxy', 'serialize-javascript': 'unenv/runtime/mock/proxy', // Vue 3 'estree-walker': 'unenv/runtime/mock/proxy', '@babel/parser': 'unenv/runtime/mock/proxy', '@vue/compiler-core': 'unenv/runtime/mock/proxy', '@vue/compiler-dom': 'unenv/runtime/mock/proxy', '@vue/compiler-ssr': 'unenv/runtime/mock/proxy' } } const env = unenv.env(nodePreset, builtinPreset, nitroContext.env) delete env.alias['node-fetch'] // FIX ME if (nitroContext.sourceMap) { env.polyfill.push('source-map-support/register') } const buildServerDir = join(nitroContext._nuxt.buildDir, 'dist/server') const runtimeAppDir = join(nitroContext._internal.runtimeDir, 'app') const rollupConfig: RollupConfig = { input: resolvePath(nitroContext, nitroContext.entry), output: { dir: nitroContext.output.serverDir, entryFileNames: 'index.js', chunkFileNames (chunkInfo) { let prefix = '' const modules = Object.keys(chunkInfo.modules) const lastModule = modules[modules.length - 1] if (lastModule.startsWith(buildServerDir)) { prefix = join('app', relative(buildServerDir, dirname(lastModule))) } else if (lastModule.startsWith(runtimeAppDir)) { prefix = 'app' } else if (lastModule.startsWith(nitroContext._nuxt.buildDir)) { prefix = 'nuxt' } else if (lastModule.startsWith(nitroContext._internal.runtimeDir)) { prefix = 'nitro' } else if (!prefix && nitroContext.middleware.find(m => lastModule.startsWith(m.handle as string))) { prefix = 'middleware' } else if (lastModule.includes('assets')) { prefix = 'assets' } return join('chunks', prefix, '[name].js') }, inlineDynamicImports: nitroContext.inlineDynamicImports, format: 'cjs', exports: 'auto', intro: '', outro: '', preferConst: true, sourcemap: nitroContext.sourceMap, sourcemapExcludeSources: true, sourcemapPathTransform (relativePath, sourcemapPath) { return resolve(dirname(sourcemapPath), relativePath) } }, external: env.external, // https://github.com/rollup/rollup/pull/4021#issuecomment-809985618 // https://github.com/nuxt/framework/issues/160 makeAbsoluteExternalsRelative: false, plugins: [], onwarn (warning, rollupWarn) { if ( !['CIRCULAR_DEPENDENCY', 'EVAL'].includes(warning.code) && !warning.message.includes('Unsupported source map comment') ) { rollupWarn(warning) } } } if (nitroContext.timing) { rollupConfig.plugins.push(timing()) } // Raw asset loader rollupConfig.plugins.push(raw()) // https://github.com/rollup/plugins/tree/master/packages/replace rollupConfig.plugins.push(replace({ // @ts-ignore https://github.com/rollup/plugins/pull/810 preventAssignment: true, values: { 'process.env.NODE_ENV': nitroContext._nuxt.dev ? '"development"' : '"production"', 'typeof window': '"undefined"', 'global.': 'globalThis.', 'process.server': 'true', 'process.client': 'false', 'process.env.ROUTER_BASE': JSON.stringify(nitroContext._nuxt.routerBase), 'process.env.PUBLIC_PATH': JSON.stringify(nitroContext._nuxt.publicPath), 'process.env.NUXT_STATIC_BASE': JSON.stringify(nitroContext._nuxt.staticAssets.base), 'process.env.NUXT_STATIC_VERSION': JSON.stringify(nitroContext._nuxt.staticAssets.version), 'process.env.NUXT_FULL_STATIC': nitroContext._nuxt.fullStatic as unknown as string, 'process.env.NITRO_PRESET': JSON.stringify(nitroContext.preset), 'process.env.RUNTIME_CONFIG': JSON.stringify(nitroContext._nuxt.runtimeConfig), 'process.env.DEBUG': JSON.stringify(nitroContext._nuxt.dev) } })) // ESBuild rollupConfig.plugins.push(esbuild({ target: 'es2019', sourceMap: true })) // Dynamic Require Support rollupConfig.plugins.push(dynamicRequire({ dir: resolve(nitroContext._nuxt.buildDir, 'dist/server'), inline: nitroContext.node === false || nitroContext.inlineDynamicImports, globbyOptions: { ignore: [ 'server.js' ] } })) // Assets rollupConfig.plugins.push(assets(nitroContext.assets)) // Static // TODO: use assets plugin if (nitroContext.serveStatic) { rollupConfig.plugins.push(dirnames()) rollupConfig.plugins.push(staticAssets(nitroContext)) } // Storage rollupConfig.plugins.push(storage(nitroContext.storage)) // Middleware rollupConfig.plugins.push(middleware(() => { const _middleware = [ ...nitroContext.scannedMiddleware, ...nitroContext.middleware ] if (nitroContext.serveStatic) { _middleware.unshift({ route: '/', handle: '#nitro/server/static' }) } return _middleware })) // Polyfill rollupConfig.plugins.push(virtual({ '#polyfill': env.polyfill.map(p => `import '${p}';`).join('\n') })) // https://github.com/rollup/plugins/tree/master/packages/alias const renderer = nitroContext.renderer || (nitroContext._nuxt.majorVersion === 3 ? 'vue3' : 'vue2') const vue2ServerRenderer = 'vue-server-renderer/' + (nitroContext._nuxt.dev ? 'build.dev.js' : 'build.prod.js') rollupConfig.plugins.push(alias({ entries: { '#nitro': nitroContext._internal.runtimeDir, '#nitro-renderer': require.resolve(resolve(nitroContext._internal.runtimeDir, 'app', renderer)), '#config': require.resolve(resolve(nitroContext._internal.runtimeDir, 'app/config')), '#nitro-vue-renderer': vue2ServerRenderer, '#build': nitroContext._nuxt.buildDir, '~': nitroContext._nuxt.srcDir, '@/': nitroContext._nuxt.srcDir, '~~': nitroContext._nuxt.rootDir, '@@/': nitroContext._nuxt.rootDir, ...env.alias } })) const moduleDirectories = [ resolve(nitroContext._nuxt.rootDir, 'node_modules'), resolve(MODULE_DIR, 'node_modules'), resolve(MODULE_DIR, '../node_modules'), 'node_modules' ] // Externals Plugin if (nitroContext.externals) { rollupConfig.plugins.push(externals(defu(nitroContext.externals as any, { outDir: nitroContext.output.serverDir, moduleDirectories, external: [ ...(nitroContext._nuxt.dev ? [nitroContext._nuxt.buildDir] : []) ], inline: [ '#', '~', '@/', '~~', '@@/', 'virtual:', nitroContext._internal.runtimeDir, nitroContext._nuxt.srcDir, nitroContext._nuxt.rootDir, nitroContext._nuxt.serverDir, ...nitroContext.middleware.map(m => m.handle), ...(nitroContext._nuxt.dev ? [] : ['vue', '@vue/', '@nuxt/']) ], traceOptions: { base: '/', processCwd: nitroContext._nuxt.rootDir } }))) } // https://github.com/rollup/plugins/tree/master/packages/node-resolve rollupConfig.plugins.push(nodeResolve({ extensions, preferBuiltins: true, rootDir: nitroContext._nuxt.rootDir, moduleDirectories, mainFields: ['main'] // Force resolve CJS (@vue/runtime-core ssrUtils) })) // Automatically mock unresolved externals // rollupConfig.plugins.push(autoMock()) // https://github.com/rollup/plugins/tree/master/packages/commonjs rollupConfig.plugins.push(commonjs({ requireReturnsDefault: 'auto' })) // https://github.com/rollup/plugins/tree/master/packages/json rollupConfig.plugins.push(json()) // https://github.com/rollup/plugins/tree/master/packages/inject rollupConfig.plugins.push(inject(env.inject)) if (nitroContext.analyze) { // https://github.com/doesdev/rollup-plugin-analyzer rollupConfig.plugins.push(analyze()) } // https://github.com/TrySound/rollup-plugin-terser // https://github.com/terser/terser#minify-nitroContext if (nitroContext.minify) { rollupConfig.plugins.push(terser({ mangle: { keep_fnames: true, keep_classnames: true }, format: { comments: false } })) } return rollupConfig }
packages/nitro/src/rollup/config.ts
0
https://github.com/nuxt/nuxt/commit/b53d8a77ffe1bdd69ae8dcc41da9d37a867329cc
[ 0.00017521566769573838, 0.00017072581977117807, 0.00016316633264068514, 0.00017116189701482654, 0.0000029895550142100547 ]
{ "id": 7, "code_window": [ " return ` '${c.pascalName}': typeof import('${c.filePath}')['${c.export}']`\n", "}).join(',\\n') %>\n", " }\n", "}\n" ], "labels": [ "keep", "keep", "keep", "add" ], "after_edit": [ "\n", "// export required to turn this into a module for TS augmentation purposes\n", "export { }" ], "file_path": "packages/components/src/runtime/components.tmpl.d.ts", "type": "add", "edit_start_line_idx": 7 }
import { asyncData } from '@nuxt/app' export { default as NuxtContent } from './content.vue' export function useContent (slug) { return asyncData(`content:${slug}`, () => globalThis.$fetch(`/api/content${slug}`)) }
docs/src/v3/modules/content/runtime/index.ts
0
https://github.com/nuxt/nuxt/commit/b53d8a77ffe1bdd69ae8dcc41da9d37a867329cc
[ 0.000166496800375171, 0.000166496800375171, 0.000166496800375171, 0.000166496800375171, 0 ]
{ "id": 8, "code_window": [ " $config: any\n", " }\n", " }\n", "}\n", "\n", "// type export required to turn this into a module for TS augmentation purposes\n", "export type A = {}\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace" ], "after_edit": [ "// export required to turn this into a module for TS augmentation purposes\n", "export { }" ], "file_path": "packages/nitro/src/runtime/types.d.ts", "type": "replace", "edit_start_line_idx": 9 }
declare global { namespace NodeJS { interface Global { __timing__: any $config: any } } } // type export required to turn this into a module for TS augmentation purposes export type A = {}
packages/nitro/src/runtime/types.d.ts
1
https://github.com/nuxt/nuxt/commit/b53d8a77ffe1bdd69ae8dcc41da9d37a867329cc
[ 0.9976328611373901, 0.8975200653076172, 0.797407329082489, 0.8975200653076172, 0.10011276602745056 ]
{ "id": 8, "code_window": [ " $config: any\n", " }\n", " }\n", "}\n", "\n", "// type export required to turn this into a module for TS augmentation purposes\n", "export type A = {}\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace" ], "after_edit": [ "// export required to turn this into a module for TS augmentation purposes\n", "export { }" ], "file_path": "packages/nitro/src/runtime/types.d.ts", "type": "replace", "edit_start_line_idx": 9 }
export { client } from './client' export { server } from './server'
packages/webpack/src/configs/index.ts
0
https://github.com/nuxt/nuxt/commit/b53d8a77ffe1bdd69ae8dcc41da9d37a867329cc
[ 0.00017346306412946433, 0.00017346306412946433, 0.00017346306412946433, 0.00017346306412946433, 0 ]