repo
stringlengths
5
106
file_url
stringlengths
78
301
file_path
stringlengths
4
211
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 14:56:49
2026-01-05 02:23:25
truncated
bool
2 classes
facebook/create-react-app
https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/packages/react-error-overlay/src/components/Footer.js
packages/react-error-overlay/src/components/Footer.js
/** * Copyright (c) 2015-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ /* @flow */ import React, { useContext } from 'react'; import { ThemeContext } from '../iframeScript'; import type { Theme } from '../styles'; const footerStyle = (theme: Theme) => ({ fontFamily: 'sans-serif', color: theme.footer, marginTop: '0.5rem', flex: '0 0 auto', }); type FooterPropsType = {| line1: string, line2?: string, |}; function Footer(props: FooterPropsType) { const theme = useContext(ThemeContext); return ( <div style={footerStyle(theme)}> {props.line1} <br /> {props.line2} </div> ); } export default Footer;
javascript
MIT
6254386531d263688ccfa542d0e628fbc0de0b28
2026-01-04T14:56:49.538607Z
false
facebook/create-react-app
https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/packages/react-error-overlay/src/components/Header.js
packages/react-error-overlay/src/components/Header.js
/** * Copyright (c) 2015-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ /* @flow */ import React, { useContext } from 'react'; import { ThemeContext } from '../iframeScript'; import type { Theme } from '../styles'; const headerStyle = (theme: Theme) => ({ fontSize: '2em', fontFamily: 'sans-serif', color: theme.headerColor, whiteSpace: 'pre-wrap', // Top bottom margin spaces header // Right margin revents overlap with close button margin: '0 2rem 0.75rem 0', flex: '0 0 auto', maxHeight: '50%', overflow: 'auto', }); type HeaderPropType = {| headerText: string, |}; function Header(props: HeaderPropType) { const theme = useContext(ThemeContext); return <div style={headerStyle(theme)}>{props.headerText}</div>; } export default Header;
javascript
MIT
6254386531d263688ccfa542d0e628fbc0de0b28
2026-01-04T14:56:49.538607Z
false
facebook/create-react-app
https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/packages/react-error-overlay/src/components/ErrorOverlay.js
packages/react-error-overlay/src/components/ErrorOverlay.js
/** * Copyright (c) 2015-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ /* @flow */ import React, { useContext, useEffect } from 'react'; import { ThemeContext } from '../iframeScript'; import type { Node as ReactNode } from 'react'; import type { Theme } from '../styles'; const overlayStyle = (theme: Theme) => ({ position: 'relative', display: 'inline-flex', flexDirection: 'column', height: '100%', width: '1024px', maxWidth: '100%', overflowX: 'hidden', overflowY: 'auto', padding: '0.5rem', boxSizing: 'border-box', textAlign: 'left', fontFamily: 'Consolas, Menlo, monospace', fontSize: '11px', whiteSpace: 'pre-wrap', wordBreak: 'break-word', lineHeight: 1.5, color: theme.color, }); type ErrorOverlayPropsType = {| children: ReactNode, shortcutHandler?: (eventKey: string) => void, |}; let iframeWindow: window = null; function ErrorOverlay(props: ErrorOverlayPropsType) { const theme = useContext(ThemeContext); const getIframeWindow = (element: ?HTMLDivElement) => { if (element) { const document = element.ownerDocument; iframeWindow = document.defaultView; } }; const { shortcutHandler } = props; useEffect(() => { const onKeyDown = (e: KeyboardEvent) => { if (shortcutHandler) { shortcutHandler(e.key); } }; window.addEventListener('keydown', onKeyDown); if (iframeWindow) { iframeWindow.addEventListener('keydown', onKeyDown); } return () => { window.removeEventListener('keydown', onKeyDown); if (iframeWindow) { iframeWindow.removeEventListener('keydown', onKeyDown); } }; }, [shortcutHandler]); return ( <div style={overlayStyle(theme)} ref={getIframeWindow}> {props.children} </div> ); } export default ErrorOverlay;
javascript
MIT
6254386531d263688ccfa542d0e628fbc0de0b28
2026-01-04T14:56:49.538607Z
false
facebook/create-react-app
https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/packages/react-error-overlay/src/components/Collapsible.js
packages/react-error-overlay/src/components/Collapsible.js
/** * Copyright (c) 2015-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ /* @flow */ import React, { useState, useContext } from 'react'; import { ThemeContext } from '../iframeScript'; import type { Element as ReactElement } from 'react'; import type { Theme } from '../styles'; const _collapsibleStyle = { cursor: 'pointer', border: 'none', display: 'block', width: '100%', textAlign: 'left', fontFamily: 'Consolas, Menlo, monospace', fontSize: '1em', padding: '0px', lineHeight: '1.5', }; const collapsibleCollapsedStyle = (theme: Theme) => ({ ..._collapsibleStyle, color: theme.color, background: theme.background, marginBottom: '1.5em', }); const collapsibleExpandedStyle = (theme: Theme) => ({ ..._collapsibleStyle, color: theme.color, background: theme.background, marginBottom: '0.6em', }); type CollapsiblePropsType = {| children: ReactElement<any>[], |}; function Collapsible(props: CollapsiblePropsType) { const theme = useContext(ThemeContext); const [collapsed, setCollapsed] = useState(true); const toggleCollapsed = () => { setCollapsed(!collapsed); }; const count = props.children.length; return ( <div> <button onClick={toggleCollapsed} style={ collapsed ? collapsibleCollapsedStyle(theme) : collapsibleExpandedStyle(theme) } > {(collapsed ? '▶' : '▼') + ` ${count} stack frames were ` + (collapsed ? 'collapsed.' : 'expanded.')} </button> <div style={{ display: collapsed ? 'none' : 'block' }}> {props.children} <button onClick={toggleCollapsed} style={collapsibleExpandedStyle(theme)} > {`▲ ${count} stack frames were expanded.`} </button> </div> </div> ); } export default Collapsible;
javascript
MIT
6254386531d263688ccfa542d0e628fbc0de0b28
2026-01-04T14:56:49.538607Z
false
facebook/create-react-app
https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/packages/react-error-overlay/src/components/NavigationBar.js
packages/react-error-overlay/src/components/NavigationBar.js
/** * Copyright (c) 2015-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ /* @flow */ import React, { useContext } from 'react'; import { ThemeContext } from '../iframeScript'; import type { Theme } from '../styles'; const navigationBarStyle = { marginBottom: '0.5rem', }; const buttonContainerStyle = { marginRight: '1em', }; const _navButtonStyle = { border: 'none', borderRadius: '4px', padding: '3px 6px', cursor: 'pointer', }; const leftButtonStyle = (theme: Theme) => ({ ..._navButtonStyle, backgroundColor: theme.navBackground, color: theme.navArrow, borderTopRightRadius: '0px', borderBottomRightRadius: '0px', marginRight: '1px', }); const rightButtonStyle = (theme: Theme) => ({ ..._navButtonStyle, backgroundColor: theme.navBackground, color: theme.navArrow, borderTopLeftRadius: '0px', borderBottomLeftRadius: '0px', }); type Callback = () => void; type NavigationBarPropsType = {| currentError: number, totalErrors: number, previous: Callback, next: Callback, |}; function NavigationBar(props: NavigationBarPropsType) { const theme = useContext(ThemeContext); const { currentError, totalErrors, previous, next } = props; return ( <div style={navigationBarStyle}> <span style={buttonContainerStyle}> <button onClick={previous} style={leftButtonStyle(theme)}> ← </button> <button onClick={next} style={rightButtonStyle(theme)}> → </button> </span> {`${currentError} of ${totalErrors} errors on the page`} </div> ); } export default NavigationBar;
javascript
MIT
6254386531d263688ccfa542d0e628fbc0de0b28
2026-01-04T14:56:49.538607Z
false
facebook/create-react-app
https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/packages/react-error-overlay/src/components/CloseButton.js
packages/react-error-overlay/src/components/CloseButton.js
/** * Copyright (c) 2015-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ /* @flow */ import React, { useContext } from 'react'; import { ThemeContext } from '../iframeScript'; import type { Theme } from '../styles'; const closeButtonStyle = (theme: Theme) => ({ color: theme.closeColor, lineHeight: '1rem', fontSize: '1.5rem', padding: '1rem', cursor: 'pointer', position: 'absolute', right: 0, top: 0, }); type CloseButtonPropsType = {| close: () => void, |}; function CloseButton({ close }: CloseButtonPropsType) { const theme = useContext(ThemeContext); return ( <span title="Click or press Escape to dismiss." onClick={close} style={closeButtonStyle(theme)} > × </span> ); } export default CloseButton;
javascript
MIT
6254386531d263688ccfa542d0e628fbc0de0b28
2026-01-04T14:56:49.538607Z
false
facebook/create-react-app
https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/packages/react-error-overlay/src/utils/isBultinErrorName.js
packages/react-error-overlay/src/utils/isBultinErrorName.js
/** * Copyright (c) 2015-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ /* @flow */ function isBultinErrorName(errorName: ?string) { switch (errorName) { case 'EvalError': case 'InternalError': case 'RangeError': case 'ReferenceError': case 'SyntaxError': case 'TypeError': case 'URIError': return true; default: return false; } } export { isBultinErrorName }; export default isBultinErrorName;
javascript
MIT
6254386531d263688ccfa542d0e628fbc0de0b28
2026-01-04T14:56:49.538607Z
false
facebook/create-react-app
https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/packages/react-error-overlay/src/utils/generateAnsiHTML.js
packages/react-error-overlay/src/utils/generateAnsiHTML.js
/** * Copyright (c) 2015-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ /* @flow */ import Anser from 'anser'; import { encode } from 'html-entities'; import type { Theme } from '../styles'; // Map ANSI colors from what babel-code-frame uses to base16-github // See: https://github.com/babel/babel/blob/e86f62b304d280d0bab52c38d61842b853848ba6/packages/babel-code-frame/src/index.js#L9-L22 const colors = (theme: Theme) => ({ reset: [theme.base05, 'transparent'], black: theme.base05, red: theme.base08 /* marker, bg-invalid */, green: theme.base0B /* string */, yellow: theme.base08 /* capitalized, jsx_tag, punctuator */, blue: theme.base0C, magenta: theme.base0C /* regex */, cyan: theme.base0E /* keyword */, gray: theme.base03 /* comment, gutter */, lightgrey: theme.base01, darkgrey: theme.base03, }); const anserMap = { 'ansi-bright-black': 'black', 'ansi-bright-yellow': 'yellow', 'ansi-yellow': 'yellow', 'ansi-bright-green': 'green', 'ansi-green': 'green', 'ansi-bright-cyan': 'cyan', 'ansi-cyan': 'cyan', 'ansi-bright-red': 'red', 'ansi-red': 'red', 'ansi-bright-magenta': 'magenta', 'ansi-magenta': 'magenta', 'ansi-white': 'darkgrey', }; function generateAnsiHTML(txt: string, theme: Theme): string { const arr = new Anser().ansiToJson(encode(txt), { use_classes: true, }); let result = ''; let open = false; for (let index = 0; index < arr.length; ++index) { const c = arr[index]; const content = c.content, fg = c.fg; const contentParts = content.split('\n'); for (let _index = 0; _index < contentParts.length; ++_index) { if (!open) { result += '<span data-ansi-line="true">'; open = true; } const part = contentParts[_index].replace('\r', ''); const color = colors(theme)[anserMap[fg]]; if (color != null) { result += '<span style="color: ' + color + ';">' + part + '</span>'; } else { if (fg != null) { console.log('Missing color mapping: ', fg); } result += '<span>' + part + '</span>'; } if (_index < contentParts.length - 1) { result += '</span>'; open = false; result += '<br/>'; } } } if (open) { result += '</span>'; open = false; } return result; } export default generateAnsiHTML;
javascript
MIT
6254386531d263688ccfa542d0e628fbc0de0b28
2026-01-04T14:56:49.538607Z
false
facebook/create-react-app
https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/packages/react-error-overlay/src/utils/unmapper.js
packages/react-error-overlay/src/utils/unmapper.js
/** * Copyright (c) 2015-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ /* @flow */ import StackFrame from './stack-frame'; import { getSourceMap } from './getSourceMap'; import { getLinesAround } from './getLinesAround'; import path from 'path'; function count(search: string, string: string): number { // Count starts at -1 because a do-while loop always runs at least once let count = -1, index = -1; do { // First call or the while case evaluated true, meaning we have to make // count 0 or we found a character ++count; // Find the index of our search string, starting after the previous index index = string.indexOf(search, index + 1); } while (index !== -1); return count; } /** * Turns a set of mapped <code>StackFrame</code>s back into their generated code position and enhances them with code. * @param {string} fileUri The URI of the <code>bundle.js</code> file. * @param {StackFrame[]} frames A set of <code>StackFrame</code>s which are already mapped and missing their generated positions. * @param {number} [fileContents=3] The number of lines to provide before and after the line specified in the <code>StackFrame</code>. */ async function unmap( _fileUri: string | { uri: string, contents: string }, frames: StackFrame[], contextLines: number = 3 ): Promise<StackFrame[]> { let fileContents = typeof _fileUri === 'object' ? _fileUri.contents : null; let fileUri = typeof _fileUri === 'object' ? _fileUri.uri : _fileUri; if (fileContents == null) { fileContents = await fetch(fileUri).then(res => res.text()); } const map = await getSourceMap(fileUri, fileContents); return frames.map(frame => { const { functionName, lineNumber, columnNumber, _originalLineNumber } = frame; if (_originalLineNumber != null) { return frame; } let { fileName } = frame; if (fileName) { // The web version of this module only provides POSIX support, so Windows // paths like C:\foo\\baz\..\\bar\ cannot be normalized. // A simple solution to this is to replace all `\` with `/`, then // normalize afterwards. fileName = path.normalize(fileName.replace(/[\\]+/g, '/')); } if (fileName == null) { return frame; } const fN: string = fileName; const source = map .getSources() // Prepare path for normalization; see comment above for reasoning. .map(s => s.replace(/[\\]+/g, '/')) .filter(p => { p = path.normalize(p); const i = p.lastIndexOf(fN); return i !== -1 && i === p.length - fN.length; }) .map(p => ({ token: p, seps: count(path.sep, path.normalize(p)), penalties: count('node_modules', p) + count('~', p), })) .sort((a, b) => { const s = Math.sign(a.seps - b.seps); if (s !== 0) { return s; } return Math.sign(a.penalties - b.penalties); }); if (source.length < 1 || lineNumber == null) { return new StackFrame( null, null, null, null, null, functionName, fN, lineNumber, columnNumber, null ); } const sourceT = source[0].token; const { line, column } = map.getGeneratedPosition( sourceT, lineNumber, // $FlowFixMe columnNumber ); const originalSource = map.getSource(sourceT); return new StackFrame( functionName, fileUri, line, column || null, getLinesAround(line, contextLines, fileContents || []), functionName, fN, lineNumber, columnNumber, getLinesAround(lineNumber, contextLines, originalSource) ); }); } export { unmap }; export default unmap;
javascript
MIT
6254386531d263688ccfa542d0e628fbc0de0b28
2026-01-04T14:56:49.538607Z
false
facebook/create-react-app
https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/packages/react-error-overlay/src/utils/warnings.js
packages/react-error-overlay/src/utils/warnings.js
/** * Copyright (c) 2015-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ /* @flow */ import type { ReactFrame } from '../effects/proxyConsole'; function stripInlineStacktrace(message: string): string { return message .split('\n') .filter(line => !line.match(/^\s*in/)) .join('\n'); // " in Foo" } function massage( warning: string, frames: ReactFrame[] ): { message: string, stack: string } { let message = stripInlineStacktrace(warning); // Reassemble the stack with full filenames provided by React let stack = ''; let lastFilename; let lastLineNumber; for (let index = 0; index < frames.length; ++index) { const { fileName, lineNumber } = frames[index]; if (fileName == null || lineNumber == null) { continue; } // TODO: instead, collapse them in the UI if ( fileName === lastFilename && typeof lineNumber === 'number' && typeof lastLineNumber === 'number' && Math.abs(lineNumber - lastLineNumber) < 3 ) { continue; } lastFilename = fileName; lastLineNumber = lineNumber; let { name } = frames[index]; name = name || '(anonymous function)'; stack += `in ${name} (at ${fileName}:${lineNumber})\n`; } return { message, stack }; } export { massage };
javascript
MIT
6254386531d263688ccfa542d0e628fbc0de0b28
2026-01-04T14:56:49.538607Z
false
facebook/create-react-app
https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/packages/react-error-overlay/src/utils/isInternalFile.js
packages/react-error-overlay/src/utils/isInternalFile.js
/** * Copyright (c) 2015-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ /* @flow */ function isInternalFile(sourceFileName: ?string, fileName: ?string) { return ( sourceFileName == null || sourceFileName === '' || sourceFileName.indexOf('/~/') !== -1 || sourceFileName.indexOf('/node_modules/') !== -1 || sourceFileName.trim().indexOf(' ') !== -1 || fileName == null || fileName === '' ); } export { isInternalFile };
javascript
MIT
6254386531d263688ccfa542d0e628fbc0de0b28
2026-01-04T14:56:49.538607Z
false
facebook/create-react-app
https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/packages/react-error-overlay/src/utils/mapper.js
packages/react-error-overlay/src/utils/mapper.js
/** * Copyright (c) 2015-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ /* @flow */ import StackFrame from './stack-frame'; import { getSourceMap } from './getSourceMap'; import { getLinesAround } from './getLinesAround'; import { settle } from 'settle-promise'; /** * Enhances a set of <code>StackFrame</code>s with their original positions and code (when available). * @param {StackFrame[]} frames A set of <code>StackFrame</code>s which contain (generated) code positions. * @param {number} [contextLines=3] The number of lines to provide before and after the line specified in the <code>StackFrame</code>. */ async function map( frames: StackFrame[], contextLines: number = 3 ): Promise<StackFrame[]> { const cache: any = {}; const files: string[] = []; frames.forEach(frame => { const { fileName } = frame; if (fileName == null) { return; } if (files.indexOf(fileName) !== -1) { return; } files.push(fileName); }); await settle( files.map(async fileName => { const fetchUrl = fileName.indexOf('webpack-internal:') === 0 ? `/__get-internal-source?fileName=${encodeURIComponent(fileName)}` : fileName; const fileSource = await fetch(fetchUrl).then(r => r.text()); const map = await getSourceMap(fileName, fileSource); cache[fileName] = { fileSource, map }; }) ); return frames.map(frame => { const { functionName, fileName, lineNumber, columnNumber } = frame; let { map, fileSource } = cache[fileName] || {}; if (map == null || lineNumber == null) { return frame; } const { source, line, column } = map.getOriginalPosition( lineNumber, columnNumber ); const originalSource = source == null ? [] : map.getSource(source); return new StackFrame( functionName, fileName, lineNumber, columnNumber, getLinesAround(lineNumber, contextLines, fileSource), functionName, source, line, column, getLinesAround(line, contextLines, originalSource) ); }); } export { map }; export default map;
javascript
MIT
6254386531d263688ccfa542d0e628fbc0de0b28
2026-01-04T14:56:49.538607Z
false
facebook/create-react-app
https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/packages/react-error-overlay/src/utils/getPrettyURL.js
packages/react-error-overlay/src/utils/getPrettyURL.js
/** * Copyright (c) 2015-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ /* @flow */ function getPrettyURL( sourceFileName: ?string, sourceLineNumber: ?number, sourceColumnNumber: ?number, fileName: ?string, lineNumber: ?number, columnNumber: ?number, compiled: boolean ): string { let prettyURL; if (!compiled && sourceFileName && typeof sourceLineNumber === 'number') { // Remove everything up to the first /src/ or /node_modules/ const trimMatch = /^[/|\\].*?[/|\\]((src|node_modules)[/|\\].*)/.exec( sourceFileName ); if (trimMatch && trimMatch[1]) { prettyURL = trimMatch[1]; } else { prettyURL = sourceFileName; } prettyURL += ':' + sourceLineNumber; // Note: we intentionally skip 0's because they're produced by cheap webpack maps if (sourceColumnNumber) { prettyURL += ':' + sourceColumnNumber; } } else if (fileName && typeof lineNumber === 'number') { prettyURL = fileName + ':' + lineNumber; // Note: we intentionally skip 0's because they're produced by cheap webpack maps if (columnNumber) { prettyURL += ':' + columnNumber; } } else { prettyURL = 'unknown'; } return prettyURL.replace('webpack://', '.'); } export { getPrettyURL }; export default getPrettyURL;
javascript
MIT
6254386531d263688ccfa542d0e628fbc0de0b28
2026-01-04T14:56:49.538607Z
false
facebook/create-react-app
https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/packages/react-error-overlay/src/utils/getSourceMap.js
packages/react-error-overlay/src/utils/getSourceMap.js
/** * Copyright (c) 2015-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ /* @flow */ import { SourceMapConsumer } from 'source-map'; /** * A wrapped instance of a <code>{@link https://github.com/mozilla/source-map SourceMapConsumer}</code>. * * This exposes methods which will be indifferent to changes made in <code>{@link https://github.com/mozilla/source-map source-map}</code>. */ class SourceMap { __source_map: SourceMapConsumer; // $FlowFixMe constructor(sourceMap) { this.__source_map = sourceMap; } /** * Returns the original code position for a generated code position. * @param {number} line The line of the generated code position. * @param {number} column The column of the generated code position. */ getOriginalPosition( line: number, column: number ): { source: string, line: number, column: number } { const { line: l, column: c, source: s, } = this.__source_map.originalPositionFor({ line, column, }); return { line: l, column: c, source: s }; } /** * Returns the generated code position for an original position. * @param {string} source The source file of the original code position. * @param {number} line The line of the original code position. * @param {number} column The column of the original code position. */ getGeneratedPosition( source: string, line: number, column: number ): { line: number, column: number } { const { line: l, column: c } = this.__source_map.generatedPositionFor({ source, line, column, }); return { line: l, column: c, }; } /** * Returns the code for a given source file name. * @param {string} sourceName The name of the source file. */ getSource(sourceName: string): string { return this.__source_map.sourceContentFor(sourceName); } getSources(): string[] { return this.__source_map.sources; } } function extractSourceMapUrl( fileUri: string, fileContents: string ): Promise<string> { const regex = /\/\/[#@] ?sourceMappingURL=([^\s'"]+)\s*$/gm; let match = null; for (;;) { let next = regex.exec(fileContents); if (next == null) { break; } match = next; } if (!(match && match[1])) { return Promise.reject(`Cannot find a source map directive for ${fileUri}.`); } return Promise.resolve(match[1].toString()); } /** * Returns an instance of <code>{@link SourceMap}</code> for a given fileUri and fileContents. * @param {string} fileUri The URI of the source file. * @param {string} fileContents The contents of the source file. */ async function getSourceMap( fileUri: string, fileContents: string ): Promise<SourceMap> { let sm = await extractSourceMapUrl(fileUri, fileContents); if (sm.indexOf('data:') === 0) { const base64 = /^data:application\/json;([\w=:"-]+;)*base64,/; const match2 = sm.match(base64); if (!match2) { throw new Error( 'Sorry, non-base64 inline source-map encoding is not supported.' ); } sm = sm.substring(match2[0].length); sm = window.atob(sm); sm = JSON.parse(sm); return new SourceMap(new SourceMapConsumer(sm)); } else { const index = fileUri.lastIndexOf('/'); const url = fileUri.substring(0, index + 1) + sm; const obj = await fetch(url).then(res => res.json()); return new SourceMap(new SourceMapConsumer(obj)); } } export { extractSourceMapUrl, getSourceMap }; export default getSourceMap;
javascript
MIT
6254386531d263688ccfa542d0e628fbc0de0b28
2026-01-04T14:56:49.538607Z
false
facebook/create-react-app
https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/packages/react-error-overlay/src/utils/getLinesAround.js
packages/react-error-overlay/src/utils/getLinesAround.js
/** * Copyright (c) 2015-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ /* @flow */ import { ScriptLine } from './stack-frame'; /** * * @param {number} line The line number to provide context around. * @param {number} count The number of lines you'd like for context. * @param {string[] | string} lines The source code. */ function getLinesAround( line: number, count: number, lines: string[] | string ): ScriptLine[] { if (typeof lines === 'string') { lines = lines.split('\n'); } const result = []; for ( let index = Math.max(0, line - 1 - count); index <= Math.min(lines.length - 1, line - 1 + count); ++index ) { result.push(new ScriptLine(index + 1, lines[index], index === line - 1)); } return result; } export { getLinesAround }; export default getLinesAround;
javascript
MIT
6254386531d263688ccfa542d0e628fbc0de0b28
2026-01-04T14:56:49.538607Z
false
facebook/create-react-app
https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/packages/react-error-overlay/src/utils/parser.js
packages/react-error-overlay/src/utils/parser.js
/** * Copyright (c) 2015-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ /* @flow */ import StackFrame from './stack-frame'; const regexExtractLocation = /\(?(.+?)(?::(\d+))?(?::(\d+))?\)?$/; // $FlowFixMe function extractLocation(token: string): [string, number, number] { return ( regexExtractLocation .exec(token) // $FlowFixMe .slice(1) .map(v => { const p = Number(v); if (!isNaN(p)) { return p; } return v; }) ); } const regexValidFrame_Chrome = /^\s*(at|in)\s.+(:\d+)/; const regexValidFrame_FireFox = /(^|@)\S+:\d+|.+line\s+\d+\s+>\s+(eval|Function).+/; function parseStack(stack: string[]): StackFrame[] { const frames = stack .filter( e => regexValidFrame_Chrome.test(e) || regexValidFrame_FireFox.test(e) ) .map(e => { if (regexValidFrame_FireFox.test(e)) { // Strip eval, we don't care about it let isEval = false; if (/ > (eval|Function)/.test(e)) { e = e.replace( / line (\d+)(?: > eval line \d+)* > (eval|Function):\d+:\d+/g, ':$1' ); isEval = true; } const data = e.split(/[@]/g); const last = data.pop(); return new StackFrame( data.join('@') || (isEval ? 'eval' : null), ...extractLocation(last) ); } else { // Strip eval, we don't care about it if (e.indexOf('(eval ') !== -1) { e = e.replace(/(\(eval at [^()]*)|(\),.*$)/g, ''); } if (e.indexOf('(at ') !== -1) { e = e.replace(/\(at /, '('); } const data = e.trim().split(/\s+/g).slice(1); const last = data.pop(); return new StackFrame(data.join(' ') || null, ...extractLocation(last)); } }); return frames; } /** * Turns an <code>Error</code>, or similar object, into a set of <code>StackFrame</code>s. * @alias parse */ function parseError(error: Error | string | string[]): StackFrame[] { if (error == null) { throw new Error('You cannot pass a null object.'); } if (typeof error === 'string') { return parseStack(error.split('\n')); } if (Array.isArray(error)) { return parseStack(error); } if (typeof error.stack === 'string') { return parseStack(error.stack.split('\n')); } throw new Error('The error you provided does not contain a stack trace.'); } export { parseError as parse }; export default parseError;
javascript
MIT
6254386531d263688ccfa542d0e628fbc0de0b28
2026-01-04T14:56:49.538607Z
false
facebook/create-react-app
https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/packages/react-error-overlay/src/utils/parseCompileError.js
packages/react-error-overlay/src/utils/parseCompileError.js
// @flow import Anser from 'anser'; export type ErrorLocation = {| fileName: string, lineNumber: number, colNumber?: number, |}; const filePathRegex = /^\.(\/[^/\n ]+)+\.[^/\n ]+$/; const lineNumberRegexes = [ // Babel syntax errors // Based on syntax error formating of babylon parser // https://github.com/babel/babylon/blob/v7.0.0-beta.22/src/parser/location.js#L19 /^.*\((\d+):(\d+)\)$/, // ESLint errors // Based on eslintFormatter in react-dev-utils /^Line (\d+):.+$/, ]; // Based on error formatting of webpack // https://github.com/webpack/webpack/blob/v3.5.5/lib/Stats.js#L183-L217 function parseCompileError(message: string): ?ErrorLocation { const lines: Array<string> = message.split('\n'); let fileName: string = ''; let lineNumber: number = 0; let colNumber: number = 0; for (let i = 0; i < lines.length; i++) { const line: string = Anser.ansiToText(lines[i]).trim(); if (!line) { continue; } if (!fileName && line.match(filePathRegex)) { fileName = line; } let k = 0; while (k < lineNumberRegexes.length) { const match: ?Array<string> = line.match(lineNumberRegexes[k]); if (match) { lineNumber = parseInt(match[1], 10); // colNumber starts with 0 and hence add 1 colNumber = parseInt(match[2], 10) + 1 || 1; break; } k++; } if (fileName && lineNumber) { break; } } return fileName && lineNumber ? { fileName, lineNumber, colNumber } : null; } export default parseCompileError;
javascript
MIT
6254386531d263688ccfa542d0e628fbc0de0b28
2026-01-04T14:56:49.538607Z
false
facebook/create-react-app
https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/packages/react-error-overlay/src/utils/stack-frame.js
packages/react-error-overlay/src/utils/stack-frame.js
/** * Copyright (c) 2015-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ /* @flow */ /** A container holding a script line. */ class ScriptLine { /** The line number of this line of source. */ lineNumber: number; /** The content (or value) of this line of source. */ content: string; /** Whether or not this line should be highlighted. Particularly useful for error reporting with context. */ highlight: boolean; constructor(lineNumber: number, content: string, highlight: boolean = false) { this.lineNumber = lineNumber; this.content = content; this.highlight = highlight; } } /** * A representation of a stack frame. */ class StackFrame { functionName: string | null; fileName: string | null; lineNumber: number | null; columnNumber: number | null; _originalFunctionName: string | null; _originalFileName: string | null; _originalLineNumber: number | null; _originalColumnNumber: number | null; _scriptCode: ScriptLine[] | null; _originalScriptCode: ScriptLine[] | null; constructor( functionName: string | null = null, fileName: string | null = null, lineNumber: number | null = null, columnNumber: number | null = null, scriptCode: ScriptLine[] | null = null, sourceFunctionName: string | null = null, sourceFileName: string | null = null, sourceLineNumber: number | null = null, sourceColumnNumber: number | null = null, sourceScriptCode: ScriptLine[] | null = null ) { if (functionName && functionName.indexOf('Object.') === 0) { functionName = functionName.slice('Object.'.length); } if ( // Chrome has a bug with inferring function.name: // https://github.com/facebook/create-react-app/issues/2097 // Let's ignore a meaningless name we get for top-level modules. functionName === 'friendlySyntaxErrorLabel' || functionName === 'exports.__esModule' || functionName === '<anonymous>' || !functionName ) { functionName = null; } this.functionName = functionName; this.fileName = fileName; this.lineNumber = lineNumber; this.columnNumber = columnNumber; this._originalFunctionName = sourceFunctionName; this._originalFileName = sourceFileName; this._originalLineNumber = sourceLineNumber; this._originalColumnNumber = sourceColumnNumber; this._scriptCode = scriptCode; this._originalScriptCode = sourceScriptCode; } /** * Returns the name of this function. */ getFunctionName(): string { return this.functionName || '(anonymous function)'; } /** * Returns the source of the frame. * This contains the file name, line number, and column number when available. */ getSource(): string { let str = ''; if (this.fileName != null) { str += this.fileName + ':'; } if (this.lineNumber != null) { str += this.lineNumber + ':'; } if (this.columnNumber != null) { str += this.columnNumber + ':'; } return str.slice(0, -1); } /** * Returns a pretty version of this stack frame. */ toString(): string { const functionName = this.getFunctionName(); const source = this.getSource(); return `${functionName}${source ? ` (${source})` : ``}`; } } export { StackFrame, ScriptLine }; export default StackFrame;
javascript
MIT
6254386531d263688ccfa542d0e628fbc0de0b28
2026-01-04T14:56:49.538607Z
false
facebook/create-react-app
https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/packages/react-error-overlay/src/utils/getStackFrames.js
packages/react-error-overlay/src/utils/getStackFrames.js
/** * Copyright (c) 2015-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ /* @flow */ import type { StackFrame } from './stack-frame'; import { parse } from './parser'; import { map } from './mapper'; import { unmap } from './unmapper'; function getStackFrames( error: Error, unhandledRejection: boolean = false, contextSize: number = 3 ): Promise<StackFrame[] | null> { const parsedFrames = parse(error); let enhancedFramesPromise; // $FlowFixMe if (error.__unmap_source) { enhancedFramesPromise = unmap( // $FlowFixMe error.__unmap_source, parsedFrames, contextSize ); } else { enhancedFramesPromise = map(parsedFrames, contextSize); } return enhancedFramesPromise.then(enhancedFrames => { if ( enhancedFrames .map(f => f._originalFileName) .filter(f => f != null && f.indexOf('node_modules') === -1).length === 0 ) { return null; } return enhancedFrames.filter( ({ functionName }) => functionName == null || functionName.indexOf('__stack_frame_overlay_proxy_console__') === -1 ); }); } export default getStackFrames; export { getStackFrames };
javascript
MIT
6254386531d263688ccfa542d0e628fbc0de0b28
2026-01-04T14:56:49.538607Z
false
facebook/create-react-app
https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/packages/react-error-overlay/src/utils/dom/css.js
packages/react-error-overlay/src/utils/dom/css.js
/** * Copyright (c) 2015-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ /* @flow */ import { lightTheme, darkTheme } from '../../styles'; let injectedCount = 0; const injectedCache = {}; function getHead(document: Document) { return document.head || document.getElementsByTagName('head')[0]; } function injectCss(document: Document, css: string): number { const head = getHead(document); const style = document.createElement('style'); style.type = 'text/css'; style.appendChild(document.createTextNode(css)); head.appendChild(style); injectedCache[++injectedCount] = style; return injectedCount; } function removeCss(document: Document, ref: number) { if (injectedCache[ref] == null) { return; } const head = getHead(document); head.removeChild(injectedCache[ref]); delete injectedCache[ref]; } function applyStyles(element: HTMLElement, styles: Object) { element.setAttribute('style', ''); for (const key in styles) { if (!Object.prototype.hasOwnProperty.call(styles, key)) { continue; } // $FlowFixMe element.style[key] = styles[key]; } } function getTheme() { return window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches ? darkTheme : lightTheme; } export { getHead, injectCss, removeCss, applyStyles, getTheme };
javascript
MIT
6254386531d263688ccfa542d0e628fbc0de0b28
2026-01-04T14:56:49.538607Z
false
facebook/create-react-app
https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/packages/react-error-overlay/src/utils/dom/absolutifyCaret.js
packages/react-error-overlay/src/utils/dom/absolutifyCaret.js
/** * Copyright (c) 2015-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ /* @flow */ function removeNextBr(parent, component: ?Element) { while (component != null && component.tagName.toLowerCase() !== 'br') { component = component.nextElementSibling; } if (component != null) { parent.removeChild(component); } } function absolutifyCaret(component: Node) { const ccn = component.childNodes; for (let index = 0; index < ccn.length; ++index) { const c = ccn[index]; // $FlowFixMe if (c.tagName.toLowerCase() !== 'span') { continue; } const _text = c.innerText; if (_text == null) { continue; } const text = _text.replace(/\s/g, ''); if (text !== '|^') { continue; } // $FlowFixMe c.style.position = 'absolute'; // $FlowFixMe removeNextBr(component, c); } } export { absolutifyCaret };
javascript
MIT
6254386531d263688ccfa542d0e628fbc0de0b28
2026-01-04T14:56:49.538607Z
false
facebook/create-react-app
https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/packages/react-error-overlay/src/__tests__/unmapper.js
packages/react-error-overlay/src/__tests__/unmapper.js
/** * Copyright (c) 2015-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import { unmap } from '../utils/unmapper'; import { parse } from '../utils/parser'; import fs from 'fs'; import { resolve } from 'path'; test('basic warning', async () => { expect.assertions(2); const error = `Warning: Each child in an array or iterator should have a unique "key" prop. Check the render method of \`B\`. See https://fb.me/react-warning-keys for more information. in div (at B.js:8) in B (at A.js:6) in A (at App.js:8) in div (at App.js:10) in App (at index.js:6)`; fetch.mockResponseOnce( fs .readFileSync(resolve(__dirname, '../../fixtures/bundle_u.mjs')) .toString('utf8') ); fetch.mockResponseOnce( fs .readFileSync(resolve(__dirname, '../../fixtures/bundle_u.mjs.map')) .toString('utf8') ); const frames = await unmap('/static/js/bundle.js', parse(error), 0); const expected = JSON.parse( fs .readFileSync(resolve(__dirname, '../../fixtures/bundle2.json')) .toString('utf8') ); expect(frames).toEqual(expected); fetch.mockResponseOnce( fs .readFileSync(resolve(__dirname, '../../fixtures/bundle_u.mjs')) .toString('utf8') ); fetch.mockResponseOnce( fs .readFileSync(resolve(__dirname, '../../fixtures/bundle_u.mjs.map')) .toString('utf8') ); expect(await unmap('/static/js/bundle.js', expected)).toEqual(expected); }); test('default context & unfound source', async () => { expect.assertions(1); const error = `Warning: Each child in an array or iterator should have a unique "key" prop. Check the render method of \`B\`. See https://fb.me/react-warning-keys for more information. in div (at B.js:8) in unknown (at blabla.js:10)`; fetch.mockResponseOnce( fs .readFileSync(resolve(__dirname, '../../fixtures/bundle_u.mjs')) .toString('utf8') ); fetch.mockResponseOnce( fs .readFileSync(resolve(__dirname, '../../fixtures/bundle_u.mjs.map')) .toString('utf8') ); const frames = await unmap('/static/js/bundle.js', parse(error)); expect(frames).toMatchSnapshot(); });
javascript
MIT
6254386531d263688ccfa542d0e628fbc0de0b28
2026-01-04T14:56:49.538607Z
false
facebook/create-react-app
https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/packages/react-error-overlay/src/__tests__/mapper.js
packages/react-error-overlay/src/__tests__/mapper.js
/** * Copyright (c) 2015-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import { map } from '../utils/mapper'; import { parse } from '../utils/parser'; import fs from 'fs'; import { resolve } from 'path'; test('basic error; 0 context', async () => { expect.assertions(1); const error = 'TypeError: document.body.missing is not a function\n at App.componentDidMount (http://localhost:3000/static/js/bundle.js:26122:21)\n at http://localhost:3000/static/js/bundle.js:30091:25\n at measureLifeCyclePerf (http://localhost:3000/static/js/bundle.js:29901:12)\n at http://localhost:3000/static/js/bundle.js:30090:11\n at CallbackQueue.notifyAll (http://localhost:3000/static/js/bundle.js:13256:22)\n at ReactReconcileTransaction.close (http://localhost:3000/static/js/bundle.js:35124:26)\n at ReactReconcileTransaction.closeAll (http://localhost:3000/static/js/bundle.js:7390:25)\n at ReactReconcileTransaction.perform (http://localhost:3000/static/js/bundle.js:7337:16)\n at batchedMountComponentIntoNode (http://localhost:3000/static/js/bundle.js:14204:15)\n at ReactDefaultBatchingStrategyTransaction.perform (http://localhost:3000/static/js/bundle.js:7324:20)\n at Object.batchedUpdates (http://localhost:3000/static/js/bundle.js:33900:26)\n at Object.batchedUpdates (http://localhost:3000/static/js/bundle.js:2181:27)\n at Object._renderNewRootComponent (http://localhost:3000/static/js/bundle.js:14398:18)\n at Object._renderSubtreeIntoContainer (http://localhost:3000/static/js/bundle.js:14479:32)\n at Object.render (http://localhost:3000/static/js/bundle.js:14500:23)\n at Object.friendlySyntaxErrorLabel (http://localhost:3000/static/js/bundle.js:17287:20)\n at __webpack_require__ (http://localhost:3000/static/js/bundle.js:660:30)\n at fn (http://localhost:3000/static/js/bundle.js:84:20)\n at Object.<anonymous> (http://localhost:3000/static/js/bundle.js:41219:18)\n at __webpack_require__ (http://localhost:3000/static/js/bundle.js:660:30)\n at validateFormat (http://localhost:3000/static/js/bundle.js:709:39)\n at http://localhost:3000/static/js/bundle.js:712:10'; fetch.mockResponseOnce( fs .readFileSync(resolve(__dirname, '../../fixtures/bundle.mjs')) .toString('utf8') ); fetch.mockResponseOnce( fs .readFileSync(resolve(__dirname, '../../fixtures/bundle.mjs.map')) .toString('utf8') ); const frames = await map(parse(error), 0); expect(frames).toEqual( JSON.parse( fs .readFileSync(resolve(__dirname, '../../fixtures/bundle.json')) .toString('utf8') ) ); }); test('default context (3)', async () => { expect.assertions(1); const error = 'TypeError: document.body.missing is not a function\n at App.componentDidMount (http://localhost:3000/static/js/bundle.js:26122:21)'; fetch.mockResponseOnce( fs .readFileSync(resolve(__dirname, '../../fixtures/bundle.mjs')) .toString('utf8') ); fetch.mockResponseOnce( fs .readFileSync(resolve(__dirname, '../../fixtures/bundle.mjs.map')) .toString('utf8') ); const frames = await map(parse(error)); expect(frames).toEqual( JSON.parse( fs .readFileSync(resolve(__dirname, '../../fixtures/bundle-default.json')) .toString('utf8') ) ); }); test('bad comes back same', async () => { expect.assertions(2); const error = 'TypeError: document.body.missing is not a function\n at App.componentDidMount (A:1:2)'; const orig = parse(error); expect(orig).toEqual([ { _originalColumnNumber: null, _originalFileName: null, _originalFunctionName: null, _originalLineNumber: null, _originalScriptCode: null, _scriptCode: null, columnNumber: 2, fileName: 'A', functionName: 'App.componentDidMount', lineNumber: 1, }, ]); const frames = await map(orig); expect(frames).toEqual(orig); });
javascript
MIT
6254386531d263688ccfa542d0e628fbc0de0b28
2026-01-04T14:56:49.538607Z
false
facebook/create-react-app
https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/packages/react-error-overlay/src/__tests__/extract-source-map.js
packages/react-error-overlay/src/__tests__/extract-source-map.js
/** * Copyright (c) 2015-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import { extractSourceMapUrl } from '../utils/getSourceMap'; test('extracts last source map directive', async () => { const res = await extractSourceMapUrl( `test.js`, `//# sourceMappingURL=test.js.map\nconsole.log('a')\n//# sourceMappingURL=bundle.js.map` ); expect(res).toBe('bundle.js.map'); }); test('errors when no source map', async () => { const testFileName = 'test.js'; let error; try { await extractSourceMapUrl( testFileName, `console.log('hi')\n\nconsole.log('bye')` ); } catch (e) { error = e; } expect(error).toBe(`Cannot find a source map directive for ${testFileName}.`); });
javascript
MIT
6254386531d263688ccfa542d0e628fbc0de0b28
2026-01-04T14:56:49.538607Z
false
facebook/create-react-app
https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/packages/react-error-overlay/src/__tests__/get-source-map.js
packages/react-error-overlay/src/__tests__/get-source-map.js
/** * Copyright (c) 2015-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @jest-environment jsdom */ import { getSourceMap } from '../utils/getSourceMap'; import fs from 'fs'; import { resolve } from 'path'; test('finds an external source map', async () => { const file = fs .readFileSync(resolve(__dirname, '../../fixtures/bundle.mjs')) .toString('utf8'); fetch.mockResponseOnce( fs .readFileSync(resolve(__dirname, '../../fixtures/bundle.mjs.map')) .toString('utf8') ); const sm = await getSourceMap('/', file); expect(sm.getOriginalPosition(26122, 21)).toEqual({ line: 7, column: 0, source: 'webpack:///packages/react-scripts/template/src/App.js', }); }); test('find an inline source map', async () => { const sourceName = 'test.js'; const file = fs .readFileSync(resolve(__dirname, '../../fixtures/inline.mjs')) .toString('utf8'); const fileO = fs .readFileSync(resolve(__dirname, '../../fixtures/inline.es6.mjs')) .toString('utf8'); const sm = await getSourceMap('/', file); expect(sm.getSources()).toEqual([sourceName]); expect(sm.getSource(sourceName)).toBe(fileO); expect(sm.getGeneratedPosition(sourceName, 5, 10)).toEqual({ line: 10, column: 8, }); }); test('error on a source map with unsupported encoding', async () => { expect.assertions(2); const file = fs .readFileSync(resolve(__dirname, '../../fixtures/junk-inline.mjs')) .toString('utf8'); let error; try { await getSourceMap('/', file); } catch (e) { error = e; } expect(error instanceof Error).toBe(true); expect(error.message).toBe( 'Sorry, non-base64 inline source-map encoding is not supported.' ); });
javascript
MIT
6254386531d263688ccfa542d0e628fbc0de0b28
2026-01-04T14:56:49.538607Z
false
facebook/create-react-app
https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/packages/react-error-overlay/src/__tests__/setupJest.js
packages/react-error-overlay/src/__tests__/setupJest.js
/** * Copyright (c) 2015-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ global.fetch = require('jest-fetch-mock');
javascript
MIT
6254386531d263688ccfa542d0e628fbc0de0b28
2026-01-04T14:56:49.538607Z
false
facebook/create-react-app
https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/packages/react-error-overlay/src/__tests__/script-lines.js
packages/react-error-overlay/src/__tests__/script-lines.js
/** * Copyright (c) 2015-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import { ScriptLine } from '../utils/stack-frame'; test('script line shape', () => { expect(new ScriptLine(5, 'foobar', true)).toMatchSnapshot(); }); test('script line to provide default highlight', () => { expect(new ScriptLine(5, 'foobar')).toMatchSnapshot(); });
javascript
MIT
6254386531d263688ccfa542d0e628fbc0de0b28
2026-01-04T14:56:49.538607Z
false
facebook/create-react-app
https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/packages/react-error-overlay/src/__tests__/stack-frame.js
packages/react-error-overlay/src/__tests__/stack-frame.js
/** * Copyright (c) 2015-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import { StackFrame } from '../utils/stack-frame'; test('proper empty shape', () => { const empty = new StackFrame(); expect(empty).toMatchSnapshot(); expect(empty.getFunctionName()).toBe('(anonymous function)'); expect(empty.getSource()).toBe(''); expect(empty.toString()).toBe('(anonymous function)'); }); test('proper full shape', () => { const empty = new StackFrame( 'a', 'b.js', 13, 37, undefined, 'apple', 'test.js', 37, 13 ); expect(empty).toMatchSnapshot(); expect(empty.getFunctionName()).toBe('a'); expect(empty.getSource()).toBe('b.js:13:37'); expect(empty.toString()).toBe('a (b.js:13:37)'); });
javascript
MIT
6254386531d263688ccfa542d0e628fbc0de0b28
2026-01-04T14:56:49.538607Z
false
facebook/create-react-app
https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/packages/react-error-overlay/src/__tests__/lines-around.js
packages/react-error-overlay/src/__tests__/lines-around.js
/** * Copyright (c) 2015-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import { getLinesAround } from '../utils/getLinesAround'; const arr = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight']; test('should return lines around from a string', () => { expect(getLinesAround(4, 2, arr)).toMatchSnapshot(); }); test('should return lines around from an array', () => { expect(getLinesAround(4, 2, arr.join('\n'))).toMatchSnapshot(); });
javascript
MIT
6254386531d263688ccfa542d0e628fbc0de0b28
2026-01-04T14:56:49.538607Z
false
facebook/create-react-app
https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/packages/react-error-overlay/src/__tests__/parser/react.js
packages/react-error-overlay/src/__tests__/parser/react.js
/** * Copyright (c) 2015-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import { parse } from '../../utils/parser'; test('15.y.z', () => { expect( parse( `Warning: Each child in array should have a unique "key" prop. Check render method of \`FileA\`. in div (at FileA.js:9) in FileA (at App.js:9) in div (at App.js:8) in App (at index.js:7)` ) ).toMatchSnapshot(); });
javascript
MIT
6254386531d263688ccfa542d0e628fbc0de0b28
2026-01-04T14:56:49.538607Z
false
facebook/create-react-app
https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/packages/react-error-overlay/src/__tests__/parser/generic.js
packages/react-error-overlay/src/__tests__/parser/generic.js
/** * Copyright (c) 2015-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import { parse } from '../../utils/parser'; test('throws on null', () => { let error; try { parse(null); } catch (e) { error = e; } expect(error instanceof Error).toBe(true); expect(error.message).toBe('You cannot pass a null object.'); }); test('throws on unparsable', () => { let error; try { parse({}); } catch (e) { error = e; } expect(error instanceof Error).toBe(true); expect(error.message).toBe( 'The error you provided does not contain a stack trace.' ); });
javascript
MIT
6254386531d263688ccfa542d0e628fbc0de0b28
2026-01-04T14:56:49.538607Z
false
facebook/create-react-app
https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/packages/react-error-overlay/src/__tests__/parser/safari.js
packages/react-error-overlay/src/__tests__/parser/safari.js
/** * Copyright (c) 2015-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import { parse } from '../../utils/parser'; test('stack with eval', () => { expect( parse( `e@file:///Users/joe/Documents/Development/OSS/stack-frame/index.html:25:18 eval code eval@[native code] a@file:///Users/joe/Documents/Development/OSS/stack-frame/index.html:8:10 global code@file:///Users/joe/Documents/Development/OSS/stack-frame/index.html:32:8` ) ).toMatchSnapshot(); });
javascript
MIT
6254386531d263688ccfa542d0e628fbc0de0b28
2026-01-04T14:56:49.538607Z
false
facebook/create-react-app
https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/packages/react-error-overlay/src/__tests__/parser/chrome.js
packages/react-error-overlay/src/__tests__/parser/chrome.js
/** * Copyright (c) 2015-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import { parse } from '../../utils/parser'; test('stack with eval', () => { expect( parse( `TypeError: window[f] is not a function at e (file:///Users/joe/Documents/Development/OSS/stack-frame/index.html:25:18) at eval (eval at c (file:///Users/joe/Documents/Development/OSS/stack-frame/index.html:12:9), <anonymous>:1:1) at a (file:///Users/joe/Documents/Development/OSS/stack-frame/index.html:8:9) at file:///Users/joe/Documents/Development/OSS/stack-frame/index.html:32:7` ) ).toMatchSnapshot(); });
javascript
MIT
6254386531d263688ccfa542d0e628fbc0de0b28
2026-01-04T14:56:49.538607Z
false
facebook/create-react-app
https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/packages/react-error-overlay/src/__tests__/parser/firefox.js
packages/react-error-overlay/src/__tests__/parser/firefox.js
/** * Copyright (c) 2015-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import { parse } from '../../utils/parser'; test('eval 1', () => { expect( parse( `test1@file:///C:/example.html line 7 > eval line 1 > eval:1:1 test2@file:///C:/example.html line 7 > eval:1:1 test3@file:///C:/example.html:7:6`.split('\n') ) ).toMatchSnapshot(); }); test('eval 2', () => { expect( parse({ stack: `anonymous@file:///C:/example.html line 7 > Function:1:1 @file:///C:/example.html:7:6`, }) ).toMatchSnapshot(); }); test('stack with eval', () => { expect( parse( `e@file:///Users/joe/Documents/Development/OSS/stack-frame/index.html:25:9 @file:///Users/joe/Documents/Development/OSS/stack-frame/index.html line 17 > eval:1:1 a@file:///Users/joe/Documents/Development/OSS/stack-frame/index.html:8:9 @file:///Users/joe/Documents/Development/OSS/stack-frame/index.html:32:7` ) ).toMatchSnapshot(); }); test('v14 to v29', () => { expect( parse( `trace@file:///C:/example.html:9 b@file:///C:/example.html:16 a@file:///C:/example.html:19 @file:///C:/example.html:21` ) ).toMatchSnapshot(); }); test('v30+', () => { expect( parse( `trace@file:///C:/example.html:9:17 b@file:///C:/example.html:16:13 a@file:///C:/example.html:19:13 @file:///C:/example.html:21:9` ) ).toMatchSnapshot(); });
javascript
MIT
6254386531d263688ccfa542d0e628fbc0de0b28
2026-01-04T14:56:49.538607Z
false
facebook/create-react-app
https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/packages/react-error-overlay/src/effects/stackTraceLimit.js
packages/react-error-overlay/src/effects/stackTraceLimit.js
/** * Copyright (c) 2015-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ /* @flow */ let stackTraceRegistered: boolean = false; // Default: https://docs.microsoft.com/en-us/scripting/javascript/reference/stacktracelimit-property-error-javascript let restoreStackTraceValue: number = 10; const MAX_STACK_LENGTH: number = 50; function registerStackTraceLimit(limit: number = MAX_STACK_LENGTH) { if (stackTraceRegistered) { return; } try { restoreStackTraceValue = Error.stackTraceLimit; Error.stackTraceLimit = limit; stackTraceRegistered = true; } catch (e) { // Not all browsers support this so we don't care if it errors } } function unregisterStackTraceLimit() { if (!stackTraceRegistered) { return; } try { Error.stackTraceLimit = restoreStackTraceValue; stackTraceRegistered = false; } catch (e) { // Not all browsers support this so we don't care if it errors } } export { registerStackTraceLimit as register, unregisterStackTraceLimit as unregister, };
javascript
MIT
6254386531d263688ccfa542d0e628fbc0de0b28
2026-01-04T14:56:49.538607Z
false
facebook/create-react-app
https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/packages/react-error-overlay/src/effects/unhandledRejection.js
packages/react-error-overlay/src/effects/unhandledRejection.js
/** * Copyright (c) 2015-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ /* @flow */ let boundRejectionHandler = null; type ErrorCallback = (error: Error) => void; function rejectionHandler( callback: ErrorCallback, e: PromiseRejectionEvent ): void { if (e == null || e.reason == null) { return callback(new Error('Unknown')); } let { reason } = e; if (reason instanceof Error) { return callback(reason); } // A non-error was rejected, we don't have a trace :( // Look in your browser's devtools for more information return callback(new Error(reason)); } function registerUnhandledRejection( target: EventTarget, callback: ErrorCallback ) { if (boundRejectionHandler !== null) { return; } boundRejectionHandler = rejectionHandler.bind(undefined, callback); // $FlowFixMe target.addEventListener('unhandledrejection', boundRejectionHandler); } function unregisterUnhandledRejection(target: EventTarget) { if (boundRejectionHandler === null) { return; } // $FlowFixMe target.removeEventListener('unhandledrejection', boundRejectionHandler); boundRejectionHandler = null; } export { registerUnhandledRejection as register, unregisterUnhandledRejection as unregister, };
javascript
MIT
6254386531d263688ccfa542d0e628fbc0de0b28
2026-01-04T14:56:49.538607Z
false
facebook/create-react-app
https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/packages/react-error-overlay/src/effects/proxyConsole.js
packages/react-error-overlay/src/effects/proxyConsole.js
/** * Copyright (c) 2015-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ /* @flow */ type ReactFrame = { fileName: string | null, lineNumber: number | null, name: string | null, }; const reactFrameStack: Array<ReactFrame[]> = []; export type { ReactFrame }; // This is a stripped down barebones version of this proposal: // https://gist.github.com/sebmarkbage/bdefa100f19345229d526d0fdd22830f // We're implementing just enough to get the invalid element type warnings // to display the component stack in React 15.6+: // https://github.com/facebook/react/pull/9679 /// TODO: a more comprehensive implementation. const registerReactStack = () => { if (typeof console !== 'undefined') { // $FlowFixMe console.reactStack = frames => reactFrameStack.push(frames); // $FlowFixMe console.reactStackEnd = frames => reactFrameStack.pop(); } }; const unregisterReactStack = () => { if (typeof console !== 'undefined') { // $FlowFixMe console.reactStack = undefined; // $FlowFixMe console.reactStackEnd = undefined; } }; type ConsoleProxyCallback = (message: string, frames: ReactFrame[]) => void; const permanentRegister = function proxyConsole( type: string, callback: ConsoleProxyCallback ) { if (typeof console !== 'undefined') { const orig = console[type]; if (typeof orig === 'function') { console[type] = function __stack_frame_overlay_proxy_console__() { try { const message = arguments[0]; if (typeof message === 'string' && reactFrameStack.length > 0) { callback(message, reactFrameStack[reactFrameStack.length - 1]); } } catch (err) { // Warnings must never crash. Rethrow with a clean stack. setTimeout(function () { throw err; }); } return orig.apply(this, arguments); }; } } }; export { permanentRegister, registerReactStack, unregisterReactStack };
javascript
MIT
6254386531d263688ccfa542d0e628fbc0de0b28
2026-01-04T14:56:49.538607Z
false
facebook/create-react-app
https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/packages/react-error-overlay/src/effects/unhandledError.js
packages/react-error-overlay/src/effects/unhandledError.js
/** * Copyright (c) 2015-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ /* @flow */ let boundErrorHandler = null; type ErrorCallback = (error: Error) => void; function errorHandler(callback: ErrorCallback, e: Event): void { // $FlowFixMe if (!e.error) { return; } // $FlowFixMe const { error } = e; if (error instanceof Error) { callback(error); } else { // A non-error was thrown, we don't have a trace. :( // Look in your browser's devtools for more information callback(new Error(error)); } } function registerUnhandledError(target: EventTarget, callback: ErrorCallback) { if (boundErrorHandler !== null) { return; } boundErrorHandler = errorHandler.bind(undefined, callback); target.addEventListener('error', boundErrorHandler); } function unregisterUnhandledError(target: EventTarget) { if (boundErrorHandler === null) { return; } target.removeEventListener('error', boundErrorHandler); boundErrorHandler = null; } export { registerUnhandledError as register, unregisterUnhandledError as unregister, };
javascript
MIT
6254386531d263688ccfa542d0e628fbc0de0b28
2026-01-04T14:56:49.538607Z
false
facebook/create-react-app
https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/packages/react-error-overlay/src/containers/RuntimeErrorContainer.js
packages/react-error-overlay/src/containers/RuntimeErrorContainer.js
/** * Copyright (c) 2015-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ /* @flow */ import React, { PureComponent } from 'react'; import ErrorOverlay from '../components/ErrorOverlay'; import CloseButton from '../components/CloseButton'; import NavigationBar from '../components/NavigationBar'; import RuntimeError from './RuntimeError'; import Footer from '../components/Footer'; import type { ErrorRecord } from './RuntimeError'; import type { ErrorLocation } from '../utils/parseCompileError'; type Props = {| errorRecords: ErrorRecord[], close: () => void, editorHandler: (errorLoc: ErrorLocation) => void, |}; type State = {| currentIndex: number, |}; class RuntimeErrorContainer extends PureComponent<Props, State> { state = { currentIndex: 0, }; previous = () => { this.setState((state, props) => ({ currentIndex: state.currentIndex > 0 ? state.currentIndex - 1 : props.errorRecords.length - 1, })); }; next = () => { this.setState((state, props) => ({ currentIndex: state.currentIndex < props.errorRecords.length - 1 ? state.currentIndex + 1 : 0, })); }; shortcutHandler = (key: string) => { if (key === 'Escape') { this.props.close(); } else if (key === 'ArrowLeft') { this.previous(); } else if (key === 'ArrowRight') { this.next(); } }; render() { const { errorRecords, close } = this.props; const totalErrors = errorRecords.length; return ( <ErrorOverlay shortcutHandler={this.shortcutHandler}> <CloseButton close={close} /> {totalErrors > 1 && ( <NavigationBar currentError={this.state.currentIndex + 1} totalErrors={totalErrors} previous={this.previous} next={this.next} /> )} <RuntimeError errorRecord={errorRecords[this.state.currentIndex]} editorHandler={this.props.editorHandler} /> <Footer line1="This screen is visible only in development. It will not appear if the app crashes in production." line2="Open your browser’s developer console to further inspect this error. Click the 'X' or hit ESC to dismiss this message." /> </ErrorOverlay> ); } } export default RuntimeErrorContainer;
javascript
MIT
6254386531d263688ccfa542d0e628fbc0de0b28
2026-01-04T14:56:49.538607Z
false
facebook/create-react-app
https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/packages/react-error-overlay/src/containers/StackFrame.js
packages/react-error-overlay/src/containers/StackFrame.js
/** * Copyright (c) 2015-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ /* @flow */ import React, { useState, useContext } from 'react'; import { ThemeContext } from '../iframeScript'; import CodeBlock from './StackFrameCodeBlock'; import { getPrettyURL } from '../utils/getPrettyURL'; import type { StackFrame as StackFrameType } from '../utils/stack-frame'; import type { ErrorLocation } from '../utils/parseCompileError'; import type { Theme } from '../styles'; const linkStyle = (theme: Theme) => ({ fontSize: '0.9em', marginBottom: '0.9em', }); const anchorStyle = (theme: Theme) => ({ textDecoration: 'none', color: theme.anchorColor, cursor: 'pointer', }); const codeAnchorStyle = (theme: Theme) => ({ cursor: 'pointer', }); const toggleStyle = (theme: Theme) => ({ marginBottom: '1.5em', color: theme.toggleColor, cursor: 'pointer', border: 'none', display: 'block', width: '100%', textAlign: 'left', background: theme.toggleBackground, fontFamily: 'Consolas, Menlo, monospace', fontSize: '1em', padding: '0px', lineHeight: '1.5', }); type StackFramePropsType = {| frame: StackFrameType, contextSize: number, critical: boolean, showCode: boolean, editorHandler: (errorLoc: ErrorLocation) => void, |}; function StackFrame(props: StackFramePropsType) { const theme = useContext(ThemeContext); const [compiled, setCompiled] = useState(false); const toggleCompiled = () => { setCompiled(!compiled); }; const getErrorLocation = (): ErrorLocation | null => { const { _originalFileName: fileName, _originalLineNumber: lineNumber } = props.frame; // Unknown file if (!fileName) { return null; } // e.g. "/path-to-my-app/webpack/bootstrap eaddeb46b67d75e4dfc1" const isInternalWebpackBootstrapCode = fileName.trim().indexOf(' ') !== -1; if (isInternalWebpackBootstrapCode) { return null; } // Code is in a real file return { fileName, lineNumber: lineNumber || 1 }; }; const editorHandler = () => { const errorLoc = getErrorLocation(); if (!errorLoc) { return; } props.editorHandler(errorLoc); }; const onKeyDown = (e: SyntheticKeyboardEvent<any>) => { if (e.key === 'Enter') { editorHandler(); } }; const { frame, contextSize, critical, showCode } = props; const { fileName, lineNumber, columnNumber, _scriptCode: scriptLines, _originalFileName: sourceFileName, _originalLineNumber: sourceLineNumber, _originalColumnNumber: sourceColumnNumber, _originalScriptCode: sourceLines, } = frame; const functionName = frame.getFunctionName(); const url = getPrettyURL( sourceFileName, sourceLineNumber, sourceColumnNumber, fileName, lineNumber, columnNumber, compiled ); let codeBlockProps = null; if (showCode) { if ( compiled && scriptLines && scriptLines.length !== 0 && lineNumber != null ) { codeBlockProps = { lines: scriptLines, lineNum: lineNumber, columnNum: columnNumber, contextSize, main: critical, }; } else if ( !compiled && sourceLines && sourceLines.length !== 0 && sourceLineNumber != null ) { codeBlockProps = { lines: sourceLines, lineNum: sourceLineNumber, columnNum: sourceColumnNumber, contextSize, main: critical, }; } } const canOpenInEditor = getErrorLocation() !== null && props.editorHandler !== null; return ( <div> <div>{functionName}</div> <div style={linkStyle(theme)}> <span style={canOpenInEditor ? anchorStyle(theme) : null} onClick={canOpenInEditor ? editorHandler : null} onKeyDown={canOpenInEditor ? onKeyDown : null} tabIndex={canOpenInEditor ? '0' : null} > {url} </span> </div> {codeBlockProps && ( <span> <span onClick={canOpenInEditor ? editorHandler : null} style={canOpenInEditor ? codeAnchorStyle(theme) : null} > <CodeBlock {...codeBlockProps} /> </span> <button style={toggleStyle(theme)} onClick={toggleCompiled}> {'View ' + (compiled ? 'source' : 'compiled')} </button> </span> )} </div> ); } export default StackFrame;
javascript
MIT
6254386531d263688ccfa542d0e628fbc0de0b28
2026-01-04T14:56:49.538607Z
false
facebook/create-react-app
https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/packages/react-error-overlay/src/containers/RuntimeError.js
packages/react-error-overlay/src/containers/RuntimeError.js
/** * Copyright (c) 2015-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ /* @flow */ import React from 'react'; import Header from '../components/Header'; import StackTrace from './StackTrace'; import type { StackFrame } from '../utils/stack-frame'; import type { ErrorLocation } from '../utils/parseCompileError'; const wrapperStyle = { display: 'flex', flexDirection: 'column', }; export type ErrorRecord = {| error: Error, unhandledRejection: boolean, contextSize: number, stackFrames: StackFrame[], |}; type Props = {| errorRecord: ErrorRecord, editorHandler: (errorLoc: ErrorLocation) => void, |}; function RuntimeError({ errorRecord, editorHandler }: Props) { const { error, unhandledRejection, contextSize, stackFrames } = errorRecord; const errorName = unhandledRejection ? 'Unhandled Rejection (' + error.name + ')' : error.name; // Make header prettier const message = error.message; let headerText = message.match(/^\w*:/) || !errorName ? message : errorName + ': ' + message; headerText = headerText // TODO: maybe remove this prefix from fbjs? // It's just scaring people .replace(/^Invariant Violation:\s*/, '') // This is not helpful either: .replace(/^Warning:\s*/, '') // Break the actionable part to the next line. // AFAIK React 16+ should already do this. .replace(' Check the render method', '\n\nCheck the render method') .replace(' Check your code at', '\n\nCheck your code at'); return ( <div style={wrapperStyle}> <Header headerText={headerText} /> <StackTrace stackFrames={stackFrames} errorName={errorName} contextSize={contextSize} editorHandler={editorHandler} /> </div> ); } export default RuntimeError;
javascript
MIT
6254386531d263688ccfa542d0e628fbc0de0b28
2026-01-04T14:56:49.538607Z
false
facebook/create-react-app
https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/packages/react-error-overlay/src/containers/StackTrace.js
packages/react-error-overlay/src/containers/StackTrace.js
/** * Copyright (c) 2015-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ /* @flow */ import React, { Component } from 'react'; import StackFrame from './StackFrame'; import Collapsible from '../components/Collapsible'; import { isInternalFile } from '../utils/isInternalFile'; import { isBultinErrorName } from '../utils/isBultinErrorName'; import type { StackFrame as StackFrameType } from '../utils/stack-frame'; import type { ErrorLocation } from '../utils/parseCompileError'; const traceStyle = { fontSize: '1em', flex: '0 1 auto', minHeight: '0px', overflow: 'auto', }; type Props = {| stackFrames: StackFrameType[], errorName: string, contextSize: number, editorHandler: (errorLoc: ErrorLocation) => void, |}; class StackTrace extends Component<Props> { renderFrames() { const { stackFrames, errorName, contextSize, editorHandler } = this.props; const renderedFrames = []; let hasReachedAppCode = false, currentBundle = [], bundleCount = 0; stackFrames.forEach((frame, index) => { const { fileName, _originalFileName: sourceFileName } = frame; const isInternalUrl = isInternalFile(sourceFileName, fileName); const isThrownIntentionally = !isBultinErrorName(errorName); const shouldCollapse = isInternalUrl && (isThrownIntentionally || hasReachedAppCode); if (!isInternalUrl) { hasReachedAppCode = true; } const frameEle = ( <StackFrame key={'frame-' + index} frame={frame} contextSize={contextSize} critical={index === 0} showCode={!shouldCollapse} editorHandler={editorHandler} /> ); const lastElement = index === stackFrames.length - 1; if (shouldCollapse) { currentBundle.push(frameEle); } if (!shouldCollapse || lastElement) { if (currentBundle.length === 1) { renderedFrames.push(currentBundle[0]); } else if (currentBundle.length > 1) { bundleCount++; renderedFrames.push( <Collapsible key={'bundle-' + bundleCount}> {currentBundle} </Collapsible> ); } currentBundle = []; } if (!shouldCollapse) { renderedFrames.push(frameEle); } }); return renderedFrames; } render() { return <div style={traceStyle}>{this.renderFrames()}</div>; } } export default StackTrace;
javascript
MIT
6254386531d263688ccfa542d0e628fbc0de0b28
2026-01-04T14:56:49.538607Z
false
facebook/create-react-app
https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/packages/react-error-overlay/src/containers/CompileErrorContainer.js
packages/react-error-overlay/src/containers/CompileErrorContainer.js
/** * Copyright (c) 2015-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ /* @flow */ import React, { useContext } from 'react'; import { ThemeContext } from '../iframeScript'; import ErrorOverlay from '../components/ErrorOverlay'; import Footer from '../components/Footer'; import Header from '../components/Header'; import CodeBlock from '../components/CodeBlock'; import generateAnsiHTML from '../utils/generateAnsiHTML'; import parseCompileError from '../utils/parseCompileError'; import type { ErrorLocation } from '../utils/parseCompileError'; const codeAnchorStyle = { cursor: 'pointer', }; type CompileErrorContainerPropsType = {| error: string, editorHandler: (errorLoc: ErrorLocation) => void, |}; function CompileErrorContainer(props: CompileErrorContainerPropsType) { const theme = useContext(ThemeContext); const { error, editorHandler } = props; const errLoc: ?ErrorLocation = parseCompileError(error); const canOpenInEditor = errLoc !== null && editorHandler !== null; return ( <ErrorOverlay> <Header headerText="Failed to compile" /> <div onClick={canOpenInEditor && errLoc ? () => editorHandler(errLoc) : null} style={canOpenInEditor ? codeAnchorStyle : null} > <CodeBlock main={true} codeHTML={generateAnsiHTML(error, theme)} /> </div> <Footer line1="This error occurred during the build time and cannot be dismissed." /> </ErrorOverlay> ); } export default CompileErrorContainer;
javascript
MIT
6254386531d263688ccfa542d0e628fbc0de0b28
2026-01-04T14:56:49.538607Z
false
facebook/create-react-app
https://github.com/facebook/create-react-app/blob/6254386531d263688ccfa542d0e628fbc0de0b28/packages/react-error-overlay/src/containers/StackFrameCodeBlock.js
packages/react-error-overlay/src/containers/StackFrameCodeBlock.js
/** * Copyright (c) 2015-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ /* @flow */ import React, { useContext } from 'react'; import { ThemeContext } from '../iframeScript'; import CodeBlock from '../components/CodeBlock'; import { absolutifyCaret } from '../utils/dom/absolutifyCaret'; import type { ScriptLine } from '../utils/stack-frame'; import generateAnsiHTML from '../utils/generateAnsiHTML'; import { codeFrameColumns } from '@babel/code-frame'; type StackFrameCodeBlockPropsType = {| lines: ScriptLine[], lineNum: number, columnNum: ?number, contextSize: number, main: boolean, |}; // Exact type workaround for spread operator. // See: https://github.com/facebook/flow/issues/2405 type Exact<T> = $Shape<T>; function StackFrameCodeBlock(props: Exact<StackFrameCodeBlockPropsType>) { const theme = useContext(ThemeContext); const { lines, lineNum, columnNum, contextSize, main } = props; const sourceCode = []; let whiteSpace = Infinity; lines.forEach(function (e) { const { content: text } = e; const m = text.match(/^\s*/); if (text === '') { return; } if (m && m[0]) { whiteSpace = Math.min(whiteSpace, m[0].length); } else { whiteSpace = 0; } }); lines.forEach(function (e) { let { content: text } = e; const { lineNumber: line } = e; if (isFinite(whiteSpace)) { text = text.substring(whiteSpace); } sourceCode[line - 1] = text; }); const ansiHighlight = codeFrameColumns( sourceCode.join('\n'), { start: { line: lineNum, column: columnNum == null ? 0 : columnNum - (isFinite(whiteSpace) ? whiteSpace : 0), }, }, { forceColor: true, linesAbove: contextSize, linesBelow: contextSize, } ); const htmlHighlight = generateAnsiHTML(ansiHighlight, theme); const code = document.createElement('code'); code.innerHTML = htmlHighlight; absolutifyCaret(code); const ccn = code.childNodes; // eslint-disable-next-line oLoop: for (let index = 0; index < ccn.length; ++index) { const node = ccn[index]; const ccn2 = node.childNodes; for (let index2 = 0; index2 < ccn2.length; ++index2) { const lineNode = ccn2[index2]; const text = lineNode.innerText; if (text == null) { continue; } if (text.indexOf(' ' + lineNum + ' |') === -1) { continue; } // eslint-disable-next-line break oLoop; } } return <CodeBlock main={main} codeHTML={code.innerHTML} />; } export default StackFrameCodeBlock;
javascript
MIT
6254386531d263688ccfa542d0e628fbc0de0b28
2026-01-04T14:56:49.538607Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/ecosystem.config.js
ecosystem.config.js
module.exports = { apps: [{ name: "uptime-kuma", script: "./server/server.js", }] };
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/.eslintrc.js
.eslintrc.js
module.exports = { ignorePatterns: [ "test/*.js", "server/modules/*", "src/util.js" ], root: true, env: { browser: true, commonjs: true, es2020: true, node: true, }, extends: [ "eslint:recommended", "plugin:vue/vue3-recommended", "plugin:jsdoc/recommended-error", ], parser: "vue-eslint-parser", parserOptions: { parser: "@typescript-eslint/parser", sourceType: "module", requireConfigFile: false, }, plugins: [ "jsdoc", "@typescript-eslint", ], rules: { "yoda": "error", eqeqeq: [ "warn", "smart" ], "linebreak-style": [ "error", "unix" ], "camelcase": [ "warn", { "properties": "never", "ignoreImports": true }], "no-unused-vars": [ "warn", { "args": "none" }], indent: [ "error", 4, { ignoredNodes: [ "TemplateLiteral" ], SwitchCase: 1, }, ], quotes: [ "error", "double" ], semi: "error", "vue/html-indent": [ "error", 4 ], // default: 2 "vue/max-attributes-per-line": "off", "vue/singleline-html-element-content-newline": "off", "vue/html-self-closing": "off", "vue/require-component-is": "off", // not allow is="style" https://github.com/vuejs/eslint-plugin-vue/issues/462#issuecomment-430234675 "vue/attribute-hyphenation": "off", // This change noNL to "no-n-l" unexpectedly "vue/multi-word-component-names": "off", "no-multi-spaces": [ "error", { ignoreEOLComments: true, }], "array-bracket-spacing": [ "warn", "always", { "singleValue": true, "objectsInArrays": false, "arraysInArrays": false }], "space-before-function-paren": [ "error", { "anonymous": "always", "named": "never", "asyncArrow": "always" }], "curly": "error", "object-curly-spacing": [ "error", "always" ], "object-curly-newline": "off", "object-property-newline": "error", "comma-spacing": "error", "brace-style": "error", "no-var": "error", "key-spacing": "warn", "keyword-spacing": "warn", "space-infix-ops": "error", "arrow-spacing": "warn", "no-throw-literal": "error", "no-trailing-spaces": "error", "no-constant-condition": [ "error", { "checkLoops": false, }], "space-before-blocks": "warn", //"no-console": "warn", "no-extra-boolean-cast": "off", "no-multiple-empty-lines": [ "warn", { "max": 1, "maxBOF": 0, }], "lines-between-class-members": [ "warn", "always", { exceptAfterSingleLine: true, }], "no-unneeded-ternary": "error", "array-bracket-newline": [ "error", "consistent" ], "eol-last": [ "error", "always" ], //"prefer-template": "error", "template-curly-spacing": [ "warn", "never" ], "comma-dangle": [ "warn", "only-multiline" ], "no-empty": [ "error", { "allowEmptyCatch": true }], "no-control-regex": "off", "one-var": [ "error", "never" ], "max-statements-per-line": [ "error", { "max": 1 }], "jsdoc/check-tag-names": [ "error", { "definedTags": [ "link" ] } ], "jsdoc/no-undefined-types": "off", "jsdoc/no-defaults": [ "error", { "noOptionalParamNames": true } ], "jsdoc/require-throws": "warn", "jsdoc/require-jsdoc": [ "error", { "require": { "FunctionDeclaration": true, "MethodDefinition": true, } } ], "jsdoc/no-blank-block-descriptions": "error", "jsdoc/require-returns-description": "warn", "jsdoc/require-returns-check": [ "error", { "reportMissingReturnForUndefinedTypes": false } ], "jsdoc/require-returns": [ "warn", { "forceRequireReturn": true, "forceReturnsWithAsync": true } ], "jsdoc/require-param-type": "warn", "jsdoc/require-param-description": "warn" }, "overrides": [ { "files": [ "src/languages/*.js", "src/icon.js" ], "rules": { "comma-dangle": [ "error", "always-multiline" ], } }, // Override for TypeScript { "files": [ "**/*.ts", ], extends: [ "plugin:@typescript-eslint/recommended", ], "rules": { "jsdoc/require-returns-type": "off", "jsdoc/require-param-type": "off", "@typescript-eslint/no-explicit-any": "off", "prefer-const": "off", } } ] };
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/db/knex_init_db.js
db/knex_init_db.js
const { R } = require("redbean-node"); const { log } = require("../src/util"); /** * ⚠️⚠️⚠️⚠️⚠️⚠️ DO NOT ADD ANYTHING HERE! * IF YOU NEED TO ADD FIELDS, ADD IT TO ./db/knex_migrations * See ./db/knex_migrations/README.md for more information * @returns {Promise<void>} */ async function createTables() { log.info("mariadb", "Creating basic tables for MariaDB"); const knex = R.knex; // TODO: Should check later if it is really the final patch sql file. // docker_host await knex.schema.createTable("docker_host", (table) => { table.increments("id"); table.integer("user_id").unsigned().notNullable(); table.string("docker_daemon", 255); table.string("docker_type", 255); table.string("name", 255); }); // group await knex.schema.createTable("group", (table) => { table.increments("id"); table.string("name", 255).notNullable(); table.datetime("created_date").notNullable().defaultTo(knex.fn.now()); table.boolean("public").notNullable().defaultTo(false); table.boolean("active").notNullable().defaultTo(true); table.integer("weight").notNullable().defaultTo(1000); table.integer("status_page_id").unsigned(); }); // proxy await knex.schema.createTable("proxy", (table) => { table.increments("id"); table.integer("user_id").unsigned().notNullable(); table.string("protocol", 10).notNullable(); table.string("host", 255).notNullable(); table.smallint("port").notNullable(); // TODO: Maybe a issue with MariaDB, need migration to int table.boolean("auth").notNullable(); table.string("username", 255).nullable(); table.string("password", 255).nullable(); table.boolean("active").notNullable().defaultTo(true); table.boolean("default").notNullable().defaultTo(false); table.datetime("created_date").notNullable().defaultTo(knex.fn.now()); table.index("user_id", "proxy_user_id"); }); // user await knex.schema.createTable("user", (table) => { table.increments("id"); table.string("username", 255).notNullable().unique().collate("utf8_general_ci"); table.string("password", 255); table.boolean("active").notNullable().defaultTo(true); table.string("timezone", 150); table.string("twofa_secret", 64); table.boolean("twofa_status").notNullable().defaultTo(false); table.string("twofa_last_token", 6); }); // monitor await knex.schema.createTable("monitor", (table) => { table.increments("id"); table.string("name", 150); table.boolean("active").notNullable().defaultTo(true); table.integer("user_id").unsigned() .references("id").inTable("user") .onDelete("SET NULL") .onUpdate("CASCADE"); table.integer("interval").notNullable().defaultTo(20); table.text("url"); table.string("type", 20); table.integer("weight").defaultTo(2000); table.string("hostname", 255); table.integer("port"); table.datetime("created_date").notNullable().defaultTo(knex.fn.now()); table.string("keyword", 255); table.integer("maxretries").notNullable().defaultTo(0); table.boolean("ignore_tls").notNullable().defaultTo(false); table.boolean("upside_down").notNullable().defaultTo(false); table.integer("maxredirects").notNullable().defaultTo(10); table.text("accepted_statuscodes_json").notNullable().defaultTo("[\"200-299\"]"); table.string("dns_resolve_type", 5); table.string("dns_resolve_server", 255); table.string("dns_last_result", 255); table.integer("retry_interval").notNullable().defaultTo(0); table.string("push_token", 20).defaultTo(null); table.text("method").notNullable().defaultTo("GET"); table.text("body").defaultTo(null); table.text("headers").defaultTo(null); table.text("basic_auth_user").defaultTo(null); table.text("basic_auth_pass").defaultTo(null); table.integer("docker_host").unsigned() .references("id").inTable("docker_host"); table.string("docker_container", 255); table.integer("proxy_id").unsigned() .references("id").inTable("proxy"); table.boolean("expiry_notification").defaultTo(true); table.text("mqtt_topic"); table.string("mqtt_success_message", 255); table.string("mqtt_username", 255); table.string("mqtt_password", 255); table.string("database_connection_string", 2000); table.text("database_query"); table.string("auth_method", 250); table.text("auth_domain"); table.text("auth_workstation"); table.string("grpc_url", 255).defaultTo(null); table.text("grpc_protobuf").defaultTo(null); table.text("grpc_body").defaultTo(null); table.text("grpc_metadata").defaultTo(null); table.text("grpc_method").defaultTo(null); table.text("grpc_service_name").defaultTo(null); table.boolean("grpc_enable_tls").notNullable().defaultTo(false); table.string("radius_username", 255); table.string("radius_password", 255); table.string("radius_calling_station_id", 50); table.string("radius_called_station_id", 50); table.string("radius_secret", 255); table.integer("resend_interval").notNullable().defaultTo(0); table.integer("packet_size").notNullable().defaultTo(56); table.string("game", 255); }); // heartbeat await knex.schema.createTable("heartbeat", (table) => { table.increments("id"); table.boolean("important").notNullable().defaultTo(false); table.integer("monitor_id").unsigned().notNullable() .references("id").inTable("monitor") .onDelete("CASCADE") .onUpdate("CASCADE"); table.smallint("status").notNullable(); table.text("msg"); table.datetime("time").notNullable(); table.integer("ping"); table.integer("duration").notNullable().defaultTo(0); table.integer("down_count").notNullable().defaultTo(0); table.index("important"); table.index([ "monitor_id", "time" ], "monitor_time_index"); table.index("monitor_id"); table.index([ "monitor_id", "important", "time" ], "monitor_important_time_index"); }); // incident await knex.schema.createTable("incident", (table) => { table.increments("id"); table.string("title", 255).notNullable(); table.text("content", 255).notNullable(); table.string("style", 30).notNullable().defaultTo("warning"); table.datetime("created_date").notNullable().defaultTo(knex.fn.now()); table.datetime("last_updated_date"); table.boolean("pin").notNullable().defaultTo(true); table.boolean("active").notNullable().defaultTo(true); table.integer("status_page_id").unsigned(); }); // maintenance await knex.schema.createTable("maintenance", (table) => { table.increments("id"); table.string("title", 150).notNullable(); table.text("description").notNullable(); table.integer("user_id").unsigned() .references("id").inTable("user") .onDelete("SET NULL") .onUpdate("CASCADE"); table.boolean("active").notNullable().defaultTo(true); table.string("strategy", 50).notNullable().defaultTo("single"); table.datetime("start_date"); table.datetime("end_date"); table.time("start_time"); table.time("end_time"); table.string("weekdays", 250).defaultTo("[]"); table.text("days_of_month").defaultTo("[]"); table.integer("interval_day"); table.index("active"); table.index([ "strategy", "active" ], "manual_active"); table.index("user_id", "maintenance_user_id"); }); // status_page await knex.schema.createTable("status_page", (table) => { table.increments("id"); table.string("slug", 255).notNullable().unique().collate("utf8_general_ci"); table.string("title", 255).notNullable(); table.text("description"); table.string("icon", 255).notNullable(); table.string("theme", 30).notNullable(); table.boolean("published").notNullable().defaultTo(true); table.boolean("search_engine_index").notNullable().defaultTo(true); table.boolean("show_tags").notNullable().defaultTo(false); table.string("password"); table.datetime("created_date").notNullable().defaultTo(knex.fn.now()); table.datetime("modified_date").notNullable().defaultTo(knex.fn.now()); table.text("footer_text"); table.text("custom_css"); table.boolean("show_powered_by").notNullable().defaultTo(true); table.string("google_analytics_tag_id"); }); // maintenance_status_page await knex.schema.createTable("maintenance_status_page", (table) => { table.increments("id"); table.integer("status_page_id").unsigned().notNullable() .references("id").inTable("status_page") .onDelete("CASCADE") .onUpdate("CASCADE"); table.integer("maintenance_id").unsigned().notNullable() .references("id").inTable("maintenance") .onDelete("CASCADE") .onUpdate("CASCADE"); }); // maintenance_timeslot await knex.schema.createTable("maintenance_timeslot", (table) => { table.increments("id"); table.integer("maintenance_id").unsigned().notNullable() .references("id").inTable("maintenance") .onDelete("CASCADE") .onUpdate("CASCADE"); table.datetime("start_date").notNullable(); table.datetime("end_date"); table.boolean("generated_next").defaultTo(false); table.index("maintenance_id"); table.index([ "maintenance_id", "start_date", "end_date" ], "active_timeslot_index"); table.index("generated_next", "generated_next_index"); }); // monitor_group await knex.schema.createTable("monitor_group", (table) => { table.increments("id"); table.integer("monitor_id").unsigned().notNullable() .references("id").inTable("monitor") .onDelete("CASCADE") .onUpdate("CASCADE"); table.integer("group_id").unsigned().notNullable() .references("id").inTable("group") .onDelete("CASCADE") .onUpdate("CASCADE"); table.integer("weight").notNullable().defaultTo(1000); table.boolean("send_url").notNullable().defaultTo(false); table.index([ "monitor_id", "group_id" ], "fk"); }); // monitor_maintenance await knex.schema.createTable("monitor_maintenance", (table) => { table.increments("id"); table.integer("monitor_id").unsigned().notNullable() .references("id").inTable("monitor") .onDelete("CASCADE") .onUpdate("CASCADE"); table.integer("maintenance_id").unsigned().notNullable() .references("id").inTable("maintenance") .onDelete("CASCADE") .onUpdate("CASCADE"); table.index("maintenance_id", "maintenance_id_index2"); table.index("monitor_id", "monitor_id_index"); }); // notification await knex.schema.createTable("notification", (table) => { table.increments("id"); table.string("name", 255); table.boolean("active").notNullable().defaultTo(true); table.integer("user_id").unsigned(); table.boolean("is_default").notNullable().defaultTo(false); table.text("config", "longtext"); }); // monitor_notification await knex.schema.createTable("monitor_notification", (table) => { table.increments("id").unsigned(); // TODO: no auto increment???? table.integer("monitor_id").unsigned().notNullable() .references("id").inTable("monitor") .onDelete("CASCADE") .onUpdate("CASCADE"); table.integer("notification_id").unsigned().notNullable() .references("id").inTable("notification") .onDelete("CASCADE") .onUpdate("CASCADE"); table.index([ "monitor_id", "notification_id" ], "monitor_notification_index"); }); // tag await knex.schema.createTable("tag", (table) => { table.increments("id"); table.string("name", 255).notNullable(); table.string("color", 255).notNullable(); table.datetime("created_date").notNullable().defaultTo(knex.fn.now()); }); // monitor_tag await knex.schema.createTable("monitor_tag", (table) => { table.increments("id"); table.integer("monitor_id").unsigned().notNullable() .references("id").inTable("monitor") .onDelete("CASCADE") .onUpdate("CASCADE"); table.integer("tag_id").unsigned().notNullable() .references("id").inTable("tag") .onDelete("CASCADE") .onUpdate("CASCADE"); table.text("value"); }); // monitor_tls_info await knex.schema.createTable("monitor_tls_info", (table) => { table.increments("id"); table.integer("monitor_id").unsigned().notNullable() .references("id").inTable("monitor") .onDelete("CASCADE") .onUpdate("CASCADE"); table.text("info_json"); }); // notification_sent_history await knex.schema.createTable("notification_sent_history", (table) => { table.increments("id"); table.string("type", 50).notNullable(); table.integer("monitor_id").unsigned().notNullable(); table.integer("days").notNullable(); table.unique([ "type", "monitor_id", "days" ]); table.index([ "type", "monitor_id", "days" ], "good_index"); }); // setting await knex.schema.createTable("setting", (table) => { table.increments("id"); table.string("key", 200).notNullable().unique().collate("utf8_general_ci"); table.text("value"); table.string("type", 20); }); // status_page_cname await knex.schema.createTable("status_page_cname", (table) => { table.increments("id"); table.integer("status_page_id").unsigned() .references("id").inTable("status_page") .onDelete("CASCADE") .onUpdate("CASCADE"); table.string("domain").notNullable().unique().collate("utf8_general_ci"); }); /********************* * Converted Patch here *********************/ // 2023-06-30-1348-http-body-encoding.js // ALTER TABLE monitor ADD http_body_encoding VARCHAR(25); // UPDATE monitor SET http_body_encoding = 'json' WHERE (type = 'http' or type = 'keyword') AND http_body_encoding IS NULL; await knex.schema.table("monitor", function (table) { table.string("http_body_encoding", 25); }); await knex("monitor") .where(function () { this.where("type", "http").orWhere("type", "keyword"); }) .whereNull("http_body_encoding") .update({ http_body_encoding: "json", }); // 2023-06-30-1354-add-description-monitor.js // ALTER TABLE monitor ADD description TEXT default null; await knex.schema.table("monitor", function (table) { table.text("description").defaultTo(null); }); // 2023-06-30-1357-api-key-table.js /* CREATE TABLE [api_key] ( [id] INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, [key] VARCHAR(255) NOT NULL, [name] VARCHAR(255) NOT NULL, [user_id] INTEGER NOT NULL, [created_date] DATETIME DEFAULT (DATETIME('now')) NOT NULL, [active] BOOLEAN DEFAULT 1 NOT NULL, [expires] DATETIME DEFAULT NULL, CONSTRAINT FK_user FOREIGN KEY ([user_id]) REFERENCES [user]([id]) ON DELETE CASCADE ON UPDATE CASCADE ); */ await knex.schema.createTable("api_key", function (table) { table.increments("id").primary(); table.string("key", 255).notNullable(); table.string("name", 255).notNullable(); table.integer("user_id").unsigned().notNullable() .references("id").inTable("user") .onDelete("CASCADE") .onUpdate("CASCADE"); table.dateTime("created_date").defaultTo(knex.fn.now()).notNullable(); table.boolean("active").defaultTo(1).notNullable(); table.dateTime("expires").defaultTo(null); }); // 2023-06-30-1400-monitor-tls.js /* ALTER TABLE monitor ADD tls_ca TEXT default null; ALTER TABLE monitor ADD tls_cert TEXT default null; ALTER TABLE monitor ADD tls_key TEXT default null; */ await knex.schema.table("monitor", function (table) { table.text("tls_ca").defaultTo(null); table.text("tls_cert").defaultTo(null); table.text("tls_key").defaultTo(null); }); // 2023-06-30-1401-maintenance-cron.js /* -- 999 characters. https://stackoverflow.com/questions/46134830/maximum-length-for-cron-job DROP TABLE maintenance_timeslot; ALTER TABLE maintenance ADD cron TEXT; ALTER TABLE maintenance ADD timezone VARCHAR(255); ALTER TABLE maintenance ADD duration INTEGER; */ await knex.schema .dropTableIfExists("maintenance_timeslot") .table("maintenance", function (table) { table.text("cron"); table.string("timezone", 255); table.integer("duration"); }); // 2023-06-30-1413-add-parent-monitor.js. /* ALTER TABLE monitor ADD parent INTEGER REFERENCES [monitor] ([id]) ON DELETE SET NULL ON UPDATE CASCADE; */ await knex.schema.table("monitor", function (table) { table.integer("parent").unsigned() .references("id").inTable("monitor") .onDelete("SET NULL") .onUpdate("CASCADE"); }); /* patch-add-invert-keyword.sql ALTER TABLE monitor ADD invert_keyword BOOLEAN default 0 not null; */ await knex.schema.table("monitor", function (table) { table.boolean("invert_keyword").defaultTo(0).notNullable(); }); /* patch-added-json-query.sql ALTER TABLE monitor ADD json_path TEXT; ALTER TABLE monitor ADD expected_value VARCHAR(255); */ await knex.schema.table("monitor", function (table) { table.text("json_path"); table.string("expected_value", 255); }); /* patch-added-kafka-producer.sql ALTER TABLE monitor ADD kafka_producer_topic VARCHAR(255); ALTER TABLE monitor ADD kafka_producer_brokers TEXT; ALTER TABLE monitor ADD kafka_producer_ssl INTEGER; ALTER TABLE monitor ADD kafka_producer_allow_auto_topic_creation VARCHAR(255); ALTER TABLE monitor ADD kafka_producer_sasl_options TEXT; ALTER TABLE monitor ADD kafka_producer_message TEXT; */ await knex.schema.table("monitor", function (table) { table.string("kafka_producer_topic", 255); table.text("kafka_producer_brokers"); // patch-fix-kafka-producer-booleans.sql table.boolean("kafka_producer_ssl").defaultTo(0).notNullable(); table.boolean("kafka_producer_allow_auto_topic_creation").defaultTo(0).notNullable(); table.text("kafka_producer_sasl_options"); table.text("kafka_producer_message"); }); /* patch-add-certificate-expiry-status-page.sql ALTER TABLE status_page ADD show_certificate_expiry BOOLEAN default 0 NOT NULL; */ await knex.schema.table("status_page", function (table) { table.boolean("show_certificate_expiry").defaultTo(0).notNullable(); }); /* patch-monitor-oauth-cc.sql ALTER TABLE monitor ADD oauth_client_id TEXT default null; ALTER TABLE monitor ADD oauth_client_secret TEXT default null; ALTER TABLE monitor ADD oauth_token_url TEXT default null; ALTER TABLE monitor ADD oauth_scopes TEXT default null; ALTER TABLE monitor ADD oauth_auth_method TEXT default null; */ await knex.schema.table("monitor", function (table) { table.text("oauth_client_id").defaultTo(null); table.text("oauth_client_secret").defaultTo(null); table.text("oauth_token_url").defaultTo(null); table.text("oauth_scopes").defaultTo(null); table.text("oauth_auth_method").defaultTo(null); }); /* patch-add-timeout-monitor.sql ALTER TABLE monitor ADD timeout DOUBLE default 0 not null; */ await knex.schema.table("monitor", function (table) { table.double("timeout").defaultTo(0).notNullable(); }); /* patch-add-gamedig-given-port.sql ALTER TABLE monitor ADD gamedig_given_port_only BOOLEAN default 1 not null; */ await knex.schema.table("monitor", function (table) { table.boolean("gamedig_given_port_only").defaultTo(1).notNullable(); }); log.info("mariadb", "Created basic tables for MariaDB"); } module.exports = { createTables, };
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/db/knex_migrations/2024-10-1315-rabbitmq-monitor.js
db/knex_migrations/2024-10-1315-rabbitmq-monitor.js
exports.up = function (knex) { return knex.schema.alterTable("monitor", function (table) { table.text("rabbitmq_nodes"); table.string("rabbitmq_username"); table.string("rabbitmq_password"); }); }; exports.down = function (knex) { return knex.schema.alterTable("monitor", function (table) { table.dropColumn("rabbitmq_nodes"); table.dropColumn("rabbitmq_username"); table.dropColumn("rabbitmq_password"); }); };
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/db/knex_migrations/2025-06-24-0000-add-audience-to-oauth.js
db/knex_migrations/2025-06-24-0000-add-audience-to-oauth.js
exports.up = function (knex) { return knex.schema .alterTable("monitor", function (table) { table.string("oauth_audience").nullable().defaultTo(null); }); }; exports.down = function (knex) { return knex.schema.alterTable("monitor", function (table) { table.string("oauth_audience").alter(); }); };
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/db/knex_migrations/2025-02-15-2312-add-wstest.js
db/knex_migrations/2025-02-15-2312-add-wstest.js
// Add websocket ignore headers and websocket subprotocol exports.up = function (knex) { return knex.schema .alterTable("monitor", function (table) { table.boolean("ws_ignore_sec_websocket_accept_header").notNullable().defaultTo(false); table.string("ws_subprotocol", 255).notNullable().defaultTo(""); }); }; exports.down = function (knex) { return knex.schema.alterTable("monitor", function (table) { table.dropColumn("ws_ignore_sec_websocket_accept_header"); table.dropColumn("ws_subprotocol"); }); };
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/db/knex_migrations/2023-12-20-0000-alter-status-page.js
db/knex_migrations/2023-12-20-0000-alter-status-page.js
exports.up = function (knex) { return knex.schema .alterTable("status_page", function (table) { table.integer("auto_refresh_interval").defaultTo(300).unsigned(); }); }; exports.down = function (knex) { return knex.schema.alterTable("status_page", function (table) { table.dropColumn("auto_refresh_interval"); }); };
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/db/knex_migrations/2025-06-13-0000-maintenance-add-last-start.js
db/knex_migrations/2025-06-13-0000-maintenance-add-last-start.js
// Add column last_start_date to maintenance table exports.up = async function (knex) { await knex.schema .alterTable("maintenance", function (table) { table.datetime("last_start_date"); }); // Perform migration for recurring-interval strategy const recurringMaintenances = await knex("maintenance").where({ strategy: "recurring-interval", cron: "* * * * *" }).select("id", "start_time"); // eslint-disable-next-line camelcase const maintenanceUpdates = recurringMaintenances.map(async ({ start_time, id }) => { // eslint-disable-next-line camelcase const [ hourStr, minuteStr ] = start_time.split(":"); const hour = parseInt(hourStr, 10); const minute = parseInt(minuteStr, 10); const cron = `${minute} ${hour} * * *`; await knex("maintenance") .where({ id }) .update({ cron }); }); await Promise.all(maintenanceUpdates); }; exports.down = function (knex) { return knex.schema.alterTable("maintenance", function (table) { table.dropColumn("last_start_date"); }); };
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/db/knex_migrations/2025-12-09-0000-add-system-service-monitor.js
db/knex_migrations/2025-12-09-0000-add-system-service-monitor.js
/** * @param {import("knex").Knex} knex The Knex.js instance for database interaction. * @returns {Promise<void>} */ exports.up = async (knex) => { await knex.schema.alterTable("monitor", (table) => { table.string("system_service_name"); }); }; /** * @param {import("knex").Knex} knex The Knex.js instance for database interaction. * @returns {Promise<void>} */ exports.down = async (knex) => { await knex.schema.alterTable("monitor", (table) => { table.dropColumn("system_service_name"); }); };
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/db/knex_migrations/2023-10-16-0000-create-remote-browsers.js
db/knex_migrations/2023-10-16-0000-create-remote-browsers.js
exports.up = function (knex) { return knex.schema .createTable("remote_browser", function (table) { table.increments("id"); table.string("name", 255).notNullable(); table.string("url", 255).notNullable(); table.integer("user_id").unsigned(); }).alterTable("monitor", function (table) { // Add new column monitor.remote_browser table.integer("remote_browser").nullable().defaultTo(null).unsigned() .index() .references("id") .inTable("remote_browser"); }); }; exports.down = function (knex) { return knex.schema.dropTable("remote_browser").alterTable("monitor", function (table) { table.dropColumn("remote_browser"); }); };
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/db/knex_migrations/2025-09-02-0000-add-domain-expiry.js
db/knex_migrations/2025-09-02-0000-add-domain-expiry.js
exports.up = function (knex) { return knex.schema .alterTable("monitor", function (table) { table.boolean("domain_expiry_notification").defaultTo(1); }) .createTable("domain_expiry", (table) => { table.increments("id"); table.datetime("last_check"); table.text("domain").unique().notNullable(); table.datetime("expiry"); table.integer("last_expiry_notification_sent").defaultTo(null); }); }; exports.down = function (knex) { return knex.schema .alterTable("monitor", function (table) { table.boolean("domain_expiry_notification").alter(); }) .dropTable("domain_expiry"); };
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/db/knex_migrations/2024-11-27-1927-fix-info-json-data-type.js
db/knex_migrations/2024-11-27-1927-fix-info-json-data-type.js
// Update info_json column to LONGTEXT mainly for MariaDB exports.up = function (knex) { return knex.schema .alterTable("monitor_tls_info", function (table) { table.text("info_json", "longtext").alter(); }); }; exports.down = function (knex) { return knex.schema.alterTable("monitor_tls_info", function (table) { table.text("info_json", "text").alter(); }); };
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/db/knex_migrations/2025-02-17-2142-generalize-analytics.js
db/knex_migrations/2025-02-17-2142-generalize-analytics.js
// Udpate status_page table to generalize analytics fields exports.up = function (knex) { return knex.schema .alterTable("status_page", function (table) { table.renameColumn("google_analytics_tag_id", "analytics_id"); table.string("analytics_script_url"); table.enu("analytics_type", [ "google", "umami", "plausible", "matomo" ]).defaultTo(null); }).then(() => { // After a succesful migration, add google as default for previous pages knex("status_page").whereNotNull("analytics_id").update({ "analytics_type": "google", }); }); }; exports.down = function (knex) { return knex.schema.alterTable("status_page", function (table) { table.renameColumn("analytics_id", "google_analytics_tag_id"); table.dropColumn("analytics_script_url"); table.dropColumn("analytics_type"); }); };
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/db/knex_migrations/2025-12-29-0000-remove-line-notify.js
db/knex_migrations/2025-12-29-0000-remove-line-notify.js
exports.up = async function (knex) { const notifications = await knex("notification").select("id", "config"); const lineNotifyIDs = []; for (const { id, config } of notifications) { try { const parsedConfig = JSON.parse(config || "{}"); const type = typeof parsedConfig.type === "string" ? parsedConfig.type.toLowerCase() : ""; if (type === "linenotify" || type === "line-notify") { lineNotifyIDs.push(id); } } catch (error) { // Ignore invalid JSON blobs here; they are handled elsewhere in the app. } } if (lineNotifyIDs.length === 0) { return; } await knex.transaction(async (trx) => { await trx("monitor_notification").whereIn("notification_id", lineNotifyIDs).del(); await trx("notification").whereIn("id", lineNotifyIDs).del(); }); }; exports.down = async function () { // Removal of LINE Notify configs is not reversible. };
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/db/knex_migrations/2025-03-04-0000-ping-advanced-options.js
db/knex_migrations/2025-03-04-0000-ping-advanced-options.js
/* SQL: ALTER TABLE monitor ADD ping_count INTEGER default 1 not null; ALTER TABLE monitor ADD ping_numeric BOOLEAN default true not null; ALTER TABLE monitor ADD ping_per_request_timeout INTEGER default 2 not null; */ exports.up = function (knex) { // Add new columns to table monitor return knex.schema .alterTable("monitor", function (table) { table.integer("ping_count").defaultTo(1).notNullable(); table.boolean("ping_numeric").defaultTo(true).notNullable(); table.integer("ping_per_request_timeout").defaultTo(2).notNullable(); }); }; exports.down = function (knex) { return knex.schema .alterTable("monitor", function (table) { table.dropColumn("ping_count"); table.dropColumn("ping_numeric"); table.dropColumn("ping_per_request_timeout"); }); };
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/db/knex_migrations/2025-06-03-0000-add-ip-family.js
db/knex_migrations/2025-06-03-0000-add-ip-family.js
exports.up = function (knex) { return knex.schema .alterTable("monitor", function (table) { table.boolean("ip_family").defaultTo(null); }); }; exports.down = function (knex) { return knex.schema .alterTable("monitor", function (table) { table.dropColumn("ip_family"); }); };
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/db/knex_migrations/2026-01-02-0713-gamedig-v4-to-v5.js
db/knex_migrations/2026-01-02-0713-gamedig-v4-to-v5.js
// Migration to update monitor.game from GameDig v4 to v5 game IDs // Reference: https://github.com/gamedig/node-gamedig/blob/master/MIGRATE_IDS.md // Lookup table mapping v4 game IDs to v5 game IDs const gameDig4to5IdMap = { "americasarmypg": "aapg", "7d2d": "sdtd", "as": "actionsource", "ageofchivalry": "aoc", "arkse": "ase", "arcasimracing": "asr08", "arma": "aaa", "arma2oa": "a2oa", "armacwa": "acwa", "armar": "armaresistance", "armare": "armareforger", "armagetron": "armagetronadvanced", "bat1944": "battalion1944", "bf1942": "battlefield1942", "bfv": "battlefieldvietnam", "bf2": "battlefield2", "bf2142": "battlefield2142", "bfbc2": "bbc2", "bf3": "battlefield3", "bf4": "battlefield4", "bfh": "battlefieldhardline", "bd": "basedefense", "bs": "bladesymphony", "buildandshoot": "bas", "cod4": "cod4mw", "callofjuarez": "coj", "chivalry": "cmw", "commandos3": "c3db", "cacrenegade": "cacr", "contactjack": "contractjack", "cs15": "counterstrike15", "cs16": "counterstrike16", "cs2": "counterstrike2", "crossracing": "crce", "darkesthour": "dhe4445", "daysofwar": "dow", "deadlydozenpt": "ddpt", "dh2005": "deerhunter2005", "dinodday": "ddd", "dirttrackracing2": "dtr2", "dmc": "deathmatchclassic", "dnl": "dal", "drakan": "dootf", "dys": "dystopia", "em": "empiresmod", "empyrion": "egs", "f12002": "formulaone2002", "flashpointresistance": "ofr", "fivem": "gta5f", "forrest": "theforrest", "graw": "tcgraw", "graw2": "tcgraw2", "giantscitizenkabuto": "gck", "ges": "goldeneyesource", "gore": "gus", "hldm": "hld", "hldms": "hlds", "hlopfor": "hlof", "hl2dm": "hl2d", "hidden": "thehidden", "had2": "hiddendangerous2", "igi2": "i2cs", "il2": "il2sturmovik", "insurgencymic": "imic", "isle": "theisle", "jamesbondnightfire": "jb007n", "jc2mp": "jc2m", "jc3mp": "jc3m", "kingpin": "kloc", "kisspc": "kpctnc", "kspdmp": "kspd", "kzmod": "kreedzclimbing", "left4dead": "l4d", "left4dead2": "l4d2", "m2mp": "m2m", "mohsh": "mohaas", "mohbt": "mohaab", "mohab": "moha", "moh2010": "moh", "mohwf": "mohw", "minecraftbe": "mbe", "mtavc": "gtavcmta", "mtasa": "gtasamta", "ns": "naturalselection", "ns2": "naturalselection2", "nwn": "neverwinternights", "nwn2": "neverwinternights2", "nolf": "tonolf", "nolf2": "nolf2asihw", "pvkii": "pvak2", "ps": "postscriptum", "primalcarnage": "pce", "pc": "projectcars", "pc2": "projectcars2", "prbf2": "prb2", "przomboid": "projectzomboid", "quake1": "quake", "quake3": "q3a", "ragdollkungfu": "rdkf", "r6": "rainbowsix", "r6roguespear": "rs2rs", "r6ravenshield": "rs3rs", "redorchestraost": "roo4145", "redm": "rdr2r", "riseofnations": "ron", "rs2": "rs2v", "samp": "gtasam", "saomp": "gtasao", "savage2": "s2ats", "ss": "serioussam", "ss2": "serioussam2", "ship": "theship", "sinep": "sinepisodes", "sonsoftheforest": "sotf", "swbf": "swb", "swbf2": "swb2", "swjk": "swjkja", "swjk2": "swjk2jo", "takeonhelicopters": "toh", "tf2": "teamfortress2", "terraria": "terrariatshock", "tribes1": "t1s", "ut": "unrealtournament", "ut2003": "unrealtournament2003", "ut2004": "unrealtournament2004", "ut3": "unrealtournament3", "v8supercar": "v8sc", "vcmp": "vcm", "vs": "vampireslayer", "wheeloftime": "wot", "wolfenstein2009": "wolfenstein", "wolfensteinet": "wet", "wurm": "wurmunlimited", }; /** * Migrate game IDs from v4 to v5 * @param {import("knex").Knex} knex - Knex instance * @returns {Promise<void>} */ exports.up = async function (knex) { await knex.transaction(async (trx) => { // Get all monitors that use the gamedig type const monitors = await trx("monitor") .select("id", "game") .where("type", "gamedig") .whereNotNull("game"); // Update each monitor with the new game ID if it needs migration for (const monitor of monitors) { const oldGameId = monitor.game; const newGameId = gameDig4to5IdMap[oldGameId]; if (newGameId) { await trx("monitor") .where("id", monitor.id) .update({ game: newGameId }); } } }); }; /** * Revert game IDs from v5 back to v4 * @param {import("knex").Knex} knex - Knex instance * @returns {Promise<void>} */ exports.down = async function (knex) { // Create reverse mapping from the same LUT const gameDig5to4IdMap = Object.fromEntries( Object.entries(gameDig4to5IdMap).map(([ v4, v5 ]) => [ v5, v4 ]) ); await knex.transaction(async (trx) => { // Get all monitors that use the gamedig type const monitors = await trx("monitor") .select("id", "game") .where("type", "gamedig") .whereNotNull("game"); // Revert each monitor back to the old game ID if it was migrated for (const monitor of monitors) { const newGameId = monitor.game; const oldGameId = gameDig5to4IdMap[newGameId]; if (oldGameId) { await trx("monitor") .where("id", monitor.id) .update({ game: oldGameId }); } } }); };
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/db/knex_migrations/2024-10-31-0000-fix-snmp-monitor.js
db/knex_migrations/2024-10-31-0000-fix-snmp-monitor.js
exports.up = function (knex) { return knex("monitor").whereNull("json_path_operator").update("json_path_operator", "=="); }; exports.down = function (knex) { // changing the json_path_operator back to null for all "==" is not possible anymore // we have lost the context which fields have been set explicitely in >= v2.0 and which would need to be reverted };
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/db/knex_migrations/2025-07-17-0000-mqtt-websocket-path.js
db/knex_migrations/2025-07-17-0000-mqtt-websocket-path.js
exports.up = function (knex) { // Add new column monitor.mqtt_websocket_path return knex.schema .alterTable("monitor", function (table) { table.string("mqtt_websocket_path", 255).nullable(); }); }; exports.down = function (knex) { // Drop column monitor.mqtt_websocket_path return knex.schema .alterTable("monitor", function (table) { table.dropColumn("mqtt_websocket_path"); }); };
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/db/knex_migrations/2025-01-01-0000-add-smtp.js
db/knex_migrations/2025-01-01-0000-add-smtp.js
exports.up = function (knex) { return knex.schema .alterTable("monitor", function (table) { table.string("smtp_security").defaultTo(null); }); }; exports.down = function (knex) { return knex.schema.alterTable("monitor", function (table) { table.dropColumn("smtp_security"); }); };
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/db/knex_migrations/2023-09-29-0000-heartbeat-retires.js
db/knex_migrations/2023-09-29-0000-heartbeat-retires.js
exports.up = function (knex) { // Add new column heartbeat.retries return knex.schema .alterTable("heartbeat", function (table) { table.integer("retries").notNullable().defaultTo(0); }); }; exports.down = function (knex) { return knex.schema .alterTable("heartbeat", function (table) { table.dropColumn("retries"); }); };
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/db/knex_migrations/2024-01-22-0000-stats-extras.js
db/knex_migrations/2024-01-22-0000-stats-extras.js
exports.up = function (knex) { return knex.schema .alterTable("stat_daily", function (table) { table.text("extras").defaultTo(null).comment("Extra statistics during this time period"); }) .alterTable("stat_minutely", function (table) { table.text("extras").defaultTo(null).comment("Extra statistics during this time period"); }) .alterTable("stat_hourly", function (table) { table.text("extras").defaultTo(null).comment("Extra statistics during this time period"); }); }; exports.down = function (knex) { return knex.schema .alterTable("stat_daily", function (table) { table.dropColumn("extras"); }) .alterTable("stat_minutely", function (table) { table.dropColumn("extras"); }) .alterTable("stat_hourly", function (table) { table.dropColumn("extras"); }); };
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/db/knex_migrations/2026-01-02-0551-dns-last-result-to-text.js
db/knex_migrations/2026-01-02-0551-dns-last-result-to-text.js
// Change dns_last_result column from VARCHAR(255) to TEXT to handle longer DNS TXT records exports.up = function (knex) { return knex.schema .alterTable("monitor", function (table) { table.text("dns_last_result").alter(); }); }; exports.down = function (knex) { return knex.schema .alterTable("monitor", function (table) { table.string("dns_last_result", 255).alter(); }); };
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/db/knex_migrations/2025-10-15-0000-stat-table-fix.js
db/knex_migrations/2025-10-15-0000-stat-table-fix.js
// Fix for #4315. Logically, setting it to 0 ping may not be correct, but it is better than throwing errors exports.up = function (knex) { return knex.schema .alterTable("stat_daily", function (table) { table.integer("ping").defaultTo(0).alter(); }) .alterTable("stat_hourly", function (table) { table.integer("ping").defaultTo(0).alter(); }) .alterTable("stat_minutely", function (table) { table.integer("ping").defaultTo(0).alter(); }); }; exports.down = function (knex) { return knex.schema .alterTable("stat_daily", function (table) { table.integer("ping").alter(); }) .alterTable("stat_hourly", function (table) { table.integer("ping").alter(); }) .alterTable("stat_minutely", function (table) { table.integer("ping").alter(); }); };
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/db/knex_migrations/2025-10-14-0000-add-ip-family-fix.js
db/knex_migrations/2025-10-14-0000-add-ip-family-fix.js
exports.up = function (knex) { return knex.schema .alterTable("monitor", function (table) { // Fix ip_family, change to varchar instead of boolean // possible values are "ipv4" and "ipv6" table.string("ip_family", 4).defaultTo(null).alter(); }); }; exports.down = function (knex) { return knex.schema .alterTable("monitor", function (table) { // Rollback to boolean table.boolean("ip_family").defaultTo(null).alter(); }); };
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/db/knex_migrations/2023-12-22-0000-hourly-uptime.js
db/knex_migrations/2023-12-22-0000-hourly-uptime.js
exports.up = function (knex) { return knex.schema .createTable("stat_hourly", function (table) { table.increments("id"); table.comment("This table contains the hourly aggregate statistics for each monitor"); table.integer("monitor_id").unsigned().notNullable() .references("id").inTable("monitor") .onDelete("CASCADE") .onUpdate("CASCADE"); table.integer("timestamp") .notNullable() .comment("Unix timestamp rounded down to the nearest hour"); table.float("ping").notNullable().comment("Average ping in milliseconds"); table.float("ping_min").notNullable().defaultTo(0).comment("Minimum ping during this period in milliseconds"); table.float("ping_max").notNullable().defaultTo(0).comment("Maximum ping during this period in milliseconds"); table.smallint("up").notNullable(); table.smallint("down").notNullable(); table.unique([ "monitor_id", "timestamp" ]); }); }; exports.down = function (knex) { return knex.schema .dropTable("stat_hourly"); };
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/db/knex_migrations/2025-05-09-0000-add-custom-url.js
db/knex_migrations/2025-05-09-0000-add-custom-url.js
// Add column custom_url to monitor_group table exports.up = function (knex) { return knex.schema .alterTable("monitor_group", function (table) { table.text("custom_url", "text"); }); }; exports.down = function (knex) { return knex.schema.alterTable("monitor_group", function (table) { table.dropColumn("custom_url"); }); };
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/db/knex_migrations/2024-04-26-0000-snmp-monitor.js
db/knex_migrations/2024-04-26-0000-snmp-monitor.js
exports.up = function (knex) { return knex.schema .alterTable("monitor", function (table) { table.string("snmp_oid").defaultTo(null); table.enum("snmp_version", [ "1", "2c", "3" ]).defaultTo("2c"); table.string("json_path_operator").defaultTo(null); }); }; exports.down = function (knex) { return knex.schema.alterTable("monitor", function (table) { table.dropColumn("snmp_oid"); table.dropColumn("snmp_version"); table.dropColumn("json_path_operator"); }); };
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/db/knex_migrations/2024-08-24-000-add-cache-bust.js
db/knex_migrations/2024-08-24-000-add-cache-bust.js
exports.up = function (knex) { return knex.schema .alterTable("monitor", function (table) { table.boolean("cache_bust").notNullable().defaultTo(false); }); }; exports.down = function (knex) { return knex.schema .alterTable("monitor", function (table) { table.dropColumn("cache_bust"); }); };
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/db/knex_migrations/2023-10-11-1915-push-token-to-32.js
db/knex_migrations/2023-10-11-1915-push-token-to-32.js
exports.up = function (knex) { // update monitor.push_token to 32 length return knex.schema .alterTable("monitor", function (table) { table.string("push_token", 32).alter(); }); }; exports.down = function (knex) { return knex.schema .alterTable("monitor", function (table) { table.string("push_token", 20).alter(); }); };
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/db/knex_migrations/2023-12-21-0000-stat-ping-min-max.js
db/knex_migrations/2023-12-21-0000-stat-ping-min-max.js
exports.up = function (knex) { return knex.schema .alterTable("stat_daily", function (table) { table.float("ping_min").notNullable().defaultTo(0).comment("Minimum ping during this period in milliseconds"); table.float("ping_max").notNullable().defaultTo(0).comment("Maximum ping during this period in milliseconds"); }) .alterTable("stat_minutely", function (table) { table.float("ping_min").notNullable().defaultTo(0).comment("Minimum ping during this period in milliseconds"); table.float("ping_max").notNullable().defaultTo(0).comment("Maximum ping during this period in milliseconds"); }); }; exports.down = function (knex) { return knex.schema .alterTable("stat_daily", function (table) { table.dropColumn("ping_min"); table.dropColumn("ping_max"); }) .alterTable("stat_minutely", function (table) { table.dropColumn("ping_min"); table.dropColumn("ping_max"); }); };
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/db/knex_migrations/2023-08-16-0000-create-uptime.js
db/knex_migrations/2023-08-16-0000-create-uptime.js
exports.up = function (knex) { return knex.schema .createTable("stat_minutely", function (table) { table.increments("id"); table.comment("This table contains the minutely aggregate statistics for each monitor"); table.integer("monitor_id").unsigned().notNullable() .references("id").inTable("monitor") .onDelete("CASCADE") .onUpdate("CASCADE"); table.integer("timestamp") .notNullable() .comment("Unix timestamp rounded down to the nearest minute"); table.float("ping").notNullable().comment("Average ping in milliseconds"); table.smallint("up").notNullable(); table.smallint("down").notNullable(); table.unique([ "monitor_id", "timestamp" ]); }) .createTable("stat_daily", function (table) { table.increments("id"); table.comment("This table contains the daily aggregate statistics for each monitor"); table.integer("monitor_id").unsigned().notNullable() .references("id").inTable("monitor") .onDelete("CASCADE") .onUpdate("CASCADE"); table.integer("timestamp") .notNullable() .comment("Unix timestamp rounded down to the nearest day"); table.float("ping").notNullable().comment("Average ping in milliseconds"); table.smallint("up").notNullable(); table.smallint("down").notNullable(); table.unique([ "monitor_id", "timestamp" ]); }); }; exports.down = function (knex) { return knex.schema .dropTable("stat_minutely") .dropTable("stat_daily"); };
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/db/knex_migrations/2025-10-24-0000-show-only-last-heartbeat.js
db/knex_migrations/2025-10-24-0000-show-only-last-heartbeat.js
exports.up = function (knex) { // Add new column status_page.show_only_last_heartbeat return knex.schema .alterTable("status_page", function (table) { table.boolean("show_only_last_heartbeat").notNullable().defaultTo(false); }); }; exports.down = function (knex) { // Drop column status_page.show_only_last_heartbeat return knex.schema .alterTable("status_page", function (table) { table.dropColumn("show_only_last_heartbeat"); }); };
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/db/knex_migrations/2025-06-11-0000-add-manual-monitor.js
db/knex_migrations/2025-06-11-0000-add-manual-monitor.js
exports.up = function (knex) { return knex.schema .alterTable("monitor", function (table) { table.string("manual_status").defaultTo(null); }); }; exports.down = function (knex) { return knex.schema.alterTable("monitor", function (table) { table.dropColumn("manual_status"); }); };
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/db/knex_migrations/2023-08-18-0301-heartbeat.js
db/knex_migrations/2023-08-18-0301-heartbeat.js
exports.up = function (knex) { // Add new column heartbeat.end_time return knex.schema .alterTable("heartbeat", function (table) { table.datetime("end_time").nullable().defaultTo(null); }); }; exports.down = function (knex) { // Rename heartbeat.start_time to heartbeat.time return knex.schema .alterTable("heartbeat", function (table) { table.dropColumn("end_time"); }); };
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/db/knex_migrations/2025-06-15-0001-manual-monitor-fix.js
db/knex_migrations/2025-06-15-0001-manual-monitor-fix.js
// Fix: Change manual_status column type to smallint exports.up = function (knex) { return knex.schema .alterTable("monitor", function (table) { table.smallint("manual_status").alter(); }); }; exports.down = function (knex) { return knex.schema.alterTable("monitor", function (table) { table.string("manual_status").alter(); }); };
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/db/knex_migrations/2023-10-08-0000-mqtt-query.js
db/knex_migrations/2023-10-08-0000-mqtt-query.js
exports.up = function (knex) { // Add new column monitor.mqtt_check_type return knex.schema .alterTable("monitor", function (table) { table.string("mqtt_check_type", 255).notNullable().defaultTo("keyword"); }); }; exports.down = function (knex) { // Drop column monitor.mqtt_check_type return knex.schema .alterTable("monitor", function (table) { table.dropColumn("mqtt_check_type"); }); };
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/db/knex_migrations/2025-03-25-0127-fix-5721.js
db/knex_migrations/2025-03-25-0127-fix-5721.js
// Fix #5721: Change proxy port column type to integer to support larger port numbers exports.up = function (knex) { return knex.schema .alterTable("proxy", function (table) { table.integer("port").alter(); }); }; exports.down = function (knex) { return knex.schema.alterTable("proxy", function (table) { table.smallint("port").alter(); }); };
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/db/knex_migrations/2024-08-24-0000-conditions.js
db/knex_migrations/2024-08-24-0000-conditions.js
exports.up = function (knex) { return knex.schema .alterTable("monitor", function (table) { table.text("conditions").notNullable().defaultTo("[]"); }); }; exports.down = function (knex) { return knex.schema.alterTable("monitor", function (table) { table.dropColumn("conditions"); }); };
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/db/knex_migrations/2025-12-22-0121-optimize-important-indexes.js
db/knex_migrations/2025-12-22-0121-optimize-important-indexes.js
exports.up = async function (knex) { const isSQLite = knex.client.dialect === "sqlite3"; if (isSQLite) { // For SQLite: Use partial indexes with WHERE important = 1 // Drop existing indexes using IF EXISTS await knex.raw("DROP INDEX IF EXISTS monitor_important_time_index"); await knex.raw("DROP INDEX IF EXISTS heartbeat_important_index"); // Create partial indexes with predicate await knex.schema.alterTable("heartbeat", function (table) { table.index([ "monitor_id", "time" ], "monitor_important_time_index", { predicate: knex.whereRaw("important = 1") }); table.index([ "important" ], "heartbeat_important_index", { predicate: knex.whereRaw("important = 1") }); }); } // For MariaDB/MySQL: No changes (partial indexes not supported) }; exports.down = async function (knex) { const isSQLite = knex.client.dialect === "sqlite3"; if (isSQLite) { // Restore original indexes await knex.raw("DROP INDEX IF EXISTS monitor_important_time_index"); await knex.raw("DROP INDEX IF EXISTS heartbeat_important_index"); await knex.schema.alterTable("heartbeat", function (table) { table.index([ "monitor_id", "important", "time" ], "monitor_important_time_index"); table.index([ "important" ]); }); } // For MariaDB/MySQL: No changes };
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/src/router.js
src/router.js
import { createRouter, createWebHistory } from "vue-router"; import EmptyLayout from "./layouts/EmptyLayout.vue"; import Layout from "./layouts/Layout.vue"; import Dashboard from "./pages/Dashboard.vue"; import DashboardHome from "./pages/DashboardHome.vue"; import Details from "./pages/Details.vue"; import EditMonitor from "./pages/EditMonitor.vue"; import EditMaintenance from "./pages/EditMaintenance.vue"; import List from "./pages/List.vue"; const Settings = () => import("./pages/Settings.vue"); import Setup from "./pages/Setup.vue"; import StatusPage from "./pages/StatusPage.vue"; import Entry from "./pages/Entry.vue"; import ManageStatusPage from "./pages/ManageStatusPage.vue"; import AddStatusPage from "./pages/AddStatusPage.vue"; import NotFound from "./pages/NotFound.vue"; import DockerHosts from "./components/settings/Docker.vue"; import MaintenanceDetails from "./pages/MaintenanceDetails.vue"; import ManageMaintenance from "./pages/ManageMaintenance.vue"; import APIKeys from "./components/settings/APIKeys.vue"; import SetupDatabase from "./pages/SetupDatabase.vue"; // Settings - Sub Pages import Appearance from "./components/settings/Appearance.vue"; import General from "./components/settings/General.vue"; const Notifications = () => import("./components/settings/Notifications.vue"); import ReverseProxy from "./components/settings/ReverseProxy.vue"; import Tags from "./components/settings/Tags.vue"; import MonitorHistory from "./components/settings/MonitorHistory.vue"; const Security = () => import("./components/settings/Security.vue"); import Proxies from "./components/settings/Proxies.vue"; import About from "./components/settings/About.vue"; import RemoteBrowsers from "./components/settings/RemoteBrowsers.vue"; const routes = [ { path: "/", component: Entry, }, { // If it is "/dashboard", the active link is not working // If it is "", it overrides the "/" unexpectedly // Give a random name to solve the problem. path: "/empty", component: Layout, children: [ { path: "", component: Dashboard, children: [ { name: "DashboardHome", path: "/dashboard", component: DashboardHome, children: [ { path: "/dashboard/:id", component: EmptyLayout, children: [ { path: "", component: Details, }, { path: "/edit/:id", component: EditMonitor, }, ], }, ], }, { path: "/add", component: EditMonitor, children: [ { path: "/clone/:id", component: EditMonitor, }, ] }, { path: "/list", component: List, }, { path: "/settings", component: Settings, children: [ { path: "general", component: General, }, { path: "appearance", component: Appearance, }, { path: "notifications", component: Notifications, }, { path: "reverse-proxy", component: ReverseProxy, }, { path: "tags", component: Tags, }, { path: "monitor-history", component: MonitorHistory, }, { path: "docker-hosts", component: DockerHosts, }, { path: "remote-browsers", component: RemoteBrowsers, }, { path: "security", component: Security, }, { path: "api-keys", component: APIKeys, }, { path: "proxies", component: Proxies, }, { path: "about", component: About, }, ] }, { path: "/manage-status-page", component: ManageStatusPage, }, { path: "/add-status-page", component: AddStatusPage, }, { path: "/maintenance", component: ManageMaintenance, }, { path: "/maintenance/:id", component: MaintenanceDetails, }, { path: "/add-maintenance", component: EditMaintenance, }, { path: "/maintenance/edit/:id", component: EditMaintenance, }, { path: "/maintenance/clone/:id", component: EditMaintenance, } ], }, ], }, { path: "/setup", component: Setup, }, { path: "/setup-database", component: SetupDatabase, }, { path: "/status-page", component: StatusPage, }, { path: "/status", component: StatusPage, }, { path: "/status/:slug", component: StatusPage, }, { path: "/:pathMatch(.*)*", component: NotFound, }, ]; export const router = createRouter({ linkActiveClass: "active", history: createWebHistory(), routes, });
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/src/main.js
src/main.js
import "bootstrap"; import { createApp, h } from "vue"; import contenteditable from "vue-contenteditable"; import Toast from "vue-toastification"; import "vue-toastification/dist/index.css"; import App from "./App.vue"; import "./assets/app.scss"; import "./assets/vue-datepicker.scss"; import { i18n } from "./i18n"; import { FontAwesomeIcon } from "./icon.js"; import datetime from "./mixins/datetime"; import mobile from "./mixins/mobile"; import publicMixin from "./mixins/public"; import socket from "./mixins/socket"; import theme from "./mixins/theme"; import lang from "./mixins/lang"; import { router } from "./router"; import { appName } from "./util.ts"; import dayjs from "dayjs"; import timezone from "./modules/dayjs/plugin/timezone"; import utc from "dayjs/plugin/utc"; import relativeTime from "dayjs/plugin/relativeTime"; import { loadToastSettings } from "./util-frontend"; dayjs.extend(utc); dayjs.extend(timezone); dayjs.extend(relativeTime); const app = createApp({ mixins: [ socket, theme, mobile, datetime, publicMixin, lang, ], data() { return { appName: appName }; }, render: () => h(App), }); app.use(router); app.use(i18n); app.use(Toast, loadToastSettings()); app.component("Editable", contenteditable); app.component("FontAwesomeIcon", FontAwesomeIcon); app.mount("#app"); // Expose the vue instance for development if (process.env.NODE_ENV === "development") { console.log("Dev Only: window.app is the vue instance"); window.app = app._instance; }
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/src/icon.js
src/icon.js
import { library } from "@fortawesome/fontawesome-svg-core"; import { FontAwesomeIcon } from "@fortawesome/vue-fontawesome"; // Add Free Font Awesome Icons // https://fontawesome.com/v5.15/icons?d=gallery&p=2&s=solid&m=free // In order to add an icon, you have to: // 1) add the icon name in the import statement below; // 2) add the icon name to the library.add() statement below. import { faArrowAltCircleUp, faArrowDown, faArrowUp, faCog, faEdit, faExclamationTriangle, faEye, faEyeSlash, faList, faPause, faPlay, faPlus, faSearch, faTachometerAlt, faTimes, faTimesCircle, faTrash, faCheckCircle, faStream, faSave, faExclamationCircle, faBullhorn, faArrowsAltV, faUnlink, faQuestionCircle, faImages, faUpload, faCopy, faCheck, faFile, faAward, faLink, faChevronDown, faSignOutAlt, faPen, faExternalLinkSquareAlt, faSpinner, faUndo, faPlusCircle, faAngleDown, faWrench, faHeartbeat, faFilter, faInfoCircle, faClone, faCertificate, } from "@fortawesome/free-solid-svg-icons"; library.add( faArrowAltCircleUp, faArrowDown, faArrowUp, faCog, faEdit, faExclamationTriangle, faEye, faEyeSlash, faList, faPause, faPlay, faPlus, faSearch, faTachometerAlt, faTimes, faTimesCircle, faTrash, faCheckCircle, faStream, faSave, faExclamationCircle, faBullhorn, faArrowsAltV, faUnlink, faQuestionCircle, faImages, faUpload, faCopy, faCheck, faFile, faAward, faLink, faChevronDown, faSignOutAlt, faPen, faExternalLinkSquareAlt, faSpinner, faUndo, faPlusCircle, faAngleDown, faLink, faWrench, faHeartbeat, faFilter, faInfoCircle, faClone, faCertificate, ); export { FontAwesomeIcon };
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/src/i18n.js
src/i18n.js
import { createI18n } from "vue-i18n/dist/vue-i18n.esm-browser.prod.js"; import en from "./lang/en.json"; const languageList = { "ar-SY": "العربية", "cs-CZ": "Čeština", "zh-HK": "繁體中文 (香港)", "bg-BG": "Български", "be": "Беларуская", "de-DE": "Deutsch (Deutschland)", "de-CH": "Deutsch (Schweiz)", "nl-NL": "Nederlands", "nb-NO": "Norsk", "es-ES": "Español", "eu": "Euskara", "fa": "Farsi", "pt-PT": "Português (Portugal)", "pt-BR": "Português (Brasileiro)", "fi": "Suomi", "fr-FR": "Français (France)", "he-IL": "עברית", "hu": "Magyar", "hr-HR": "Hrvatski", "it-IT": "Italiano (Italian)", "id-ID": "Bahasa Indonesia (Indonesian)", "ja": "日本語", "da-DK": "Danish (Danmark)", "sr": "Српски", "sl-SI": "Slovenščina", "sr-latn": "Srpski", "sv-SE": "Svenska", "tr-TR": "Türkçe", "ko-KR": "한국어", "lt": "Lietuvių", "ru-RU": "Русский", "zh-CN": "简体中文", "pl": "Polski", "et-EE": "eesti", "vi-VN": "Tiếng Việt", "zh-TW": "繁體中文 (台灣)", "uk-UA": "Українська", "th-TH": "ไทย", "el-GR": "Ελληνικά", "yue": "繁體中文 (廣東話 / 粵語)", "ro": "Limba română", "ur": "Urdu", "ge": "ქართული", "uz": "O'zbek tili", "ga": "Gaeilge", "sk": "Slovenčina", }; let messages = { en, }; for (let lang in languageList) { messages[lang] = { languageName: languageList[lang] }; } const rtlLangs = [ "he-IL", "fa", "ar-SY", "ur" ]; /** * Find the best matching locale to display * If no locale can be matched, the default is "en" * @returns {string} the locale that should be displayed */ export function currentLocale() { for (const locale of [ localStorage.locale, navigator.language, ...navigator.languages ]) { // localstorage might not have a value or there might not be a language in `navigator.language` if (!locale) { continue; } if (locale in messages) { return locale; } // If the locale is a 2-letter code, we can try to find a regional variant // e.g. "fr" may not be in the messages, but "fr-FR" is if (locale.length === 2) { const regionalLocale = `${locale}-${locale.toUpperCase()}`; if (regionalLocale in messages) { return regionalLocale; } } else { // Some locales are further specified such as "en-US". // If we only have a generic locale for this, we can use it too const genericLocale = locale.slice(0, 2); if (genericLocale in messages) { return genericLocale; } } } return "en"; } export const localeDirection = () => { return rtlLangs.includes(currentLocale()) ? "rtl" : "ltr"; }; export const i18n = createI18n({ locale: currentLocale(), fallbackLocale: "en", silentFallbackWarn: true, silentTranslationWarn: true, messages: messages, });
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/src/util-frontend.js
src/util-frontend.js
import dayjs from "dayjs"; import { getTimeZones } from "@vvo/tzdb"; import { localeDirection, currentLocale } from "./i18n"; import { POSITION } from "vue-toastification"; /** * Returns the offset from UTC in hours for the current locale. * @param {string} timeZone Timezone to get offset for * @returns {number} The offset from UTC in hours. * * Generated by Trelent */ function getTimezoneOffset(timeZone) { const now = new Date(); const tzString = now.toLocaleString("en-US", { timeZone, }); const localString = now.toLocaleString("en-US"); const diff = (Date.parse(localString) - Date.parse(tzString)) / 3600000; const offset = diff + now.getTimezoneOffset() / 60; return -offset; } /** * Returns a list of timezones sorted by their offset from UTC. * @returns {object[]} A list of the given timezones sorted by their offset from UTC. * * Generated by Trelent */ export function timezoneList() { let result = []; const timeZones = getTimeZones(); for (let timezone of timeZones) { try { let display = dayjs().tz(timezone.name).format("Z"); result.push({ name: `(UTC${display}) ${timezone.name}`, value: timezone.name, time: getTimezoneOffset(timezone.name), }); } catch (e) { // Skipping not supported timezone.name by dayjs } } result.sort((a, b) => { if (a.time > b.time) { return 1; } if (b.time > a.time) { return -1; } return 0; }); return result; } /** * Set the locale of the HTML page * @returns {void} */ export function setPageLocale() { const html = document.documentElement; html.setAttribute("lang", currentLocale() ); html.setAttribute("dir", localeDirection() ); } /** * Get the base URL * Mainly used for dev, because the backend and the frontend are in different ports. * @returns {string} Base URL */ export function getResBaseURL() { const env = process.env.NODE_ENV; if (env === "development" && isDevContainer()) { return location.protocol + "//" + getDevContainerServerHostname(); } else if (env === "development" || localStorage.dev === "dev") { return location.protocol + "//" + location.hostname + ":3001"; } else { return ""; } } /** * Are we currently running in a dev container? * @returns {boolean} Running in dev container? */ export function isDevContainer() { // eslint-disable-next-line no-undef return (typeof DEVCONTAINER === "string" && DEVCONTAINER === "1"); } /** * Supports GitHub Codespaces only currently * @returns {string} Dev container server hostname */ export function getDevContainerServerHostname() { if (!isDevContainer()) { return ""; } // eslint-disable-next-line no-undef return CODESPACE_NAME + "-3001." + GITHUB_CODESPACES_PORT_FORWARDING_DOMAIN; } /** * Regex pattern fr identifying hostnames and IP addresses * @param {boolean} mqtt whether or not the regex should take into * account the fact that it is an mqtt uri * @returns {RegExp} The requested regex */ export function hostNameRegexPattern(mqtt = false) { // mqtt, mqtts, ws and wss schemes accepted by mqtt.js (https://github.com/mqttjs/MQTT.js/#connect) const mqttSchemeRegexPattern = "((mqtt|ws)s?:\\/\\/)?"; // Source: https://digitalfortress.tech/tips/top-15-commonly-used-regex/ const ipRegexPattern = `((^${mqtt ? mqttSchemeRegexPattern : ""}((([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]))$)|(^((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:)))(%.+)?$))`; // Source: https://stackoverflow.com/questions/106179/regular-expression-to-match-dns-hostname-or-ip-address const hostNameRegexPattern = `^${mqtt ? mqttSchemeRegexPattern : ""}([a-zA-Z0-9])?(([a-zA-Z0-9_]|[a-zA-Z0-9_][a-zA-Z0-9\\-_]*[a-zA-Z0-9_])\\.)*([A-Za-z0-9_]|[A-Za-z0-9_][A-Za-z0-9\\-_]*[A-Za-z0-9_])(\\.)?$`; return `${ipRegexPattern}|${hostNameRegexPattern}`; } /** * Get the tag color options * Shared between components * @param {any} self Component * @returns {object[]} Colour options */ export function colorOptions(self) { return [ { name: self.$t("Gray"), color: "#4B5563" }, { name: self.$t("Red"), color: "#DC2626" }, { name: self.$t("Orange"), color: "#D97706" }, { name: self.$t("Green"), color: "#059669" }, { name: self.$t("Blue"), color: "#2563EB" }, { name: self.$t("Indigo"), color: "#4F46E5" }, { name: self.$t("Purple"), color: "#7C3AED" }, { name: self.$t("Pink"), color: "#DB2777" }, ]; } /** * Loads the toast timeout settings from storage. * @returns {object} The toast plugin options object. */ export function loadToastSettings() { return { position: POSITION.BOTTOM_RIGHT, containerClassName: "toast-container mb-5", showCloseButtonOnHover: true, filterBeforeCreate: (toast, toasts) => { if (toast.timeout === 0) { return false; } else { return toast; } }, }; } /** * Get timeout for success toasts * @returns {(number|boolean)} Timeout in ms. If false timeout disabled. */ export function getToastSuccessTimeout() { let successTimeout = 20000; if (localStorage.toastSuccessTimeout !== undefined) { const parsedTimeout = parseInt(localStorage.toastSuccessTimeout); if (parsedTimeout != null && !Number.isNaN(parsedTimeout)) { successTimeout = parsedTimeout; } } if (successTimeout === -1) { successTimeout = false; } return successTimeout; } /** * Get timeout for error toasts * @returns {(number|boolean)} Timeout in ms. If false timeout disabled. */ export function getToastErrorTimeout() { let errorTimeout = -1; if (localStorage.toastErrorTimeout !== undefined) { const parsedTimeout = parseInt(localStorage.toastErrorTimeout); if (parsedTimeout != null && !Number.isNaN(parsedTimeout)) { errorTimeout = parsedTimeout; } } if (errorTimeout === -1) { errorTimeout = false; } return errorTimeout; } class TimeDurationFormatter { /** * Default locale and options for Time Duration Formatter (supports both DurationFormat and RelativeTimeFormat) */ constructor() { this.durationFormatOptions = { style: "long" }; this.relativeTimeFormatOptions = { numeric: "always" }; if (Intl.DurationFormat !== undefined) { this.durationFormatInstance = new Intl.DurationFormat(currentLocale(), this.durationFormatOptions); } else { this.relativeTimeFormatInstance = new Intl.RelativeTimeFormat(currentLocale(), this.relativeTimeFormatOptions); } } /** * Method to update the instance locale and options * @param {string} locale Localization identifier (e.g., "en", "ar-sy") to update the instance with. * @returns {void} No return value. */ updateLocale(locale) { if (Intl.DurationFormat !== undefined) { this.durationFormatInstance = new Intl.DurationFormat(locale, this.durationFormatOptions); } else { this.relativeTimeFormatInstance = new Intl.RelativeTimeFormat(locale, this.relativeTimeFormatOptions); } } /** * Method to convert seconds into Human readable format * @param {number} seconds Receive value in seconds. * @returns {string} String converted to Days Mins Seconds Format */ secondsToHumanReadableFormat(seconds) { const days = Math.floor(seconds / 86400); const hours = Math.floor((seconds % 86400) / 3600); const minutes = Math.floor(((seconds % 86400) % 3600) / 60); const secs = ((seconds % 86400) % 3600) % 60; if (this.durationFormatInstance !== undefined) { // use Intl.DurationFormat if available return this.durationFormatInstance.format({ days, hours, minutes, seconds: secs }); } const parts = []; /** * Build the formatted string from parts * 1. Get the relative time formatted parts from the instance. * 2. Filter out the relevant parts literal (unit of time) or integer (value). * 3. Map out the required values. * @param {number} value Receives value in seconds. * @param {string} unitOfTime Expected unit of time after conversion. * @returns {void} */ const toFormattedPart = (value, unitOfTime) => { const partsArray = this.relativeTimeFormatInstance.formatToParts(value, unitOfTime); const filteredParts = partsArray .filter( (part, index) => part.type === "integer" || (part.type === "literal" && index > 0) ) .map((part) => part.value); const formattedString = filteredParts.join("").trim(); parts.push(formattedString); }; if (days > 0) { toFormattedPart(days, "day"); } if (hours > 0) { toFormattedPart(hours, "hour"); } if (minutes > 0) { toFormattedPart(minutes, "minute"); } if (secs > 0) { toFormattedPart(secs, "second"); } if (parts.length > 0) { return `${parts.join(" ")}`; } return this.relativeTimeFormatInstance.format(0, "second"); // Handle case for 0 seconds } } export const timeDurationFormatter = new TimeDurationFormatter();
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/src/util.js
src/util.js
"use strict"; /*! // Common Util for frontend and backend // // DOT NOT MODIFY util.js! // Need to run "npm run tsc" to compile if there are any changes. // // Backend uses the compiled file util.js // Frontend uses util.ts */ var _a; Object.defineProperty(exports, "__esModule", { value: true }); exports.CONSOLE_STYLE_FgPink = exports.CONSOLE_STYLE_FgBrown = exports.CONSOLE_STYLE_FgViolet = exports.CONSOLE_STYLE_FgLightBlue = exports.CONSOLE_STYLE_FgLightGreen = exports.CONSOLE_STYLE_FgOrange = exports.CONSOLE_STYLE_FgGray = exports.CONSOLE_STYLE_FgWhite = exports.CONSOLE_STYLE_FgCyan = exports.CONSOLE_STYLE_FgMagenta = exports.CONSOLE_STYLE_FgBlue = exports.CONSOLE_STYLE_FgYellow = exports.CONSOLE_STYLE_FgGreen = exports.CONSOLE_STYLE_FgRed = exports.CONSOLE_STYLE_FgBlack = exports.CONSOLE_STYLE_Hidden = exports.CONSOLE_STYLE_Reverse = exports.CONSOLE_STYLE_Blink = exports.CONSOLE_STYLE_Underscore = exports.CONSOLE_STYLE_Dim = exports.CONSOLE_STYLE_Bright = exports.CONSOLE_STYLE_Reset = exports.PING_PER_REQUEST_TIMEOUT_DEFAULT = exports.PING_PER_REQUEST_TIMEOUT_MAX = exports.PING_PER_REQUEST_TIMEOUT_MIN = exports.PING_COUNT_DEFAULT = exports.PING_COUNT_MAX = exports.PING_COUNT_MIN = exports.PING_GLOBAL_TIMEOUT_DEFAULT = exports.PING_GLOBAL_TIMEOUT_MAX = exports.PING_GLOBAL_TIMEOUT_MIN = exports.PING_PACKET_SIZE_DEFAULT = exports.PING_PACKET_SIZE_MAX = exports.PING_PACKET_SIZE_MIN = exports.MIN_INTERVAL_SECOND = exports.MAX_INTERVAL_SECOND = exports.SQL_DATETIME_FORMAT_WITHOUT_SECOND = exports.SQL_DATETIME_FORMAT = exports.SQL_DATE_FORMAT = exports.STATUS_PAGE_MAINTENANCE = exports.STATUS_PAGE_PARTIAL_DOWN = exports.STATUS_PAGE_ALL_UP = exports.STATUS_PAGE_ALL_DOWN = exports.MAINTENANCE = exports.PENDING = exports.UP = exports.DOWN = exports.appName = exports.isNode = exports.isDev = void 0; exports.evaluateJsonQuery = exports.intHash = exports.localToUTC = exports.utcToLocal = exports.utcToISODateTime = exports.isoToUTCDateTime = exports.parseTimeFromTimeObject = exports.parseTimeObject = exports.getMaintenanceRelativeURL = exports.getMonitorRelativeURL = exports.genSecret = exports.getCryptoRandomInt = exports.getRandomInt = exports.getRandomArbitrary = exports.TimeLogger = exports.polyfill = exports.log = exports.debug = exports.ucfirst = exports.sleep = exports.flipStatus = exports.badgeConstants = exports.CONSOLE_STYLE_BgGray = exports.CONSOLE_STYLE_BgWhite = exports.CONSOLE_STYLE_BgCyan = exports.CONSOLE_STYLE_BgMagenta = exports.CONSOLE_STYLE_BgBlue = exports.CONSOLE_STYLE_BgYellow = exports.CONSOLE_STYLE_BgGreen = exports.CONSOLE_STYLE_BgRed = exports.CONSOLE_STYLE_BgBlack = void 0; const dayjs_1 = require("dayjs"); const jsonata = require("jsonata"); exports.isDev = process.env.NODE_ENV === "development"; exports.isNode = typeof process !== "undefined" && ((_a = process === null || process === void 0 ? void 0 : process.versions) === null || _a === void 0 ? void 0 : _a.node); const dayjs = (exports.isNode) ? require("dayjs") : dayjs_1.default; exports.appName = "Uptime Kuma"; exports.DOWN = 0; exports.UP = 1; exports.PENDING = 2; exports.MAINTENANCE = 3; exports.STATUS_PAGE_ALL_DOWN = 0; exports.STATUS_PAGE_ALL_UP = 1; exports.STATUS_PAGE_PARTIAL_DOWN = 2; exports.STATUS_PAGE_MAINTENANCE = 3; exports.SQL_DATE_FORMAT = "YYYY-MM-DD"; exports.SQL_DATETIME_FORMAT = "YYYY-MM-DD HH:mm:ss"; exports.SQL_DATETIME_FORMAT_WITHOUT_SECOND = "YYYY-MM-DD HH:mm"; exports.MAX_INTERVAL_SECOND = 2073600; exports.MIN_INTERVAL_SECOND = 1; exports.PING_PACKET_SIZE_MIN = 1; exports.PING_PACKET_SIZE_MAX = 65500; exports.PING_PACKET_SIZE_DEFAULT = 56; exports.PING_GLOBAL_TIMEOUT_MIN = 1; exports.PING_GLOBAL_TIMEOUT_MAX = 300; exports.PING_GLOBAL_TIMEOUT_DEFAULT = 10; exports.PING_COUNT_MIN = 1; exports.PING_COUNT_MAX = 100; exports.PING_COUNT_DEFAULT = 1; exports.PING_PER_REQUEST_TIMEOUT_MIN = 1; exports.PING_PER_REQUEST_TIMEOUT_MAX = 60; exports.PING_PER_REQUEST_TIMEOUT_DEFAULT = 2; exports.CONSOLE_STYLE_Reset = "\x1b[0m"; exports.CONSOLE_STYLE_Bright = "\x1b[1m"; exports.CONSOLE_STYLE_Dim = "\x1b[2m"; exports.CONSOLE_STYLE_Underscore = "\x1b[4m"; exports.CONSOLE_STYLE_Blink = "\x1b[5m"; exports.CONSOLE_STYLE_Reverse = "\x1b[7m"; exports.CONSOLE_STYLE_Hidden = "\x1b[8m"; exports.CONSOLE_STYLE_FgBlack = "\x1b[30m"; exports.CONSOLE_STYLE_FgRed = "\x1b[31m"; exports.CONSOLE_STYLE_FgGreen = "\x1b[32m"; exports.CONSOLE_STYLE_FgYellow = "\x1b[33m"; exports.CONSOLE_STYLE_FgBlue = "\x1b[34m"; exports.CONSOLE_STYLE_FgMagenta = "\x1b[35m"; exports.CONSOLE_STYLE_FgCyan = "\x1b[36m"; exports.CONSOLE_STYLE_FgWhite = "\x1b[37m"; exports.CONSOLE_STYLE_FgGray = "\x1b[90m"; exports.CONSOLE_STYLE_FgOrange = "\x1b[38;5;208m"; exports.CONSOLE_STYLE_FgLightGreen = "\x1b[38;5;119m"; exports.CONSOLE_STYLE_FgLightBlue = "\x1b[38;5;117m"; exports.CONSOLE_STYLE_FgViolet = "\x1b[38;5;141m"; exports.CONSOLE_STYLE_FgBrown = "\x1b[38;5;130m"; exports.CONSOLE_STYLE_FgPink = "\x1b[38;5;219m"; exports.CONSOLE_STYLE_BgBlack = "\x1b[40m"; exports.CONSOLE_STYLE_BgRed = "\x1b[41m"; exports.CONSOLE_STYLE_BgGreen = "\x1b[42m"; exports.CONSOLE_STYLE_BgYellow = "\x1b[43m"; exports.CONSOLE_STYLE_BgBlue = "\x1b[44m"; exports.CONSOLE_STYLE_BgMagenta = "\x1b[45m"; exports.CONSOLE_STYLE_BgCyan = "\x1b[46m"; exports.CONSOLE_STYLE_BgWhite = "\x1b[47m"; exports.CONSOLE_STYLE_BgGray = "\x1b[100m"; const consoleModuleColors = [ exports.CONSOLE_STYLE_FgCyan, exports.CONSOLE_STYLE_FgGreen, exports.CONSOLE_STYLE_FgLightGreen, exports.CONSOLE_STYLE_FgBlue, exports.CONSOLE_STYLE_FgLightBlue, exports.CONSOLE_STYLE_FgMagenta, exports.CONSOLE_STYLE_FgOrange, exports.CONSOLE_STYLE_FgViolet, exports.CONSOLE_STYLE_FgBrown, exports.CONSOLE_STYLE_FgPink, ]; const consoleLevelColors = { "INFO": exports.CONSOLE_STYLE_FgCyan, "WARN": exports.CONSOLE_STYLE_FgYellow, "ERROR": exports.CONSOLE_STYLE_FgRed, "DEBUG": exports.CONSOLE_STYLE_FgGray, }; exports.badgeConstants = { naColor: "#999", defaultUpColor: "#66c20a", defaultWarnColor: "#eed202", defaultDownColor: "#c2290a", defaultPendingColor: "#f8a306", defaultMaintenanceColor: "#1747f5", defaultPingColor: "blue", defaultStyle: "flat", defaultPingValueSuffix: "ms", defaultPingLabelSuffix: "h", defaultUptimeValueSuffix: "%", defaultUptimeLabelSuffix: "h", defaultCertExpValueSuffix: " days", defaultCertExpLabelSuffix: "h", defaultCertExpireWarnDays: "14", defaultCertExpireDownDays: "7" }; function flipStatus(s) { if (s === exports.UP) { return exports.DOWN; } if (s === exports.DOWN) { return exports.UP; } return s; } exports.flipStatus = flipStatus; function sleep(ms) { return new Promise(resolve => setTimeout(resolve, ms)); } exports.sleep = sleep; function ucfirst(str) { if (!str) { return str; } const firstLetter = str.substr(0, 1); return firstLetter.toUpperCase() + str.substr(1); } exports.ucfirst = ucfirst; function debug(msg) { exports.log.log("", "debug", msg); } exports.debug = debug; class Logger { constructor() { this.hideLog = { info: [], warn: [], error: [], debug: [], }; if (typeof process !== "undefined" && process.env.UPTIME_KUMA_HIDE_LOG) { const list = process.env.UPTIME_KUMA_HIDE_LOG.split(",").map(v => v.toLowerCase()); for (const pair of list) { const values = pair.split(/_(.*)/s); if (values.length >= 2) { this.hideLog[values[0]].push(values[1]); } } this.debug("server", "UPTIME_KUMA_HIDE_LOG is set"); this.debug("server", this.hideLog); } } log(module, level, ...msg) { if (level === "DEBUG" && !exports.isDev) { return; } if (this.hideLog[level] && this.hideLog[level].includes(module.toLowerCase())) { return; } module = module.toUpperCase(); level = level.toUpperCase(); let now; if (dayjs.tz) { now = dayjs.tz(new Date()).format(); } else { now = dayjs().format(); } const levelColor = consoleLevelColors[level]; const moduleColor = consoleModuleColors[intHash(module, consoleModuleColors.length)]; let timePart; let modulePart; let levelPart; if (exports.isNode) { switch (level) { case "DEBUG": timePart = exports.CONSOLE_STYLE_FgGray + now + exports.CONSOLE_STYLE_Reset; break; default: timePart = exports.CONSOLE_STYLE_FgCyan + now + exports.CONSOLE_STYLE_Reset; break; } modulePart = "[" + moduleColor + module + exports.CONSOLE_STYLE_Reset + "]"; levelPart = levelColor + `${level}:` + exports.CONSOLE_STYLE_Reset; } else { timePart = now; modulePart = `[${module}]`; levelPart = `${level}:`; } switch (level) { case "ERROR": console.error(timePart, modulePart, levelPart, ...msg); break; case "WARN": console.warn(timePart, modulePart, levelPart, ...msg); break; case "INFO": console.info(timePart, modulePart, levelPart, ...msg); break; case "DEBUG": if (exports.isDev) { console.debug(timePart, modulePart, levelPart, ...msg); } break; default: console.log(timePart, modulePart, levelPart, ...msg); break; } } info(module, ...msg) { this.log(module, "info", ...msg); } warn(module, ...msg) { this.log(module, "warn", ...msg); } error(module, ...msg) { this.log(module, "error", ...msg); } debug(module, ...msg) { this.log(module, "debug", ...msg); } exception(module, exception, ...msg) { this.log(module, "error", ...msg, exception); } } exports.log = new Logger(); function polyfill() { if (!String.prototype.replaceAll) { String.prototype.replaceAll = function (str, newStr) { if (Object.prototype.toString.call(str).toLowerCase() === "[object regexp]") { return this.replace(str, newStr); } return this.replace(new RegExp(str, "g"), newStr); }; } } exports.polyfill = polyfill; class TimeLogger { constructor() { this.startTime = dayjs().valueOf(); } print(name) { if (exports.isDev && process.env.TIMELOGGER === "1") { console.log(name + ": " + (dayjs().valueOf() - this.startTime) + "ms"); } } } exports.TimeLogger = TimeLogger; function getRandomArbitrary(min, max) { return Math.random() * (max - min) + min; } exports.getRandomArbitrary = getRandomArbitrary; function getRandomInt(min, max) { min = Math.ceil(min); max = Math.floor(max); return Math.floor(Math.random() * (max - min + 1)) + min; } exports.getRandomInt = getRandomInt; const getRandomBytes = ((typeof window !== "undefined" && window.crypto) ? function () { return (numBytes) => { const randomBytes = new Uint8Array(numBytes); for (let i = 0; i < numBytes; i += 65536) { window.crypto.getRandomValues(randomBytes.subarray(i, i + Math.min(numBytes - i, 65536))); } return randomBytes; }; } : function () { return require("crypto").randomBytes; })(); function getCryptoRandomInt(min, max) { const range = max - min; if (range >= Math.pow(2, 32)) { console.log("Warning! Range is too large."); } let tmpRange = range; let bitsNeeded = 0; let bytesNeeded = 0; let mask = 1; while (tmpRange > 0) { if (bitsNeeded % 8 === 0) { bytesNeeded += 1; } bitsNeeded += 1; mask = mask << 1 | 1; tmpRange = tmpRange >>> 1; } const randomBytes = getRandomBytes(bytesNeeded); let randomValue = 0; for (let i = 0; i < bytesNeeded; i++) { randomValue |= randomBytes[i] << 8 * i; } randomValue = randomValue & mask; if (randomValue <= range) { return min + randomValue; } else { return getCryptoRandomInt(min, max); } } exports.getCryptoRandomInt = getCryptoRandomInt; function genSecret(length = 64) { let secret = ""; const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; const charsLength = chars.length; for (let i = 0; i < length; i++) { secret += chars.charAt(getCryptoRandomInt(0, charsLength - 1)); } return secret; } exports.genSecret = genSecret; function getMonitorRelativeURL(id) { return "/dashboard/" + id; } exports.getMonitorRelativeURL = getMonitorRelativeURL; function getMaintenanceRelativeURL(id) { return "/maintenance/" + id; } exports.getMaintenanceRelativeURL = getMaintenanceRelativeURL; function parseTimeObject(time) { if (!time) { return { hours: 0, minutes: 0, }; } const array = time.split(":"); if (array.length < 2) { throw new Error("parseVueDatePickerTimeFormat: Invalid Time"); } const obj = { hours: parseInt(array[0]), minutes: parseInt(array[1]), seconds: 0, }; if (array.length >= 3) { obj.seconds = parseInt(array[2]); } return obj; } exports.parseTimeObject = parseTimeObject; function parseTimeFromTimeObject(obj) { if (!obj) { return obj; } let result = ""; result += obj.hours.toString().padStart(2, "0") + ":" + obj.minutes.toString().padStart(2, "0"); if (obj.seconds) { result += ":" + obj.seconds.toString().padStart(2, "0"); } return result; } exports.parseTimeFromTimeObject = parseTimeFromTimeObject; function isoToUTCDateTime(input) { return dayjs(input).utc().format(exports.SQL_DATETIME_FORMAT); } exports.isoToUTCDateTime = isoToUTCDateTime; function utcToISODateTime(input) { return dayjs.utc(input).toISOString(); } exports.utcToISODateTime = utcToISODateTime; function utcToLocal(input, format = exports.SQL_DATETIME_FORMAT) { return dayjs.utc(input).local().format(format); } exports.utcToLocal = utcToLocal; function localToUTC(input, format = exports.SQL_DATETIME_FORMAT) { return dayjs(input).utc().format(format); } exports.localToUTC = localToUTC; function intHash(str, length = 10) { let hash = 0; for (let i = 0; i < str.length; i++) { hash += str.charCodeAt(i); } return (hash % length + length) % length; } exports.intHash = intHash; async function evaluateJsonQuery(data, jsonPath, jsonPathOperator, expectedValue) { let response; try { response = JSON.parse(data); } catch (_a) { response = (typeof data === "object" || typeof data === "number") && !Buffer.isBuffer(data) ? data : data.toString(); } try { response = (jsonPath) ? await jsonata(jsonPath).evaluate(response) : response; if (response === null || response === undefined) { throw new Error("Empty or undefined response. Check query syntax and response structure"); } if (Array.isArray(response)) { const responseStr = JSON.stringify(response); const truncatedResponse = responseStr.length > 25 ? responseStr.substring(0, 25) + "...]" : responseStr; throw new Error("JSON query returned the array " + truncatedResponse + ", but a primitive value is required. " + "Modify your query to return a single value via [0] to get the first element or use an aggregation like $count(), $sum() or $boolean()."); } if (typeof response === "object" || response instanceof Date || typeof response === "function") { throw new Error(`The post-JSON query evaluated response from the server is of type ${typeof response}, which cannot be directly compared to the expected value`); } let jsonQueryExpression; switch (jsonPathOperator) { case ">": case ">=": case "<": case "<=": jsonQueryExpression = `$number($.value) ${jsonPathOperator} $number($.expected)`; break; case "!=": jsonQueryExpression = "$.value != $.expected"; break; case "==": jsonQueryExpression = "$.value = $.expected"; break; case "contains": jsonQueryExpression = "$contains($.value, $.expected)"; break; default: throw new Error(`Invalid condition ${jsonPathOperator}`); } const expression = jsonata(jsonQueryExpression); const status = await expression.evaluate({ value: response.toString(), expected: expectedValue.toString() }); if (status === undefined) { throw new Error("Query evaluation returned undefined. Check query syntax and the structure of the response data"); } return { status, response }; } catch (err) { response = JSON.stringify(response); response = (response && response.length > 50) ? `${response.substring(0, 100)}… (truncated)` : response; throw new Error(`Error evaluating JSON query: ${err.message}. Response from server was: ${response}`); } } exports.evaluateJsonQuery = evaluateJsonQuery;
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/src/components/notifications/index.js
src/components/notifications/index.js
import Alerta from "./Alerta.vue"; import AlertNow from "./AlertNow.vue"; import AliyunSMS from "./AliyunSms.vue"; import Apprise from "./Apprise.vue"; import Bale from "./Bale.vue"; import Bark from "./Bark.vue"; import Bitrix24 from "./Bitrix24.vue"; import Notifery from "./Notifery.vue"; import ClickSendSMS from "./ClickSendSMS.vue"; import CallMeBot from "./CallMeBot.vue"; import SMSC from "./SMSC.vue"; import DingDing from "./DingDing.vue"; import Discord from "./Discord.vue"; import Elks from "./46elks.vue"; import Feishu from "./Feishu.vue"; import FreeMobile from "./FreeMobile.vue"; import GoogleChat from "./GoogleChat.vue"; import Gorush from "./Gorush.vue"; import Gotify from "./Gotify.vue"; import GrafanaOncall from "./GrafanaOncall.vue"; import GtxMessaging from "./GtxMessaging.vue"; import HomeAssistant from "./HomeAssistant.vue"; import HeiiOnCall from "./HeiiOnCall.vue"; import Keep from "./Keep.vue"; import Kook from "./Kook.vue"; import Line from "./Line.vue"; import LunaSea from "./LunaSea.vue"; import Matrix from "./Matrix.vue"; import Mattermost from "./Mattermost.vue"; import NextcloudTalk from "./NextcloudTalk.vue"; import Nostr from "./Nostr.vue"; import Ntfy from "./Ntfy.vue"; import Octopush from "./Octopush.vue"; import OneChat from "./OneChat.vue"; import OneBot from "./OneBot.vue"; import Onesender from "./Onesender.vue"; import Opsgenie from "./Opsgenie.vue"; import PagerDuty from "./PagerDuty.vue"; import FlashDuty from "./FlashDuty.vue"; import PagerTree from "./PagerTree.vue"; import PromoSMS from "./PromoSMS.vue"; import Pumble from "./Pumble.vue"; import Pushbullet from "./Pushbullet.vue"; import PushDeer from "./PushDeer.vue"; import Pushover from "./Pushover.vue"; import PushPlus from "./PushPlus.vue"; import Pushy from "./Pushy.vue"; import RocketChat from "./RocketChat.vue"; import ServerChan from "./ServerChan.vue"; import SerwerSMS from "./SerwerSMS.vue"; import Signal from "./Signal.vue"; import SMSManager from "./SMSManager.vue"; import SMSPartner from "./SMSPartner.vue"; import Slack from "./Slack.vue"; import Squadcast from "./Squadcast.vue"; import SMSEagle from "./SMSEagle.vue"; import Stackfield from "./Stackfield.vue"; import STMP from "./SMTP.vue"; import Teams from "./Teams.vue"; import TechulusPush from "./TechulusPush.vue"; import Telegram from "./Telegram.vue"; import Threema from "./Threema.vue"; import Twilio from "./Twilio.vue"; import Webhook from "./Webhook.vue"; import WeCom from "./WeCom.vue"; import GoAlert from "./GoAlert.vue"; import ZohoCliq from "./ZohoCliq.vue"; import Splunk from "./Splunk.vue"; import SpugPush from "./SpugPush.vue"; import SevenIO from "./SevenIO.vue"; import Whapi from "./Whapi.vue"; import WAHA from "./WAHA.vue"; import Evolution from "./Evolution.vue"; import Cellsynt from "./Cellsynt.vue"; import WPush from "./WPush.vue"; import SIGNL4 from "./SIGNL4.vue"; import SendGrid from "./SendGrid.vue"; import Brevo from "./Brevo.vue"; import YZJ from "./YZJ.vue"; import SMSPlanet from "./SMSPlanet.vue"; import SMSIR from "./SMSIR.vue"; import Webpush from "./Webpush.vue"; import Resend from "./Resend.vue"; /** * Manage all notification form. * @type { Record<string, any> } */ const NotificationFormList = { "alerta": Alerta, "AlertNow": AlertNow, "AliyunSMS": AliyunSMS, "apprise": Apprise, bale: Bale, "Bark": Bark, "Bitrix24": Bitrix24, "clicksendsms": ClickSendSMS, "CallMeBot": CallMeBot, "smsc": SMSC, "smsir": SMSIR, "DingDing": DingDing, "discord": Discord, "Elks": Elks, "Feishu": Feishu, "FreeMobile": FreeMobile, "GoogleChat": GoogleChat, "gorush": Gorush, "gotify": Gotify, "GrafanaOncall": GrafanaOncall, "HomeAssistant": HomeAssistant, "HeiiOnCall": HeiiOnCall, "Keep": Keep, "Kook": Kook, "line": Line, "lunasea": LunaSea, "matrix": Matrix, "mattermost": Mattermost, "nextcloudtalk": NextcloudTalk, "nostr": Nostr, "ntfy": Ntfy, "octopush": Octopush, "OneChat": OneChat, "OneBot": OneBot, "Onesender": Onesender, "Opsgenie": Opsgenie, "PagerDuty": PagerDuty, "FlashDuty": FlashDuty, "PagerTree": PagerTree, "promosms": PromoSMS, "pumble": Pumble, "pushbullet": Pushbullet, "PushByTechulus": TechulusPush, "PushDeer": PushDeer, "pushover": Pushover, "PushPlus": PushPlus, "pushy": Pushy, "rocket.chat": RocketChat, "serwersms": SerwerSMS, "signal": Signal, "SIGNL4": SIGNL4, "SMSManager": SMSManager, "SMSPartner": SMSPartner, "slack": Slack, "squadcast": Squadcast, "SMSEagle": SMSEagle, "smtp": STMP, "stackfield": Stackfield, "teams": Teams, "telegram": Telegram, "threema": Threema, "twilio": Twilio, "Splunk": Splunk, "SpugPush": SpugPush, "webhook": Webhook, "WeCom": WeCom, "GoAlert": GoAlert, "ServerChan": ServerChan, "ZohoCliq": ZohoCliq, "SevenIO": SevenIO, "whapi": Whapi, "evolution": Evolution, "notifery": Notifery, "waha": WAHA, "gtxmessaging": GtxMessaging, "Cellsynt": Cellsynt, "WPush": WPush, "SendGrid": SendGrid, "Brevo": Brevo, "Resend": Resend, "YZJ": YZJ, "SMSPlanet": SMSPlanet, "Webpush": Webpush, }; export default NotificationFormList;
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/src/modules/dayjs/constant.js
src/modules/dayjs/constant.js
export let SECONDS_A_MINUTE = 60; export let SECONDS_A_HOUR = SECONDS_A_MINUTE * 60; export let SECONDS_A_DAY = SECONDS_A_HOUR * 24; export let SECONDS_A_WEEK = SECONDS_A_DAY * 7; export let MILLISECONDS_A_SECOND = 1e3; export let MILLISECONDS_A_MINUTE = SECONDS_A_MINUTE * MILLISECONDS_A_SECOND; export let MILLISECONDS_A_HOUR = SECONDS_A_HOUR * MILLISECONDS_A_SECOND; export let MILLISECONDS_A_DAY = SECONDS_A_DAY * MILLISECONDS_A_SECOND; export let MILLISECONDS_A_WEEK = SECONDS_A_WEEK * MILLISECONDS_A_SECOND; // English locales export let MS = "millisecond"; export let S = "second"; export let MIN = "minute"; export let H = "hour"; export let D = "day"; export let W = "week"; export let M = "month"; export let Q = "quarter"; export let Y = "year"; export let DATE = "date"; export let FORMAT_DEFAULT = "YYYY-MM-DDTHH:mm:ssZ"; export let INVALID_DATE_STRING = "Invalid Date"; // regex export let REGEX_PARSE = /^(\d{4})[-/]?(\d{1,2})?[-/]?(\d{0,2})[Tt\s]*(\d{1,2})?:?(\d{1,2})?:?(\d{1,2})?[.:]?(\d+)?$/; export let REGEX_FORMAT = /\[([^\]]+)]|Y{1,4}|M{1,4}|D{1,2}|d{1,4}|H{1,2}|h{1,2}|a|A|m{1,2}|s{1,2}|Z{1,2}|SSS/g;
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/src/modules/dayjs/plugin/timezone/index.js
src/modules/dayjs/plugin/timezone/index.js
/** * Copy from node_modules/dayjs/plugin/timezone.js * Try to fix https://github.com/louislam/uptime-kuma/issues/2318 * Source: https://github.com/iamkun/dayjs/tree/dev/src/plugin/utc * License: MIT */ import { MIN, MS } from "../../constant"; let typeToPos = { year: 0, month: 1, day: 2, hour: 3, minute: 4, second: 5 }; // Cache time-zone lookups from Intl.DateTimeFormat, // as it is a *very* slow method. let dtfCache = {}; let getDateTimeFormat = function getDateTimeFormat(timezone, options) { if (options === void 0) { options = {}; } let timeZoneName = options.timeZoneName || "short"; let key = timezone + "|" + timeZoneName; let dtf = dtfCache[key]; if (!dtf) { dtf = new Intl.DateTimeFormat("en-US", { hour12: false, timeZone: timezone, year: "numeric", month: "2-digit", day: "2-digit", hour: "2-digit", minute: "2-digit", second: "2-digit", timeZoneName: timeZoneName }); dtfCache[key] = dtf; } return dtf; }; export default (function (o, c, d) { let defaultTimezone; let makeFormatParts = function makeFormatParts(timestamp, timezone, options) { if (options === void 0) { options = {}; } let date = new Date(timestamp); let dtf = getDateTimeFormat(timezone, options); return dtf.formatToParts(date); }; let tzOffset = function tzOffset(timestamp, timezone) { let formatResult = makeFormatParts(timestamp, timezone); let filled = []; for (let i = 0; i < formatResult.length; i += 1) { let _formatResult$i = formatResult[i]; let type = _formatResult$i.type; let value = _formatResult$i.value; let pos = typeToPos[type]; if (pos >= 0) { filled[pos] = parseInt(value, 10); } } let hour = filled[3]; // Workaround for the same behavior in different node version // https://github.com/nodejs/node/issues/33027 /* istanbul ignore next */ let fixedHour = hour === 24 ? 0 : hour; let utcString = filled[0] + "-" + filled[1] + "-" + filled[2] + " " + fixedHour + ":" + filled[4] + ":" + filled[5] + ":000"; let utcTs = d.utc(utcString).valueOf(); let asTS = +timestamp; let over = asTS % 1000; asTS -= over; return (utcTs - asTS) / (60 * 1000); }; // find the right offset a given local time. The o input is our guess, which determines which // offset we'll pick in ambiguous cases (e.g. there are two 3 AMs b/c Fallback DST) // https://github.com/moment/luxon/blob/master/src/datetime.js#L76 let fixOffset = function fixOffset(localTS, o0, tz) { // Our UTC time is just a guess because our offset is just a guess let utcGuess = localTS - o0 * 60 * 1000; // Test whether the zone matches the offset for this ts let o2 = tzOffset(utcGuess, tz); // If so, offset didn't change and we're done if (o0 === o2) { return [ utcGuess, o0 ]; } // If not, change the ts by the difference in the offset utcGuess -= (o2 - o0) * 60 * 1000; // If that gives us the local time we want, we're done let o3 = tzOffset(utcGuess, tz); if (o2 === o3) { return [ utcGuess, o2 ]; } // If it's different, we're in a hole time. // The offset has changed, but the we don't adjust the time return [ localTS - Math.min(o2, o3) * 60 * 1000, Math.max(o2, o3) ]; }; let proto = c.prototype; proto.tz = function (timezone, keepLocalTime) { if (timezone === void 0) { timezone = defaultTimezone; } let oldOffset = this.utcOffset(); let date = this.toDate(); let target = date.toLocaleString("en-US", { timeZone: timezone }).replace("\u202f", " "); let diff = Math.round((date - new Date(target)) / 1000 / 60); let ins = d(target).$set(MS, this.$ms).utcOffset(-Math.round(date.getTimezoneOffset() / 15) * 15 - diff, true); if (keepLocalTime) { let newOffset = ins.utcOffset(); ins = ins.add(oldOffset - newOffset, MIN); } ins.$x.$timezone = timezone; return ins; }; proto.offsetName = function (type) { // type: short(default) / long let zone = this.$x.$timezone || d.tz.guess(); let result = makeFormatParts(this.valueOf(), zone, { timeZoneName: type }).find(function (m) { return m.type.toLowerCase() === "timezonename"; }); return result && result.value; }; let oldStartOf = proto.startOf; proto.startOf = function (units, startOf) { if (!this.$x || !this.$x.$timezone) { return oldStartOf.call(this, units, startOf); } let withoutTz = d(this.format("YYYY-MM-DD HH:mm:ss:SSS")); let startOfWithoutTz = oldStartOf.call(withoutTz, units, startOf); return startOfWithoutTz.tz(this.$x.$timezone, true); }; d.tz = function (input, arg1, arg2) { let parseFormat = arg2 && arg1; let timezone = arg2 || arg1 || defaultTimezone; let previousOffset = tzOffset(+d(), timezone); if (typeof input !== "string") { // timestamp number || js Date || Day.js return d(input).tz(timezone); } let localTs = d.utc(input, parseFormat).valueOf(); let _fixOffset = fixOffset(localTs, previousOffset, timezone); let targetTs = _fixOffset[0]; let targetOffset = _fixOffset[1]; let ins = d(targetTs).utcOffset(targetOffset); ins.$x.$timezone = timezone; return ins; }; d.tz.guess = function () { return Intl.DateTimeFormat().resolvedOptions().timeZone; }; d.tz.setDefault = function (timezone) { defaultTimezone = timezone; }; });
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/src/mixins/public.js
src/mixins/public.js
import axios from "axios"; import { getDevContainerServerHostname, isDevContainer } from "../util-frontend"; const env = process.env.NODE_ENV || "production"; // change the axios base url for development if (env === "development" && isDevContainer()) { axios.defaults.baseURL = location.protocol + "//" + getDevContainerServerHostname(); } else if (env === "development" || localStorage.dev === "dev") { axios.defaults.baseURL = location.protocol + "//" + location.hostname + ":3001"; } export default { data() { return { publicGroupList: [], }; }, computed: { publicMonitorList() { let result = {}; for (let group of this.publicGroupList) { for (let monitor of group.monitorList) { result[monitor.id] = monitor; } } return result; }, publicLastHeartbeatList() { let result = {}; for (let monitorID in this.publicMonitorList) { if (this.lastHeartbeatList[monitorID]) { result[monitorID] = this.lastHeartbeatList[monitorID]; } } return result; }, baseURL() { if (this.$root.info.primaryBaseURL) { return this.$root.info.primaryBaseURL; } if (env === "development" || localStorage.dev === "dev") { return axios.defaults.baseURL; } else { return location.protocol + "//" + location.host; } }, } };
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/src/mixins/datetime.js
src/mixins/datetime.js
import dayjs from "dayjs"; /** * DateTime Mixin * Handled timezone and format */ export default { data() { return { userTimezone: localStorage.timezone || "auto", }; }, methods: { /** * Convert value to UTC * @param {string | number | Date | dayjs.Dayjs} value Time * value to convert * @returns {dayjs.Dayjs} Converted time */ toUTC(value) { return dayjs.tz(value, this.timezone).utc().format(); }, /** * Used for <input type="datetime" /> * @param {string | number | Date | dayjs.Dayjs} value Value to * convert * @returns {string} Datetime string */ toDateTimeInputFormat(value) { return this.datetimeFormat(value, "YYYY-MM-DDTHH:mm"); }, /** * Return a given value in the format YYYY-MM-DD HH:mm:ss * @param {any} value Value to format as date time * @returns {string} Formatted string */ datetime(value) { return this.datetimeFormat(value, "YYYY-MM-DD HH:mm:ss"); }, /** * Converts a Unix timestamp to a formatted date and time string. * @param {number} value - The Unix timestamp to convert. * @returns {string} The formatted date and time string. */ unixToDateTime(value) { return dayjs.unix(value).tz(this.timezone).format("YYYY-MM-DD HH:mm:ss"); }, /** * Converts a Unix timestamp to a dayjs object. * @param {number} value - The Unix timestamp to convert. * @returns {dayjs.Dayjs} The dayjs object representing the given timestamp. */ unixToDayjs(value) { return dayjs.unix(value).tz(this.timezone); }, /** * Converts the given value to a dayjs object. * @param {string} value - the value to be converted * @returns {dayjs.Dayjs} a dayjs object in the timezone of this instance */ toDayjs(value) { return dayjs.utc(value).tz(this.timezone); }, /** * Get time for maintenance * @param {string | number | Date | dayjs.Dayjs} value Time to * format * @returns {string} Formatted string */ datetimeMaintenance(value) { const inputDate = new Date(value); const now = new Date(Date.now()); if (inputDate.getFullYear() === now.getUTCFullYear() && inputDate.getMonth() === now.getUTCMonth() && inputDate.getDay() === now.getUTCDay()) { return this.datetimeFormat(value, "HH:mm"); } else { return this.datetimeFormat(value, "YYYY-MM-DD HH:mm"); } }, /** * Return a given value in the format YYYY-MM-DD * @param {any} value Value to format as date * @returns {string} Formatted string */ date(value) { return this.datetimeFormat(value, "YYYY-MM-DD"); }, /** * Return a given value in the format HH:mm or if second is set * to true, HH:mm:ss * @param {any} value Value to format * @param {boolean} second Should seconds be included? * @returns {string} Formatted string */ time(value, second = true) { let secondString; if (second) { secondString = ":ss"; } else { secondString = ""; } return this.datetimeFormat(value, "HH:mm" + secondString); }, /** * Return a value in a custom format * @param {any} value Value to format * @param {any} format Format to return value in * @returns {string} Formatted string */ datetimeFormat(value, format) { if (value !== undefined && value !== "") { return dayjs.utc(value).tz(this.timezone).format(format); } return ""; }, }, computed: { timezone() { if (this.userTimezone === "auto") { return dayjs.tz.guess(); } return this.userTimezone; }, } };
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/src/mixins/theme.js
src/mixins/theme.js
export default { data() { return { system: (window.matchMedia("(prefers-color-scheme: dark)").matches) ? "dark" : "light", userTheme: localStorage.theme, userHeartbeatBar: localStorage.heartbeatBarTheme, styleElapsedTime: localStorage.styleElapsedTime, statusPageTheme: "light", forceStatusPageTheme: false, path: "", }; }, mounted() { // Default Light if (! this.userTheme) { this.userTheme = "auto"; } // Default Heartbeat Bar if (!this.userHeartbeatBar) { this.userHeartbeatBar = "normal"; } // Default Elapsed Time Style if (!this.styleElapsedTime) { this.styleElapsedTime = "no-line"; } document.body.classList.add(this.theme); this.updateThemeColorMeta(); }, computed: { theme() { // As entry can be status page now, set forceStatusPageTheme to true to use status page theme if (this.forceStatusPageTheme) { if (this.statusPageTheme === "auto") { return this.system; } return this.statusPageTheme; } // Entry no need dark if (this.path === "") { return "light"; } if (this.path.startsWith("/status-page") || this.path.startsWith("/status")) { if (this.statusPageTheme === "auto") { return this.system; } return this.statusPageTheme; } else { if (this.userTheme === "auto") { return this.system; } return this.userTheme; } }, isDark() { return this.theme === "dark"; } }, watch: { "$route.fullPath"(path) { this.path = path; }, userTheme(to, from) { localStorage.theme = to; }, styleElapsedTime(to, from) { localStorage.styleElapsedTime = to; }, theme(to, from) { document.body.classList.remove(from); document.body.classList.add(this.theme); this.updateThemeColorMeta(); }, userHeartbeatBar(to, from) { localStorage.heartbeatBarTheme = to; }, heartbeatBarTheme(to, from) { document.body.classList.remove(from); document.body.classList.add(this.heartbeatBarTheme); } }, methods: { /** * Update the theme color meta tag * @returns {void} */ updateThemeColorMeta() { if (this.theme === "dark") { document.querySelector("#theme-color").setAttribute("content", "#161B22"); } else { document.querySelector("#theme-color").setAttribute("content", "#5cdd8b"); } } } };
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/src/mixins/lang.js
src/mixins/lang.js
import { currentLocale } from "../i18n"; import { setPageLocale, timeDurationFormatter } from "../util-frontend"; const langModules = import.meta.glob("../lang/*.json"); export default { data() { return { language: currentLocale(), }; }, async created() { if (this.language !== "en") { await this.changeLang(this.language); } }, watch: { async language(lang) { await this.changeLang(lang); }, }, methods: { /** * Change the application language * @param {string} lang Language code to switch to * @returns {Promise<void>} */ async changeLang(lang) { let message = (await langModules["../lang/" + lang + ".json"]()) .default; this.$i18n.setLocaleMessage(lang, message); this.$i18n.locale = lang; localStorage.locale = lang; setPageLocale(); timeDurationFormatter.updateLocale(lang); }, }, };
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/src/mixins/mobile.js
src/mixins/mobile.js
export default { data() { return { windowWidth: window.innerWidth, }; }, created() { window.addEventListener("resize", this.onResize); this.updateBody(); }, methods: { /** * Handle screen resize * @returns {void} */ onResize() { this.windowWidth = window.innerWidth; this.updateBody(); }, /** * Add css-class "mobile" to body if needed * @returns {void} */ updateBody() { if (this.isMobile) { document.body.classList.add("mobile"); } else { document.body.classList.remove("mobile"); } } }, computed: { isMobile() { return this.windowWidth <= 767.98; }, }, };
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/src/mixins/socket.js
src/mixins/socket.js
import { io } from "socket.io-client"; import { useToast } from "vue-toastification"; import jwtDecode from "jwt-decode"; import Favico from "favico.js"; import dayjs from "dayjs"; import mitt from "mitt"; import { DOWN, MAINTENANCE, PENDING, UP } from "../util.ts"; import { getDevContainerServerHostname, isDevContainer, getToastSuccessTimeout, getToastErrorTimeout } from "../util-frontend.js"; const toast = useToast(); let socket; const noSocketIOPages = [ /^\/status-page$/, // /status-page /^\/status/, // /status** /^\/$/ // / ]; const favicon = new Favico({ animation: "none" }); export default { data() { return { info: { }, socket: { token: null, firstConnect: true, connected: false, connectCount: 0, initedSocketIO: false, }, username: null, remember: (localStorage.remember !== "0"), allowLoginDialog: false, // Allowed to show login dialog, but "loggedIn" have to be true too. This exists because prevent the login dialog show 0.1s in first before the socket server auth-ed. loggedIn: false, monitorList: { }, monitorTypeList: {}, maintenanceList: {}, apiKeyList: {}, heartbeatList: { }, avgPingList: { }, uptimeList: { }, tlsInfoList: {}, domainInfoList: {}, notificationList: [], dockerHostList: [], remoteBrowserList: [], statusPageListLoaded: false, statusPageList: [], proxyList: [], connectionErrorMsg: `${this.$t("Cannot connect to the socket server.")} ${this.$t("Reconnecting...")}`, showReverseProxyGuide: true, cloudflared: { cloudflareTunnelToken: "", installed: null, running: false, message: "", errorMessage: "", currentPassword: "", }, faviconUpdateDebounce: null, emitter: mitt(), }; }, created() { this.initSocketIO(); }, methods: { /** * Initialize connection to socket server * @param {boolean} bypass Should the check for if we * are on a status page be bypassed? * @returns {void} */ initSocketIO(bypass = false) { // No need to re-init if (this.socket.initedSocketIO) { return; } // No need to connect to the socket.io for status page if (! bypass && location.pathname) { for (let page of noSocketIOPages) { if (location.pathname.match(page)) { return; } } } // Also don't need to connect to the socket.io for setup database page if (location.pathname === "/setup-database") { return; } this.socket.initedSocketIO = true; let protocol = location.protocol + "//"; let url; const env = process.env.NODE_ENV || "production"; if (env === "development" && isDevContainer()) { url = protocol + getDevContainerServerHostname(); } else if (env === "development" || localStorage.dev === "dev") { url = protocol + location.hostname + ":3001"; } else { // Connect to the current url url = undefined; } socket = io(url); socket.on("info", (info) => { this.info = info; }); socket.on("setup", (monitorID, data) => { this.$router.push("/setup"); }); socket.on("autoLogin", (monitorID, data) => { this.loggedIn = true; this.storage().token = "autoLogin"; this.socket.token = "autoLogin"; this.allowLoginDialog = false; }); socket.on("loginRequired", () => { let token = this.storage().token; if (token && token !== "autoLogin") { this.loginByToken(token); } else { this.$root.storage().removeItem("token"); this.allowLoginDialog = true; } }); socket.on("monitorList", (data) => { this.assignMonitorUrlParser(data); this.monitorList = data; }); socket.on("updateMonitorIntoList", (data) => { this.assignMonitorUrlParser(data); Object.entries(data).forEach(([ monitorID, updatedMonitor ]) => { this.monitorList[monitorID] = updatedMonitor; }); }); socket.on("deleteMonitorFromList", (monitorID) => { if (this.monitorList[monitorID]) { delete this.monitorList[monitorID]; } }); socket.on("monitorTypeList", (data) => { this.monitorTypeList = data; }); socket.on("maintenanceList", (data) => { this.maintenanceList = data; }); socket.on("apiKeyList", (data) => { this.apiKeyList = data; }); socket.on("notificationList", (data) => { this.notificationList = data; }); socket.on("statusPageList", (data) => { this.statusPageListLoaded = true; this.statusPageList = data; }); socket.on("proxyList", (data) => { this.proxyList = data.map(item => { item.auth = !!item.auth; item.active = !!item.active; item.default = !!item.default; return item; }); }); socket.on("dockerHostList", (data) => { this.dockerHostList = data; }); socket.on("remoteBrowserList", (data) => { this.remoteBrowserList = data; }); socket.on("heartbeat", (data) => { if (! (data.monitorID in this.heartbeatList)) { this.heartbeatList[data.monitorID] = []; } this.heartbeatList[data.monitorID].push(data); if (this.heartbeatList[data.monitorID].length >= 150) { this.heartbeatList[data.monitorID].shift(); } // Add to important list if it is important // Also toast if (data.important) { if (this.monitorList[data.monitorID] !== undefined) { if (data.status === 0) { toast.error(`[${this.monitorList[data.monitorID].name}] [DOWN] ${data.msg}`, { timeout: getToastErrorTimeout(), }); } else if (data.status === 1) { toast.success(`[${this.monitorList[data.monitorID].name}] [Up] ${data.msg}`, { timeout: getToastSuccessTimeout(), }); } else { toast(`[${this.monitorList[data.monitorID].name}] ${data.msg}`); } } this.emitter.emit("newImportantHeartbeat", data); } }); socket.on("heartbeatList", (monitorID, data, overwrite = false) => { if (! (monitorID in this.heartbeatList) || overwrite) { this.heartbeatList[monitorID] = data; } else { this.heartbeatList[monitorID] = data.concat(this.heartbeatList[monitorID]); } }); socket.on("avgPing", (monitorID, data) => { this.avgPingList[monitorID] = data; }); socket.on("uptime", (monitorID, type, data) => { this.uptimeList[`${monitorID}_${type}`] = data; }); socket.on("certInfo", (monitorID, data) => { this.tlsInfoList[monitorID] = JSON.parse(data); }); socket.on("domainInfo", (monitorID, daysRemaining, expiresOn) => { this.domainInfoList[monitorID] = { daysRemaining: daysRemaining, expiresOn: expiresOn }; }); socket.on("connect_error", (err) => { console.error(`Failed to connect to the backend. Socket.io connect_error: ${err.message}`); this.connectionErrorMsg = `${this.$t("Cannot connect to the socket server.")} [${err}] ${this.$t("Reconnecting...")}`; this.showReverseProxyGuide = true; this.socket.connected = false; this.socket.firstConnect = false; }); socket.on("disconnect", () => { console.log("disconnect"); this.connectionErrorMsg = `${this.$t("Lost connection to the socket server.")} ${this.$t("Reconnecting...")}`; this.socket.connected = false; }); socket.on("connect", () => { console.log("Connected to the socket server"); this.socket.connectCount++; this.socket.connected = true; this.showReverseProxyGuide = false; // Reset Heartbeat list if it is re-connect if (this.socket.connectCount >= 2) { this.clearData(); } this.socket.firstConnect = false; }); // cloudflared socket.on("cloudflared_installed", (res) => this.cloudflared.installed = res); socket.on("cloudflared_running", (res) => this.cloudflared.running = res); socket.on("cloudflared_message", (res) => this.cloudflared.message = res); socket.on("cloudflared_errorMessage", (res) => this.cloudflared.errorMessage = res); socket.on("cloudflared_token", (res) => this.cloudflared.cloudflareTunnelToken = res); socket.on("initServerTimezone", () => { socket.emit("initServerTimezone", dayjs.tz.guess()); }); socket.on("refresh", () => { location.reload(); }); }, /** * parse all urls from list. * @param {object} data Monitor data to modify * @returns {object} list */ assignMonitorUrlParser(data) { Object.entries(data).forEach(([ monitorID, monitor ]) => { monitor.getUrl = () => { try { return new URL(monitor.url); } catch (_) { return null; } }; }); return data; }, /** * The storage currently in use * @returns {Storage} Current storage */ storage() { return (this.remember) ? localStorage : sessionStorage; }, /** * Get payload of JWT cookie * @returns {(object | undefined)} JWT payload */ getJWTPayload() { const jwtToken = this.$root.storage().token; if (jwtToken && jwtToken !== "autoLogin") { return jwtDecode(jwtToken); } return undefined; }, /** * Get current socket * @returns {Socket} Current socket */ getSocket() { return socket; }, /** * Show success or error toast dependent on response status code * @param {object} res Response object * @returns {void} */ toastRes(res) { let msg = res.msg; if (res.msgi18n) { if (msg != null && typeof msg === "object") { msg = this.$t(msg.key, msg.values); } else { msg = this.$t(msg); } } if (res.ok) { toast.success(msg); } else { toast.error(msg); } }, /** * Show a success toast * @param {string} msg Message to show * @returns {void} */ toastSuccess(msg) { toast.success(this.$t(msg)); }, /** * Show an error toast * @param {string} msg Message to show * @returns {void} */ toastError(msg) { toast.error(this.$t(msg)); }, /** * Callback for login * @callback loginCB * @param {object} res Response object */ /** * Send request to log user in * @param {string} username Username to log in with * @param {string} password Password to log in with * @param {string} token User token * @param {loginCB} callback Callback to call with result * @returns {void} */ login(username, password, token, callback) { socket.emit("login", { username, password, token, }, (res) => { if (res.tokenRequired) { callback(res); } if (res.ok) { this.storage().token = res.token; this.socket.token = res.token; this.loggedIn = true; this.username = this.getJWTPayload()?.username; // Trigger Chrome Save Password history.pushState({}, ""); } callback(res); }); }, /** * Log in using a token * @param {string} token Token to log in with * @returns {void} */ loginByToken(token) { socket.emit("loginByToken", token, (res) => { this.allowLoginDialog = true; if (! res.ok) { this.logout(); } else { this.loggedIn = true; this.username = this.getJWTPayload()?.username; } }); }, /** * Log out of the web application * @returns {void} */ logout() { socket.emit("logout", () => { }); this.storage().removeItem("token"); this.socket.token = null; this.loggedIn = false; this.username = null; this.clearData(); }, /** * Callback for general socket requests * @callback socketCB * @param {object} res Result of operation */ /** * Prepare 2FA configuration * @param {socketCB} callback Callback for socket response * @returns {void} */ prepare2FA(callback) { socket.emit("prepare2FA", callback); }, /** * Save the current 2FA configuration * @param {any} secret Unused * @param {socketCB} callback Callback for socket response * @returns {void} */ save2FA(secret, callback) { socket.emit("save2FA", callback); }, /** * Disable 2FA for this user * @param {socketCB} callback Callback for socket response * @returns {void} */ disable2FA(callback) { socket.emit("disable2FA", callback); }, /** * Verify the provided 2FA token * @param {string} token Token to verify * @param {socketCB} callback Callback for socket response * @returns {void} */ verifyToken(token, callback) { socket.emit("verifyToken", token, callback); }, /** * Get current 2FA status * @param {socketCB} callback Callback for socket response * @returns {void} */ twoFAStatus(callback) { socket.emit("twoFAStatus", callback); }, /** * Get list of monitors * @param {socketCB} callback Callback for socket response * @returns {void} */ getMonitorList(callback) { if (! callback) { callback = () => { }; } socket.emit("getMonitorList", callback); }, /** * Get list of maintenances * @param {socketCB} callback Callback for socket response * @returns {void} */ getMaintenanceList(callback) { if (! callback) { callback = () => { }; } socket.emit("getMaintenanceList", callback); }, /** * Send list of API keys * @param {socketCB} callback Callback for socket response * @returns {void} */ getAPIKeyList(callback) { if (!callback) { callback = () => { }; } socket.emit("getAPIKeyList", callback); }, /** * Add a monitor * @param {object} monitor Object representing monitor to add * @param {socketCB} callback Callback for socket response * @returns {void} */ add(monitor, callback) { socket.emit("add", monitor, callback); }, /** * Adds a maintenance * @param {object} maintenance Maintenance to add * @param {socketCB} callback Callback for socket response * @returns {void} */ addMaintenance(maintenance, callback) { socket.emit("addMaintenance", maintenance, callback); }, /** * Add monitors to maintenance * @param {number} maintenanceID Maintenance to modify * @param {number[]} monitors IDs of monitors to add * @param {socketCB} callback Callback for socket response * @returns {void} */ addMonitorMaintenance(maintenanceID, monitors, callback) { socket.emit("addMonitorMaintenance", maintenanceID, monitors, callback); }, /** * Add status page to maintenance * @param {number} maintenanceID Maintenance to modify * @param {number} statusPages ID of status page to add * @param {socketCB} callback Callback for socket response * @returns {void} */ addMaintenanceStatusPage(maintenanceID, statusPages, callback) { socket.emit("addMaintenanceStatusPage", maintenanceID, statusPages, callback); }, /** * Get monitors affected by maintenance * @param {number} maintenanceID Maintenance to read * @param {socketCB} callback Callback for socket response * @returns {void} */ getMonitorMaintenance(maintenanceID, callback) { socket.emit("getMonitorMaintenance", maintenanceID, callback); }, /** * Get status pages where maintenance is shown * @param {number} maintenanceID Maintenance to read * @param {socketCB} callback Callback for socket response * @returns {void} */ getMaintenanceStatusPage(maintenanceID, callback) { socket.emit("getMaintenanceStatusPage", maintenanceID, callback); }, /** * Delete monitor by ID * @param {number} monitorID ID of monitor to delete * @param {boolean} deleteChildren Whether to delete child monitors (for groups) * @param {socketCB} callback Callback for socket response * @returns {void} */ deleteMonitor(monitorID, deleteChildren, callback) { socket.emit("deleteMonitor", monitorID, deleteChildren, callback); }, /** * Delete specified maintenance * @param {number} maintenanceID Maintenance to delete * @param {socketCB} callback Callback for socket response * @returns {void} */ deleteMaintenance(maintenanceID, callback) { socket.emit("deleteMaintenance", maintenanceID, callback); }, /** * Add an API key * @param {object} key API key to add * @param {socketCB} callback Callback for socket response * @returns {void} */ addAPIKey(key, callback) { socket.emit("addAPIKey", key, callback); }, /** * Delete specified API key * @param {int} keyID ID of key to delete * @param {socketCB} callback Callback for socket response * @returns {void} */ deleteAPIKey(keyID, callback) { socket.emit("deleteAPIKey", keyID, callback); }, /** * Clear the hearbeat list * @returns {void} */ clearData() { console.log("reset heartbeat list"); this.heartbeatList = {}; }, /** * Upload the provided backup * @param {string} uploadedJSON JSON to upload * @param {string} importHandle Type of import. If set to * most data in database will be replaced * @param {socketCB} callback Callback for socket response * @returns {void} */ uploadBackup(uploadedJSON, importHandle, callback) { socket.emit("uploadBackup", uploadedJSON, importHandle, callback); }, /** * Clear events for a specified monitor * @param {number} monitorID ID of monitor to clear * @param {socketCB} callback Callback for socket response * @returns {void} */ clearEvents(monitorID, callback) { socket.emit("clearEvents", monitorID, callback); }, /** * Clear the heartbeats of a specified monitor * @param {number} monitorID Id of monitor to clear * @param {socketCB} callback Callback for socket response * @returns {void} */ clearHeartbeats(monitorID, callback) { socket.emit("clearHeartbeats", monitorID, callback); }, /** * Clear all statistics * @param {socketCB} callback Callback for socket response * @returns {void} */ clearStatistics(callback) { socket.emit("clearStatistics", callback); }, /** * Get monitor beats for a specific monitor in a time range * @param {number} monitorID ID of monitor to fetch * @param {number} period Time in hours from now * @param {socketCB} callback Callback for socket response * @returns {void} */ getMonitorBeats(monitorID, period, callback) { socket.emit("getMonitorBeats", monitorID, period, callback); }, /** * Retrieves monitor chart data. * @param {string} monitorID - The ID of the monitor. * @param {number} period - The time period for the chart data, in hours. * @param {socketCB} callback - The callback function to handle the chart data. * @returns {void} */ getMonitorChartData(monitorID, period, callback) { socket.emit("getMonitorChartData", monitorID, period, callback); } }, computed: { usernameFirstChar() { if (typeof this.username == "string" && this.username.length >= 1) { return this.username.charAt(0).toUpperCase(); } else { return "🐻"; } }, lastHeartbeatList() { let result = {}; for (let monitorID in this.heartbeatList) { let index = this.heartbeatList[monitorID].length - 1; result[monitorID] = this.heartbeatList[monitorID][index]; } return result; }, statusList() { let result = {}; let unknown = { text: this.$t("Unknown"), color: "secondary", }; for (let monitorID in this.lastHeartbeatList) { let lastHeartBeat = this.lastHeartbeatList[monitorID]; if (! lastHeartBeat) { result[monitorID] = unknown; } else if (lastHeartBeat.status === UP) { result[monitorID] = { text: this.$t("Up"), color: "primary", }; } else if (lastHeartBeat.status === DOWN) { result[monitorID] = { text: this.$t("Down"), color: "danger", }; } else if (lastHeartBeat.status === PENDING) { result[monitorID] = { text: this.$t("Pending"), color: "warning", }; } else if (lastHeartBeat.status === MAINTENANCE) { result[monitorID] = { text: this.$t("statusMaintenance"), color: "maintenance", }; } else { result[monitorID] = unknown; } } return result; }, stats() { let result = { active: 0, up: 0, down: 0, maintenance: 0, pending: 0, unknown: 0, pause: 0, }; for (let monitorID in this.$root.monitorList) { let beat = this.$root.lastHeartbeatList[monitorID]; let monitor = this.$root.monitorList[monitorID]; if (monitor && ! monitor.active) { result.pause++; } else if (beat) { result.active++; if (beat.status === UP) { result.up++; } else if (beat.status === DOWN) { result.down++; } else if (beat.status === PENDING) { result.pending++; } else if (beat.status === MAINTENANCE) { result.maintenance++; } else { result.unknown++; } } else { result.unknown++; } } return result; }, /** * Frontend Version * It should be compiled to a static value while building the frontend. * Please see ./config/vite.config.js, it is defined via vite.js * @returns {string} Current version */ frontendVersion() { // eslint-disable-next-line no-undef return FRONTEND_VERSION; }, /** * Are both frontend and backend in the same version? * @returns {boolean} The frontend and backend match? */ isFrontendBackendVersionMatched() { if (!this.info.version) { return true; } return this.info.version === this.frontendVersion; } }, watch: { // Update Badge "stats.down"(to, from) { if (to !== from) { if (this.faviconUpdateDebounce != null) { clearTimeout(this.faviconUpdateDebounce); } this.faviconUpdateDebounce = setTimeout(() => { favicon.badge(to); }, 1000); } }, // Reload the SPA if the server version is changed. "info.version"(to, from) { if (from && from !== to) { window.location.reload(); } }, remember() { localStorage.remember = (this.remember) ? "1" : "0"; }, // Reconnect the socket io, if status-page to dashboard "$route.fullPath"(newValue, oldValue) { if (newValue) { for (let page of noSocketIOPages) { if (newValue.match(page)) { return; } } } this.initSocketIO(); }, }, };
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false
louislam/uptime-kuma
https://github.com/louislam/uptime-kuma/blob/a0a009f31c929444b3cca292f96a93db368b65e8/test/mock-testdb.js
test/mock-testdb.js
const { sync: rimrafSync } = require("rimraf"); const Database = require("../server/database"); class TestDB { dataDir; constructor(dir = "./data/test") { this.dataDir = dir; } async create() { Database.initDataDir({ "data-dir": this.dataDir }); Database.dbConfig = { type: "sqlite" }; Database.writeDBConfig(Database.dbConfig); await Database.connect(true); await Database.patch(); } async destroy() { await Database.close(); this.dataDir && rimrafSync(this.dataDir); } } module.exports = TestDB;
javascript
MIT
a0a009f31c929444b3cca292f96a93db368b65e8
2026-01-04T14:56:49.617448Z
false