hunk
dict
file
stringlengths
0
11.8M
file_path
stringlengths
2
234
label
int64
0
1
commit_url
stringlengths
74
103
dependency_score
sequencelengths
5
5
{ "id": 0, "code_window": [ "import React, { useRef, useState } from 'react';\n", "import { Button, Tabs } from 'antd';\n", "\n", "const defaultPanes = new Array(2).fill(null).map((_, index) => {\n", " const id = String(index + 1);\n", " return { label: `Tab ${id}`, children: `Content of Tab Pane ${index + 1}`, key: id };\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "type TargetKey = React.MouseEvent | React.KeyboardEvent | string;\n", "\n" ], "file_path": "components/tabs/demo/custom-add-trigger.tsx", "type": "add", "edit_start_line_idx": 3 }
import type { Dayjs } from 'dayjs'; import * as React from 'react'; import DatePicker from '../date-picker'; import type { PickerTimeProps, RangePickerTimeProps } from '../date-picker/generatePicker'; import genPurePanel from '../_util/PurePanel'; import type { InputStatus } from '../_util/statusUtils'; import warning from '../_util/warning'; const { TimePicker: InternalTimePicker, RangePicker: InternalRangePicker } = DatePicker; export interface TimePickerLocale { placeholder?: string; rangePlaceholder?: [string, string]; } export interface TimeRangePickerProps extends Omit<RangePickerTimeProps<Dayjs>, 'picker'> { popupClassName?: string; } const RangePicker = React.forwardRef<any, TimeRangePickerProps>((props, ref) => ( <InternalRangePicker {...props} picker="time" mode={undefined} ref={ref} /> )); export interface TimePickerProps extends Omit<PickerTimeProps<Dayjs>, 'picker'> { addon?: () => React.ReactNode; status?: InputStatus; popupClassName?: string; } const TimePicker = React.forwardRef<any, TimePickerProps>( ({ addon, renderExtraFooter, ...restProps }, ref) => { const internalRenderExtraFooter = React.useMemo(() => { if (renderExtraFooter) { return renderExtraFooter; } if (addon) { warning( false, 'TimePicker', '`addon` is deprecated. Please use `renderExtraFooter` instead.', ); return addon; } return undefined; }, [addon, renderExtraFooter]); return ( <InternalTimePicker {...restProps} mode={undefined} ref={ref} renderExtraFooter={internalRenderExtraFooter} /> ); }, ); if (process.env.NODE_ENV !== 'production') { TimePicker.displayName = 'TimePicker'; } // We don't care debug panel /* istanbul ignore next */ const PurePanel = genPurePanel(TimePicker, 'picker'); (TimePicker as MergedTimePicker)._InternalPanelDoNotUseOrYouWillBeFired = PurePanel; type MergedTimePicker = typeof TimePicker & { RangePicker: typeof RangePicker; _InternalPanelDoNotUseOrYouWillBeFired: typeof PurePanel; }; (TimePicker as MergedTimePicker).RangePicker = RangePicker; (TimePicker as MergedTimePicker)._InternalPanelDoNotUseOrYouWillBeFired = PurePanel; export default TimePicker as MergedTimePicker;
components/time-picker/index.tsx
0
https://github.com/ant-design/ant-design/commit/546bda457f3724092edd01f8778d738deecc95de
[ 0.003223320934921503, 0.0006534919375553727, 0.00016632273036520928, 0.00017276659491471946, 0.0010066821705549955 ]
{ "id": 0, "code_window": [ "import React, { useRef, useState } from 'react';\n", "import { Button, Tabs } from 'antd';\n", "\n", "const defaultPanes = new Array(2).fill(null).map((_, index) => {\n", " const id = String(index + 1);\n", " return { label: `Tab ${id}`, children: `Content of Tab Pane ${index + 1}`, key: id };\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "type TargetKey = React.MouseEvent | React.KeyboardEvent | string;\n", "\n" ], "file_path": "components/tabs/demo/custom-add-trigger.tsx", "type": "add", "edit_start_line_idx": 3 }
/* eslint-disable no-template-curly-in-string */ import Pagination from 'rc-pagination/lib/locale/tk_TK'; import Calendar from '../calendar/locale/tk_TK'; import DatePicker from '../date-picker/locale/tk_TK'; import type { Locale } from '.'; import TimePicker from '../time-picker/locale/tk_TK'; const typeTemplate: string = '${label} ${type} görnüşinde däl'; const localeValues: Locale = { locale: 'tk', Pagination, DatePicker, TimePicker, Calendar, global: { placeholder: 'Saýlaň', }, Table: { filterTitle: 'Filter', filterConfirm: 'Bolýar', filterReset: 'Arassala', filterEmptyText: 'Filtersiz', emptyText: 'Maglumat ýok', selectAll: 'Ählisini saýla', selectInvert: 'Tersini saýlaň', selectNone: 'Ähli maglumatlary arassala', selectionAll: 'Ähli maglumatlary saýla', sortTitle: 'Tertiple', expand: 'Setirleri aç', collapse: 'Setirleri ýygna', triggerDesc: 'Kemelýän tertipde tertiple', triggerAsc: 'Artýan tertipde tertiple', cancelSort: 'Tertipleri arassala', }, Modal: { okText: 'Bolýar', cancelText: 'Ýatyr', justOkText: 'Bolýar', }, Popconfirm: { okText: 'Bolýar', cancelText: 'Ýatyr', }, Transfer: { titles: ['', ''], searchPlaceholder: 'Gözle', itemUnit: 'elem.', itemsUnit: 'elem.', remove: 'Poz', selectAll: 'Ähli maglumatlary saýla', selectCurrent: 'Şu sahypany saýlaň', selectInvert: 'Ters tertipde görkez', removeAll: 'Ähli maglumatlary poz', removeCurrent: 'Şu sahypany poz', }, Upload: { uploading: 'Ugradylýar...', removeFile: 'Faýly poz', uploadError: 'Ugratmakda näsazlyk ýüze çykdy', previewFile: 'Faýly görmek', downloadFile: 'Faýly ýükle', }, Empty: { description: 'Maglumat ýok', }, Icon: { icon: 'nyşan', }, Text: { edit: 'Üýtgetmek', copy: 'Göçürmek', copied: 'Göçürildi', expand: 'Ýygnamak', }, PageHeader: { back: 'Yza', }, Form: { defaultValidateMessages: { default: '${label} meýdany barlanmady', required: '${label} meýdany giriziň', enum: '${label} meýdan şulardan biri bolmaly: [${enum}]', whitespace: '${label} meýdany boş bolup bilmeýär', date: { format: '${label} ýalňyş wagt formaty', parse: '${label} meýdany wagta çalşyp bolmady', invalid: '${label} meýdany nädogry wagt', }, types: { string: typeTemplate, method: typeTemplate, array: typeTemplate, object: typeTemplate, number: typeTemplate, date: typeTemplate, boolean: typeTemplate, integer: typeTemplate, float: typeTemplate, regexp: typeTemplate, email: typeTemplate, url: typeTemplate, hex: typeTemplate, }, string: { len: '${label} meýdany ${len} simwol bolmaly', min: '${label} meýdany ${min} simwoldan az bolmaly däl', max: '${label} meýdany ${max} simwoldan köp bolmaly däl', range: '${label} meýdany ${min}-${max} simwol aralygynda bolmaly', }, number: { len: '${label} meýdan ${len} simwol bolmaly', min: '${label} meýdany ${min} simwoldan az bolmaly däl', max: '${label} meýdany ${max} simwoldan köp bolmaly däl', }, array: { len: '${label} meýdanynyň elementleriniň sany ${len} deň bolmaly', min: '${label} meýdanynyň elementleriniň sany ${min} az bolmaly däl', max: '${label} meýdanynyň elementleriniň sany ${max} köp bolmaly däl', range: '${label} meýdanynyň elementleriniň sany ${min} we ${max} aralykda bolmaly', }, pattern: { mismatch: '${label} meýdany ${pattern} şablony bilen gabat gelmeýär', }, }, }, Image: { preview: 'Öňünden görmek', }, }; export default localeValues;
components/locale/tk_TK.ts
0
https://github.com/ant-design/ant-design/commit/546bda457f3724092edd01f8778d738deecc95de
[ 0.00018025815370492637, 0.00017705492791719735, 0.00017209928773809224, 0.00017753028078004718, 0.000002392074520685128 ]
{ "id": 1, "code_window": [ " setActiveKey(newActiveKey);\n", " };\n", "\n", " const remove = (targetKey: string) => {\n", " const targetIndex = items.findIndex((pane) => pane.key === targetKey);\n", " const newPanes = items.filter((pane) => pane.key !== targetKey);\n", " if (newPanes.length && targetKey === activeKey) {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " const remove = (targetKey: TargetKey) => {\n" ], "file_path": "components/tabs/demo/custom-add-trigger.tsx", "type": "replace", "edit_start_line_idx": 23 }
import React, { useRef, useState } from 'react'; import { Button, Tabs } from 'antd'; const defaultPanes = new Array(2).fill(null).map((_, index) => { const id = String(index + 1); return { label: `Tab ${id}`, children: `Content of Tab Pane ${index + 1}`, key: id }; }); const App: React.FC = () => { const [activeKey, setActiveKey] = useState(defaultPanes[0].key); const [items, setItems] = useState(defaultPanes); const newTabIndex = useRef(0); const onChange = (key: string) => { setActiveKey(key); }; const add = () => { const newActiveKey = `newTab${newTabIndex.current++}`; setItems([...items, { label: 'New Tab', children: 'New Tab Pane', key: newActiveKey }]); setActiveKey(newActiveKey); }; const remove = (targetKey: string) => { const targetIndex = items.findIndex((pane) => pane.key === targetKey); const newPanes = items.filter((pane) => pane.key !== targetKey); if (newPanes.length && targetKey === activeKey) { const { key } = newPanes[targetIndex === newPanes.length ? targetIndex - 1 : targetIndex]; setActiveKey(key); } setItems(newPanes); }; const onEdit = (targetKey: string, action: 'add' | 'remove') => { if (action === 'add') { add(); } else { remove(targetKey); } }; return ( <div> <div style={{ marginBottom: 16 }}> <Button onClick={add}>ADD</Button> </div> <Tabs hideAdd onChange={onChange} activeKey={activeKey} type="editable-card" onEdit={onEdit} items={items} /> </div> ); }; export default App;
components/tabs/demo/custom-add-trigger.tsx
1
https://github.com/ant-design/ant-design/commit/546bda457f3724092edd01f8778d738deecc95de
[ 0.9985321760177612, 0.49819517135620117, 0.00017294679128099233, 0.49596676230430603, 0.49535423517227173 ]
{ "id": 1, "code_window": [ " setActiveKey(newActiveKey);\n", " };\n", "\n", " const remove = (targetKey: string) => {\n", " const targetIndex = items.findIndex((pane) => pane.key === targetKey);\n", " const newPanes = items.filter((pane) => pane.key !== targetKey);\n", " if (newPanes.length && targetKey === activeKey) {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " const remove = (targetKey: TargetKey) => {\n" ], "file_path": "components/tabs/demo/custom-add-trigger.tsx", "type": "replace", "edit_start_line_idx": 23 }
import { SmileOutlined } from '@ant-design/icons'; import React, { useState } from 'react'; import type { ConfigConsumerProps } from '..'; import ConfigProvider, { ConfigContext } from '..'; import mountTest from '../../../tests/shared/mountTest'; import { fireEvent, render } from '../../../tests/utils'; import Button from '../../button'; import Input from '../../input'; import Table from '../../table'; import Select from '../../select'; describe('ConfigProvider', () => { mountTest(() => ( <ConfigProvider> <div /> </ConfigProvider> )); it('autoInsertSpaceInButton', () => { const text = '确定'; const { container } = render( <ConfigProvider autoInsertSpaceInButton={false}> <Button>{text}</Button> </ConfigProvider>, ); expect(container.querySelector('span')?.innerHTML).toBe(text); }); it('renderEmpty', () => { const text = 'empty placeholder'; const { container } = render( <ConfigProvider renderEmpty={() => <div>{text}</div>}> <Table /> </ConfigProvider>, ); expect(container.querySelector('.ant-table-placeholder')?.querySelector('div')?.innerHTML).toBe( text, ); }); it('nest prefixCls', () => { const { container } = render( <ConfigProvider prefixCls="bamboo"> <ConfigProvider> <Button /> </ConfigProvider> </ConfigProvider>, ); expect(container.querySelector('button.bamboo-btn')).toBeTruthy(); }); it('dynamic prefixCls', () => { const DynamicPrefixCls: React.FC = () => { const [prefixCls, setPrefixCls] = useState('bamboo'); return ( <div> <Button onClick={() => setPrefixCls('light')} className="toggle-button"> toggle </Button> <ConfigProvider prefixCls={prefixCls}> <ConfigProvider> <Button /> </ConfigProvider> </ConfigProvider> </div> ); }; const { container } = render(<DynamicPrefixCls />); expect(container.querySelector('button.bamboo-btn')).toBeTruthy(); fireEvent.click(container.querySelector('.toggle-button')!); expect(container.querySelector('button.light-btn')).toBeTruthy(); }); it('iconPrefixCls', () => { const { container } = render( <ConfigProvider iconPrefixCls="bamboo"> <SmileOutlined /> </ConfigProvider>, ); expect(container.querySelector('[role="img"]')).toHaveClass('bamboo'); expect(container.querySelector('[role="img"]')).toHaveClass('bamboo-smile'); }); it('input autoComplete', () => { const { container } = render( <ConfigProvider input={{ autoComplete: 'off' }}> <Input /> </ConfigProvider>, ); expect(container.querySelector('input')?.autocomplete).toEqual('off'); }); it('select showSearch', () => { const { container } = render( <ConfigProvider select={{ showSearch: true }}> <Select /> </ConfigProvider>, ); expect(container.querySelectorAll('.ant-select-show-search').length).toBe(1); }); it('render empty', () => { let rendered = false; let cacheRenderEmpty; const App: React.FC = () => { const { renderEmpty } = React.useContext<ConfigConsumerProps>(ConfigContext); rendered = true; cacheRenderEmpty = renderEmpty; return null; }; render( <ConfigProvider> <App /> </ConfigProvider>, ); expect(rendered).toBeTruthy(); expect(cacheRenderEmpty).toBeFalsy(); }); });
components/config-provider/__tests__/index.test.tsx
0
https://github.com/ant-design/ant-design/commit/546bda457f3724092edd01f8778d738deecc95de
[ 0.00017729875980876386, 0.00017274169658776373, 0.00016592135943938047, 0.00017271576507482678, 0.0000034962076824740507 ]
{ "id": 1, "code_window": [ " setActiveKey(newActiveKey);\n", " };\n", "\n", " const remove = (targetKey: string) => {\n", " const targetIndex = items.findIndex((pane) => pane.key === targetKey);\n", " const newPanes = items.filter((pane) => pane.key !== targetKey);\n", " if (newPanes.length && targetKey === activeKey) {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " const remove = (targetKey: TargetKey) => {\n" ], "file_path": "components/tabs/demo/custom-add-trigger.tsx", "type": "replace", "edit_start_line_idx": 23 }
## zh-CN 图片不存在时,如果 `src` 本身是个 ReactElement,会尝试回退到 `src`,否则尝试回退到 `icon`,最后回退到显示 `children`。 ## en-US 图片不存在时,如果 `src` 本身是个 ReactElement,会尝试回退到 `src`,否则尝试回退到 `icon`,最后回退到显示 `children`。
components/avatar/demo/fallback.md
0
https://github.com/ant-design/ant-design/commit/546bda457f3724092edd01f8778d738deecc95de
[ 0.0001706550974631682, 0.0001706550974631682, 0.0001706550974631682, 0.0001706550974631682, 0 ]
{ "id": 1, "code_window": [ " setActiveKey(newActiveKey);\n", " };\n", "\n", " const remove = (targetKey: string) => {\n", " const targetIndex = items.findIndex((pane) => pane.key === targetKey);\n", " const newPanes = items.filter((pane) => pane.key !== targetKey);\n", " if (newPanes.length && targetKey === activeKey) {\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " const remove = (targetKey: TargetKey) => {\n" ], "file_path": "components/tabs/demo/custom-add-trigger.tsx", "type": "replace", "edit_start_line_idx": 23 }
import glES from '../../date-picker/locale/gl_ES'; export default glES;
components/calendar/locale/gl_ES.ts
0
https://github.com/ant-design/ant-design/commit/546bda457f3724092edd01f8778d738deecc95de
[ 0.00017846042464952916, 0.00017846042464952916, 0.00017846042464952916, 0.00017846042464952916, 0 ]
{ "id": 2, "code_window": [ " }\n", " setItems(newPanes);\n", " };\n", "\n", " const onEdit = (targetKey: string, action: 'add' | 'remove') => {\n", " if (action === 'add') {\n", " add();\n", " } else {\n", " remove(targetKey);\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " const onEdit = (targetKey: TargetKey, action: 'add' | 'remove') => {\n" ], "file_path": "components/tabs/demo/custom-add-trigger.tsx", "type": "replace", "edit_start_line_idx": 33 }
import React, { useRef, useState } from 'react'; import { Button, Tabs } from 'antd'; const defaultPanes = new Array(2).fill(null).map((_, index) => { const id = String(index + 1); return { label: `Tab ${id}`, children: `Content of Tab Pane ${index + 1}`, key: id }; }); const App: React.FC = () => { const [activeKey, setActiveKey] = useState(defaultPanes[0].key); const [items, setItems] = useState(defaultPanes); const newTabIndex = useRef(0); const onChange = (key: string) => { setActiveKey(key); }; const add = () => { const newActiveKey = `newTab${newTabIndex.current++}`; setItems([...items, { label: 'New Tab', children: 'New Tab Pane', key: newActiveKey }]); setActiveKey(newActiveKey); }; const remove = (targetKey: string) => { const targetIndex = items.findIndex((pane) => pane.key === targetKey); const newPanes = items.filter((pane) => pane.key !== targetKey); if (newPanes.length && targetKey === activeKey) { const { key } = newPanes[targetIndex === newPanes.length ? targetIndex - 1 : targetIndex]; setActiveKey(key); } setItems(newPanes); }; const onEdit = (targetKey: string, action: 'add' | 'remove') => { if (action === 'add') { add(); } else { remove(targetKey); } }; return ( <div> <div style={{ marginBottom: 16 }}> <Button onClick={add}>ADD</Button> </div> <Tabs hideAdd onChange={onChange} activeKey={activeKey} type="editable-card" onEdit={onEdit} items={items} /> </div> ); }; export default App;
components/tabs/demo/custom-add-trigger.tsx
1
https://github.com/ant-design/ant-design/commit/546bda457f3724092edd01f8778d738deecc95de
[ 0.9982819557189941, 0.33405372500419617, 0.00018929656653199345, 0.0034429002553224564, 0.4691295325756073 ]
{ "id": 2, "code_window": [ " }\n", " setItems(newPanes);\n", " };\n", "\n", " const onEdit = (targetKey: string, action: 'add' | 'remove') => {\n", " if (action === 'add') {\n", " add();\n", " } else {\n", " remove(targetKey);\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " const onEdit = (targetKey: TargetKey, action: 'add' | 'remove') => {\n" ], "file_path": "components/tabs/demo/custom-add-trigger.tsx", "type": "replace", "edit_start_line_idx": 33 }
## zh-CN 使用勾选框实现多选功能。 ## en-US Multiple and checkable.
components/tree-select/demo/checkable.md
0
https://github.com/ant-design/ant-design/commit/546bda457f3724092edd01f8778d738deecc95de
[ 0.0001705831673461944, 0.0001705831673461944, 0.0001705831673461944, 0.0001705831673461944, 0 ]
{ "id": 2, "code_window": [ " }\n", " setItems(newPanes);\n", " };\n", "\n", " const onEdit = (targetKey: string, action: 'add' | 'remove') => {\n", " if (action === 'add') {\n", " add();\n", " } else {\n", " remove(targetKey);\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " const onEdit = (targetKey: TargetKey, action: 'add' | 'remove') => {\n" ], "file_path": "components/tabs/demo/custom-add-trigger.tsx", "type": "replace", "edit_start_line_idx": 33 }
import ThemeEditor from '../theme-editor'; export default ThemeEditor;
.dumi/pages/theme-editor-cn/index.ts
0
https://github.com/ant-design/ant-design/commit/546bda457f3724092edd01f8778d738deecc95de
[ 0.0001767508510965854, 0.0001767508510965854, 0.0001767508510965854, 0.0001767508510965854, 0 ]
{ "id": 2, "code_window": [ " }\n", " setItems(newPanes);\n", " };\n", "\n", " const onEdit = (targetKey: string, action: 'add' | 'remove') => {\n", " if (action === 'add') {\n", " add();\n", " } else {\n", " remove(targetKey);\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " const onEdit = (targetKey: TargetKey, action: 'add' | 'remove') => {\n" ], "file_path": "components/tabs/demo/custom-add-trigger.tsx", "type": "replace", "edit_start_line_idx": 33 }
--- category: Components subtitle: 时间轴 group: 数据展示 title: Timeline cover: https://mdn.alipayobjects.com/huamei_7uahnr/afts/img/A*FkTySqNt3sYAAAAAAAAAAAAADrJ8AQ/original demo: cols: 2 --- 垂直展示的时间流信息。 ## 何时使用 - 当有一系列信息需按时间排列时,可正序和倒序。 - 需要有一条时间轴进行视觉上的串联时。 ## 代码演示 <!-- prettier-ignore --> <code src="./demo/basic.tsx">基本用法</code> <code src="./demo/color.tsx">圆圈颜色</code> <code src="./demo/pending.tsx">最后一个及排序</code> <code src="./demo/alternate.tsx">交替展现</code> <code src="./demo/custom.tsx">自定义时间轴点</code> <code src="./demo/right.tsx">右侧时间轴点</code> <code src="./demo/label.tsx">标签</code> <code src="./demo/wireframe.tsx" debug>线框风格</code> ## API ```jsx <Timeline> <Timeline.Item>创建服务现场 2015-09-01</Timeline.Item> <Timeline.Item>初步排除网络异常 2015-09-01</Timeline.Item> <Timeline.Item>技术测试异常 2015-09-01</Timeline.Item> <Timeline.Item>网络异常正在修复 2015-09-01</Timeline.Item> </Timeline> ``` ### Timeline 时间轴。 | 参数 | 说明 | 类型 | 默认值 | | --- | --- | --- | --- | | mode | 通过设置 `mode` 可以改变时间轴和内容的相对位置 | `left` \| `alternate` \| `right` | - | | pending | 指定最后一个幽灵节点是否存在或内容 | boolean \| ReactNode | false | | pendingDot | 当最后一个幽灵节点存在時,指定其时间图点 | ReactNode | &lt;LoadingOutlined /> | | reverse | 节点排序 | boolean | false | ### Timeline.Item 时间轴的每一个节点。 | 参数 | 说明 | 类型 | 默认值 | | --- | --- | --- | --- | | color | 指定圆圈颜色 `blue`、`red`、`green`、`gray`,或自定义的色值 | string | `blue` | | dot | 自定义时间轴点 | ReactNode | - | | label | 设置标签 | ReactNode | - | | position | 自定义节点位置 | `left` \| `right` | - |
components/timeline/index.zh-CN.md
0
https://github.com/ant-design/ant-design/commit/546bda457f3724092edd01f8778d738deecc95de
[ 0.00017721307813189924, 0.0001705222821328789, 0.0001661534479353577, 0.00016841202159412205, 0.00000376138473257015 ]
{ "id": 3, "code_window": [ "import React, { useRef, useState } from 'react';\n", "import { Tabs } from 'antd';\n", "\n", "const initialItems = [\n", " { label: 'Tab 1', children: 'Content of Tab 1', key: '1' },\n", " { label: 'Tab 2', children: 'Content of Tab 2', key: '2' },\n", " {\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "type TargetKey = React.MouseEvent | React.KeyboardEvent | string;\n", "\n" ], "file_path": "components/tabs/demo/editable-card.tsx", "type": "add", "edit_start_line_idx": 3 }
import React, { useRef, useState } from 'react'; import { Button, Tabs } from 'antd'; const defaultPanes = new Array(2).fill(null).map((_, index) => { const id = String(index + 1); return { label: `Tab ${id}`, children: `Content of Tab Pane ${index + 1}`, key: id }; }); const App: React.FC = () => { const [activeKey, setActiveKey] = useState(defaultPanes[0].key); const [items, setItems] = useState(defaultPanes); const newTabIndex = useRef(0); const onChange = (key: string) => { setActiveKey(key); }; const add = () => { const newActiveKey = `newTab${newTabIndex.current++}`; setItems([...items, { label: 'New Tab', children: 'New Tab Pane', key: newActiveKey }]); setActiveKey(newActiveKey); }; const remove = (targetKey: string) => { const targetIndex = items.findIndex((pane) => pane.key === targetKey); const newPanes = items.filter((pane) => pane.key !== targetKey); if (newPanes.length && targetKey === activeKey) { const { key } = newPanes[targetIndex === newPanes.length ? targetIndex - 1 : targetIndex]; setActiveKey(key); } setItems(newPanes); }; const onEdit = (targetKey: string, action: 'add' | 'remove') => { if (action === 'add') { add(); } else { remove(targetKey); } }; return ( <div> <div style={{ marginBottom: 16 }}> <Button onClick={add}>ADD</Button> </div> <Tabs hideAdd onChange={onChange} activeKey={activeKey} type="editable-card" onEdit={onEdit} items={items} /> </div> ); }; export default App;
components/tabs/demo/custom-add-trigger.tsx
1
https://github.com/ant-design/ant-design/commit/546bda457f3724092edd01f8778d738deecc95de
[ 0.9650745987892151, 0.16255630552768707, 0.000168639249750413, 0.00023417484771925956, 0.35891300439834595 ]
{ "id": 3, "code_window": [ "import React, { useRef, useState } from 'react';\n", "import { Tabs } from 'antd';\n", "\n", "const initialItems = [\n", " { label: 'Tab 1', children: 'Content of Tab 1', key: '1' },\n", " { label: 'Tab 2', children: 'Content of Tab 2', key: '2' },\n", " {\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "type TargetKey = React.MouseEvent | React.KeyboardEvent | string;\n", "\n" ], "file_path": "components/tabs/demo/editable-card.tsx", "type": "add", "edit_start_line_idx": 3 }
import React, { useState } from 'react'; import { act } from 'react-dom/test-utils'; import { UserOutlined } from '@ant-design/icons'; import Layout from '..'; import mountTest from '../../../tests/shared/mountTest'; import rtlTest from '../../../tests/shared/rtlTest'; import Menu from '../../menu'; import { fireEvent, render } from '../../../tests/utils'; const { Sider, Content, Footer, Header } = Layout; describe('Layout', () => { mountTest(Layout); mountTest(Content); mountTest(Sider); mountTest(() => ( <Layout> <Sider breakpoint="xs" /> <Content /> </Layout> )); rtlTest(Layout); rtlTest(Content); rtlTest(Sider); it('detect the sider as children', () => { const { container, unmount } = render( <Layout> <Sider>Sider</Sider> <Content>Content</Content> </Layout>, ); expect(container.querySelector('.ant-layout')?.className.includes('ant-layout-has-sider')).toBe( true, ); unmount(); }); it('umount from multiple siders', async () => { const App: React.FC = () => { const [hide1, setHide1] = useState(false); const [hide2, setHide2] = useState(false); return ( <Layout> {hide1 ? null : <Sider>Sider</Sider>} {hide2 ? null : <Sider>Sider</Sider>} <Content> <button onClick={() => setHide1(true)} type="button"> hide sider 1 </button> <button onClick={() => setHide2(true)} type="button"> hide sider 2 </button> </Content> </Layout> ); }; const { container } = render(<App />); expect(container.querySelector('.ant-layout')?.className.includes('ant-layout-has-sider')).toBe( true, ); fireEvent.click(container.querySelectorAll('button')[0]); expect(container.querySelector('.ant-layout')?.className.includes('ant-layout-has-sider')).toBe( true, ); fireEvent.click(container.querySelectorAll('button')[1]); expect(container.querySelector('.ant-layout')?.className.includes('ant-layout-has-sider')).toBe( false, ); }); it('detect the sider inside the children', async () => { const { container } = render( <Layout> <div> <Sider>Sider</Sider> </div> <Content>Content</Content> </Layout>, ); expect(container.querySelector('.ant-layout')?.className.includes('ant-layout-has-sider')).toBe( true, ); }); it('detect ant-layout-sider-has-trigger class in sider when ant-layout-sider-trigger div tag exists', async () => { const { container } = render( <Layout> <div> <Sider collapsible>Sider</Sider> </div> <Content>Content</Content> </Layout>, ); expect( container .querySelector('.ant-layout-sider') ?.className.includes('ant-layout-sider-has-trigger'), ).toBe(true); }); it('should have 50% width of sidebar', async () => { const { container } = render( <Layout> <div> <Sider width="50%">Sider</Sider> </div> <Content>Content</Content> </Layout>, ); expect(container.querySelector<HTMLElement>('.ant-layout-sider')?.style.width).toBe('50%'); expect(container.querySelector<HTMLElement>('.ant-layout-sider')?.style.flex).toBe('0 0 50%'); }); describe('zeroWidth', () => { it('detect ant-layout-sider-zero-width class in sider when its width is 0%', async () => { const { container } = render( <Layout> <div> <Sider width="0%">Sider</Sider> </div> <Content>Content</Content> </Layout>, ); expect( container .querySelector('.ant-layout-sider') ?.className.includes('ant-layout-sider-zero-width'), ).toBe(true); }); describe('should collapsible', () => { it('uncontrolled', () => { const onCollapse = jest.fn(); const { container } = render( <Layout> <Sider collapsible breakpoint="lg" collapsedWidth="0" onCollapse={onCollapse}> Sider </Sider> <Content>Content</Content> </Layout>, ); onCollapse.mockReset(); fireEvent.click(container.querySelector('.ant-layout-sider-zero-width-trigger')!); expect(onCollapse).toHaveBeenCalledTimes(1); }); it('controlled', () => { const Demo: React.FC = () => { const [collapsed, setCollapsed] = React.useState(true); return ( <Layout> <Sider collapsed={collapsed} collapsible breakpoint="lg" collapsedWidth="0" onCollapse={setCollapsed} > Sider </Sider> <Content>Content</Content> </Layout> ); }; const { container } = render(<Demo />); expect(container.querySelector('.ant-layout-sider-collapsed')).toBeTruthy(); fireEvent.click(container.querySelector('.ant-layout-sider-zero-width-trigger')!); expect(container.querySelector('.ant-layout-sider-collapsed')).toBeFalsy(); }); }); }); it('detect ant-layout-sider-dark as default theme', async () => { const { container } = render(<Sider>Sider</Sider>); expect( container.querySelector('.ant-layout-sider')?.className.includes('ant-layout-sider-dark'), ).toBe(true); }); it('detect ant-layout-sider-light when set light theme', async () => { const { container } = render(<Sider theme="light">Sider</Sider>); expect( container.querySelector('.ant-layout-sider')?.className.includes('ant-layout-sider-light'), ).toBe(true); }); it('renders string width correctly', () => { const { asFragment } = render(<Sider width="200">Sider</Sider>); expect(asFragment().firstChild).toMatchSnapshot(); }); it('should be controlled by collapsed', () => { const { asFragment, rerender } = render(<Sider>Sider</Sider>); expect(asFragment().firstChild).toMatchSnapshot(); rerender(<Sider collapsed>Sider</Sider>); expect(asFragment().firstChild).toMatchSnapshot(); }); it('should not add ant-layout-has-sider when `hasSider` is `false`', () => { const { container } = render( <Layout hasSider={false}> <Sider>Sider</Sider> </Layout>, ); expect(container.querySelector('.ant-layout')?.className.includes('ant-layout-has-sider')).toBe( false, ); }); it('render correct with Tooltip', () => { jest.useFakeTimers(); const { container, rerender } = render( <Sider collapsible collapsed={false}> <Menu mode="inline"> <Menu.Item key="1"> <UserOutlined /> <span>Light</span> </Menu.Item> </Menu> </Sider>, ); fireEvent.mouseEnter(container.querySelector('.ant-menu-item')!); act(() => { jest.runAllTimers(); }); expect(container.querySelectorAll('.ant-tooltip-inner').length).toBeFalsy(); rerender( <Sider collapsible collapsed> <Menu mode="inline"> <Menu.Item key="1"> <UserOutlined /> <span>Light</span> </Menu.Item> </Menu> </Sider>, ); fireEvent.mouseEnter(container.querySelector('.ant-menu-item')!); act(() => { jest.runAllTimers(); }); expect(container.querySelectorAll('.ant-tooltip-inner').length).toBeTruthy(); jest.useRealTimers(); }); }); describe('Sider', () => { const errorSpy = jest.spyOn(console, 'error').mockImplementation(() => {}); afterEach(() => { errorSpy.mockReset(); }); afterAll(() => { errorSpy.mockRestore(); }); it('should trigger onBreakpoint', async () => { const onBreakpoint = jest.fn(); render( <Sider breakpoint="md" onBreakpoint={onBreakpoint}> Sider </Sider>, ); expect(onBreakpoint).toHaveBeenCalledWith(true); }); it('should warning if use `inlineCollapsed` with menu', () => { render( <Sider collapsible> <Menu mode="inline" inlineCollapsed /> </Sider>, ); expect(errorSpy).toHaveBeenCalledWith( 'Warning: [antd: Menu] `inlineCollapsed` not control Menu under Sider. Should set `collapsed` on Sider instead.', ); }); it('zeroWidthTriggerStyle should work', () => { const { container } = render( <Sider collapsedWidth={0} collapsible zeroWidthTriggerStyle={{ background: '#F96' }}> <Menu theme="dark" mode="inline" defaultSelectedKeys={['1']}> <Menu.Item key="1"> <UserOutlined /> <span>nav 1</span> </Menu.Item> </Menu> </Sider>, ); expect( container.querySelector<HTMLDivElement>('.ant-layout-sider-zero-width-trigger')?.style .background, ).toEqual('rgb(255, 153, 102)'); }); it('should be able to customize zero width trigger by trigger prop', () => { const { container } = render( <Sider collapsedWidth={0} collapsible trigger={<span className="my-trigger" />}> <Menu theme="dark" mode="inline" defaultSelectedKeys={['1']}> <Menu.Item key="1"> <UserOutlined /> <span>nav 1</span> </Menu.Item> </Menu> </Sider>, ); expect( container.querySelector('.ant-layout-sider-zero-width-trigger')?.querySelector('.my-trigger'), ).toBeTruthy(); }); (['Layout', 'Header', 'Footer', 'Sider'] as const).forEach((tag) => { const ComponentMap = { Layout, Header, Footer, Sider }; it(`should get ${tag} element from ref`, () => { const ref = React.createRef<HTMLDivElement>(); const onSelect = jest.fn(); const Component = ComponentMap[tag]; render( <Component onSelect={onSelect} ref={ref}> {tag} </Component>, ); expect(ref.current instanceof HTMLElement).toBe(true); }); }); });
components/layout/__tests__/index.test.tsx
0
https://github.com/ant-design/ant-design/commit/546bda457f3724092edd01f8778d738deecc95de
[ 0.00032497759093530476, 0.00017684928025119007, 0.00016570743173360825, 0.0001707014162093401, 0.000026297493604943156 ]
{ "id": 3, "code_window": [ "import React, { useRef, useState } from 'react';\n", "import { Tabs } from 'antd';\n", "\n", "const initialItems = [\n", " { label: 'Tab 1', children: 'Content of Tab 1', key: '1' },\n", " { label: 'Tab 2', children: 'Content of Tab 2', key: '2' },\n", " {\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "type TargetKey = React.MouseEvent | React.KeyboardEvent | string;\n", "\n" ], "file_path": "components/tabs/demo/editable-card.tsx", "type": "add", "edit_start_line_idx": 3 }
import demoTest from '../../../tests/shared/demoTest'; demoTest('tabs');
components/tabs/__tests__/demo.test.ts
0
https://github.com/ant-design/ant-design/commit/546bda457f3724092edd01f8778d738deecc95de
[ 0.00016923848306760192, 0.00016923848306760192, 0.00016923848306760192, 0.00016923848306760192, 0 ]
{ "id": 3, "code_window": [ "import React, { useRef, useState } from 'react';\n", "import { Tabs } from 'antd';\n", "\n", "const initialItems = [\n", " { label: 'Tab 1', children: 'Content of Tab 1', key: '1' },\n", " { label: 'Tab 2', children: 'Content of Tab 2', key: '2' },\n", " {\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "type TargetKey = React.MouseEvent | React.KeyboardEvent | string;\n", "\n" ], "file_path": "components/tabs/demo/editable-card.tsx", "type": "add", "edit_start_line_idx": 3 }
import React from 'react'; import { Checkbox } from 'antd'; const App: React.FC = () => ( <> <Checkbox defaultChecked={false} disabled /> <br /> <Checkbox indeterminate disabled /> <br /> <Checkbox defaultChecked disabled /> </> ); export default App;
components/checkbox/demo/disabled.tsx
0
https://github.com/ant-design/ant-design/commit/546bda457f3724092edd01f8778d738deecc95de
[ 0.0005916587542742491, 0.0003834569361060858, 0.00017525510338600725, 0.0003834569361060858, 0.0002082018181681633 ]
{ "id": 4, "code_window": [ " newPanes.push({ label: 'New Tab', children: 'Content of new Tab', key: newActiveKey });\n", " setItems(newPanes);\n", " setActiveKey(newActiveKey);\n", " };\n", "\n", " const remove = (targetKey: string) => {\n", " let newActiveKey = activeKey;\n", " let lastIndex = -1;\n", " items.forEach((item, i) => {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " const remove = (targetKey: TargetKey) => {\n" ], "file_path": "components/tabs/demo/editable-card.tsx", "type": "replace", "edit_start_line_idx": 31 }
import React, { useRef, useState } from 'react'; import { Tabs } from 'antd'; const initialItems = [ { label: 'Tab 1', children: 'Content of Tab 1', key: '1' }, { label: 'Tab 2', children: 'Content of Tab 2', key: '2' }, { label: 'Tab 3', children: 'Content of Tab 3', key: '3', closable: false, }, ]; const App: React.FC = () => { const [activeKey, setActiveKey] = useState(initialItems[0].key); const [items, setItems] = useState(initialItems); const newTabIndex = useRef(0); const onChange = (newActiveKey: string) => { setActiveKey(newActiveKey); }; const add = () => { const newActiveKey = `newTab${newTabIndex.current++}`; const newPanes = [...items]; newPanes.push({ label: 'New Tab', children: 'Content of new Tab', key: newActiveKey }); setItems(newPanes); setActiveKey(newActiveKey); }; const remove = (targetKey: string) => { let newActiveKey = activeKey; let lastIndex = -1; items.forEach((item, i) => { if (item.key === targetKey) { lastIndex = i - 1; } }); const newPanes = items.filter((item) => item.key !== targetKey); if (newPanes.length && newActiveKey === targetKey) { if (lastIndex >= 0) { newActiveKey = newPanes[lastIndex].key; } else { newActiveKey = newPanes[0].key; } } setItems(newPanes); setActiveKey(newActiveKey); }; const onEdit = (targetKey: string, action: 'add' | 'remove') => { if (action === 'add') { add(); } else { remove(targetKey); } }; return ( <Tabs type="editable-card" onChange={onChange} activeKey={activeKey} onEdit={onEdit} items={items} /> ); }; export default App;
components/tabs/demo/editable-card.tsx
1
https://github.com/ant-design/ant-design/commit/546bda457f3724092edd01f8778d738deecc95de
[ 0.9991853833198547, 0.4311606287956238, 0.0001696829858701676, 0.23012733459472656, 0.46064749360084534 ]
{ "id": 4, "code_window": [ " newPanes.push({ label: 'New Tab', children: 'Content of new Tab', key: newActiveKey });\n", " setItems(newPanes);\n", " setActiveKey(newActiveKey);\n", " };\n", "\n", " const remove = (targetKey: string) => {\n", " let newActiveKey = activeKey;\n", " let lastIndex = -1;\n", " items.forEach((item, i) => {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " const remove = (targetKey: TargetKey) => {\n" ], "file_path": "components/tabs/demo/editable-card.tsx", "type": "replace", "edit_start_line_idx": 31 }
import React from 'react'; import { Grid, Tag } from 'antd'; const { useBreakpoint } = Grid; const App: React.FC = () => { const screens = useBreakpoint(); return ( <> Current break point:{' '} {Object.entries(screens) .filter((screen) => !!screen[1]) .map((screen) => ( <Tag color="blue" key={screen[0]}> {screen[0]} </Tag> ))} </> ); }; export default App;
components/grid/demo/useBreakpoint.tsx
0
https://github.com/ant-design/ant-design/commit/546bda457f3724092edd01f8778d738deecc95de
[ 0.00017640384612604976, 0.00017212341481354088, 0.0001643881550990045, 0.00017557824321556836, 0.000005480029813043075 ]
{ "id": 4, "code_window": [ " newPanes.push({ label: 'New Tab', children: 'Content of new Tab', key: newActiveKey });\n", " setItems(newPanes);\n", " setActiveKey(newActiveKey);\n", " };\n", "\n", " const remove = (targetKey: string) => {\n", " let newActiveKey = activeKey;\n", " let lastIndex = -1;\n", " items.forEach((item, i) => {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " const remove = (targetKey: TargetKey) => {\n" ], "file_path": "components/tabs/demo/editable-card.tsx", "type": "replace", "edit_start_line_idx": 31 }
import type { TimePickerLocale } from '../index'; const locale: TimePickerLocale = { placeholder: 'Hora', }; export default locale;
components/time-picker/locale/pt_PT.ts
0
https://github.com/ant-design/ant-design/commit/546bda457f3724092edd01f8778d738deecc95de
[ 0.0001772984251147136, 0.0001772984251147136, 0.0001772984251147136, 0.0001772984251147136, 0 ]
{ "id": 4, "code_window": [ " newPanes.push({ label: 'New Tab', children: 'Content of new Tab', key: newActiveKey });\n", " setItems(newPanes);\n", " setActiveKey(newActiveKey);\n", " };\n", "\n", " const remove = (targetKey: string) => {\n", " let newActiveKey = activeKey;\n", " let lastIndex = -1;\n", " items.forEach((item, i) => {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " const remove = (targetKey: TargetKey) => {\n" ], "file_path": "components/tabs/demo/editable-card.tsx", "type": "replace", "edit_start_line_idx": 31 }
import React, { useState } from 'react'; import { AppstoreOutlined, CalendarOutlined, LinkOutlined, MailOutlined, SettingOutlined, } from '@ant-design/icons'; import { Divider, Menu, Switch } from 'antd'; import type { MenuProps, MenuTheme } from 'antd/es/menu'; type MenuItem = Required<MenuProps>['items'][number]; function getItem( label: React.ReactNode, key?: React.Key | null, icon?: React.ReactNode, children?: MenuItem[], ): MenuItem { return { key, icon, children, label, } as MenuItem; } const items: MenuItem[] = [ getItem('Navigation One', '1', <MailOutlined />), getItem('Navigation Two', '2', <CalendarOutlined />), getItem('Navigation Two', 'sub1', <AppstoreOutlined />, [ getItem('Option 3', '3'), getItem('Option 4', '4'), getItem('Submenu', 'sub1-2', null, [getItem('Option 5', '5'), getItem('Option 6', '6')]), ]), getItem('Navigation Three', 'sub2', <SettingOutlined />, [ getItem('Option 7', '7'), getItem('Option 8', '8'), getItem('Option 9', '9'), getItem('Option 10', '10'), ]), getItem( <a href="https://ant.design" target="_blank" rel="noopener noreferrer"> Ant Design </a>, 'link', <LinkOutlined />, ), ]; const App: React.FC = () => { const [mode, setMode] = useState<'vertical' | 'inline'>('inline'); const [theme, setTheme] = useState<MenuTheme>('light'); const changeMode = (value: boolean) => { setMode(value ? 'vertical' : 'inline'); }; const changeTheme = (value: boolean) => { setTheme(value ? 'dark' : 'light'); }; return ( <> <Switch onChange={changeMode} /> Change Mode <Divider type="vertical" /> <Switch onChange={changeTheme} /> Change Style <br /> <br /> <Menu style={{ width: 256 }} defaultSelectedKeys={['1']} defaultOpenKeys={['sub1']} mode={mode} theme={theme} items={items} /> </> ); }; export default App;
components/menu/demo/switch-mode.tsx
0
https://github.com/ant-design/ant-design/commit/546bda457f3724092edd01f8778d738deecc95de
[ 0.001389409531839192, 0.00030819192761555314, 0.00016297399997711182, 0.00017425963596906513, 0.00038229304482229054 ]
{ "id": 5, "code_window": [ " setActiveKey(newActiveKey);\n", " };\n", "\n", " const onEdit = (targetKey: string, action: 'add' | 'remove') => {\n", " if (action === 'add') {\n", " add();\n", " } else {\n", " remove(targetKey);\n", " }\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " const onEdit = (\n", " targetKey: React.MouseEvent | React.KeyboardEvent | string,\n", " action: 'add' | 'remove',\n", " ) => {\n" ], "file_path": "components/tabs/demo/editable-card.tsx", "type": "replace", "edit_start_line_idx": 51 }
import React, { useRef, useState } from 'react'; import { Button, Tabs } from 'antd'; const defaultPanes = new Array(2).fill(null).map((_, index) => { const id = String(index + 1); return { label: `Tab ${id}`, children: `Content of Tab Pane ${index + 1}`, key: id }; }); const App: React.FC = () => { const [activeKey, setActiveKey] = useState(defaultPanes[0].key); const [items, setItems] = useState(defaultPanes); const newTabIndex = useRef(0); const onChange = (key: string) => { setActiveKey(key); }; const add = () => { const newActiveKey = `newTab${newTabIndex.current++}`; setItems([...items, { label: 'New Tab', children: 'New Tab Pane', key: newActiveKey }]); setActiveKey(newActiveKey); }; const remove = (targetKey: string) => { const targetIndex = items.findIndex((pane) => pane.key === targetKey); const newPanes = items.filter((pane) => pane.key !== targetKey); if (newPanes.length && targetKey === activeKey) { const { key } = newPanes[targetIndex === newPanes.length ? targetIndex - 1 : targetIndex]; setActiveKey(key); } setItems(newPanes); }; const onEdit = (targetKey: string, action: 'add' | 'remove') => { if (action === 'add') { add(); } else { remove(targetKey); } }; return ( <div> <div style={{ marginBottom: 16 }}> <Button onClick={add}>ADD</Button> </div> <Tabs hideAdd onChange={onChange} activeKey={activeKey} type="editable-card" onEdit={onEdit} items={items} /> </div> ); }; export default App;
components/tabs/demo/custom-add-trigger.tsx
1
https://github.com/ant-design/ant-design/commit/546bda457f3724092edd01f8778d738deecc95de
[ 0.995654821395874, 0.3328734040260315, 0.0011288630776107311, 0.004492893815040588, 0.4662115275859833 ]
{ "id": 5, "code_window": [ " setActiveKey(newActiveKey);\n", " };\n", "\n", " const onEdit = (targetKey: string, action: 'add' | 'remove') => {\n", " if (action === 'add') {\n", " add();\n", " } else {\n", " remove(targetKey);\n", " }\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " const onEdit = (\n", " targetKey: React.MouseEvent | React.KeyboardEvent | string,\n", " action: 'add' | 'remove',\n", " ) => {\n" ], "file_path": "components/tabs/demo/editable-card.tsx", "type": "replace", "edit_start_line_idx": 51 }
import React, { forwardRef } from 'react'; import InputNumber from '..'; import focusTest from '../../../tests/shared/focusTest'; import { fireEvent, render } from '../../../tests/utils'; describe('prefix', () => { focusTest( forwardRef((props, ref) => <InputNumber {...props} prefix="A" ref={ref} />), { refFocus: true }, ); it('should support className when has prefix', () => { const { container } = render(<InputNumber prefix="suffix" className="my-class-name" />); expect((container.firstChild as HTMLElement)?.className.includes('my-class-name')).toBe(true); expect(container.querySelector('input')?.className.includes('my-class-name')).toBe(false); }); it('should trigger focus when prefix is clicked', () => { const { container } = render(<InputNumber prefix={<i>123</i>} />); const mockFocus = jest.spyOn(container.querySelector('input')!, 'focus'); fireEvent.mouseUp(container.querySelector('i')!); expect(mockFocus).toHaveBeenCalled(); }); });
components/input-number/__tests__/prefix.test.tsx
0
https://github.com/ant-design/ant-design/commit/546bda457f3724092edd01f8778d738deecc95de
[ 0.00017757962632458657, 0.0001745415065670386, 0.0001729515934130177, 0.00017309329996351153, 0.0000021490538983925944 ]
{ "id": 5, "code_window": [ " setActiveKey(newActiveKey);\n", " };\n", "\n", " const onEdit = (targetKey: string, action: 'add' | 'remove') => {\n", " if (action === 'add') {\n", " add();\n", " } else {\n", " remove(targetKey);\n", " }\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " const onEdit = (\n", " targetKey: React.MouseEvent | React.KeyboardEvent | string,\n", " action: 'add' | 'remove',\n", " ) => {\n" ], "file_path": "components/tabs/demo/editable-card.tsx", "type": "replace", "edit_start_line_idx": 51 }
import React from 'react'; import { Button, ConfigProvider, Form, InputNumber } from 'antd'; import { SketchPicker } from 'react-color'; type ThemeData = { borderRadius: number; colorPrimary: string; }; const defaultData: ThemeData = { borderRadius: 6, colorPrimary: '#1677ff', }; export default () => { const [form] = Form.useForm(); const [data, setData] = React.useState<ThemeData>(defaultData); return ( <ConfigProvider theme={{ token: { colorPrimary: data.colorPrimary, borderRadius: data.borderRadius } }} > <Form form={form} onValuesChange={(changedValues, allValues) => { const colorObj = changedValues?.colorPrimary ? { colorPrimary: allValues?.colorPrimary?.hex } : {}; setData({ ...allValues, ...colorObj, }); }} name="theme" initialValues={defaultData} labelCol={{ span: 4 }} wrapperCol={{ span: 20 }} > <Form.Item valuePropName="color" name="colorPrimary" label="Primary Color"> <SketchPicker /> </Form.Item> <Form.Item name="borderRadius" label="Border Radius"> <InputNumber /> </Form.Item> <Form.Item name="submit" wrapperCol={{ offset: 4, span: 20 }}> <Button type="primary">Submit</Button> </Form.Item> </Form> </ConfigProvider> ); };
components/config-provider/demo/theme.tsx
0
https://github.com/ant-design/ant-design/commit/546bda457f3724092edd01f8778d738deecc95de
[ 0.00017750429105944932, 0.00017368591215927154, 0.00016721131396479905, 0.0001753749093040824, 0.00000360299645763007 ]
{ "id": 5, "code_window": [ " setActiveKey(newActiveKey);\n", " };\n", "\n", " const onEdit = (targetKey: string, action: 'add' | 'remove') => {\n", " if (action === 'add') {\n", " add();\n", " } else {\n", " remove(targetKey);\n", " }\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " const onEdit = (\n", " targetKey: React.MouseEvent | React.KeyboardEvent | string,\n", " action: 'add' | 'remove',\n", " ) => {\n" ], "file_path": "components/tabs/demo/editable-card.tsx", "type": "replace", "edit_start_line_idx": 51 }
## zh-CN 设置状态点的位置偏移,格式为 `[left, top]`,表示状态点距默认位置左侧、上方的偏移量。 ## en-US Set offset of the badge dot, the format is `[left, top]`, which represents the offset of the status dot from the left and top of the default position.
components/badge/demo/offset.md
0
https://github.com/ant-design/ant-design/commit/546bda457f3724092edd01f8778d738deecc95de
[ 0.00016950865392573178, 0.00016950865392573178, 0.00016950865392573178, 0.00016950865392573178, 0 ]
{ "id": 0, "code_window": [ "import { HttpServer, VersioningType } from '@nestjs/common';\n", "import { RequestMethod } from '@nestjs/common/enums/request-method.enum';\n", "import {\n", " MiddlewareConfiguration,\n" ], "labels": [ "replace", "keep", "keep", "keep" ], "after_edit": [ "import { HttpServer, Logger, VersioningType } from '@nestjs/common';\n" ], "file_path": "packages/core/middleware/middleware-module.ts", "type": "replace", "edit_start_line_idx": 0 }
import { HttpServer, VersioningType } from '@nestjs/common'; import { RequestMethod } from '@nestjs/common/enums/request-method.enum'; import { MiddlewareConfiguration, NestMiddleware, RouteInfo, } from '@nestjs/common/interfaces/middleware'; import { addLeadingSlash, isUndefined, } from '@nestjs/common/utils/shared.utils'; import { ApplicationConfig } from '../application-config'; import { InvalidMiddlewareException } from '../errors/exceptions/invalid-middleware.exception'; import { RuntimeException } from '../errors/exceptions/runtime.exception'; import { ContextIdFactory } from '../helpers/context-id-factory'; import { ExecutionContextHost } from '../helpers/execution-context-host'; import { STATIC_CONTEXT } from '../injector/constants'; import { NestContainer } from '../injector/container'; import { Injector } from '../injector/injector'; import { InstanceWrapper } from '../injector/instance-wrapper'; import { InstanceToken, Module } from '../injector/module'; import { GraphInspector } from '../inspector/graph-inspector'; import { Entrypoint, MiddlewareEntrypointMetadata, } from '../inspector/interfaces/entrypoint.interface'; import { REQUEST_CONTEXT_ID } from '../router/request/request-constants'; import { RoutePathFactory } from '../router/route-path-factory'; import { RouterExceptionFilters } from '../router/router-exception-filters'; import { RouterProxy } from '../router/router-proxy'; import { isRequestMethodAll, isRouteExcluded } from '../router/utils'; import { MiddlewareBuilder } from './builder'; import { MiddlewareContainer } from './container'; import { MiddlewareResolver } from './resolver'; import { RoutesMapper } from './routes-mapper'; export class MiddlewareModule { private readonly routerProxy = new RouterProxy(); private readonly exceptionFiltersCache = new WeakMap(); private injector: Injector; private routerExceptionFilter: RouterExceptionFilters; private routesMapper: RoutesMapper; private resolver: MiddlewareResolver; private config: ApplicationConfig; private container: NestContainer; private httpAdapter: HttpServer; private graphInspector: GraphInspector; constructor(private readonly routePathFactory: RoutePathFactory) {} public async register( middlewareContainer: MiddlewareContainer, container: NestContainer, config: ApplicationConfig, injector: Injector, httpAdapter: HttpServer, graphInspector: GraphInspector, ) { const appRef = container.getHttpAdapterRef(); this.routerExceptionFilter = new RouterExceptionFilters( container, config, appRef, ); this.routesMapper = new RoutesMapper(container); this.resolver = new MiddlewareResolver(middlewareContainer, injector); this.config = config; this.injector = injector; this.container = container; this.httpAdapter = httpAdapter; this.graphInspector = graphInspector; const modules = container.getModules(); await this.resolveMiddleware(middlewareContainer, modules); } public async resolveMiddleware( middlewareContainer: MiddlewareContainer, modules: Map<string, Module>, ) { const moduleEntries = [...modules.entries()]; const loadMiddlewareConfiguration = async ([moduleName, moduleRef]: [ string, Module, ]) => { await this.loadConfiguration(middlewareContainer, moduleRef, moduleName); await this.resolver.resolveInstances(moduleRef, moduleName); }; await Promise.all(moduleEntries.map(loadMiddlewareConfiguration)); } public async loadConfiguration( middlewareContainer: MiddlewareContainer, moduleRef: Module, moduleKey: string, ) { const { instance } = moduleRef; if (!instance.configure) { return; } const middlewareBuilder = new MiddlewareBuilder( this.routesMapper, this.httpAdapter, ); await instance.configure(middlewareBuilder); if (!(middlewareBuilder instanceof MiddlewareBuilder)) { return; } const config = middlewareBuilder.build(); middlewareContainer.insertConfig(config, moduleKey); } public async registerMiddleware( middlewareContainer: MiddlewareContainer, applicationRef: any, ) { const configs = middlewareContainer.getConfigurations(); const registerAllConfigs = async ( moduleKey: string, middlewareConfig: MiddlewareConfiguration[], ) => { for (const config of middlewareConfig) { await this.registerMiddlewareConfig( middlewareContainer, config, moduleKey, applicationRef, ); } }; const entriesSortedByDistance = [...configs.entries()].sort( ([moduleA], [moduleB]) => { return ( this.container.getModuleByKey(moduleA).distance - this.container.getModuleByKey(moduleB).distance ); }, ); for (const [moduleRef, moduleConfigurations] of entriesSortedByDistance) { await registerAllConfigs(moduleRef, [...moduleConfigurations]); } } public async registerMiddlewareConfig( middlewareContainer: MiddlewareContainer, config: MiddlewareConfiguration, moduleKey: string, applicationRef: any, ) { const { forRoutes } = config; for (const routeInfo of forRoutes) { await this.registerRouteMiddleware( middlewareContainer, routeInfo as RouteInfo, config, moduleKey, applicationRef, ); } } public async registerRouteMiddleware( middlewareContainer: MiddlewareContainer, routeInfo: RouteInfo, config: MiddlewareConfiguration, moduleKey: string, applicationRef: any, ) { const middlewareCollection = [].concat(config.middleware); const moduleRef = this.container.getModuleByKey(moduleKey); for (const metatype of middlewareCollection) { const collection = middlewareContainer.getMiddlewareCollection(moduleKey); const instanceWrapper = collection.get(metatype); if (isUndefined(instanceWrapper)) { throw new RuntimeException(); } if (instanceWrapper.isTransient) { return; } this.graphInspector.insertClassNode( moduleRef, instanceWrapper, 'middleware', ); const middlewareDefinition: Entrypoint<MiddlewareEntrypointMetadata> = { type: 'middleware', methodName: 'use', className: instanceWrapper.name, classNodeId: instanceWrapper.id, metadata: { key: routeInfo.path, path: routeInfo.path, requestMethod: (RequestMethod[routeInfo.method] as keyof typeof RequestMethod) ?? 'ALL', version: routeInfo.version, }, }; this.graphInspector.insertEntrypointDefinition( middlewareDefinition, instanceWrapper.id, ); await this.bindHandler( instanceWrapper, applicationRef, routeInfo, moduleRef, collection, ); } } private async bindHandler( wrapper: InstanceWrapper<NestMiddleware>, applicationRef: HttpServer, routeInfo: RouteInfo, moduleRef: Module, collection: Map<InstanceToken, InstanceWrapper>, ) { const { instance, metatype } = wrapper; if (isUndefined(instance?.use)) { throw new InvalidMiddlewareException(metatype.name); } const isStatic = wrapper.isDependencyTreeStatic(); if (isStatic) { const proxy = await this.createProxy(instance); return this.registerHandler(applicationRef, routeInfo, proxy); } await this.registerHandler( applicationRef, routeInfo, async <TRequest, TResponse>( req: TRequest, res: TResponse, next: () => void, ) => { try { const contextId = ContextIdFactory.getByRequest(req); if (!req[REQUEST_CONTEXT_ID]) { Object.defineProperty(req, REQUEST_CONTEXT_ID, { value: contextId, enumerable: false, writable: false, configurable: false, }); this.container.registerRequestProvider( contextId.getParent ? contextId.payload : req, contextId, ); } const contextInstance = await this.injector.loadPerContext( instance, moduleRef, collection, contextId, ); const proxy = await this.createProxy<TRequest, TResponse>( contextInstance, contextId, ); return proxy(req, res, next); } catch (err) { let exceptionsHandler = this.exceptionFiltersCache.get(instance.use); if (!exceptionsHandler) { exceptionsHandler = this.routerExceptionFilter.create( instance, instance.use, undefined, ); this.exceptionFiltersCache.set(instance.use, exceptionsHandler); } const host = new ExecutionContextHost([req, res, next]); exceptionsHandler.next(err, host); } }, ); } private async createProxy<TRequest = unknown, TResponse = unknown>( instance: NestMiddleware, contextId = STATIC_CONTEXT, ): Promise<(req: TRequest, res: TResponse, next: () => void) => void> { const exceptionsHandler = this.routerExceptionFilter.create( instance, instance.use, undefined, contextId, ); const middleware = instance.use.bind(instance); return this.routerProxy.createProxy(middleware, exceptionsHandler); } private async registerHandler( applicationRef: HttpServer, { path, method, version }: RouteInfo, proxy: <TRequest, TResponse>( req: TRequest, res: TResponse, next: () => void, ) => void, ) { const prefix = this.config.getGlobalPrefix(); const excludedRoutes = this.config.getGlobalPrefixOptions().exclude; if ( (Array.isArray(excludedRoutes) && isRouteExcluded(excludedRoutes, path, method)) || ['*', '/*', '(.*)', '/(.*)'].includes(path) ) { path = addLeadingSlash(path); } else { const basePath = addLeadingSlash(prefix); if (basePath?.endsWith('/') && path?.startsWith('/')) { // strip slash when a wildcard is being used // and global prefix has been set path = path?.slice(1); } path = basePath + path; } const applicationVersioningConfig = this.config.getVersioning(); if (version && applicationVersioningConfig.type === VersioningType.URI) { const versionPrefix = this.routePathFactory.getVersionPrefix( applicationVersioningConfig, ); path = `/${versionPrefix}${version.toString()}${path}`; } const isMethodAll = isRequestMethodAll(method); const requestMethod = RequestMethod[method]; const router = await applicationRef.createMiddlewareFactory(method); router( path, isMethodAll ? proxy : <TRequest, TResponse>( req: TRequest, res: TResponse, next: () => void, ) => { if (applicationRef.getRequestMethod(req) === requestMethod) { return proxy(req, res, next); } return next(); }, ); } }
packages/core/middleware/middleware-module.ts
1
https://github.com/nestjs/nest/commit/20abe1df78159aa6d451898e8470285ed64eabe5
[ 0.9786685109138489, 0.027688678354024887, 0.00016323231102433056, 0.0003127110539935529, 0.16074548661708832 ]
{ "id": 0, "code_window": [ "import { HttpServer, VersioningType } from '@nestjs/common';\n", "import { RequestMethod } from '@nestjs/common/enums/request-method.enum';\n", "import {\n", " MiddlewareConfiguration,\n" ], "labels": [ "replace", "keep", "keep", "keep" ], "after_edit": [ "import { HttpServer, Logger, VersioningType } from '@nestjs/common';\n" ], "file_path": "packages/core/middleware/middleware-module.ts", "type": "replace", "edit_start_line_idx": 0 }
import { MESSAGE_MAPPING_METADATA, MESSAGE_METADATA } from '../constants'; /** * Subscribes to messages that fulfils chosen pattern. */ export const SubscribeMessage = <T = string>(message: T): MethodDecorator => { return ( target: object, key: string | symbol, descriptor: PropertyDescriptor, ) => { Reflect.defineMetadata(MESSAGE_MAPPING_METADATA, true, descriptor.value); Reflect.defineMetadata(MESSAGE_METADATA, message, descriptor.value); return descriptor; }; };
packages/websockets/decorators/subscribe-message.decorator.ts
0
https://github.com/nestjs/nest/commit/20abe1df78159aa6d451898e8470285ed64eabe5
[ 0.00016854985733516514, 0.0001679595443420112, 0.00016736923134885728, 0.0001679595443420112, 5.903129931539297e-7 ]
{ "id": 0, "code_window": [ "import { HttpServer, VersioningType } from '@nestjs/common';\n", "import { RequestMethod } from '@nestjs/common/enums/request-method.enum';\n", "import {\n", " MiddlewareConfiguration,\n" ], "labels": [ "replace", "keep", "keep", "keep" ], "after_edit": [ "import { HttpServer, Logger, VersioningType } from '@nestjs/common';\n" ], "file_path": "packages/core/middleware/middleware-module.ts", "type": "replace", "edit_start_line_idx": 0 }
/** * Interface defining method called once the host module has been initialized. * * @see [Lifecycle Events](https://docs.nestjs.com/fundamentals/lifecycle-events) * * @publicApi */ export interface OnModuleInit { onModuleInit(): any; }
packages/common/interfaces/hooks/on-init.interface.ts
0
https://github.com/nestjs/nest/commit/20abe1df78159aa6d451898e8470285ed64eabe5
[ 0.00017459543596487492, 0.00017345680680591613, 0.00017231817764695734, 0.00017345680680591613, 0.0000011386291589587927 ]
{ "id": 0, "code_window": [ "import { HttpServer, VersioningType } from '@nestjs/common';\n", "import { RequestMethod } from '@nestjs/common/enums/request-method.enum';\n", "import {\n", " MiddlewareConfiguration,\n" ], "labels": [ "replace", "keep", "keep", "keep" ], "after_edit": [ "import { HttpServer, Logger, VersioningType } from '@nestjs/common';\n" ], "file_path": "packages/core/middleware/middleware-module.ts", "type": "replace", "edit_start_line_idx": 0 }
# Contributing to Nest We would love for you to contribute to Nest and help make it even better than it is today! As a contributor, here are the guidelines we would like you to follow: <!--* [Code of Conduct](#coc)--> - [Question or Problem?](#question) - [Issues and Bugs](#issue) - [Feature Requests](#feature) - [Submission Guidelines](#submit) - [Development Setup](#development) - [Coding Rules](#rules) - [Commit Message Guidelines](#commit) <!-- - [Signing the CLA](#cla) --> <!-- ## <a name="coc"></a> Code of Conduct Help us keep Nest open and inclusive. Please read and follow our [Code of Conduct][coc]. --> ## <a name="question"></a> Got a Question or Problem? **Do not open issues for general support questions as we want to keep GitHub issues for bug reports and feature requests.** You've got much better chances of getting your question answered on [Stack Overflow][stackoverflow] where the questions should be tagged with tag `nestjs`. Stack Overflow is a much better place to ask questions since: <!-- - there are thousands of people willing to help on Stack Overflow [maybe one day] --> - questions and answers stay available for public viewing so your question / answer might help someone else - Stack Overflow's voting system assures that the best answers are prominently visible. To save your and our time, we will systematically close all issues that are requests for general support and redirect people to Stack Overflow. If you would like to chat about the question in real-time, you can reach out via [our discord channel][discord]. ## <a name="issue"></a> Found a Bug? If you find a bug in the source code, you can help us by [submitting an issue](#submit-issue) to our [GitHub Repository][github]. Even better, you can [submit a Pull Request](#submit-pr) with a fix. ## <a name="feature"></a> Missing a Feature? You can _request_ a new feature by [submitting an issue](#submit-issue) to our GitHub Repository. If you would like to _implement_ a new feature, please submit an issue with a proposal for your work first, to be sure that we can use it. Please consider what kind of change it is: - For a **Major Feature**, first open an issue and outline your proposal so that it can be discussed. This will also allow us to better coordinate our efforts, prevent duplication of work, and help you to craft the change so that it is successfully accepted into the project. For your issue name, please prefix your proposal with `[discussion]`, for example "[discussion]: your feature idea". - **Small Features** can be crafted and directly [submitted as a Pull Request](#submit-pr). ## <a name="submit"></a> Submission Guidelines ### <a name="submit-issue"></a> Submitting an Issue Before you submit an issue, please search the issue tracker, maybe an issue for your problem already exists and the discussion might inform you of workarounds readily available. We want to fix all the issues as soon as possible, but before fixing a bug we need to reproduce and confirm it. In order to reproduce bugs we will systematically ask you to provide a minimal reproduction scenario using a repository or [Gist](https://gist.github.com/). Having a live, reproducible scenario gives us wealth of important information without going back & forth to you with additional questions like: - version of NestJS used - 3rd-party libraries and their versions - and most importantly - a use-case that fails <!-- // TODO we need to create a playground, similar to plunkr A minimal reproduce scenario using a repository or Gist allows us to quickly confirm a bug (or point out coding problem) as well as confirm that we are fixing the right problem. If neither of these are not a suitable way to demonstrate the problem (for example for issues related to our npm packaging), please create a standalone git repository demonstrating the problem. --> <!-- We will be insisting on a minimal reproduce scenario in order to save maintainers time and ultimately be able to fix more bugs. Interestingly, from our experience users often find coding problems themselves while preparing a minimal plunk. We understand that sometimes it might be hard to extract essentials bits of code from a larger code-base but we really need to isolate the problem before we can fix it. --> Unfortunately, we are not able to investigate / fix bugs without a minimal reproduction, so if we don't hear back from you we are going to close an issue that doesn't have enough info to be reproduced. You can file new issues by filling out our [new issue form][new_issue]. ### <a name="submit-pr"></a> Submitting a Pull Request (PR) Before you submit your Pull Request (PR) consider the following guidelines: <!-- To the first point 1. Please sign our [Contributor License Agreement (CLA)](#cla) before sending PRs. We cannot accept code without this. --> 1. Search [GitHub Pull Requests][gh_prs] for an open or closed PR that relates to your submission. You don't want to duplicate effort. 1. Fork this repository. 1. Make your changes in a new git branch: ```shell git checkout -b my-fix-branch master ``` 1. Create your patch, **including appropriate test cases**. 1. Follow our [Coding Rules](#rules). 1. Run the full Nest test suite (see [common scripts](#common-scripts)), and ensure that all tests pass. 1. Commit your changes using a descriptive commit message that follows our [commit message conventions](#commit). Adherence to these conventions is necessary because release notes are automatically generated from these messages. ```shell git commit -a ``` Note: the optional commit `-a` command line option will automatically "add" and "rm" edited files. 1. Push your branch to GitHub: ```shell git push origin my-fix-branch ``` 1. In GitHub, send a pull request to `nestjs:master`. - If we suggest changes then: - Make the required updates. - Re-run the Nest test suites to ensure tests are still passing. - Rebase your branch and force push to your GitHub repository (this will update your Pull Request): ```shell git rebase master -i git push -f ``` That's it! Thank you for your contribution! #### After your pull request is merged After your pull request is merged, you can safely delete your branch and pull the changes from the main (upstream) repository: - Delete the remote branch on GitHub either through the GitHub web UI or your local shell as follows: ```shell git push origin --delete my-fix-branch ``` - Check out the master branch: ```shell git checkout master -f ``` - Delete the local branch: ```shell git branch -D my-fix-branch ``` - Update your master with the latest upstream version: ```shell git pull --ff upstream master ``` ## <a name="development"></a> Development Setup You will need [Node.js](https://nodejs.org) version >= 10.13.0 (except for v13). 1. After cloning the repo, run: ```bash $ npm ci # (or yarn install) ``` 2. In order to prepare your environment run `prepare.sh` shell script: ```bash $ sh scripts/prepare.sh ``` That will compile fresh packages and afterward, move them all to `sample` directories. ### <a name="common-scripts"></a>Commonly used NPM scripts ```bash # build all packages and move to "sample" directories $ npm run build # run the full unit tests suite $ npm run test # run integration tests # docker is required(!) $ sh scripts/run-integration.sh # run linter $ npm run lint # build all packages and put them near to their source .ts files $ npm run build:prod ``` ## <a name="rules"></a> Coding Rules To ensure consistency throughout the source code, keep these rules in mind as you are working: <!-- // We're working on auto-documentation. * All public API methods **must be documented**. (Details TBC). --> - All features or bug fixes **must be tested** by one or more specs (unit-tests). - We follow [Google's JavaScript Style Guide][js-style-guide], but wrap all code at **100 characters**. An automated formatter is available (`npm run format`). ## <a name="commit"></a> Commit Message Guidelines We have very precise rules over how our git commit messages can be formatted. This leads to **more readable messages** that are easy to follow when looking through the **project history**. But also, we use the git commit messages to **generate the Nest change log**. ### Commit Message Format Each commit message consists of a **header**, a **body** and a **footer**. The header has a special format that includes a **type**, a **scope** and a **subject**: ``` <type>(<scope>): <subject> <BLANK LINE> <body> <BLANK LINE> <footer> ``` The **header** is mandatory and the **scope** of the header is optional. Any line of the commit message cannot be longer than 100 characters! This allows the message to be easier to read on GitHub as well as in various git tools. Footer should contain a [closing reference to an issue](https://help.github.com/articles/closing-issues-via-commit-messages/) if any. Samples: (even more [samples][commits_samples]) ``` docs(changelog): update change log to beta.5 fix(core): need to depend on latest rxjs and zone.js ``` ### Revert If the commit reverts a previous commit, it should begin with `revert:`, followed by the header of the reverted commit. In the body it should say: `This reverts commit <hash>.`, where the hash is the SHA of the commit being reverted. ### Type Must be one of the following: - **build**: Changes that affect the build system or external dependencies (example scopes: gulp, broccoli, npm) - **chore**: Updating tasks etc; no production code change - **ci**: Changes to our CI configuration files and scripts (example scopes: Travis, Circle, BrowserStack, SauceLabs) - **docs**: Documentation only changes - **feat**: A new feature - **fix**: A bug fix - **perf**: A code change that improves performance - **refactor**: A code change that neither fixes a bug nor adds a feature - **style**: Changes that do not affect the meaning of the code (white-space, formatting, missing semi-colons, etc) - **test**: Adding missing tests or correcting existing tests - **sample**: A change to the samples ### Scope The scope should have the name of the npm package affected (as perceived by person reading changelog generated from commit messages). The following is the list of supported scopes: - **common**: for changes made on `packages/common` directory - **core**: for changes made on `packages/core` directory - **sample**: for changes made on `packages/sample` directory - **microservices**: for changes made on `packages/microservices` directory - **express**: for changes made on `packages/platform-express` directory - **fastify**: for changes made on `packages/platform-fastify` directory - **socket.io**: for changes made on `packages/platform-socket.io` directory - **ws**: for changes made on `packages/platform-ws` directory - **testing**: for changes made on `packages/testing` directory - **websockets**: for changes made on `packages/websockets` directory If your change affect more than one package, separate the scopes with a comma (e.g. `common,core`). There are currently a few exceptions to the "use package name" rule: - **packaging**: used for changes that change the npm package layout in all of our packages, e.g. public path changes, package.json changes done to all packages, d.ts file/format changes, changes to bundles, etc. - **changelog**: used for updating the release notes in CHANGELOG.md - **sample/#**: for the example apps directory, replacing # with the example app number - none/empty string: useful for `style`, `test` and `refactor` changes that are done across all packages (e.g. `style: add missing semicolons`) ### Subject The subject contains succinct description of the change: - use the imperative, present tense: "change" not "changed" nor "changes" - don't capitalize first letter - no dot (.) at the end ### Body Just as in the **subject**, use the imperative, present tense: "change" not "changed" nor "changes". The body should include the motivation for the change and contrast this with previous behavior. ### Footer The footer should contain any information about **Breaking Changes** and is also the place to reference GitHub issues that this commit **Closes**. **Breaking Changes** should start with the word `BREAKING CHANGE:` with a space or two newlines. The rest of the commit message is then used for this. A detailed explanation can be found in this [document][commit-message-format]. <!-- ## <a name="cla"></a> Signing the CLA Please sign our Contributor License Agreement (CLA) before sending pull requests. For any code changes to be accepted, the CLA must be signed. It's a quick process, we promise! * For individuals we have a [simple click-through form][individual-cla]. * For corporations we'll need you to [print, sign and one of scan+email, fax or mail the form][corporate-cla]. --> <!-- [angular-group]: https://groups.google.com/forum/#!forum/angular --> <!-- [coc]: https://github.com/angular/code-of-conduct/blob/master/CODE_OF_CONDUCT.md --> [commit-message-format]: https://docs.google.com/document/d/1QrDFcIiPjSLDn3EL15IJygNPiHORgU1_OOAqWjiDU5Y/edit# <!-- [individual-cla]: http://code.google.com/legal/individual-cla-v1.0.html --> <!-- [corporate-cla]: http://code.google.com/legal/corporate-cla-v1.0.html --> [dev-doc]: https://github.com/nestjs/nest/blob/master/docs/DEVELOPER.md [github]: https://github.com/nestjs/nest [stackoverflow]: https://stackoverflow.com/questions/tagged/nestjs [discord]: https://discordapp.com/invite/G7Qnnhy [js-style-guide]: https://google.github.io/styleguide/jsguide.html [new_issue]: https://github.com/nestjs/nest/issues/new [gh_prs]: https://github.com/nestjs/nest/pulls [commits_samples]: https://github.com/nestjs/nest/commits/master
CONTRIBUTING.md
0
https://github.com/nestjs/nest/commit/20abe1df78159aa6d451898e8470285ed64eabe5
[ 0.00017322439816780388, 0.00016841597971506417, 0.00016212649643421173, 0.00016851862892508507, 0.0000025322601686639246 ]
{ "id": 1, "code_window": [ "import {\n", " MiddlewareConfiguration,\n", " NestMiddleware,\n", " RouteInfo,\n", "} from '@nestjs/common/interfaces/middleware';\n", "import {\n", " addLeadingSlash,\n", " isUndefined,\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "import { NestApplicationContextOptions } from '@nestjs/common/interfaces/nest-application-context-options.interface';\n" ], "file_path": "packages/core/middleware/middleware-module.ts", "type": "add", "edit_start_line_idx": 7 }
import { HttpServer, VersioningType } from '@nestjs/common'; import { RequestMethod } from '@nestjs/common/enums/request-method.enum'; import { MiddlewareConfiguration, NestMiddleware, RouteInfo, } from '@nestjs/common/interfaces/middleware'; import { addLeadingSlash, isUndefined, } from '@nestjs/common/utils/shared.utils'; import { ApplicationConfig } from '../application-config'; import { InvalidMiddlewareException } from '../errors/exceptions/invalid-middleware.exception'; import { RuntimeException } from '../errors/exceptions/runtime.exception'; import { ContextIdFactory } from '../helpers/context-id-factory'; import { ExecutionContextHost } from '../helpers/execution-context-host'; import { STATIC_CONTEXT } from '../injector/constants'; import { NestContainer } from '../injector/container'; import { Injector } from '../injector/injector'; import { InstanceWrapper } from '../injector/instance-wrapper'; import { InstanceToken, Module } from '../injector/module'; import { GraphInspector } from '../inspector/graph-inspector'; import { Entrypoint, MiddlewareEntrypointMetadata, } from '../inspector/interfaces/entrypoint.interface'; import { REQUEST_CONTEXT_ID } from '../router/request/request-constants'; import { RoutePathFactory } from '../router/route-path-factory'; import { RouterExceptionFilters } from '../router/router-exception-filters'; import { RouterProxy } from '../router/router-proxy'; import { isRequestMethodAll, isRouteExcluded } from '../router/utils'; import { MiddlewareBuilder } from './builder'; import { MiddlewareContainer } from './container'; import { MiddlewareResolver } from './resolver'; import { RoutesMapper } from './routes-mapper'; export class MiddlewareModule { private readonly routerProxy = new RouterProxy(); private readonly exceptionFiltersCache = new WeakMap(); private injector: Injector; private routerExceptionFilter: RouterExceptionFilters; private routesMapper: RoutesMapper; private resolver: MiddlewareResolver; private config: ApplicationConfig; private container: NestContainer; private httpAdapter: HttpServer; private graphInspector: GraphInspector; constructor(private readonly routePathFactory: RoutePathFactory) {} public async register( middlewareContainer: MiddlewareContainer, container: NestContainer, config: ApplicationConfig, injector: Injector, httpAdapter: HttpServer, graphInspector: GraphInspector, ) { const appRef = container.getHttpAdapterRef(); this.routerExceptionFilter = new RouterExceptionFilters( container, config, appRef, ); this.routesMapper = new RoutesMapper(container); this.resolver = new MiddlewareResolver(middlewareContainer, injector); this.config = config; this.injector = injector; this.container = container; this.httpAdapter = httpAdapter; this.graphInspector = graphInspector; const modules = container.getModules(); await this.resolveMiddleware(middlewareContainer, modules); } public async resolveMiddleware( middlewareContainer: MiddlewareContainer, modules: Map<string, Module>, ) { const moduleEntries = [...modules.entries()]; const loadMiddlewareConfiguration = async ([moduleName, moduleRef]: [ string, Module, ]) => { await this.loadConfiguration(middlewareContainer, moduleRef, moduleName); await this.resolver.resolveInstances(moduleRef, moduleName); }; await Promise.all(moduleEntries.map(loadMiddlewareConfiguration)); } public async loadConfiguration( middlewareContainer: MiddlewareContainer, moduleRef: Module, moduleKey: string, ) { const { instance } = moduleRef; if (!instance.configure) { return; } const middlewareBuilder = new MiddlewareBuilder( this.routesMapper, this.httpAdapter, ); await instance.configure(middlewareBuilder); if (!(middlewareBuilder instanceof MiddlewareBuilder)) { return; } const config = middlewareBuilder.build(); middlewareContainer.insertConfig(config, moduleKey); } public async registerMiddleware( middlewareContainer: MiddlewareContainer, applicationRef: any, ) { const configs = middlewareContainer.getConfigurations(); const registerAllConfigs = async ( moduleKey: string, middlewareConfig: MiddlewareConfiguration[], ) => { for (const config of middlewareConfig) { await this.registerMiddlewareConfig( middlewareContainer, config, moduleKey, applicationRef, ); } }; const entriesSortedByDistance = [...configs.entries()].sort( ([moduleA], [moduleB]) => { return ( this.container.getModuleByKey(moduleA).distance - this.container.getModuleByKey(moduleB).distance ); }, ); for (const [moduleRef, moduleConfigurations] of entriesSortedByDistance) { await registerAllConfigs(moduleRef, [...moduleConfigurations]); } } public async registerMiddlewareConfig( middlewareContainer: MiddlewareContainer, config: MiddlewareConfiguration, moduleKey: string, applicationRef: any, ) { const { forRoutes } = config; for (const routeInfo of forRoutes) { await this.registerRouteMiddleware( middlewareContainer, routeInfo as RouteInfo, config, moduleKey, applicationRef, ); } } public async registerRouteMiddleware( middlewareContainer: MiddlewareContainer, routeInfo: RouteInfo, config: MiddlewareConfiguration, moduleKey: string, applicationRef: any, ) { const middlewareCollection = [].concat(config.middleware); const moduleRef = this.container.getModuleByKey(moduleKey); for (const metatype of middlewareCollection) { const collection = middlewareContainer.getMiddlewareCollection(moduleKey); const instanceWrapper = collection.get(metatype); if (isUndefined(instanceWrapper)) { throw new RuntimeException(); } if (instanceWrapper.isTransient) { return; } this.graphInspector.insertClassNode( moduleRef, instanceWrapper, 'middleware', ); const middlewareDefinition: Entrypoint<MiddlewareEntrypointMetadata> = { type: 'middleware', methodName: 'use', className: instanceWrapper.name, classNodeId: instanceWrapper.id, metadata: { key: routeInfo.path, path: routeInfo.path, requestMethod: (RequestMethod[routeInfo.method] as keyof typeof RequestMethod) ?? 'ALL', version: routeInfo.version, }, }; this.graphInspector.insertEntrypointDefinition( middlewareDefinition, instanceWrapper.id, ); await this.bindHandler( instanceWrapper, applicationRef, routeInfo, moduleRef, collection, ); } } private async bindHandler( wrapper: InstanceWrapper<NestMiddleware>, applicationRef: HttpServer, routeInfo: RouteInfo, moduleRef: Module, collection: Map<InstanceToken, InstanceWrapper>, ) { const { instance, metatype } = wrapper; if (isUndefined(instance?.use)) { throw new InvalidMiddlewareException(metatype.name); } const isStatic = wrapper.isDependencyTreeStatic(); if (isStatic) { const proxy = await this.createProxy(instance); return this.registerHandler(applicationRef, routeInfo, proxy); } await this.registerHandler( applicationRef, routeInfo, async <TRequest, TResponse>( req: TRequest, res: TResponse, next: () => void, ) => { try { const contextId = ContextIdFactory.getByRequest(req); if (!req[REQUEST_CONTEXT_ID]) { Object.defineProperty(req, REQUEST_CONTEXT_ID, { value: contextId, enumerable: false, writable: false, configurable: false, }); this.container.registerRequestProvider( contextId.getParent ? contextId.payload : req, contextId, ); } const contextInstance = await this.injector.loadPerContext( instance, moduleRef, collection, contextId, ); const proxy = await this.createProxy<TRequest, TResponse>( contextInstance, contextId, ); return proxy(req, res, next); } catch (err) { let exceptionsHandler = this.exceptionFiltersCache.get(instance.use); if (!exceptionsHandler) { exceptionsHandler = this.routerExceptionFilter.create( instance, instance.use, undefined, ); this.exceptionFiltersCache.set(instance.use, exceptionsHandler); } const host = new ExecutionContextHost([req, res, next]); exceptionsHandler.next(err, host); } }, ); } private async createProxy<TRequest = unknown, TResponse = unknown>( instance: NestMiddleware, contextId = STATIC_CONTEXT, ): Promise<(req: TRequest, res: TResponse, next: () => void) => void> { const exceptionsHandler = this.routerExceptionFilter.create( instance, instance.use, undefined, contextId, ); const middleware = instance.use.bind(instance); return this.routerProxy.createProxy(middleware, exceptionsHandler); } private async registerHandler( applicationRef: HttpServer, { path, method, version }: RouteInfo, proxy: <TRequest, TResponse>( req: TRequest, res: TResponse, next: () => void, ) => void, ) { const prefix = this.config.getGlobalPrefix(); const excludedRoutes = this.config.getGlobalPrefixOptions().exclude; if ( (Array.isArray(excludedRoutes) && isRouteExcluded(excludedRoutes, path, method)) || ['*', '/*', '(.*)', '/(.*)'].includes(path) ) { path = addLeadingSlash(path); } else { const basePath = addLeadingSlash(prefix); if (basePath?.endsWith('/') && path?.startsWith('/')) { // strip slash when a wildcard is being used // and global prefix has been set path = path?.slice(1); } path = basePath + path; } const applicationVersioningConfig = this.config.getVersioning(); if (version && applicationVersioningConfig.type === VersioningType.URI) { const versionPrefix = this.routePathFactory.getVersionPrefix( applicationVersioningConfig, ); path = `/${versionPrefix}${version.toString()}${path}`; } const isMethodAll = isRequestMethodAll(method); const requestMethod = RequestMethod[method]; const router = await applicationRef.createMiddlewareFactory(method); router( path, isMethodAll ? proxy : <TRequest, TResponse>( req: TRequest, res: TResponse, next: () => void, ) => { if (applicationRef.getRequestMethod(req) === requestMethod) { return proxy(req, res, next); } return next(); }, ); } }
packages/core/middleware/middleware-module.ts
1
https://github.com/nestjs/nest/commit/20abe1df78159aa6d451898e8470285ed64eabe5
[ 0.9910873770713806, 0.054263778030872345, 0.00016681892157066613, 0.0005794320022687316, 0.21399420499801636 ]
{ "id": 1, "code_window": [ "import {\n", " MiddlewareConfiguration,\n", " NestMiddleware,\n", " RouteInfo,\n", "} from '@nestjs/common/interfaces/middleware';\n", "import {\n", " addLeadingSlash,\n", " isUndefined,\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "import { NestApplicationContextOptions } from '@nestjs/common/interfaces/nest-application-context-options.interface';\n" ], "file_path": "packages/core/middleware/middleware-module.ts", "type": "add", "edit_start_line_idx": 7 }
{ "singleQuote": true, "trailingComma": "all" }
sample/25-dynamic-modules/.prettierrc
0
https://github.com/nestjs/nest/commit/20abe1df78159aa6d451898e8470285ed64eabe5
[ 0.00017190167272929102, 0.00017190167272929102, 0.00017190167272929102, 0.00017190167272929102, 0 ]
{ "id": 1, "code_window": [ "import {\n", " MiddlewareConfiguration,\n", " NestMiddleware,\n", " RouteInfo,\n", "} from '@nestjs/common/interfaces/middleware';\n", "import {\n", " addLeadingSlash,\n", " isUndefined,\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "import { NestApplicationContextOptions } from '@nestjs/common/interfaces/nest-application-context-options.interface';\n" ], "file_path": "packages/core/middleware/middleware-module.ts", "type": "add", "edit_start_line_idx": 7 }
export * from './files-upload-module.interface';
packages/platform-express/multer/interfaces/index.ts
0
https://github.com/nestjs/nest/commit/20abe1df78159aa6d451898e8470285ed64eabe5
[ 0.00016931256686802953, 0.00016931256686802953, 0.00016931256686802953, 0.00016931256686802953, 0 ]
{ "id": 1, "code_window": [ "import {\n", " MiddlewareConfiguration,\n", " NestMiddleware,\n", " RouteInfo,\n", "} from '@nestjs/common/interfaces/middleware';\n", "import {\n", " addLeadingSlash,\n", " isUndefined,\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "import { NestApplicationContextOptions } from '@nestjs/common/interfaces/nest-application-context-options.interface';\n" ], "file_path": "packages/core/middleware/middleware-module.ts", "type": "add", "edit_start_line_idx": 7 }
import { CallHandler, ExecutionContext, Injectable, NestInterceptor, Scope, } from '@nestjs/common'; import { Observable } from 'rxjs'; @Injectable({ scope: Scope.REQUEST }) export class Interceptor implements NestInterceptor { static COUNTER = 0; constructor() { Interceptor.COUNTER++; } intercept(context: ExecutionContext, call: CallHandler): Observable<any> { return call.handle(); } }
integration/inspector/src/circular-hello/interceptors/logging.interceptor.ts
0
https://github.com/nestjs/nest/commit/20abe1df78159aa6d451898e8470285ed64eabe5
[ 0.0006158280302770436, 0.0005300510674715042, 0.00044427404645830393, 0.0005300510674715042, 0.00008577699190936983 ]
{ "id": 2, "code_window": [ "import { MiddlewareBuilder } from './builder';\n", "import { MiddlewareContainer } from './container';\n", "import { MiddlewareResolver } from './resolver';\n", "import { RoutesMapper } from './routes-mapper';\n", "\n", "export class MiddlewareModule {\n", " private readonly routerProxy = new RouterProxy();\n", " private readonly exceptionFiltersCache = new WeakMap();\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [ "export class MiddlewareModule<\n", " TAppOptions extends NestApplicationContextOptions = NestApplicationContextOptions,\n", "> {\n" ], "file_path": "packages/core/middleware/middleware-module.ts", "type": "replace", "edit_start_line_idx": 36 }
import { HttpServer, VersioningType } from '@nestjs/common'; import { RequestMethod } from '@nestjs/common/enums/request-method.enum'; import { MiddlewareConfiguration, NestMiddleware, RouteInfo, } from '@nestjs/common/interfaces/middleware'; import { addLeadingSlash, isUndefined, } from '@nestjs/common/utils/shared.utils'; import { ApplicationConfig } from '../application-config'; import { InvalidMiddlewareException } from '../errors/exceptions/invalid-middleware.exception'; import { RuntimeException } from '../errors/exceptions/runtime.exception'; import { ContextIdFactory } from '../helpers/context-id-factory'; import { ExecutionContextHost } from '../helpers/execution-context-host'; import { STATIC_CONTEXT } from '../injector/constants'; import { NestContainer } from '../injector/container'; import { Injector } from '../injector/injector'; import { InstanceWrapper } from '../injector/instance-wrapper'; import { InstanceToken, Module } from '../injector/module'; import { GraphInspector } from '../inspector/graph-inspector'; import { Entrypoint, MiddlewareEntrypointMetadata, } from '../inspector/interfaces/entrypoint.interface'; import { REQUEST_CONTEXT_ID } from '../router/request/request-constants'; import { RoutePathFactory } from '../router/route-path-factory'; import { RouterExceptionFilters } from '../router/router-exception-filters'; import { RouterProxy } from '../router/router-proxy'; import { isRequestMethodAll, isRouteExcluded } from '../router/utils'; import { MiddlewareBuilder } from './builder'; import { MiddlewareContainer } from './container'; import { MiddlewareResolver } from './resolver'; import { RoutesMapper } from './routes-mapper'; export class MiddlewareModule { private readonly routerProxy = new RouterProxy(); private readonly exceptionFiltersCache = new WeakMap(); private injector: Injector; private routerExceptionFilter: RouterExceptionFilters; private routesMapper: RoutesMapper; private resolver: MiddlewareResolver; private config: ApplicationConfig; private container: NestContainer; private httpAdapter: HttpServer; private graphInspector: GraphInspector; constructor(private readonly routePathFactory: RoutePathFactory) {} public async register( middlewareContainer: MiddlewareContainer, container: NestContainer, config: ApplicationConfig, injector: Injector, httpAdapter: HttpServer, graphInspector: GraphInspector, ) { const appRef = container.getHttpAdapterRef(); this.routerExceptionFilter = new RouterExceptionFilters( container, config, appRef, ); this.routesMapper = new RoutesMapper(container); this.resolver = new MiddlewareResolver(middlewareContainer, injector); this.config = config; this.injector = injector; this.container = container; this.httpAdapter = httpAdapter; this.graphInspector = graphInspector; const modules = container.getModules(); await this.resolveMiddleware(middlewareContainer, modules); } public async resolveMiddleware( middlewareContainer: MiddlewareContainer, modules: Map<string, Module>, ) { const moduleEntries = [...modules.entries()]; const loadMiddlewareConfiguration = async ([moduleName, moduleRef]: [ string, Module, ]) => { await this.loadConfiguration(middlewareContainer, moduleRef, moduleName); await this.resolver.resolveInstances(moduleRef, moduleName); }; await Promise.all(moduleEntries.map(loadMiddlewareConfiguration)); } public async loadConfiguration( middlewareContainer: MiddlewareContainer, moduleRef: Module, moduleKey: string, ) { const { instance } = moduleRef; if (!instance.configure) { return; } const middlewareBuilder = new MiddlewareBuilder( this.routesMapper, this.httpAdapter, ); await instance.configure(middlewareBuilder); if (!(middlewareBuilder instanceof MiddlewareBuilder)) { return; } const config = middlewareBuilder.build(); middlewareContainer.insertConfig(config, moduleKey); } public async registerMiddleware( middlewareContainer: MiddlewareContainer, applicationRef: any, ) { const configs = middlewareContainer.getConfigurations(); const registerAllConfigs = async ( moduleKey: string, middlewareConfig: MiddlewareConfiguration[], ) => { for (const config of middlewareConfig) { await this.registerMiddlewareConfig( middlewareContainer, config, moduleKey, applicationRef, ); } }; const entriesSortedByDistance = [...configs.entries()].sort( ([moduleA], [moduleB]) => { return ( this.container.getModuleByKey(moduleA).distance - this.container.getModuleByKey(moduleB).distance ); }, ); for (const [moduleRef, moduleConfigurations] of entriesSortedByDistance) { await registerAllConfigs(moduleRef, [...moduleConfigurations]); } } public async registerMiddlewareConfig( middlewareContainer: MiddlewareContainer, config: MiddlewareConfiguration, moduleKey: string, applicationRef: any, ) { const { forRoutes } = config; for (const routeInfo of forRoutes) { await this.registerRouteMiddleware( middlewareContainer, routeInfo as RouteInfo, config, moduleKey, applicationRef, ); } } public async registerRouteMiddleware( middlewareContainer: MiddlewareContainer, routeInfo: RouteInfo, config: MiddlewareConfiguration, moduleKey: string, applicationRef: any, ) { const middlewareCollection = [].concat(config.middleware); const moduleRef = this.container.getModuleByKey(moduleKey); for (const metatype of middlewareCollection) { const collection = middlewareContainer.getMiddlewareCollection(moduleKey); const instanceWrapper = collection.get(metatype); if (isUndefined(instanceWrapper)) { throw new RuntimeException(); } if (instanceWrapper.isTransient) { return; } this.graphInspector.insertClassNode( moduleRef, instanceWrapper, 'middleware', ); const middlewareDefinition: Entrypoint<MiddlewareEntrypointMetadata> = { type: 'middleware', methodName: 'use', className: instanceWrapper.name, classNodeId: instanceWrapper.id, metadata: { key: routeInfo.path, path: routeInfo.path, requestMethod: (RequestMethod[routeInfo.method] as keyof typeof RequestMethod) ?? 'ALL', version: routeInfo.version, }, }; this.graphInspector.insertEntrypointDefinition( middlewareDefinition, instanceWrapper.id, ); await this.bindHandler( instanceWrapper, applicationRef, routeInfo, moduleRef, collection, ); } } private async bindHandler( wrapper: InstanceWrapper<NestMiddleware>, applicationRef: HttpServer, routeInfo: RouteInfo, moduleRef: Module, collection: Map<InstanceToken, InstanceWrapper>, ) { const { instance, metatype } = wrapper; if (isUndefined(instance?.use)) { throw new InvalidMiddlewareException(metatype.name); } const isStatic = wrapper.isDependencyTreeStatic(); if (isStatic) { const proxy = await this.createProxy(instance); return this.registerHandler(applicationRef, routeInfo, proxy); } await this.registerHandler( applicationRef, routeInfo, async <TRequest, TResponse>( req: TRequest, res: TResponse, next: () => void, ) => { try { const contextId = ContextIdFactory.getByRequest(req); if (!req[REQUEST_CONTEXT_ID]) { Object.defineProperty(req, REQUEST_CONTEXT_ID, { value: contextId, enumerable: false, writable: false, configurable: false, }); this.container.registerRequestProvider( contextId.getParent ? contextId.payload : req, contextId, ); } const contextInstance = await this.injector.loadPerContext( instance, moduleRef, collection, contextId, ); const proxy = await this.createProxy<TRequest, TResponse>( contextInstance, contextId, ); return proxy(req, res, next); } catch (err) { let exceptionsHandler = this.exceptionFiltersCache.get(instance.use); if (!exceptionsHandler) { exceptionsHandler = this.routerExceptionFilter.create( instance, instance.use, undefined, ); this.exceptionFiltersCache.set(instance.use, exceptionsHandler); } const host = new ExecutionContextHost([req, res, next]); exceptionsHandler.next(err, host); } }, ); } private async createProxy<TRequest = unknown, TResponse = unknown>( instance: NestMiddleware, contextId = STATIC_CONTEXT, ): Promise<(req: TRequest, res: TResponse, next: () => void) => void> { const exceptionsHandler = this.routerExceptionFilter.create( instance, instance.use, undefined, contextId, ); const middleware = instance.use.bind(instance); return this.routerProxy.createProxy(middleware, exceptionsHandler); } private async registerHandler( applicationRef: HttpServer, { path, method, version }: RouteInfo, proxy: <TRequest, TResponse>( req: TRequest, res: TResponse, next: () => void, ) => void, ) { const prefix = this.config.getGlobalPrefix(); const excludedRoutes = this.config.getGlobalPrefixOptions().exclude; if ( (Array.isArray(excludedRoutes) && isRouteExcluded(excludedRoutes, path, method)) || ['*', '/*', '(.*)', '/(.*)'].includes(path) ) { path = addLeadingSlash(path); } else { const basePath = addLeadingSlash(prefix); if (basePath?.endsWith('/') && path?.startsWith('/')) { // strip slash when a wildcard is being used // and global prefix has been set path = path?.slice(1); } path = basePath + path; } const applicationVersioningConfig = this.config.getVersioning(); if (version && applicationVersioningConfig.type === VersioningType.URI) { const versionPrefix = this.routePathFactory.getVersionPrefix( applicationVersioningConfig, ); path = `/${versionPrefix}${version.toString()}${path}`; } const isMethodAll = isRequestMethodAll(method); const requestMethod = RequestMethod[method]; const router = await applicationRef.createMiddlewareFactory(method); router( path, isMethodAll ? proxy : <TRequest, TResponse>( req: TRequest, res: TResponse, next: () => void, ) => { if (applicationRef.getRequestMethod(req) === requestMethod) { return proxy(req, res, next); } return next(); }, ); } }
packages/core/middleware/middleware-module.ts
1
https://github.com/nestjs/nest/commit/20abe1df78159aa6d451898e8470285ed64eabe5
[ 0.9980736970901489, 0.06317466497421265, 0.00016502829384990036, 0.0009517539292573929, 0.22905808687210083 ]
{ "id": 2, "code_window": [ "import { MiddlewareBuilder } from './builder';\n", "import { MiddlewareContainer } from './container';\n", "import { MiddlewareResolver } from './resolver';\n", "import { RoutesMapper } from './routes-mapper';\n", "\n", "export class MiddlewareModule {\n", " private readonly routerProxy = new RouterProxy();\n", " private readonly exceptionFiltersCache = new WeakMap();\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [ "export class MiddlewareModule<\n", " TAppOptions extends NestApplicationContextOptions = NestApplicationContextOptions,\n", "> {\n" ], "file_path": "packages/core/middleware/middleware-module.ts", "type": "replace", "edit_start_line_idx": 36 }
export * from './kafka.context'; export * from './mqtt.context'; export * from './nats.context'; export * from './redis.context'; export * from './rmq.context'; export * from './tcp.context'; export * from './base-rpc.context';
packages/microservices/ctx-host/index.ts
0
https://github.com/nestjs/nest/commit/20abe1df78159aa6d451898e8470285ed64eabe5
[ 0.00017349350673612207, 0.00017349350673612207, 0.00017349350673612207, 0.00017349350673612207, 0 ]
{ "id": 2, "code_window": [ "import { MiddlewareBuilder } from './builder';\n", "import { MiddlewareContainer } from './container';\n", "import { MiddlewareResolver } from './resolver';\n", "import { RoutesMapper } from './routes-mapper';\n", "\n", "export class MiddlewareModule {\n", " private readonly routerProxy = new RouterProxy();\n", " private readonly exceptionFiltersCache = new WeakMap();\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [ "export class MiddlewareModule<\n", " TAppOptions extends NestApplicationContextOptions = NestApplicationContextOptions,\n", "> {\n" ], "file_path": "packages/core/middleware/middleware-module.ts", "type": "replace", "edit_start_line_idx": 36 }
import { ContextType } from '@nestjs/common/interfaces'; import { ExternalExceptionsHandler } from '../exceptions/external-exceptions-handler'; import { ExecutionContextHost } from '../helpers/execution-context-host'; export class ExternalErrorProxy { public createProxy<TContext extends string = ContextType>( targetCallback: (...args: any[]) => any, exceptionsHandler: ExternalExceptionsHandler, type?: TContext, ) { return async (...args: any[]) => { try { return await targetCallback(...args); } catch (e) { const host = new ExecutionContextHost(args); host.setType<TContext>(type); return exceptionsHandler.next(e, host); } }; } }
packages/core/helpers/external-proxy.ts
0
https://github.com/nestjs/nest/commit/20abe1df78159aa6d451898e8470285ed64eabe5
[ 0.00016705386224202812, 0.00016641854017507285, 0.00016526812396477908, 0.00016693363431841135, 8.149464747475577e-7 ]
{ "id": 2, "code_window": [ "import { MiddlewareBuilder } from './builder';\n", "import { MiddlewareContainer } from './container';\n", "import { MiddlewareResolver } from './resolver';\n", "import { RoutesMapper } from './routes-mapper';\n", "\n", "export class MiddlewareModule {\n", " private readonly routerProxy = new RouterProxy();\n", " private readonly exceptionFiltersCache = new WeakMap();\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep" ], "after_edit": [ "export class MiddlewareModule<\n", " TAppOptions extends NestApplicationContextOptions = NestApplicationContextOptions,\n", "> {\n" ], "file_path": "packages/core/middleware/middleware-module.ts", "type": "replace", "edit_start_line_idx": 36 }
import { GATEWAY_SERVER_METADATA } from '../constants'; /** * Attaches native Web Socket Server to a given property. */ export const WebSocketServer = (): PropertyDecorator => { return (target: object, propertyKey: string | symbol) => { Reflect.set(target, propertyKey, null); Reflect.defineMetadata(GATEWAY_SERVER_METADATA, true, target, propertyKey); }; };
packages/websockets/decorators/gateway-server.decorator.ts
0
https://github.com/nestjs/nest/commit/20abe1df78159aa6d451898e8470285ed64eabe5
[ 0.00017001661763060838, 0.0001685148454271257, 0.00016701308777555823, 0.0001685148454271257, 0.0000015017649275250733 ]
{ "id": 3, "code_window": [ " private readonly routerProxy = new RouterProxy();\n", " private readonly exceptionFiltersCache = new WeakMap();\n", "\n", " private injector: Injector;\n", " private routerExceptionFilter: RouterExceptionFilters;\n", " private routesMapper: RoutesMapper;\n" ], "labels": [ "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " private readonly logger = new Logger(MiddlewareModule.name);\n" ], "file_path": "packages/core/middleware/middleware-module.ts", "type": "add", "edit_start_line_idx": 39 }
import { HttpServer, VersioningType } from '@nestjs/common'; import { RequestMethod } from '@nestjs/common/enums/request-method.enum'; import { MiddlewareConfiguration, NestMiddleware, RouteInfo, } from '@nestjs/common/interfaces/middleware'; import { addLeadingSlash, isUndefined, } from '@nestjs/common/utils/shared.utils'; import { ApplicationConfig } from '../application-config'; import { InvalidMiddlewareException } from '../errors/exceptions/invalid-middleware.exception'; import { RuntimeException } from '../errors/exceptions/runtime.exception'; import { ContextIdFactory } from '../helpers/context-id-factory'; import { ExecutionContextHost } from '../helpers/execution-context-host'; import { STATIC_CONTEXT } from '../injector/constants'; import { NestContainer } from '../injector/container'; import { Injector } from '../injector/injector'; import { InstanceWrapper } from '../injector/instance-wrapper'; import { InstanceToken, Module } from '../injector/module'; import { GraphInspector } from '../inspector/graph-inspector'; import { Entrypoint, MiddlewareEntrypointMetadata, } from '../inspector/interfaces/entrypoint.interface'; import { REQUEST_CONTEXT_ID } from '../router/request/request-constants'; import { RoutePathFactory } from '../router/route-path-factory'; import { RouterExceptionFilters } from '../router/router-exception-filters'; import { RouterProxy } from '../router/router-proxy'; import { isRequestMethodAll, isRouteExcluded } from '../router/utils'; import { MiddlewareBuilder } from './builder'; import { MiddlewareContainer } from './container'; import { MiddlewareResolver } from './resolver'; import { RoutesMapper } from './routes-mapper'; export class MiddlewareModule { private readonly routerProxy = new RouterProxy(); private readonly exceptionFiltersCache = new WeakMap(); private injector: Injector; private routerExceptionFilter: RouterExceptionFilters; private routesMapper: RoutesMapper; private resolver: MiddlewareResolver; private config: ApplicationConfig; private container: NestContainer; private httpAdapter: HttpServer; private graphInspector: GraphInspector; constructor(private readonly routePathFactory: RoutePathFactory) {} public async register( middlewareContainer: MiddlewareContainer, container: NestContainer, config: ApplicationConfig, injector: Injector, httpAdapter: HttpServer, graphInspector: GraphInspector, ) { const appRef = container.getHttpAdapterRef(); this.routerExceptionFilter = new RouterExceptionFilters( container, config, appRef, ); this.routesMapper = new RoutesMapper(container); this.resolver = new MiddlewareResolver(middlewareContainer, injector); this.config = config; this.injector = injector; this.container = container; this.httpAdapter = httpAdapter; this.graphInspector = graphInspector; const modules = container.getModules(); await this.resolveMiddleware(middlewareContainer, modules); } public async resolveMiddleware( middlewareContainer: MiddlewareContainer, modules: Map<string, Module>, ) { const moduleEntries = [...modules.entries()]; const loadMiddlewareConfiguration = async ([moduleName, moduleRef]: [ string, Module, ]) => { await this.loadConfiguration(middlewareContainer, moduleRef, moduleName); await this.resolver.resolveInstances(moduleRef, moduleName); }; await Promise.all(moduleEntries.map(loadMiddlewareConfiguration)); } public async loadConfiguration( middlewareContainer: MiddlewareContainer, moduleRef: Module, moduleKey: string, ) { const { instance } = moduleRef; if (!instance.configure) { return; } const middlewareBuilder = new MiddlewareBuilder( this.routesMapper, this.httpAdapter, ); await instance.configure(middlewareBuilder); if (!(middlewareBuilder instanceof MiddlewareBuilder)) { return; } const config = middlewareBuilder.build(); middlewareContainer.insertConfig(config, moduleKey); } public async registerMiddleware( middlewareContainer: MiddlewareContainer, applicationRef: any, ) { const configs = middlewareContainer.getConfigurations(); const registerAllConfigs = async ( moduleKey: string, middlewareConfig: MiddlewareConfiguration[], ) => { for (const config of middlewareConfig) { await this.registerMiddlewareConfig( middlewareContainer, config, moduleKey, applicationRef, ); } }; const entriesSortedByDistance = [...configs.entries()].sort( ([moduleA], [moduleB]) => { return ( this.container.getModuleByKey(moduleA).distance - this.container.getModuleByKey(moduleB).distance ); }, ); for (const [moduleRef, moduleConfigurations] of entriesSortedByDistance) { await registerAllConfigs(moduleRef, [...moduleConfigurations]); } } public async registerMiddlewareConfig( middlewareContainer: MiddlewareContainer, config: MiddlewareConfiguration, moduleKey: string, applicationRef: any, ) { const { forRoutes } = config; for (const routeInfo of forRoutes) { await this.registerRouteMiddleware( middlewareContainer, routeInfo as RouteInfo, config, moduleKey, applicationRef, ); } } public async registerRouteMiddleware( middlewareContainer: MiddlewareContainer, routeInfo: RouteInfo, config: MiddlewareConfiguration, moduleKey: string, applicationRef: any, ) { const middlewareCollection = [].concat(config.middleware); const moduleRef = this.container.getModuleByKey(moduleKey); for (const metatype of middlewareCollection) { const collection = middlewareContainer.getMiddlewareCollection(moduleKey); const instanceWrapper = collection.get(metatype); if (isUndefined(instanceWrapper)) { throw new RuntimeException(); } if (instanceWrapper.isTransient) { return; } this.graphInspector.insertClassNode( moduleRef, instanceWrapper, 'middleware', ); const middlewareDefinition: Entrypoint<MiddlewareEntrypointMetadata> = { type: 'middleware', methodName: 'use', className: instanceWrapper.name, classNodeId: instanceWrapper.id, metadata: { key: routeInfo.path, path: routeInfo.path, requestMethod: (RequestMethod[routeInfo.method] as keyof typeof RequestMethod) ?? 'ALL', version: routeInfo.version, }, }; this.graphInspector.insertEntrypointDefinition( middlewareDefinition, instanceWrapper.id, ); await this.bindHandler( instanceWrapper, applicationRef, routeInfo, moduleRef, collection, ); } } private async bindHandler( wrapper: InstanceWrapper<NestMiddleware>, applicationRef: HttpServer, routeInfo: RouteInfo, moduleRef: Module, collection: Map<InstanceToken, InstanceWrapper>, ) { const { instance, metatype } = wrapper; if (isUndefined(instance?.use)) { throw new InvalidMiddlewareException(metatype.name); } const isStatic = wrapper.isDependencyTreeStatic(); if (isStatic) { const proxy = await this.createProxy(instance); return this.registerHandler(applicationRef, routeInfo, proxy); } await this.registerHandler( applicationRef, routeInfo, async <TRequest, TResponse>( req: TRequest, res: TResponse, next: () => void, ) => { try { const contextId = ContextIdFactory.getByRequest(req); if (!req[REQUEST_CONTEXT_ID]) { Object.defineProperty(req, REQUEST_CONTEXT_ID, { value: contextId, enumerable: false, writable: false, configurable: false, }); this.container.registerRequestProvider( contextId.getParent ? contextId.payload : req, contextId, ); } const contextInstance = await this.injector.loadPerContext( instance, moduleRef, collection, contextId, ); const proxy = await this.createProxy<TRequest, TResponse>( contextInstance, contextId, ); return proxy(req, res, next); } catch (err) { let exceptionsHandler = this.exceptionFiltersCache.get(instance.use); if (!exceptionsHandler) { exceptionsHandler = this.routerExceptionFilter.create( instance, instance.use, undefined, ); this.exceptionFiltersCache.set(instance.use, exceptionsHandler); } const host = new ExecutionContextHost([req, res, next]); exceptionsHandler.next(err, host); } }, ); } private async createProxy<TRequest = unknown, TResponse = unknown>( instance: NestMiddleware, contextId = STATIC_CONTEXT, ): Promise<(req: TRequest, res: TResponse, next: () => void) => void> { const exceptionsHandler = this.routerExceptionFilter.create( instance, instance.use, undefined, contextId, ); const middleware = instance.use.bind(instance); return this.routerProxy.createProxy(middleware, exceptionsHandler); } private async registerHandler( applicationRef: HttpServer, { path, method, version }: RouteInfo, proxy: <TRequest, TResponse>( req: TRequest, res: TResponse, next: () => void, ) => void, ) { const prefix = this.config.getGlobalPrefix(); const excludedRoutes = this.config.getGlobalPrefixOptions().exclude; if ( (Array.isArray(excludedRoutes) && isRouteExcluded(excludedRoutes, path, method)) || ['*', '/*', '(.*)', '/(.*)'].includes(path) ) { path = addLeadingSlash(path); } else { const basePath = addLeadingSlash(prefix); if (basePath?.endsWith('/') && path?.startsWith('/')) { // strip slash when a wildcard is being used // and global prefix has been set path = path?.slice(1); } path = basePath + path; } const applicationVersioningConfig = this.config.getVersioning(); if (version && applicationVersioningConfig.type === VersioningType.URI) { const versionPrefix = this.routePathFactory.getVersionPrefix( applicationVersioningConfig, ); path = `/${versionPrefix}${version.toString()}${path}`; } const isMethodAll = isRequestMethodAll(method); const requestMethod = RequestMethod[method]; const router = await applicationRef.createMiddlewareFactory(method); router( path, isMethodAll ? proxy : <TRequest, TResponse>( req: TRequest, res: TResponse, next: () => void, ) => { if (applicationRef.getRequestMethod(req) === requestMethod) { return proxy(req, res, next); } return next(); }, ); } }
packages/core/middleware/middleware-module.ts
1
https://github.com/nestjs/nest/commit/20abe1df78159aa6d451898e8470285ed64eabe5
[ 0.9987162351608276, 0.16576403379440308, 0.00016520243661943823, 0.0001710899523459375, 0.36846163868904114 ]
{ "id": 3, "code_window": [ " private readonly routerProxy = new RouterProxy();\n", " private readonly exceptionFiltersCache = new WeakMap();\n", "\n", " private injector: Injector;\n", " private routerExceptionFilter: RouterExceptionFilters;\n", " private routesMapper: RoutesMapper;\n" ], "labels": [ "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " private readonly logger = new Logger(MiddlewareModule.name);\n" ], "file_path": "packages/core/middleware/middleware-module.ts", "type": "add", "edit_start_line_idx": 39 }
export type Controller = object;
packages/common/interfaces/controllers/controller.interface.ts
0
https://github.com/nestjs/nest/commit/20abe1df78159aa6d451898e8470285ed64eabe5
[ 0.00016812450485303998, 0.00016812450485303998, 0.00016812450485303998, 0.00016812450485303998, 0 ]
{ "id": 3, "code_window": [ " private readonly routerProxy = new RouterProxy();\n", " private readonly exceptionFiltersCache = new WeakMap();\n", "\n", " private injector: Injector;\n", " private routerExceptionFilter: RouterExceptionFilters;\n", " private routesMapper: RoutesMapper;\n" ], "labels": [ "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " private readonly logger = new Logger(MiddlewareModule.name);\n" ], "file_path": "packages/core/middleware/middleware-module.ts", "type": "add", "edit_start_line_idx": 39 }
import { Module } from '@nestjs/common'; import { JwtModule } from '@nestjs/jwt'; import { PassportModule } from '@nestjs/passport'; import { UsersModule } from '../users/users.module'; import { AuthService } from './auth.service'; import { jwtConstants } from './constants'; import { JwtStrategy } from './strategies/jwt.strategy'; import { LocalStrategy } from './strategies/local.strategy'; @Module({ imports: [ UsersModule, PassportModule, JwtModule.register({ secret: jwtConstants.secret, signOptions: { expiresIn: '60s' }, }), ], providers: [AuthService, LocalStrategy, JwtStrategy], exports: [AuthService], }) export class AuthModule {}
sample/19-auth-jwt/src/auth/auth.module.ts
0
https://github.com/nestjs/nest/commit/20abe1df78159aa6d451898e8470285ed64eabe5
[ 0.00017658477008808404, 0.00017522623238619417, 0.00017310552357230335, 0.00017598838894627988, 0.000001519200850452762 ]
{ "id": 3, "code_window": [ " private readonly routerProxy = new RouterProxy();\n", " private readonly exceptionFiltersCache = new WeakMap();\n", "\n", " private injector: Injector;\n", " private routerExceptionFilter: RouterExceptionFilters;\n", " private routesMapper: RoutesMapper;\n" ], "labels": [ "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " private readonly logger = new Logger(MiddlewareModule.name);\n" ], "file_path": "packages/core/middleware/middleware-module.ts", "type": "add", "edit_start_line_idx": 39 }
{ "compilerOptions": { "deleteOutDir": true } }
sample/08-webpack/nest-cli.json
0
https://github.com/nestjs/nest/commit/20abe1df78159aa6d451898e8470285ed64eabe5
[ 0.00017869521980173886, 0.00017869521980173886, 0.00017869521980173886, 0.00017869521980173886, 0 ]
{ "id": 4, "code_window": [ " private resolver: MiddlewareResolver;\n", " private config: ApplicationConfig;\n", " private container: NestContainer;\n", " private httpAdapter: HttpServer;\n", " private graphInspector: GraphInspector;\n", "\n", " constructor(private readonly routePathFactory: RoutePathFactory) {}\n", "\n", " public async register(\n", " middlewareContainer: MiddlewareContainer,\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " private appOptions: TAppOptions;\n" ], "file_path": "packages/core/middleware/middleware-module.ts", "type": "add", "edit_start_line_idx": 48 }
import { HttpServer, VersioningType } from '@nestjs/common'; import { RequestMethod } from '@nestjs/common/enums/request-method.enum'; import { MiddlewareConfiguration, NestMiddleware, RouteInfo, } from '@nestjs/common/interfaces/middleware'; import { addLeadingSlash, isUndefined, } from '@nestjs/common/utils/shared.utils'; import { ApplicationConfig } from '../application-config'; import { InvalidMiddlewareException } from '../errors/exceptions/invalid-middleware.exception'; import { RuntimeException } from '../errors/exceptions/runtime.exception'; import { ContextIdFactory } from '../helpers/context-id-factory'; import { ExecutionContextHost } from '../helpers/execution-context-host'; import { STATIC_CONTEXT } from '../injector/constants'; import { NestContainer } from '../injector/container'; import { Injector } from '../injector/injector'; import { InstanceWrapper } from '../injector/instance-wrapper'; import { InstanceToken, Module } from '../injector/module'; import { GraphInspector } from '../inspector/graph-inspector'; import { Entrypoint, MiddlewareEntrypointMetadata, } from '../inspector/interfaces/entrypoint.interface'; import { REQUEST_CONTEXT_ID } from '../router/request/request-constants'; import { RoutePathFactory } from '../router/route-path-factory'; import { RouterExceptionFilters } from '../router/router-exception-filters'; import { RouterProxy } from '../router/router-proxy'; import { isRequestMethodAll, isRouteExcluded } from '../router/utils'; import { MiddlewareBuilder } from './builder'; import { MiddlewareContainer } from './container'; import { MiddlewareResolver } from './resolver'; import { RoutesMapper } from './routes-mapper'; export class MiddlewareModule { private readonly routerProxy = new RouterProxy(); private readonly exceptionFiltersCache = new WeakMap(); private injector: Injector; private routerExceptionFilter: RouterExceptionFilters; private routesMapper: RoutesMapper; private resolver: MiddlewareResolver; private config: ApplicationConfig; private container: NestContainer; private httpAdapter: HttpServer; private graphInspector: GraphInspector; constructor(private readonly routePathFactory: RoutePathFactory) {} public async register( middlewareContainer: MiddlewareContainer, container: NestContainer, config: ApplicationConfig, injector: Injector, httpAdapter: HttpServer, graphInspector: GraphInspector, ) { const appRef = container.getHttpAdapterRef(); this.routerExceptionFilter = new RouterExceptionFilters( container, config, appRef, ); this.routesMapper = new RoutesMapper(container); this.resolver = new MiddlewareResolver(middlewareContainer, injector); this.config = config; this.injector = injector; this.container = container; this.httpAdapter = httpAdapter; this.graphInspector = graphInspector; const modules = container.getModules(); await this.resolveMiddleware(middlewareContainer, modules); } public async resolveMiddleware( middlewareContainer: MiddlewareContainer, modules: Map<string, Module>, ) { const moduleEntries = [...modules.entries()]; const loadMiddlewareConfiguration = async ([moduleName, moduleRef]: [ string, Module, ]) => { await this.loadConfiguration(middlewareContainer, moduleRef, moduleName); await this.resolver.resolveInstances(moduleRef, moduleName); }; await Promise.all(moduleEntries.map(loadMiddlewareConfiguration)); } public async loadConfiguration( middlewareContainer: MiddlewareContainer, moduleRef: Module, moduleKey: string, ) { const { instance } = moduleRef; if (!instance.configure) { return; } const middlewareBuilder = new MiddlewareBuilder( this.routesMapper, this.httpAdapter, ); await instance.configure(middlewareBuilder); if (!(middlewareBuilder instanceof MiddlewareBuilder)) { return; } const config = middlewareBuilder.build(); middlewareContainer.insertConfig(config, moduleKey); } public async registerMiddleware( middlewareContainer: MiddlewareContainer, applicationRef: any, ) { const configs = middlewareContainer.getConfigurations(); const registerAllConfigs = async ( moduleKey: string, middlewareConfig: MiddlewareConfiguration[], ) => { for (const config of middlewareConfig) { await this.registerMiddlewareConfig( middlewareContainer, config, moduleKey, applicationRef, ); } }; const entriesSortedByDistance = [...configs.entries()].sort( ([moduleA], [moduleB]) => { return ( this.container.getModuleByKey(moduleA).distance - this.container.getModuleByKey(moduleB).distance ); }, ); for (const [moduleRef, moduleConfigurations] of entriesSortedByDistance) { await registerAllConfigs(moduleRef, [...moduleConfigurations]); } } public async registerMiddlewareConfig( middlewareContainer: MiddlewareContainer, config: MiddlewareConfiguration, moduleKey: string, applicationRef: any, ) { const { forRoutes } = config; for (const routeInfo of forRoutes) { await this.registerRouteMiddleware( middlewareContainer, routeInfo as RouteInfo, config, moduleKey, applicationRef, ); } } public async registerRouteMiddleware( middlewareContainer: MiddlewareContainer, routeInfo: RouteInfo, config: MiddlewareConfiguration, moduleKey: string, applicationRef: any, ) { const middlewareCollection = [].concat(config.middleware); const moduleRef = this.container.getModuleByKey(moduleKey); for (const metatype of middlewareCollection) { const collection = middlewareContainer.getMiddlewareCollection(moduleKey); const instanceWrapper = collection.get(metatype); if (isUndefined(instanceWrapper)) { throw new RuntimeException(); } if (instanceWrapper.isTransient) { return; } this.graphInspector.insertClassNode( moduleRef, instanceWrapper, 'middleware', ); const middlewareDefinition: Entrypoint<MiddlewareEntrypointMetadata> = { type: 'middleware', methodName: 'use', className: instanceWrapper.name, classNodeId: instanceWrapper.id, metadata: { key: routeInfo.path, path: routeInfo.path, requestMethod: (RequestMethod[routeInfo.method] as keyof typeof RequestMethod) ?? 'ALL', version: routeInfo.version, }, }; this.graphInspector.insertEntrypointDefinition( middlewareDefinition, instanceWrapper.id, ); await this.bindHandler( instanceWrapper, applicationRef, routeInfo, moduleRef, collection, ); } } private async bindHandler( wrapper: InstanceWrapper<NestMiddleware>, applicationRef: HttpServer, routeInfo: RouteInfo, moduleRef: Module, collection: Map<InstanceToken, InstanceWrapper>, ) { const { instance, metatype } = wrapper; if (isUndefined(instance?.use)) { throw new InvalidMiddlewareException(metatype.name); } const isStatic = wrapper.isDependencyTreeStatic(); if (isStatic) { const proxy = await this.createProxy(instance); return this.registerHandler(applicationRef, routeInfo, proxy); } await this.registerHandler( applicationRef, routeInfo, async <TRequest, TResponse>( req: TRequest, res: TResponse, next: () => void, ) => { try { const contextId = ContextIdFactory.getByRequest(req); if (!req[REQUEST_CONTEXT_ID]) { Object.defineProperty(req, REQUEST_CONTEXT_ID, { value: contextId, enumerable: false, writable: false, configurable: false, }); this.container.registerRequestProvider( contextId.getParent ? contextId.payload : req, contextId, ); } const contextInstance = await this.injector.loadPerContext( instance, moduleRef, collection, contextId, ); const proxy = await this.createProxy<TRequest, TResponse>( contextInstance, contextId, ); return proxy(req, res, next); } catch (err) { let exceptionsHandler = this.exceptionFiltersCache.get(instance.use); if (!exceptionsHandler) { exceptionsHandler = this.routerExceptionFilter.create( instance, instance.use, undefined, ); this.exceptionFiltersCache.set(instance.use, exceptionsHandler); } const host = new ExecutionContextHost([req, res, next]); exceptionsHandler.next(err, host); } }, ); } private async createProxy<TRequest = unknown, TResponse = unknown>( instance: NestMiddleware, contextId = STATIC_CONTEXT, ): Promise<(req: TRequest, res: TResponse, next: () => void) => void> { const exceptionsHandler = this.routerExceptionFilter.create( instance, instance.use, undefined, contextId, ); const middleware = instance.use.bind(instance); return this.routerProxy.createProxy(middleware, exceptionsHandler); } private async registerHandler( applicationRef: HttpServer, { path, method, version }: RouteInfo, proxy: <TRequest, TResponse>( req: TRequest, res: TResponse, next: () => void, ) => void, ) { const prefix = this.config.getGlobalPrefix(); const excludedRoutes = this.config.getGlobalPrefixOptions().exclude; if ( (Array.isArray(excludedRoutes) && isRouteExcluded(excludedRoutes, path, method)) || ['*', '/*', '(.*)', '/(.*)'].includes(path) ) { path = addLeadingSlash(path); } else { const basePath = addLeadingSlash(prefix); if (basePath?.endsWith('/') && path?.startsWith('/')) { // strip slash when a wildcard is being used // and global prefix has been set path = path?.slice(1); } path = basePath + path; } const applicationVersioningConfig = this.config.getVersioning(); if (version && applicationVersioningConfig.type === VersioningType.URI) { const versionPrefix = this.routePathFactory.getVersionPrefix( applicationVersioningConfig, ); path = `/${versionPrefix}${version.toString()}${path}`; } const isMethodAll = isRequestMethodAll(method); const requestMethod = RequestMethod[method]; const router = await applicationRef.createMiddlewareFactory(method); router( path, isMethodAll ? proxy : <TRequest, TResponse>( req: TRequest, res: TResponse, next: () => void, ) => { if (applicationRef.getRequestMethod(req) === requestMethod) { return proxy(req, res, next); } return next(); }, ); } }
packages/core/middleware/middleware-module.ts
1
https://github.com/nestjs/nest/commit/20abe1df78159aa6d451898e8470285ed64eabe5
[ 0.9989299178123474, 0.1453273892402649, 0.00016601677634753287, 0.0013270839117467403, 0.3268902003765106 ]
{ "id": 4, "code_window": [ " private resolver: MiddlewareResolver;\n", " private config: ApplicationConfig;\n", " private container: NestContainer;\n", " private httpAdapter: HttpServer;\n", " private graphInspector: GraphInspector;\n", "\n", " constructor(private readonly routePathFactory: RoutePathFactory) {}\n", "\n", " public async register(\n", " middlewareContainer: MiddlewareContainer,\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " private appOptions: TAppOptions;\n" ], "file_path": "packages/core/middleware/middleware-module.ts", "type": "add", "edit_start_line_idx": 48 }
import { INestApplication, Scope } from '@nestjs/common'; import { Test } from '@nestjs/testing'; import { expect } from 'chai'; import * as request from 'supertest'; import { HelloController } from '../src/circular-transient/hello.controller'; import { HelloModule } from '../src/circular-transient/hello.module'; import { HelloService } from '../src/circular-transient/hello.service'; import { UsersService } from '../src/circular-transient/users/users.service'; class Meta { static COUNTER = 0; constructor(private readonly helloService: HelloService) { Meta.COUNTER++; } } describe('Circular transient scope', () => { let server; let app: INestApplication; before(async () => { const module = await Test.createTestingModule({ imports: [ HelloModule.forRoot({ provide: 'META', useClass: Meta, scope: Scope.TRANSIENT, }), ], }).compile(); app = module.createNestApplication(); server = app.getHttpServer(); await app.init(); }); describe('when one service is request scoped', () => { before(async () => { const performHttpCall = end => request(server) .get('/hello') .end((err, res) => { if (err) return end(err); end(); }); await new Promise(resolve => performHttpCall(resolve)); await new Promise(resolve => performHttpCall(resolve)); await new Promise(resolve => performHttpCall(resolve)); }); it(`should create controller for each request`, async () => { expect(HelloController.COUNTER).to.be.eql(3); }); it(`should create service for each request`, async () => { expect(UsersService.COUNTER).to.be.eql(3); }); it(`should create service for each request`, async () => { expect(HelloService.COUNTER).to.be.eql(3); }); it(`should create provider for each inquirer`, async () => { expect(Meta.COUNTER).to.be.eql(7); }); }); after(async () => { await app.close(); }); });
integration/scopes/e2e/circular-transient-scope.spec.ts
0
https://github.com/nestjs/nest/commit/20abe1df78159aa6d451898e8470285ed64eabe5
[ 0.0008811135776340961, 0.000272334465989843, 0.00017003655375447124, 0.00017512902559246868, 0.0002315093734068796 ]
{ "id": 4, "code_window": [ " private resolver: MiddlewareResolver;\n", " private config: ApplicationConfig;\n", " private container: NestContainer;\n", " private httpAdapter: HttpServer;\n", " private graphInspector: GraphInspector;\n", "\n", " constructor(private readonly routePathFactory: RoutePathFactory) {}\n", "\n", " public async register(\n", " middlewareContainer: MiddlewareContainer,\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " private appOptions: TAppOptions;\n" ], "file_path": "packages/core/middleware/middleware-module.ts", "type": "add", "edit_start_line_idx": 48 }
import { ArgsType, Field, Int } from '@nestjs/graphql'; import { Max, Min } from 'class-validator'; @ArgsType() export class RecipesArgs { @Field(type => Int) @Min(0) skip = 0; @Field(type => Int) @Min(1) @Max(50) take = 25; }
sample/33-graphql-mercurius/src/recipes/dto/recipes.args.ts
0
https://github.com/nestjs/nest/commit/20abe1df78159aa6d451898e8470285ed64eabe5
[ 0.00017576385289430618, 0.00017446398851461709, 0.00017316410958301276, 0.00017446398851461709, 0.0000012998716556467116 ]
{ "id": 4, "code_window": [ " private resolver: MiddlewareResolver;\n", " private config: ApplicationConfig;\n", " private container: NestContainer;\n", " private httpAdapter: HttpServer;\n", " private graphInspector: GraphInspector;\n", "\n", " constructor(private readonly routePathFactory: RoutePathFactory) {}\n", "\n", " public async register(\n", " middlewareContainer: MiddlewareContainer,\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " private appOptions: TAppOptions;\n" ], "file_path": "packages/core/middleware/middleware-module.ts", "type": "add", "edit_start_line_idx": 48 }
import { CanActivate, ExecutionContext, Inject, Injectable, Scope, } from '@nestjs/common'; import { Observable } from 'rxjs'; @Injectable({ scope: Scope.REQUEST }) export class Guard implements CanActivate { static COUNTER = 0; static REQUEST_SCOPED_DATA = []; constructor(@Inject('REQUEST_ID') private readonly requestId: number) { Guard.COUNTER++; } canActivate( context: ExecutionContext, ): boolean | Promise<boolean> | Observable<boolean> { Guard.REQUEST_SCOPED_DATA.push(this.requestId); return true; } }
integration/scopes/src/msvc/guards/request-scoped.guard.ts
0
https://github.com/nestjs/nest/commit/20abe1df78159aa6d451898e8470285ed64eabe5
[ 0.00033351301681250334, 0.0002270670811412856, 0.00017370488785672933, 0.00017398336785845459, 0.00007526871922891587 ]
{ "id": 5, "code_window": [ " config: ApplicationConfig,\n", " injector: Injector,\n", " httpAdapter: HttpServer,\n", " graphInspector: GraphInspector,\n", " ) {\n" ], "labels": [ "keep", "keep", "keep", "add", "keep" ], "after_edit": [ " options: TAppOptions,\n" ], "file_path": "packages/core/middleware/middleware-module.ts", "type": "add", "edit_start_line_idx": 58 }
import { HttpServer, VersioningType } from '@nestjs/common'; import { RequestMethod } from '@nestjs/common/enums/request-method.enum'; import { MiddlewareConfiguration, NestMiddleware, RouteInfo, } from '@nestjs/common/interfaces/middleware'; import { addLeadingSlash, isUndefined, } from '@nestjs/common/utils/shared.utils'; import { ApplicationConfig } from '../application-config'; import { InvalidMiddlewareException } from '../errors/exceptions/invalid-middleware.exception'; import { RuntimeException } from '../errors/exceptions/runtime.exception'; import { ContextIdFactory } from '../helpers/context-id-factory'; import { ExecutionContextHost } from '../helpers/execution-context-host'; import { STATIC_CONTEXT } from '../injector/constants'; import { NestContainer } from '../injector/container'; import { Injector } from '../injector/injector'; import { InstanceWrapper } from '../injector/instance-wrapper'; import { InstanceToken, Module } from '../injector/module'; import { GraphInspector } from '../inspector/graph-inspector'; import { Entrypoint, MiddlewareEntrypointMetadata, } from '../inspector/interfaces/entrypoint.interface'; import { REQUEST_CONTEXT_ID } from '../router/request/request-constants'; import { RoutePathFactory } from '../router/route-path-factory'; import { RouterExceptionFilters } from '../router/router-exception-filters'; import { RouterProxy } from '../router/router-proxy'; import { isRequestMethodAll, isRouteExcluded } from '../router/utils'; import { MiddlewareBuilder } from './builder'; import { MiddlewareContainer } from './container'; import { MiddlewareResolver } from './resolver'; import { RoutesMapper } from './routes-mapper'; export class MiddlewareModule { private readonly routerProxy = new RouterProxy(); private readonly exceptionFiltersCache = new WeakMap(); private injector: Injector; private routerExceptionFilter: RouterExceptionFilters; private routesMapper: RoutesMapper; private resolver: MiddlewareResolver; private config: ApplicationConfig; private container: NestContainer; private httpAdapter: HttpServer; private graphInspector: GraphInspector; constructor(private readonly routePathFactory: RoutePathFactory) {} public async register( middlewareContainer: MiddlewareContainer, container: NestContainer, config: ApplicationConfig, injector: Injector, httpAdapter: HttpServer, graphInspector: GraphInspector, ) { const appRef = container.getHttpAdapterRef(); this.routerExceptionFilter = new RouterExceptionFilters( container, config, appRef, ); this.routesMapper = new RoutesMapper(container); this.resolver = new MiddlewareResolver(middlewareContainer, injector); this.config = config; this.injector = injector; this.container = container; this.httpAdapter = httpAdapter; this.graphInspector = graphInspector; const modules = container.getModules(); await this.resolveMiddleware(middlewareContainer, modules); } public async resolveMiddleware( middlewareContainer: MiddlewareContainer, modules: Map<string, Module>, ) { const moduleEntries = [...modules.entries()]; const loadMiddlewareConfiguration = async ([moduleName, moduleRef]: [ string, Module, ]) => { await this.loadConfiguration(middlewareContainer, moduleRef, moduleName); await this.resolver.resolveInstances(moduleRef, moduleName); }; await Promise.all(moduleEntries.map(loadMiddlewareConfiguration)); } public async loadConfiguration( middlewareContainer: MiddlewareContainer, moduleRef: Module, moduleKey: string, ) { const { instance } = moduleRef; if (!instance.configure) { return; } const middlewareBuilder = new MiddlewareBuilder( this.routesMapper, this.httpAdapter, ); await instance.configure(middlewareBuilder); if (!(middlewareBuilder instanceof MiddlewareBuilder)) { return; } const config = middlewareBuilder.build(); middlewareContainer.insertConfig(config, moduleKey); } public async registerMiddleware( middlewareContainer: MiddlewareContainer, applicationRef: any, ) { const configs = middlewareContainer.getConfigurations(); const registerAllConfigs = async ( moduleKey: string, middlewareConfig: MiddlewareConfiguration[], ) => { for (const config of middlewareConfig) { await this.registerMiddlewareConfig( middlewareContainer, config, moduleKey, applicationRef, ); } }; const entriesSortedByDistance = [...configs.entries()].sort( ([moduleA], [moduleB]) => { return ( this.container.getModuleByKey(moduleA).distance - this.container.getModuleByKey(moduleB).distance ); }, ); for (const [moduleRef, moduleConfigurations] of entriesSortedByDistance) { await registerAllConfigs(moduleRef, [...moduleConfigurations]); } } public async registerMiddlewareConfig( middlewareContainer: MiddlewareContainer, config: MiddlewareConfiguration, moduleKey: string, applicationRef: any, ) { const { forRoutes } = config; for (const routeInfo of forRoutes) { await this.registerRouteMiddleware( middlewareContainer, routeInfo as RouteInfo, config, moduleKey, applicationRef, ); } } public async registerRouteMiddleware( middlewareContainer: MiddlewareContainer, routeInfo: RouteInfo, config: MiddlewareConfiguration, moduleKey: string, applicationRef: any, ) { const middlewareCollection = [].concat(config.middleware); const moduleRef = this.container.getModuleByKey(moduleKey); for (const metatype of middlewareCollection) { const collection = middlewareContainer.getMiddlewareCollection(moduleKey); const instanceWrapper = collection.get(metatype); if (isUndefined(instanceWrapper)) { throw new RuntimeException(); } if (instanceWrapper.isTransient) { return; } this.graphInspector.insertClassNode( moduleRef, instanceWrapper, 'middleware', ); const middlewareDefinition: Entrypoint<MiddlewareEntrypointMetadata> = { type: 'middleware', methodName: 'use', className: instanceWrapper.name, classNodeId: instanceWrapper.id, metadata: { key: routeInfo.path, path: routeInfo.path, requestMethod: (RequestMethod[routeInfo.method] as keyof typeof RequestMethod) ?? 'ALL', version: routeInfo.version, }, }; this.graphInspector.insertEntrypointDefinition( middlewareDefinition, instanceWrapper.id, ); await this.bindHandler( instanceWrapper, applicationRef, routeInfo, moduleRef, collection, ); } } private async bindHandler( wrapper: InstanceWrapper<NestMiddleware>, applicationRef: HttpServer, routeInfo: RouteInfo, moduleRef: Module, collection: Map<InstanceToken, InstanceWrapper>, ) { const { instance, metatype } = wrapper; if (isUndefined(instance?.use)) { throw new InvalidMiddlewareException(metatype.name); } const isStatic = wrapper.isDependencyTreeStatic(); if (isStatic) { const proxy = await this.createProxy(instance); return this.registerHandler(applicationRef, routeInfo, proxy); } await this.registerHandler( applicationRef, routeInfo, async <TRequest, TResponse>( req: TRequest, res: TResponse, next: () => void, ) => { try { const contextId = ContextIdFactory.getByRequest(req); if (!req[REQUEST_CONTEXT_ID]) { Object.defineProperty(req, REQUEST_CONTEXT_ID, { value: contextId, enumerable: false, writable: false, configurable: false, }); this.container.registerRequestProvider( contextId.getParent ? contextId.payload : req, contextId, ); } const contextInstance = await this.injector.loadPerContext( instance, moduleRef, collection, contextId, ); const proxy = await this.createProxy<TRequest, TResponse>( contextInstance, contextId, ); return proxy(req, res, next); } catch (err) { let exceptionsHandler = this.exceptionFiltersCache.get(instance.use); if (!exceptionsHandler) { exceptionsHandler = this.routerExceptionFilter.create( instance, instance.use, undefined, ); this.exceptionFiltersCache.set(instance.use, exceptionsHandler); } const host = new ExecutionContextHost([req, res, next]); exceptionsHandler.next(err, host); } }, ); } private async createProxy<TRequest = unknown, TResponse = unknown>( instance: NestMiddleware, contextId = STATIC_CONTEXT, ): Promise<(req: TRequest, res: TResponse, next: () => void) => void> { const exceptionsHandler = this.routerExceptionFilter.create( instance, instance.use, undefined, contextId, ); const middleware = instance.use.bind(instance); return this.routerProxy.createProxy(middleware, exceptionsHandler); } private async registerHandler( applicationRef: HttpServer, { path, method, version }: RouteInfo, proxy: <TRequest, TResponse>( req: TRequest, res: TResponse, next: () => void, ) => void, ) { const prefix = this.config.getGlobalPrefix(); const excludedRoutes = this.config.getGlobalPrefixOptions().exclude; if ( (Array.isArray(excludedRoutes) && isRouteExcluded(excludedRoutes, path, method)) || ['*', '/*', '(.*)', '/(.*)'].includes(path) ) { path = addLeadingSlash(path); } else { const basePath = addLeadingSlash(prefix); if (basePath?.endsWith('/') && path?.startsWith('/')) { // strip slash when a wildcard is being used // and global prefix has been set path = path?.slice(1); } path = basePath + path; } const applicationVersioningConfig = this.config.getVersioning(); if (version && applicationVersioningConfig.type === VersioningType.URI) { const versionPrefix = this.routePathFactory.getVersionPrefix( applicationVersioningConfig, ); path = `/${versionPrefix}${version.toString()}${path}`; } const isMethodAll = isRequestMethodAll(method); const requestMethod = RequestMethod[method]; const router = await applicationRef.createMiddlewareFactory(method); router( path, isMethodAll ? proxy : <TRequest, TResponse>( req: TRequest, res: TResponse, next: () => void, ) => { if (applicationRef.getRequestMethod(req) === requestMethod) { return proxy(req, res, next); } return next(); }, ); } }
packages/core/middleware/middleware-module.ts
1
https://github.com/nestjs/nest/commit/20abe1df78159aa6d451898e8470285ed64eabe5
[ 0.04699078947305679, 0.003666456788778305, 0.00016599035006947815, 0.00020125729497522116, 0.010062829591333866 ]
{ "id": 5, "code_window": [ " config: ApplicationConfig,\n", " injector: Injector,\n", " httpAdapter: HttpServer,\n", " graphInspector: GraphInspector,\n", " ) {\n" ], "labels": [ "keep", "keep", "keep", "add", "keep" ], "after_edit": [ " options: TAppOptions,\n" ], "file_path": "packages/core/middleware/middleware-module.ts", "type": "add", "edit_start_line_idx": 58 }
import { Test, TestingModule } from '@nestjs/testing'; import { UsersService } from './users.service'; describe('UsersService', () => { let service: UsersService; beforeEach(async () => { const module: TestingModule = await Test.createTestingModule({ providers: [UsersService], }).compile(); service = module.get<UsersService>(UsersService); }); it('should be defined', () => { expect(service).toBeDefined(); }); it('should fetch a user by its id', () => { const user = service.findById(1); expect(user.id).toEqual(1); }); });
sample/31-graphql-federation-code-first/users-application/src/users/users.service.spec.ts
0
https://github.com/nestjs/nest/commit/20abe1df78159aa6d451898e8470285ed64eabe5
[ 0.0001731112861307338, 0.0001727938069961965, 0.00017218792345374823, 0.00017308224050793797, 4.2859528548433445e-7 ]
{ "id": 5, "code_window": [ " config: ApplicationConfig,\n", " injector: Injector,\n", " httpAdapter: HttpServer,\n", " graphInspector: GraphInspector,\n", " ) {\n" ], "labels": [ "keep", "keep", "keep", "add", "keep" ], "after_edit": [ " options: TAppOptions,\n" ], "file_path": "packages/core/middleware/middleware-module.ts", "type": "add", "edit_start_line_idx": 58 }
# Config file for mosquitto # # See mosquitto.conf(5) for more information. # # Default values are shown, uncomment to change. # # Use the # character to indicate a comment, but only if it is the # very first character on the line. # ================================================================= # General configuration # ================================================================= # Use per listener security settings. # # It is recommended this option be set before any other options. # # If this option is set to true, then all authentication and access control # options are controlled on a per listener basis. The following options are # affected: # # acl_file # allow_anonymous # allow_zero_length_clientid # auto_id_prefix # password_file # plugin # plugin_opt_* # psk_file # # Note that if set to true, then a durable client (i.e. with clean session set # to false) that has disconnected will use the ACL settings defined for the # listener that it was most recently connected to. # # The default behaviour is for this to be set to false, which maintains the # setting behaviour from previous versions of mosquitto. #per_listener_settings false # This option controls whether a client is allowed to connect with a zero # length client id or not. This option only affects clients using MQTT v3.1.1 # and later. If set to false, clients connecting with a zero length client id # are disconnected. If set to true, clients will be allocated a client id by # the broker. This means it is only useful for clients with clean session set # to true. #allow_zero_length_clientid true # If allow_zero_length_clientid is true, this option allows you to set a prefix # to automatically generated client ids to aid visibility in logs. # Defaults to 'auto-' #auto_id_prefix auto- # This option affects the scenario when a client subscribes to a topic that has # retained messages. It is possible that the client that published the retained # message to the topic had access at the time they published, but that access # has been subsequently removed. If check_retain_source is set to true, the # default, the source of a retained message will be checked for access rights # before it is republished. When set to false, no check will be made and the # retained message will always be published. This affects all listeners. #check_retain_source true # QoS 1 and 2 messages will be allowed inflight per client until this limit # is exceeded. Defaults to 0. (No maximum) # See also max_inflight_messages #max_inflight_bytes 0 # The maximum number of QoS 1 and 2 messages currently inflight per # client. # This includes messages that are partway through handshakes and # those that are being retried. Defaults to 20. Set to 0 for no # maximum. Setting to 1 will guarantee in-order delivery of QoS 1 # and 2 messages. #max_inflight_messages 20 # For MQTT v5 clients, it is possible to have the server send a "server # keepalive" value that will override the keepalive value set by the client. # This is intended to be used as a mechanism to say that the server will # disconnect the client earlier than it anticipated, and that the client should # use the new keepalive value. The max_keepalive option allows you to specify # that clients may only connect with keepalive less than or equal to this # value, otherwise they will be sent a server keepalive telling them to use # max_keepalive. This only applies to MQTT v5 clients. The default, and maximum # value allowable, is 65535. # # Set to 0 to allow clients to set keepalive = 0, which means no keepalive # checks are made and the client will never be disconnected by the broker if no # messages are received. You should be very sure this is the behaviour that you # want. # # For MQTT v3.1.1 and v3.1 clients, there is no mechanism to tell the client # what keepalive value they should use. If an MQTT v3.1.1 or v3.1 client # specifies a keepalive time greater than max_keepalive they will be sent a # CONNACK message with the "identifier rejected" reason code, and disconnected. # #max_keepalive 65535 # For MQTT v5 clients, it is possible to have the server send a "maximum packet # size" value that will instruct the client it will not accept MQTT packets # with size greater than max_packet_size bytes. This applies to the full MQTT # packet, not just the payload. Setting this option to a positive value will # set the maximum packet size to that number of bytes. If a client sends a # packet which is larger than this value, it will be disconnected. This applies # to all clients regardless of the protocol version they are using, but v3.1.1 # and earlier clients will of course not have received the maximum packet size # information. Defaults to no limit. Setting below 20 bytes is forbidden # because it is likely to interfere with ordinary client operation, even with # very small payloads. #max_packet_size 0 # QoS 1 and 2 messages above those currently in-flight will be queued per # client until this limit is exceeded. Defaults to 0. (No maximum) # See also max_queued_messages. # If both max_queued_messages and max_queued_bytes are specified, packets will # be queued until the first limit is reached. #max_queued_bytes 0 # Set the maximum QoS supported. Clients publishing at a QoS higher than # specified here will be disconnected. #max_qos 2 # The maximum number of QoS 1 and 2 messages to hold in a queue per client # above those that are currently in-flight. Defaults to 1000. Set # to 0 for no maximum (not recommended). # See also queue_qos0_messages. # See also max_queued_bytes. #max_queued_messages 1000 # # This option sets the maximum number of heap memory bytes that the broker will # allocate, and hence sets a hard limit on memory use by the broker. Memory # requests that exceed this value will be denied. The effect will vary # depending on what has been denied. If an incoming message is being processed, # then the message will be dropped and the publishing client will be # disconnected. If an outgoing message is being sent, then the individual # message will be dropped and the receiving client will be disconnected. # Defaults to no limit. #memory_limit 0 # This option sets the maximum publish payload size that the broker will allow. # Received messages that exceed this size will not be accepted by the broker. # The default value is 0, which means that all valid MQTT messages are # accepted. MQTT imposes a maximum payload size of 268435455 bytes. #message_size_limit 0 # This option allows persistent clients (those with clean session set to false) # to be removed if they do not reconnect within a certain time frame. # # This is a non-standard option in MQTT V3.1 but allowed in MQTT v3.1.1. # # Badly designed clients may set clean session to false whilst using a randomly # generated client id. This leads to persistent clients that will never # reconnect. This option allows these clients to be removed. # # The expiration period should be an integer followed by one of h d w m y for # hour, day, week, month and year respectively. For example # # persistent_client_expiration 2m # persistent_client_expiration 14d # persistent_client_expiration 1y # # The default if not set is to never expire persistent clients. #persistent_client_expiration # Write process id to a file. Default is a blank string which means # a pid file shouldn't be written. # This should be set to /var/run/mosquitto/mosquitto.pid if mosquitto is # being run automatically on boot with an init script and # start-stop-daemon or similar. #pid_file # Set to true to queue messages with QoS 0 when a persistent client is # disconnected. These messages are included in the limit imposed by # max_queued_messages and max_queued_bytes # Defaults to false. # This is a non-standard option for the MQTT v3.1 spec but is allowed in # v3.1.1. #queue_qos0_messages false # Set to false to disable retained message support. If a client publishes a # message with the retain bit set, it will be disconnected if this is set to # false. #retain_available true # Disable Nagle's algorithm on client sockets. This has the effect of reducing # latency of individual messages at the potential cost of increasing the number # of packets being sent. #set_tcp_nodelay false # Time in seconds between updates of the $SYS tree. # Set to 0 to disable the publishing of the $SYS tree. #sys_interval 10 # The MQTT specification requires that the QoS of a message delivered to a # subscriber is never upgraded to match the QoS of the subscription. Enabling # this option changes this behaviour. If upgrade_outgoing_qos is set true, # messages sent to a subscriber will always match the QoS of its subscription. # This is a non-standard option explicitly disallowed by the spec. #upgrade_outgoing_qos false # When run as root, drop privileges to this user and its primary # group. # Set to root to stay as root, but this is not recommended. # If set to "mosquitto", or left unset, and the "mosquitto" user does not exist # then it will drop privileges to the "nobody" user instead. # If run as a non-root user, this setting has no effect. # Note that on Windows this has no effect and so mosquitto should be started by # the user you wish it to run as. #user mosquitto # ================================================================= # Listeners # ================================================================= # Listen on a port/ip address combination. By using this variable # multiple times, mosquitto can listen on more than one port. If # this variable is used and neither bind_address nor port given, # then the default listener will not be started. # The port number to listen on must be given. Optionally, an ip # address or host name may be supplied as a second argument. In # this case, mosquitto will attempt to bind the listener to that # address and so restrict access to the associated network and # interface. By default, mosquitto will listen on all interfaces. # Note that for a websockets listener it is not possible to bind to a host # name. # # On systems that support Unix Domain Sockets, it is also possible # to create a # Unix socket rather than opening a TCP socket. In # this case, the port number should be set to 0 and a unix socket # path must be provided, e.g. # listener 0 /tmp/mosquitto.sock # # listener port-number [ip address/host name/unix socket path] #listener # By default, a listener will attempt to listen on all supported IP protocol # versions. If you do not have an IPv4 or IPv6 interface you may wish to # disable support for either of those protocol versions. In particular, note # that due to the limitations of the websockets library, it will only ever # attempt to open IPv6 sockets if IPv6 support is compiled in, and so will fail # if IPv6 is not available. # # Set to `ipv4` to force the listener to only use IPv4, or set to `ipv6` to # force the listener to only use IPv6. If you want support for both IPv4 and # IPv6, then do not use the socket_domain option. # #socket_domain # Bind the listener to a specific interface. This is similar to # the [ip address/host name] part of the listener definition, but is useful # when an interface has multiple addresses or the address may change. If used # with the [ip address/host name] part of the listener definition, then the # bind_interface option will take priority. # Not available on Windows. # # Example: bind_interface eth0 #bind_interface # When a listener is using the websockets protocol, it is possible to serve # http data as well. Set http_dir to a directory which contains the files you # wish to serve. If this option is not specified, then no normal http # connections will be possible. #http_dir # The maximum number of client connections to allow. This is # a per listener setting. # Default is -1, which means unlimited connections. # Note that other process limits mean that unlimited connections # are not really possible. Typically the default maximum number of # connections possible is around 1024. #max_connections -1 # The listener can be restricted to operating within a topic hierarchy using # the mount_point option. This is achieved be prefixing the mount_point string # to all topics for any clients connected to this listener. This prefixing only # happens internally to the broker; the client will not see the prefix. #mount_point # Choose the protocol to use when listening. # This can be either mqtt or websockets. # Certificate based TLS may be used with websockets, except that only the # cafile, certfile, keyfile, ciphers, and ciphers_tls13 options are supported. #protocol mqtt listener 1883 protocol mqtt listener 9001 protocol websockets # Set use_username_as_clientid to true to replace the clientid that a client # connected with with its username. This allows authentication to be tied to # the clientid, which means that it is possible to prevent one client # disconnecting another by using the same clientid. # If a client connects with no username it will be disconnected as not # authorised when this option is set to true. # Do not use in conjunction with clientid_prefixes. # See also use_identity_as_username. #use_username_as_clientid # Change the websockets headers size. This is a global option, it is not # possible to set per listener. This option sets the size of the buffer used in # the libwebsockets library when reading HTTP headers. If you are passing large # header data such as cookies then you may need to increase this value. If left # unset, or set to 0, then the default of 1024 bytes will be used. #websockets_headers_size # ----------------------------------------------------------------- # Certificate based SSL/TLS support # ----------------------------------------------------------------- # The following options can be used to enable certificate based SSL/TLS support # for this listener. Note that the recommended port for MQTT over TLS is 8883, # but this must be set manually. # # See also the mosquitto-tls man page and the "Pre-shared-key based SSL/TLS # support" section. Only one of certificate or PSK encryption support can be # enabled for any listener. # Both of certfile and keyfile must be defined to enable certificate based # TLS encryption. # Path to the PEM encoded server certificate. #certfile # Path to the PEM encoded keyfile. #keyfile # If you wish to control which encryption ciphers are used, use the ciphers # option. The list of available ciphers can be optained using the "openssl # ciphers" command and should be provided in the same format as the output of # that command. This applies to TLS 1.2 and earlier versions only. Use # ciphers_tls1.3 for TLS v1.3. #ciphers # Choose which TLS v1.3 ciphersuites are used for this listener. # Defaults to "TLS_AES_256_GCM_SHA384:TLS_CHACHA20_POLY1305_SHA256:TLS_AES_128_GCM_SHA256" #ciphers_tls1.3 # If you have require_certificate set to true, you can create a certificate # revocation list file to revoke access to particular client certificates. If # you have done this, use crlfile to point to the PEM encoded revocation file. #crlfile # To allow the use of ephemeral DH key exchange, which provides forward # security, the listener must load DH parameters. This can be specified with # the dhparamfile option. The dhparamfile can be generated with the command # e.g. "openssl dhparam -out dhparam.pem 2048" #dhparamfile # By default an TLS enabled listener will operate in a similar fashion to a # https enabled web server, in that the server has a certificate signed by a CA # and the client will verify that it is a trusted certificate. The overall aim # is encryption of the network traffic. By setting require_certificate to true, # the client must provide a valid certificate in order for the network # connection to proceed. This allows access to the broker to be controlled # outside of the mechanisms provided by MQTT. #require_certificate false # cafile and capath define methods of accessing the PEM encoded # Certificate Authority certificates that will be considered trusted when # checking incoming client certificates. # cafile defines the path to a file containing the CA certificates. # capath defines a directory that will be searched for files # containing the CA certificates. For capath to work correctly, the # certificate files must have ".crt" as the file ending and you must run # "openssl rehash <path to capath>" each time you add/remove a certificate. #cafile #capath # If require_certificate is true, you may set use_identity_as_username to true # to use the CN value from the client certificate as a username. If this is # true, the password_file option will not be used for this listener. #use_identity_as_username false # ----------------------------------------------------------------- # Pre-shared-key based SSL/TLS support # ----------------------------------------------------------------- # The following options can be used to enable PSK based SSL/TLS support for # this listener. Note that the recommended port for MQTT over TLS is 8883, but # this must be set manually. # # See also the mosquitto-tls man page and the "Certificate based SSL/TLS # support" section. Only one of certificate or PSK encryption support can be # enabled for any listener. # The psk_hint option enables pre-shared-key support for this listener and also # acts as an identifier for this listener. The hint is sent to clients and may # be used locally to aid authentication. The hint is a free form string that # doesn't have much meaning in itself, so feel free to be creative. # If this option is provided, see psk_file to define the pre-shared keys to be # used or create a security plugin to handle them. #psk_hint # When using PSK, the encryption ciphers used will be chosen from the list of # available PSK ciphers. If you want to control which ciphers are available, # use the "ciphers" option. The list of available ciphers can be optained # using the "openssl ciphers" command and should be provided in the same format # as the output of that command. #ciphers # Set use_identity_as_username to have the psk identity sent by the client used # as its username. Authentication will be carried out using the PSK rather than # the MQTT username/password and so password_file will not be used for this # listener. #use_identity_as_username false # ================================================================= # Persistence # ================================================================= # If persistence is enabled, save the in-memory database to disk # every autosave_interval seconds. If set to 0, the persistence # database will only be written when mosquitto exits. See also # autosave_on_changes. # Note that writing of the persistence database can be forced by # sending mosquitto a SIGUSR1 signal. #autosave_interval 1800 # If true, mosquitto will count the number of subscription changes, retained # messages received and queued messages and if the total exceeds # autosave_interval then the in-memory database will be saved to disk. # If false, mosquitto will save the in-memory database to disk by treating # autosave_interval as a time in seconds. #autosave_on_changes false # Save persistent message data to disk (true/false). # This saves information about all messages, including # subscriptions, currently in-flight messages and retained # messages. # retained_persistence is a synonym for this option. #persistence false # The filename to use for the persistent database, not including # the path. #persistence_file mosquitto.db # Location for persistent database. # Default is an empty string (current directory). # Set to e.g. /var/lib/mosquitto if running as a proper service on Linux or # similar. #persistence_location # ================================================================= # Logging # ================================================================= # Places to log to. Use multiple log_dest lines for multiple # logging destinations. # Possible destinations are: stdout stderr syslog topic file dlt # # stdout and stderr log to the console on the named output. # # syslog uses the userspace syslog facility which usually ends up # in /var/log/messages or similar. # # topic logs to the broker topic '$SYS/broker/log/<severity>', # where severity is one of D, E, W, N, I, M which are debug, error, # warning, notice, information and message. Message type severity is used by # the subscribe/unsubscribe log_types and publishes log messages to # $SYS/broker/log/M/susbcribe or $SYS/broker/log/M/unsubscribe. # # The file destination requires an additional parameter which is the file to be # logged to, e.g. "log_dest file /var/log/mosquitto.log". The file will be # closed and reopened when the broker receives a HUP signal. Only a single file # destination may be configured. # # The dlt destination is for the automotive `Diagnostic Log and Trace` tool. # This requires that Mosquitto has been compiled with DLT support. # # Note that if the broker is running as a Windows service it will default to # "log_dest none" and neither stdout nor stderr logging is available. # Use "log_dest none" if you wish to disable logging. #log_dest stderr # Types of messages to log. Use multiple log_type lines for logging # multiple types of messages. # Possible types are: debug, error, warning, notice, information, # none, subscribe, unsubscribe, websockets, all. # Note that debug type messages are for decoding the incoming/outgoing # network packets. They are not logged in "topics". #log_type error #log_type warning #log_type notice #log_type information # If set to true, client connection and disconnection messages will be included # in the log. #connection_messages true # If using syslog logging (not on Windows), messages will be logged to the # "daemon" facility by default. Use the log_facility option to choose which of # local0 to local7 to log to instead. The option value should be an integer # value, e.g. "log_facility 5" to use local5. #log_facility # If set to true, add a timestamp value to each log message. #log_timestamp true # Set the format of the log timestamp. If left unset, this is the number of # seconds since the Unix epoch. # This is a free text string which will be passed to the strftime function. To # get an ISO 8601 datetime, for example: # log_timestamp_format %Y-%m-%dT%H:%M:%S #log_timestamp_format # Change the websockets logging level. This is a global option, it is not # possible to set per listener. This is an integer that is interpreted by # libwebsockets as a bit mask for its lws_log_levels enum. See the # libwebsockets documentation for more details. "log_type websockets" must also # be enabled. #websockets_log_level 0 # ================================================================= # Security # ================================================================= # If set, only clients that have a matching prefix on their # clientid will be allowed to connect to the broker. By default, # all clients may connect. # For example, setting "secure-" here would mean a client "secure- # client" could connect but another with clientid "mqtt" couldn't. #clientid_prefixes # Boolean value that determines whether clients that connect # without providing a username are allowed to connect. If set to # false then a password file should be created (see the # password_file option) to control authenticated client access. # # Defaults to false, unless there are no listeners defined in the configuration # file, in which case it is set to true, but connections are only allowed from # the local machine. allow_anonymous true # ----------------------------------------------------------------- # Default authentication and topic access control # ----------------------------------------------------------------- # Control access to the broker using a password file. This file can be # generated using the mosquitto_passwd utility. If TLS support is not compiled # into mosquitto (it is recommended that TLS support should be included) then # plain text passwords are used, in which case the file should be a text file # with lines in the format: # username:password # The password (and colon) may be omitted if desired, although this # offers very little in the way of security. # # See the TLS client require_certificate and use_identity_as_username options # for alternative authentication options. If a plugin is used as well as # password_file, the plugin check will be made first. #password_file # Access may also be controlled using a pre-shared-key file. This requires # TLS-PSK support and a listener configured to use it. The file should be text # lines in the format: # identity:key # The key should be in hexadecimal format without a leading "0x". # If an plugin is used as well, the plugin check will be made first. #psk_file # Control access to topics on the broker using an access control list # file. If this parameter is defined then only the topics listed will # have access. # If the first character of a line of the ACL file is a # it is treated as a # comment. # Topic access is added with lines of the format: # # topic [read|write|readwrite|deny] <topic> # # The access type is controlled using "read", "write", "readwrite" or "deny". # This parameter is optional (unless <topic> contains a space character) - if # not given then the access is read/write. <topic> can contain the + or # # wildcards as in subscriptions. # # The "deny" option can used to explicity deny access to a topic that would # otherwise be granted by a broader read/write/readwrite statement. Any "deny" # topics are handled before topics that grant read/write access. # # The first set of topics are applied to anonymous clients, assuming # allow_anonymous is true. User specific topic ACLs are added after a # user line as follows: # # user <username> # # The username referred to here is the same as in password_file. It is # not the clientid. # # # If is also possible to define ACLs based on pattern substitution within the # topic. The patterns available for substition are: # # %c to match the client id of the client # %u to match the username of the client # # The substitution pattern must be the only text for that level of hierarchy. # # The form is the same as for the topic keyword, but using pattern as the # keyword. # Pattern ACLs apply to all users even if the "user" keyword has previously # been given. # # If using bridges with usernames and ACLs, connection messages can be allowed # with the following pattern: # pattern write $SYS/broker/connection/%c/state # # pattern [read|write|readwrite] <topic> # # Example: # # pattern write sensor/%u/data # # If an plugin is used as well as acl_file, the plugin check will be # made first. #acl_file # ----------------------------------------------------------------- # External authentication and topic access plugin options # ----------------------------------------------------------------- # External authentication and access control can be supported with the # plugin option. This is a path to a loadable plugin. See also the # plugin_opt_* options described below. # # The plugin option can be specified multiple times to load multiple # plugins. The plugins will be processed in the order that they are specified # here. If the plugin option is specified alongside either of # password_file or acl_file then the plugin checks will be made first. # # If the per_listener_settings option is false, the plugin will be apply to all # listeners. If per_listener_settings is true, then the plugin will apply to # the current listener being defined only. # # This option is also available as `auth_plugin`, but this use is deprecated # and will be removed in the future. # #plugin # If the plugin option above is used, define options to pass to the # plugin here as described by the plugin instructions. All options named # using the format plugin_opt_* will be passed to the plugin, for example: # # This option is also available as `auth_opt_*`, but this use is deprecated # and will be removed in the future. # # plugin_opt_db_host # plugin_opt_db_port # plugin_opt_db_username # plugin_opt_db_password # ================================================================= # Bridges # ================================================================= # A bridge is a way of connecting multiple MQTT brokers together. # Create a new bridge using the "connection" option as described below. Set # options for the bridges using the remaining parameters. You must specify the # address and at least one topic to subscribe to. # # Each connection must have a unique name. # # The address line may have multiple host address and ports specified. See # below in the round_robin description for more details on bridge behaviour if # multiple addresses are used. Note that if you use an IPv6 address, then you # are required to specify a port. # # The direction that the topic will be shared can be chosen by # specifying out, in or both, where the default value is out. # The QoS level of the bridged communication can be specified with the next # topic option. The default QoS level is 0, to change the QoS the topic # direction must also be given. # # The local and remote prefix options allow a topic to be remapped when it is # bridged to/from the remote broker. This provides the ability to place a topic # tree in an appropriate location. # # For more details see the mosquitto.conf man page. # # Multiple topics can be specified per connection, but be careful # not to create any loops. # # If you are using bridges with cleansession set to false (the default), then # you may get unexpected behaviour from incoming topics if you change what # topics you are subscribing to. This is because the remote broker keeps the # subscription for the old topic. If you have this problem, connect your bridge # with cleansession set to true, then reconnect with cleansession set to false # as normal. #connection <name> #address <host>[:<port>] [<host>[:<port>]] #topic <topic> [[[out | in | both] qos-level] local-prefix remote-prefix] # If you need to have the bridge connect over a particular network interface, # use bridge_bind_address to tell the bridge which local IP address the socket # should bind to, e.g. `bridge_bind_address 192.168.1.10` #bridge_bind_address # If a bridge has topics that have "out" direction, the default behaviour is to # send an unsubscribe request to the remote broker on that topic. This means # that changing a topic direction from "in" to "out" will not keep receiving # incoming messages. Sending these unsubscribe requests is not always # desirable, setting bridge_attempt_unsubscribe to false will disable sending # the unsubscribe request. #bridge_attempt_unsubscribe true # Set the version of the MQTT protocol to use with for this bridge. Can be one # of mqttv50, mqttv311 or mqttv31. Defaults to mqttv311. #bridge_protocol_version mqttv311 # Set the clean session variable for this bridge. # When set to true, when the bridge disconnects for any reason, all # messages and subscriptions will be cleaned up on the remote # broker. Note that with cleansession set to true, there may be a # significant amount of retained messages sent when the bridge # reconnects after losing its connection. # When set to false, the subscriptions and messages are kept on the # remote broker, and delivered when the bridge reconnects. #cleansession false # Set the amount of time a bridge using the lazy start type must be idle before # it will be stopped. Defaults to 60 seconds. #idle_timeout 60 # Set the keepalive interval for this bridge connection, in # seconds. #keepalive_interval 60 # Set the clientid to use on the local broker. If not defined, this defaults to # 'local.<clientid>'. If you are bridging a broker to itself, it is important # that local_clientid and clientid do not match. #local_clientid # If set to true, publish notification messages to the local and remote brokers # giving information about the state of the bridge connection. Retained # messages are published to the topic $SYS/broker/connection/<clientid>/state # unless the notification_topic option is used. # If the message is 1 then the connection is active, or 0 if the connection has # failed. # This uses the last will and testament feature. #notifications true # Choose the topic on which notification messages for this bridge are # published. If not set, messages are published on the topic # $SYS/broker/connection/<clientid>/state #notification_topic # Set the client id to use on the remote end of this bridge connection. If not # defined, this defaults to 'name.hostname' where name is the connection name # and hostname is the hostname of this computer. # This replaces the old "clientid" option to avoid confusion. "clientid" # remains valid for the time being. #remote_clientid # Set the password to use when connecting to a broker that requires # authentication. This option is only used if remote_username is also set. # This replaces the old "password" option to avoid confusion. "password" # remains valid for the time being. #remote_password # Set the username to use when connecting to a broker that requires # authentication. # This replaces the old "username" option to avoid confusion. "username" # remains valid for the time being. #remote_username # Set the amount of time a bridge using the automatic start type will wait # until attempting to reconnect. # This option can be configured to use a constant delay time in seconds, or to # use a backoff mechanism based on "Decorrelated Jitter", which adds a degree # of randomness to when the restart occurs. # # Set a constant timeout of 20 seconds: # restart_timeout 20 # # Set backoff with a base (start value) of 10 seconds and a cap (upper limit) of # 60 seconds: # restart_timeout 10 30 # # Defaults to jitter with a base of 5 and cap of 30 #restart_timeout 5 30 # If the bridge has more than one address given in the address/addresses # configuration, the round_robin option defines the behaviour of the bridge on # a failure of the bridge connection. If round_robin is false, the default # value, then the first address is treated as the main bridge connection. If # the connection fails, the other secondary addresses will be attempted in # turn. Whilst connected to a secondary bridge, the bridge will periodically # attempt to reconnect to the main bridge until successful. # If round_robin is true, then all addresses are treated as equals. If a # connection fails, the next address will be tried and if successful will # remain connected until it fails #round_robin false # Set the start type of the bridge. This controls how the bridge starts and # can be one of three types: automatic, lazy and once. Note that RSMB provides # a fourth start type "manual" which isn't currently supported by mosquitto. # # "automatic" is the default start type and means that the bridge connection # will be started automatically when the broker starts and also restarted # after a short delay (30 seconds) if the connection fails. # # Bridges using the "lazy" start type will be started automatically when the # number of queued messages exceeds the number set with the "threshold" # parameter. It will be stopped automatically after the time set by the # "idle_timeout" parameter. Use this start type if you wish the connection to # only be active when it is needed. # # A bridge using the "once" start type will be started automatically when the # broker starts but will not be restarted if the connection fails. #start_type automatic # Set the number of messages that need to be queued for a bridge with lazy # start type to be restarted. Defaults to 10 messages. # Must be less than max_queued_messages. #threshold 10 # If try_private is set to true, the bridge will attempt to indicate to the # remote broker that it is a bridge not an ordinary client. If successful, this # means that loop detection will be more effective and that retained messages # will be propagated correctly. Not all brokers support this feature so it may # be necessary to set try_private to false if your bridge does not connect # properly. #try_private true # Some MQTT brokers do not allow retained messages. MQTT v5 gives a mechanism # for brokers to tell clients that they do not support retained messages, but # this is not possible for MQTT v3.1.1 or v3.1. If you need to bridge to a # v3.1.1 or v3.1 broker that does not support retained messages, set the # bridge_outgoing_retain option to false. This will remove the retain bit on # all outgoing messages to that bridge, regardless of any other setting. #bridge_outgoing_retain true # If you wish to restrict the size of messages sent to a remote bridge, use the # bridge_max_packet_size option. This sets the maximum number of bytes for # the total message, including headers and payload. # Note that MQTT v5 brokers may provide their own maximum-packet-size property. # In this case, the smaller of the two limits will be used. # Set to 0 for "unlimited". #bridge_max_packet_size 0 # ----------------------------------------------------------------- # Certificate based SSL/TLS support # ----------------------------------------------------------------- # Either bridge_cafile or bridge_capath must be defined to enable TLS support # for this bridge. # bridge_cafile defines the path to a file containing the # Certificate Authority certificates that have signed the remote broker # certificate. # bridge_capath defines a directory that will be searched for files containing # the CA certificates. For bridge_capath to work correctly, the certificate # files must have ".crt" as the file ending and you must run "openssl rehash # <path to capath>" each time you add/remove a certificate. #bridge_cafile #bridge_capath # If the remote broker has more than one protocol available on its port, e.g. # MQTT and WebSockets, then use bridge_alpn to configure which protocol is # requested. Note that WebSockets support for bridges is not yet available. #bridge_alpn # When using certificate based encryption, bridge_insecure disables # verification of the server hostname in the server certificate. This can be # useful when testing initial server configurations, but makes it possible for # a malicious third party to impersonate your server through DNS spoofing, for # example. Use this option in testing only. If you need to resort to using this # option in a production environment, your setup is at fault and there is no # point using encryption. #bridge_insecure false # Path to the PEM encoded client certificate, if required by the remote broker. #bridge_certfile # Path to the PEM encoded client private key, if required by the remote broker. #bridge_keyfile # ----------------------------------------------------------------- # PSK based SSL/TLS support # ----------------------------------------------------------------- # Pre-shared-key encryption provides an alternative to certificate based # encryption. A bridge can be configured to use PSK with the bridge_identity # and bridge_psk options. These are the client PSK identity, and pre-shared-key # in hexadecimal format with no "0x". Only one of certificate and PSK based # encryption can be used on one # bridge at once. #bridge_identity #bridge_psk # ================================================================= # External config files # ================================================================= # External configuration files may be included by using the # include_dir option. This defines a directory that will be searched # for config files. All files that end in '.conf' will be loaded as # a configuration file. It is best to have this as the last option # in the main file. This option will only be processed from the main # configuration file. The directory specified must not contain the # main configuration file. # Files within include_dir will be loaded sorted in case-sensitive # alphabetical order, with capital letters ordered first. If this option is # given multiple times, all of the files from the first instance will be # processed before the next instance. See the man page for examples. #include_dir
integration/mosquitto.conf
0
https://github.com/nestjs/nest/commit/20abe1df78159aa6d451898e8470285ed64eabe5
[ 0.0002965021994896233, 0.00017039086378645152, 0.00016157508071046323, 0.00016709399642422795, 0.000016024019714677706 ]
{ "id": 5, "code_window": [ " config: ApplicationConfig,\n", " injector: Injector,\n", " httpAdapter: HttpServer,\n", " graphInspector: GraphInspector,\n", " ) {\n" ], "labels": [ "keep", "keep", "keep", "add", "keep" ], "after_edit": [ " options: TAppOptions,\n" ], "file_path": "packages/core/middleware/middleware-module.ts", "type": "add", "edit_start_line_idx": 58 }
import { expect } from 'chai'; import * as sinon from 'sinon'; import { SelectReplFn } from '../../../repl/native-functions'; import { ReplContext } from '../../../repl/repl-context'; import { NestContainer } from '../../../injector/container'; describe('SelectReplFn', () => { let selectReplFn: SelectReplFn; let replContext: ReplContext; let mockApp: { container: NestContainer; get: sinon.SinonStub; resolve: sinon.SinonSpy; select: sinon.SinonSpy; }; before(async () => { const container = new NestContainer(); mockApp = { container, get: sinon.stub(), resolve: sinon.spy(), select: sinon.spy(), }; replContext = new ReplContext(mockApp as any); }); beforeEach(() => { selectReplFn = replContext.nativeFunctions.get('select') as SelectReplFn; }); afterEach(() => sinon.restore()); it('the function name should be "select"', () => { expect(selectReplFn).to.not.be.undefined; expect(selectReplFn.fnDefinition.name).to.eql('select'); }); describe('action', () => { it('should pass arguments down to the application context', () => { const moduleCls = class TestModule {}; selectReplFn.action(moduleCls); expect(mockApp.select.calledWith(moduleCls)).to.be.true; }); }); });
packages/core/test/repl/native-functions/select-repl-fn.spec.ts
0
https://github.com/nestjs/nest/commit/20abe1df78159aa6d451898e8470285ed64eabe5
[ 0.00017589243361726403, 0.00017200203728862107, 0.0001664326700847596, 0.00017204185132868588, 0.000003155522335873684 ]
{ "id": 6, "code_window": [ " ) {\n", " const appRef = container.getHttpAdapterRef();\n", " this.routerExceptionFilter = new RouterExceptionFilters(\n", " container,\n" ], "labels": [ "add", "keep", "keep", "keep" ], "after_edit": [ " this.appOptions = options;\n", "\n" ], "file_path": "packages/core/middleware/middleware-module.ts", "type": "add", "edit_start_line_idx": 59 }
import { CanActivate, ExceptionFilter, HttpServer, INestApplication, INestMicroservice, NestHybridApplicationOptions, NestInterceptor, PipeTransform, RequestMethod, VersioningOptions, VersioningType, WebSocketAdapter, } from '@nestjs/common'; import { GlobalPrefixOptions, NestApplicationOptions, RouteInfo, } from '@nestjs/common/interfaces'; import { CorsOptions, CorsOptionsDelegate, } from '@nestjs/common/interfaces/external/cors-options.interface'; import { Logger } from '@nestjs/common/services/logger.service'; import { loadPackage } from '@nestjs/common/utils/load-package.util'; import { addLeadingSlash, isFunction, isObject, isString, } from '@nestjs/common/utils/shared.utils'; import { iterate } from 'iterare'; import { platform } from 'os'; import * as pathToRegexp from 'path-to-regexp'; import { AbstractHttpAdapter } from './adapters'; import { ApplicationConfig } from './application-config'; import { MESSAGES } from './constants'; import { optionalRequire } from './helpers/optional-require'; import { NestContainer } from './injector/container'; import { Injector } from './injector/injector'; import { GraphInspector } from './inspector/graph-inspector'; import { MiddlewareContainer } from './middleware/container'; import { MiddlewareModule } from './middleware/middleware-module'; import { NestApplicationContext } from './nest-application-context'; import { ExcludeRouteMetadata } from './router/interfaces/exclude-route-metadata.interface'; import { Resolver } from './router/interfaces/resolver.interface'; import { RoutePathFactory } from './router/route-path-factory'; import { RoutesResolver } from './router/routes-resolver'; const { SocketModule } = optionalRequire( '@nestjs/websockets/socket-module', () => require('@nestjs/websockets/socket-module'), ); const { MicroservicesModule } = optionalRequire( '@nestjs/microservices/microservices-module', () => require('@nestjs/microservices/microservices-module'), ); /** * @publicApi */ export class NestApplication extends NestApplicationContext<NestApplicationOptions> implements INestApplication { protected readonly logger = new Logger(NestApplication.name, { timestamp: true, }); private readonly middlewareModule: MiddlewareModule; private readonly middlewareContainer = new MiddlewareContainer( this.container, ); private readonly microservicesModule = MicroservicesModule && new MicroservicesModule(); private readonly socketModule = SocketModule && new SocketModule(); private readonly routesResolver: Resolver; private readonly microservices: any[] = []; private httpServer: any; private isListening = false; constructor( container: NestContainer, private readonly httpAdapter: HttpServer, private readonly config: ApplicationConfig, private readonly graphInspector: GraphInspector, appOptions: NestApplicationOptions = {}, ) { super(container, appOptions); this.selectContextModule(); this.registerHttpServer(); this.injector = new Injector({ preview: this.appOptions.preview }); this.middlewareModule = new MiddlewareModule(new RoutePathFactory(config)); this.routesResolver = new RoutesResolver( this.container, this.config, this.injector, this.graphInspector, ); } protected async dispose(): Promise<void> { this.socketModule && (await this.socketModule.close()); this.microservicesModule && (await this.microservicesModule.close()); this.httpAdapter && (await this.httpAdapter.close()); await Promise.all( iterate(this.microservices).map(async microservice => { microservice.setIsTerminated(true); await microservice.close(); }), ); } public getHttpAdapter(): AbstractHttpAdapter { return this.httpAdapter as AbstractHttpAdapter; } public registerHttpServer() { this.httpServer = this.createServer(); } public getUnderlyingHttpServer<T>(): T { return this.httpAdapter.getHttpServer(); } public applyOptions() { if (!this.appOptions || !this.appOptions.cors) { return undefined; } const passCustomOptions = isObject(this.appOptions.cors) || isFunction(this.appOptions.cors); if (!passCustomOptions) { return this.enableCors(); } return this.enableCors( this.appOptions.cors as CorsOptions | CorsOptionsDelegate<any>, ); } public createServer<T = any>(): T { this.httpAdapter.initHttpServer(this.appOptions); return this.httpAdapter.getHttpServer() as T; } public async registerModules() { this.registerWsModule(); if (this.microservicesModule) { this.microservicesModule.register( this.container, this.graphInspector, this.config, this.appOptions, ); this.microservicesModule.setupClients(this.container); } await this.middlewareModule.register( this.middlewareContainer, this.container, this.config, this.injector, this.httpAdapter, this.graphInspector, ); } public registerWsModule() { if (!this.socketModule) { return; } this.socketModule.register( this.container, this.config, this.graphInspector, this.appOptions, this.httpServer, ); } public async init(): Promise<this> { this.applyOptions(); await this.httpAdapter?.init(); const useBodyParser = this.appOptions && this.appOptions.bodyParser !== false; useBodyParser && this.registerParserMiddleware(); await this.registerModules(); await this.registerRouter(); await this.callInitHook(); await this.registerRouterHooks(); await this.callBootstrapHook(); this.isInitialized = true; this.logger.log(MESSAGES.APPLICATION_READY); return this; } public registerParserMiddleware() { const prefix = this.config.getGlobalPrefix(); const rawBody = !!this.appOptions?.rawBody; this.httpAdapter.registerParserMiddleware(prefix, rawBody); } public async registerRouter() { await this.registerMiddleware(this.httpAdapter); const prefix = this.config.getGlobalPrefix(); const basePath = addLeadingSlash(prefix); this.routesResolver.resolve(this.httpAdapter, basePath); } public async registerRouterHooks() { this.routesResolver.registerNotFoundHandler(); this.routesResolver.registerExceptionHandler(); } public connectMicroservice<T extends object>( microserviceOptions: T, hybridAppOptions: NestHybridApplicationOptions = {}, ): INestMicroservice { const { NestMicroservice } = loadPackage( '@nestjs/microservices', 'NestFactory', () => require('@nestjs/microservices'), ); const { inheritAppConfig } = hybridAppOptions; const applicationConfig = inheritAppConfig ? this.config : new ApplicationConfig(); const instance = new NestMicroservice( this.container, microserviceOptions, this.graphInspector, applicationConfig, ); instance.registerListeners(); instance.setIsInitialized(true); instance.setIsInitHookCalled(true); this.microservices.push(instance); return instance; } public getMicroservices(): INestMicroservice[] { return this.microservices; } public getHttpServer() { return this.httpServer; } public async startAllMicroservices(): Promise<this> { this.assertNotInPreviewMode('startAllMicroservices'); await Promise.all(this.microservices.map(msvc => msvc.listen())); return this; } public use(...args: [any, any?]): this { this.httpAdapter.use(...args); return this; } public enableCors(options?: CorsOptions | CorsOptionsDelegate<any>): void { this.httpAdapter.enableCors(options); } public enableVersioning( options: VersioningOptions = { type: VersioningType.URI }, ): this { this.config.enableVersioning(options); return this; } public async listen(port: number | string): Promise<any>; public async listen(port: number | string, hostname: string): Promise<any>; public async listen(port: number | string, ...args: any[]): Promise<any> { this.assertNotInPreviewMode('listen'); !this.isInitialized && (await this.init()); return new Promise((resolve, reject) => { const errorHandler = (e: any) => { this.logger.error(e?.toString?.()); reject(e); }; this.httpServer.once('error', errorHandler); const isCallbackInOriginalArgs = isFunction(args[args.length - 1]); const listenFnArgs = isCallbackInOriginalArgs ? args.slice(0, args.length - 1) : args; this.httpAdapter.listen( port, ...listenFnArgs, (...originalCallbackArgs: unknown[]) => { if (this.appOptions?.autoFlushLogs ?? true) { this.flushLogs(); } if (originalCallbackArgs[0] instanceof Error) { return reject(originalCallbackArgs[0]); } const address = this.httpServer.address(); if (address) { this.httpServer.removeListener('error', errorHandler); this.isListening = true; resolve(this.httpServer); } if (isCallbackInOriginalArgs) { args[args.length - 1](...originalCallbackArgs); } }, ); }); } public async getUrl(): Promise<string> { return new Promise((resolve, reject) => { if (!this.isListening) { this.logger.error(MESSAGES.CALL_LISTEN_FIRST); reject(MESSAGES.CALL_LISTEN_FIRST); return; } const address = this.httpServer.address(); resolve(this.formatAddress(address)); }); } private formatAddress(address: any): string { if (isString(address)) { if (platform() === 'win32') { return address; } const basePath = encodeURIComponent(address); return `${this.getProtocol()}+unix://${basePath}`; } let host = this.host(); if (address && address.family === 'IPv6') { if (host === '::') { host = '[::1]'; } else { host = `[${host}]`; } } else if (host === '0.0.0.0') { host = '127.0.0.1'; } return `${this.getProtocol()}://${host}:${address.port}`; } public setGlobalPrefix(prefix: string, options?: GlobalPrefixOptions): this { this.config.setGlobalPrefix(prefix); if (options) { const exclude = options?.exclude.map( (route: string | RouteInfo): ExcludeRouteMetadata => { if (isString(route)) { return { requestMethod: RequestMethod.ALL, pathRegex: pathToRegexp(addLeadingSlash(route)), }; } return { requestMethod: route.method, pathRegex: pathToRegexp(addLeadingSlash(route.path)), }; }, ); this.config.setGlobalPrefixOptions({ ...options, exclude, }); } return this; } public useWebSocketAdapter(adapter: WebSocketAdapter): this { this.config.setIoAdapter(adapter); return this; } public useGlobalFilters(...filters: ExceptionFilter[]): this { this.config.useGlobalFilters(...filters); filters.forEach(item => this.graphInspector.insertOrphanedEnhancer({ subtype: 'filter', ref: item, }), ); return this; } public useGlobalPipes(...pipes: PipeTransform<any>[]): this { this.config.useGlobalPipes(...pipes); pipes.forEach(item => this.graphInspector.insertOrphanedEnhancer({ subtype: 'pipe', ref: item, }), ); return this; } public useGlobalInterceptors(...interceptors: NestInterceptor[]): this { this.config.useGlobalInterceptors(...interceptors); interceptors.forEach(item => this.graphInspector.insertOrphanedEnhancer({ subtype: 'interceptor', ref: item, }), ); return this; } public useGlobalGuards(...guards: CanActivate[]): this { this.config.useGlobalGuards(...guards); guards.forEach(item => this.graphInspector.insertOrphanedEnhancer({ subtype: 'guard', ref: item, }), ); return this; } public useStaticAssets(options: any): this; public useStaticAssets(path: string, options?: any): this; public useStaticAssets(pathOrOptions: any, options?: any): this { this.httpAdapter.useStaticAssets && this.httpAdapter.useStaticAssets(pathOrOptions, options); return this; } public setBaseViewsDir(path: string | string[]): this { this.httpAdapter.setBaseViewsDir && this.httpAdapter.setBaseViewsDir(path); return this; } public setViewEngine(engineOrOptions: any): this { this.httpAdapter.setViewEngine && this.httpAdapter.setViewEngine(engineOrOptions); return this; } private host(): string | undefined { const address = this.httpServer.address(); if (isString(address)) { return undefined; } return address && address.address; } private getProtocol(): 'http' | 'https' { return this.appOptions && this.appOptions.httpsOptions ? 'https' : 'http'; } private async registerMiddleware(instance: any) { await this.middlewareModule.registerMiddleware( this.middlewareContainer, instance, ); } }
packages/core/nest-application.ts
1
https://github.com/nestjs/nest/commit/20abe1df78159aa6d451898e8470285ed64eabe5
[ 0.003752018790692091, 0.000426172191509977, 0.000164842713274993, 0.0001720482687233016, 0.0006163573125377297 ]
{ "id": 6, "code_window": [ " ) {\n", " const appRef = container.getHttpAdapterRef();\n", " this.routerExceptionFilter = new RouterExceptionFilters(\n", " container,\n" ], "labels": [ "add", "keep", "keep", "keep" ], "after_edit": [ " this.appOptions = options;\n", "\n" ], "file_path": "packages/core/middleware/middleware-module.ts", "type": "add", "edit_start_line_idx": 59 }
import { loadPackage } from '@nestjs/common/utils/load-package.util'; import { NatsCodec } from '../external/nats-client.interface'; import { IncomingResponse } from '../interfaces'; import { IncomingResponseDeserializer } from './incoming-response.deserializer'; import { NatsRequestJSONDeserializer } from './nats-request-json.deserializer'; let natsPackage = {} as any; export class NatsResponseJSONDeserializer extends IncomingResponseDeserializer { private readonly jsonCodec: NatsCodec<unknown>; constructor() { super(); natsPackage = loadPackage('nats', NatsRequestJSONDeserializer.name, () => require('nats'), ); this.jsonCodec = natsPackage.JSONCodec(); } deserialize( value: Uint8Array, options?: Record<string, any>, ): IncomingResponse { const decodedRequest = this.jsonCodec.decode(value); return super.deserialize(decodedRequest, options); } }
packages/microservices/deserializers/nats-response-json.deserializer.ts
0
https://github.com/nestjs/nest/commit/20abe1df78159aa6d451898e8470285ed64eabe5
[ 0.00017409487918484956, 0.00017188361380249262, 0.0001682707661530003, 0.000173285196069628, 0.000002575965709183947 ]
{ "id": 6, "code_window": [ " ) {\n", " const appRef = container.getHttpAdapterRef();\n", " this.routerExceptionFilter = new RouterExceptionFilters(\n", " container,\n" ], "labels": [ "add", "keep", "keep", "keep" ], "after_edit": [ " this.appOptions = options;\n", "\n" ], "file_path": "packages/core/middleware/middleware-module.ts", "type": "add", "edit_start_line_idx": 59 }
import { expect } from 'chai'; import { ModulesContainer, NestContainer } from '../../injector'; import { Module } from '../../injector/module'; import { Routes } from '../../router/interfaces'; import { RouterModule, ROUTES, targetModulesByContainer, } from '../../router/router-module'; class TestModuleClass {} describe('RouterModule', () => { const routes: Routes = [{ path: 'test', module: TestModuleClass }]; describe('register', () => { it('should return a dynamic module with routes registered as a provider', () => { expect(RouterModule.register(routes)).to.deep.equal({ module: RouterModule, providers: [ { provide: ROUTES, useValue: routes, }, ], }); }); }); describe('when instantiated', () => { it('should update the "targetModulesByContainer" weak map', () => { const moduleRef = new Module(TestModuleClass, new NestContainer(null)); const container = new ModulesContainer([ [TestModuleClass.name, moduleRef], ]); new RouterModule(container, routes); class NotRegisteredModuleClass {} new RouterModule(container, [ { path: 'random', module: NotRegisteredModuleClass, }, ]); expect(targetModulesByContainer.get(container).has(moduleRef)).to.be.true; }); }); });
packages/core/test/router/router-module.spec.ts
0
https://github.com/nestjs/nest/commit/20abe1df78159aa6d451898e8470285ed64eabe5
[ 0.014132436364889145, 0.0026073548942804337, 0.00017660969751887023, 0.00021728283900301903, 0.005157765932381153 ]
{ "id": 6, "code_window": [ " ) {\n", " const appRef = container.getHttpAdapterRef();\n", " this.routerExceptionFilter = new RouterExceptionFilters(\n", " container,\n" ], "labels": [ "add", "keep", "keep", "keep" ], "after_edit": [ " this.appOptions = options;\n", "\n" ], "file_path": "packages/core/middleware/middleware-module.ts", "type": "add", "edit_start_line_idx": 59 }
import { NestFactory } from '@nestjs/core'; import { FastifyAdapter, NestFastifyApplication, } from '@nestjs/platform-fastify'; import { join } from 'path'; import { AppModule } from './app.module'; async function bootstrap() { const app = await NestFactory.create<NestFastifyApplication>( AppModule, new FastifyAdapter(), ); app.useStaticAssets({ root: join(__dirname, '..', 'public'), prefix: '/public/', }); app.setViewEngine({ engine: { handlebars: require('handlebars'), }, templates: join(__dirname, '..', 'views'), }); await app.listen(3000); console.log(`Application is running on: ${await app.getUrl()}`); } bootstrap();
sample/17-mvc-fastify/src/main.ts
0
https://github.com/nestjs/nest/commit/20abe1df78159aa6d451898e8470285ed64eabe5
[ 0.00017245214257854968, 0.00017025585111696273, 0.00016768151544965804, 0.00017063392442651093, 0.000001965861883945763 ]
{ "id": 7, "code_window": [ " this.routesMapper,\n", " this.httpAdapter,\n", " );\n", " await instance.configure(middlewareBuilder);\n", "\n", " if (!(middlewareBuilder instanceof MiddlewareBuilder)) {\n", " return;\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " try {\n", " await instance.configure(middlewareBuilder);\n", " } catch (err) {\n", " if (!this.appOptions.preview) {\n", " throw err;\n", " }\n", " const warningMessage =\n", " `Warning! \"${moduleRef.name}\" module exposes a \"configure\" method that throws an exception in the preview mode` +\n", " ` (possibly due to missing dependencies). Note: you can ignore this message, just be aware that some of those conditional middlewares will not be reflected in your graph.`;\n", " this.logger.warn(warningMessage);\n", " }\n" ], "file_path": "packages/core/middleware/middleware-module.ts", "type": "replace", "edit_start_line_idx": 106 }
import { CanActivate, ExceptionFilter, HttpServer, INestApplication, INestMicroservice, NestHybridApplicationOptions, NestInterceptor, PipeTransform, RequestMethod, VersioningOptions, VersioningType, WebSocketAdapter, } from '@nestjs/common'; import { GlobalPrefixOptions, NestApplicationOptions, RouteInfo, } from '@nestjs/common/interfaces'; import { CorsOptions, CorsOptionsDelegate, } from '@nestjs/common/interfaces/external/cors-options.interface'; import { Logger } from '@nestjs/common/services/logger.service'; import { loadPackage } from '@nestjs/common/utils/load-package.util'; import { addLeadingSlash, isFunction, isObject, isString, } from '@nestjs/common/utils/shared.utils'; import { iterate } from 'iterare'; import { platform } from 'os'; import * as pathToRegexp from 'path-to-regexp'; import { AbstractHttpAdapter } from './adapters'; import { ApplicationConfig } from './application-config'; import { MESSAGES } from './constants'; import { optionalRequire } from './helpers/optional-require'; import { NestContainer } from './injector/container'; import { Injector } from './injector/injector'; import { GraphInspector } from './inspector/graph-inspector'; import { MiddlewareContainer } from './middleware/container'; import { MiddlewareModule } from './middleware/middleware-module'; import { NestApplicationContext } from './nest-application-context'; import { ExcludeRouteMetadata } from './router/interfaces/exclude-route-metadata.interface'; import { Resolver } from './router/interfaces/resolver.interface'; import { RoutePathFactory } from './router/route-path-factory'; import { RoutesResolver } from './router/routes-resolver'; const { SocketModule } = optionalRequire( '@nestjs/websockets/socket-module', () => require('@nestjs/websockets/socket-module'), ); const { MicroservicesModule } = optionalRequire( '@nestjs/microservices/microservices-module', () => require('@nestjs/microservices/microservices-module'), ); /** * @publicApi */ export class NestApplication extends NestApplicationContext<NestApplicationOptions> implements INestApplication { protected readonly logger = new Logger(NestApplication.name, { timestamp: true, }); private readonly middlewareModule: MiddlewareModule; private readonly middlewareContainer = new MiddlewareContainer( this.container, ); private readonly microservicesModule = MicroservicesModule && new MicroservicesModule(); private readonly socketModule = SocketModule && new SocketModule(); private readonly routesResolver: Resolver; private readonly microservices: any[] = []; private httpServer: any; private isListening = false; constructor( container: NestContainer, private readonly httpAdapter: HttpServer, private readonly config: ApplicationConfig, private readonly graphInspector: GraphInspector, appOptions: NestApplicationOptions = {}, ) { super(container, appOptions); this.selectContextModule(); this.registerHttpServer(); this.injector = new Injector({ preview: this.appOptions.preview }); this.middlewareModule = new MiddlewareModule(new RoutePathFactory(config)); this.routesResolver = new RoutesResolver( this.container, this.config, this.injector, this.graphInspector, ); } protected async dispose(): Promise<void> { this.socketModule && (await this.socketModule.close()); this.microservicesModule && (await this.microservicesModule.close()); this.httpAdapter && (await this.httpAdapter.close()); await Promise.all( iterate(this.microservices).map(async microservice => { microservice.setIsTerminated(true); await microservice.close(); }), ); } public getHttpAdapter(): AbstractHttpAdapter { return this.httpAdapter as AbstractHttpAdapter; } public registerHttpServer() { this.httpServer = this.createServer(); } public getUnderlyingHttpServer<T>(): T { return this.httpAdapter.getHttpServer(); } public applyOptions() { if (!this.appOptions || !this.appOptions.cors) { return undefined; } const passCustomOptions = isObject(this.appOptions.cors) || isFunction(this.appOptions.cors); if (!passCustomOptions) { return this.enableCors(); } return this.enableCors( this.appOptions.cors as CorsOptions | CorsOptionsDelegate<any>, ); } public createServer<T = any>(): T { this.httpAdapter.initHttpServer(this.appOptions); return this.httpAdapter.getHttpServer() as T; } public async registerModules() { this.registerWsModule(); if (this.microservicesModule) { this.microservicesModule.register( this.container, this.graphInspector, this.config, this.appOptions, ); this.microservicesModule.setupClients(this.container); } await this.middlewareModule.register( this.middlewareContainer, this.container, this.config, this.injector, this.httpAdapter, this.graphInspector, ); } public registerWsModule() { if (!this.socketModule) { return; } this.socketModule.register( this.container, this.config, this.graphInspector, this.appOptions, this.httpServer, ); } public async init(): Promise<this> { this.applyOptions(); await this.httpAdapter?.init(); const useBodyParser = this.appOptions && this.appOptions.bodyParser !== false; useBodyParser && this.registerParserMiddleware(); await this.registerModules(); await this.registerRouter(); await this.callInitHook(); await this.registerRouterHooks(); await this.callBootstrapHook(); this.isInitialized = true; this.logger.log(MESSAGES.APPLICATION_READY); return this; } public registerParserMiddleware() { const prefix = this.config.getGlobalPrefix(); const rawBody = !!this.appOptions?.rawBody; this.httpAdapter.registerParserMiddleware(prefix, rawBody); } public async registerRouter() { await this.registerMiddleware(this.httpAdapter); const prefix = this.config.getGlobalPrefix(); const basePath = addLeadingSlash(prefix); this.routesResolver.resolve(this.httpAdapter, basePath); } public async registerRouterHooks() { this.routesResolver.registerNotFoundHandler(); this.routesResolver.registerExceptionHandler(); } public connectMicroservice<T extends object>( microserviceOptions: T, hybridAppOptions: NestHybridApplicationOptions = {}, ): INestMicroservice { const { NestMicroservice } = loadPackage( '@nestjs/microservices', 'NestFactory', () => require('@nestjs/microservices'), ); const { inheritAppConfig } = hybridAppOptions; const applicationConfig = inheritAppConfig ? this.config : new ApplicationConfig(); const instance = new NestMicroservice( this.container, microserviceOptions, this.graphInspector, applicationConfig, ); instance.registerListeners(); instance.setIsInitialized(true); instance.setIsInitHookCalled(true); this.microservices.push(instance); return instance; } public getMicroservices(): INestMicroservice[] { return this.microservices; } public getHttpServer() { return this.httpServer; } public async startAllMicroservices(): Promise<this> { this.assertNotInPreviewMode('startAllMicroservices'); await Promise.all(this.microservices.map(msvc => msvc.listen())); return this; } public use(...args: [any, any?]): this { this.httpAdapter.use(...args); return this; } public enableCors(options?: CorsOptions | CorsOptionsDelegate<any>): void { this.httpAdapter.enableCors(options); } public enableVersioning( options: VersioningOptions = { type: VersioningType.URI }, ): this { this.config.enableVersioning(options); return this; } public async listen(port: number | string): Promise<any>; public async listen(port: number | string, hostname: string): Promise<any>; public async listen(port: number | string, ...args: any[]): Promise<any> { this.assertNotInPreviewMode('listen'); !this.isInitialized && (await this.init()); return new Promise((resolve, reject) => { const errorHandler = (e: any) => { this.logger.error(e?.toString?.()); reject(e); }; this.httpServer.once('error', errorHandler); const isCallbackInOriginalArgs = isFunction(args[args.length - 1]); const listenFnArgs = isCallbackInOriginalArgs ? args.slice(0, args.length - 1) : args; this.httpAdapter.listen( port, ...listenFnArgs, (...originalCallbackArgs: unknown[]) => { if (this.appOptions?.autoFlushLogs ?? true) { this.flushLogs(); } if (originalCallbackArgs[0] instanceof Error) { return reject(originalCallbackArgs[0]); } const address = this.httpServer.address(); if (address) { this.httpServer.removeListener('error', errorHandler); this.isListening = true; resolve(this.httpServer); } if (isCallbackInOriginalArgs) { args[args.length - 1](...originalCallbackArgs); } }, ); }); } public async getUrl(): Promise<string> { return new Promise((resolve, reject) => { if (!this.isListening) { this.logger.error(MESSAGES.CALL_LISTEN_FIRST); reject(MESSAGES.CALL_LISTEN_FIRST); return; } const address = this.httpServer.address(); resolve(this.formatAddress(address)); }); } private formatAddress(address: any): string { if (isString(address)) { if (platform() === 'win32') { return address; } const basePath = encodeURIComponent(address); return `${this.getProtocol()}+unix://${basePath}`; } let host = this.host(); if (address && address.family === 'IPv6') { if (host === '::') { host = '[::1]'; } else { host = `[${host}]`; } } else if (host === '0.0.0.0') { host = '127.0.0.1'; } return `${this.getProtocol()}://${host}:${address.port}`; } public setGlobalPrefix(prefix: string, options?: GlobalPrefixOptions): this { this.config.setGlobalPrefix(prefix); if (options) { const exclude = options?.exclude.map( (route: string | RouteInfo): ExcludeRouteMetadata => { if (isString(route)) { return { requestMethod: RequestMethod.ALL, pathRegex: pathToRegexp(addLeadingSlash(route)), }; } return { requestMethod: route.method, pathRegex: pathToRegexp(addLeadingSlash(route.path)), }; }, ); this.config.setGlobalPrefixOptions({ ...options, exclude, }); } return this; } public useWebSocketAdapter(adapter: WebSocketAdapter): this { this.config.setIoAdapter(adapter); return this; } public useGlobalFilters(...filters: ExceptionFilter[]): this { this.config.useGlobalFilters(...filters); filters.forEach(item => this.graphInspector.insertOrphanedEnhancer({ subtype: 'filter', ref: item, }), ); return this; } public useGlobalPipes(...pipes: PipeTransform<any>[]): this { this.config.useGlobalPipes(...pipes); pipes.forEach(item => this.graphInspector.insertOrphanedEnhancer({ subtype: 'pipe', ref: item, }), ); return this; } public useGlobalInterceptors(...interceptors: NestInterceptor[]): this { this.config.useGlobalInterceptors(...interceptors); interceptors.forEach(item => this.graphInspector.insertOrphanedEnhancer({ subtype: 'interceptor', ref: item, }), ); return this; } public useGlobalGuards(...guards: CanActivate[]): this { this.config.useGlobalGuards(...guards); guards.forEach(item => this.graphInspector.insertOrphanedEnhancer({ subtype: 'guard', ref: item, }), ); return this; } public useStaticAssets(options: any): this; public useStaticAssets(path: string, options?: any): this; public useStaticAssets(pathOrOptions: any, options?: any): this { this.httpAdapter.useStaticAssets && this.httpAdapter.useStaticAssets(pathOrOptions, options); return this; } public setBaseViewsDir(path: string | string[]): this { this.httpAdapter.setBaseViewsDir && this.httpAdapter.setBaseViewsDir(path); return this; } public setViewEngine(engineOrOptions: any): this { this.httpAdapter.setViewEngine && this.httpAdapter.setViewEngine(engineOrOptions); return this; } private host(): string | undefined { const address = this.httpServer.address(); if (isString(address)) { return undefined; } return address && address.address; } private getProtocol(): 'http' | 'https' { return this.appOptions && this.appOptions.httpsOptions ? 'https' : 'http'; } private async registerMiddleware(instance: any) { await this.middlewareModule.registerMiddleware( this.middlewareContainer, instance, ); } }
packages/core/nest-application.ts
1
https://github.com/nestjs/nest/commit/20abe1df78159aa6d451898e8470285ed64eabe5
[ 0.0020547425374388695, 0.0003610358398873359, 0.00016343197785317898, 0.0001738644641591236, 0.0004036022291984409 ]
{ "id": 7, "code_window": [ " this.routesMapper,\n", " this.httpAdapter,\n", " );\n", " await instance.configure(middlewareBuilder);\n", "\n", " if (!(middlewareBuilder instanceof MiddlewareBuilder)) {\n", " return;\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " try {\n", " await instance.configure(middlewareBuilder);\n", " } catch (err) {\n", " if (!this.appOptions.preview) {\n", " throw err;\n", " }\n", " const warningMessage =\n", " `Warning! \"${moduleRef.name}\" module exposes a \"configure\" method that throws an exception in the preview mode` +\n", " ` (possibly due to missing dependencies). Note: you can ignore this message, just be aware that some of those conditional middlewares will not be reflected in your graph.`;\n", " this.logger.warn(warningMessage);\n", " }\n" ], "file_path": "packages/core/middleware/middleware-module.ts", "type": "replace", "edit_start_line_idx": 106 }
import { Type } from '../../../common'; import { expect } from 'chai'; import { BadGatewayException, BadRequestException, ConflictException, ForbiddenException, GatewayTimeoutException, GoneException, HttpException, HttpVersionNotSupportedException, ImATeapotException, InternalServerErrorException, MethodNotAllowedException, MisdirectedException, NotAcceptableException, NotFoundException, NotImplementedException, PayloadTooLargeException, PreconditionFailedException, RequestTimeoutException, ServiceUnavailableException, UnauthorizedException, UnprocessableEntityException, UnsupportedMediaTypeException, } from '../../exceptions'; describe('HttpException', () => { describe('getResponse', () => { it('should return a response as a string when input is a string', () => { const message = 'My error message'; expect(new HttpException(message, 404).getResponse()).to.be.eql( 'My error message', ); }); it('should return a response as an object when input is an object', () => { const message = { msg: 'My error message', reason: 'this can be a human readable reason', anything: 'else', }; expect(new HttpException(message, 404).getResponse()).to.be.eql(message); }); it('should return a message from a built-in exception as an object', () => { const message = 'My error message'; expect(new BadRequestException(message).getResponse()).to.be.eql({ statusCode: 400, error: 'Bad Request', message: 'My error message', }); }); it('should return an object even when the message is undefined', () => { expect(new BadRequestException().getResponse()).to.be.eql({ statusCode: 400, message: 'Bad Request', }); }); }); describe('built-in exceptions', () => { describe('getStatus', () => { it('should return given status code', () => { const testCases: [Type<HttpException>, number][] = [ [BadRequestException, 400], [UnauthorizedException, 401], [ForbiddenException, 403], [NotFoundException, 404], [MethodNotAllowedException, 405], [NotAcceptableException, 406], [RequestTimeoutException, 408], [ConflictException, 409], [GoneException, 410], [PreconditionFailedException, 412], [PayloadTooLargeException, 413], [UnsupportedMediaTypeException, 415], [ImATeapotException, 418], [MisdirectedException, 421], [UnprocessableEntityException, 422], [InternalServerErrorException, 500], [NotImplementedException, 501], [BadGatewayException, 502], [ServiceUnavailableException, 503], [GatewayTimeoutException, 504], [HttpVersionNotSupportedException, 505], ]; testCases.forEach(([ExceptionClass, expectedStatus]) => { expect(new ExceptionClass().getStatus()).to.be.eql(expectedStatus); }); }); }); describe('getResponse', () => { it('should return a response with default message and status code', () => { const testCases: [Type<HttpException>, number, string][] = [ [BadRequestException, 400, 'Bad Request'], [UnauthorizedException, 401, 'Unauthorized'], [ForbiddenException, 403, 'Forbidden'], [NotFoundException, 404, 'Not Found'], [MethodNotAllowedException, 405, 'Method Not Allowed'], [NotAcceptableException, 406, 'Not Acceptable'], [RequestTimeoutException, 408, 'Request Timeout'], [ConflictException, 409, 'Conflict'], [GoneException, 410, 'Gone'], [PreconditionFailedException, 412, 'Precondition Failed'], [PayloadTooLargeException, 413, 'Payload Too Large'], [UnsupportedMediaTypeException, 415, 'Unsupported Media Type'], [ImATeapotException, 418, "I'm a teapot"], [MisdirectedException, 421, 'Misdirected'], [UnprocessableEntityException, 422, 'Unprocessable Entity'], [InternalServerErrorException, 500, 'Internal Server Error'], [NotImplementedException, 501, 'Not Implemented'], [BadGatewayException, 502, 'Bad Gateway'], [ServiceUnavailableException, 503, 'Service Unavailable'], [GatewayTimeoutException, 504, 'Gateway Timeout'], [HttpVersionNotSupportedException, 505, 'HTTP Version Not Supported'], ]; testCases.forEach( ([ExceptionClass, expectedStatus, expectedMessage]) => { expect(new ExceptionClass().getResponse()).to.be.eql({ message: expectedMessage, statusCode: expectedStatus, }); }, ); }); it('should return a response with an "error" attribute when description was provided as the "option" object', () => { const badRequestError = new BadRequestException('ErrorMessage', { description: 'Some error description', }); expect(badRequestError.getResponse()).to.be.eql({ message: 'ErrorMessage', error: 'Some error description', statusCode: 400, }); }); }); }); it('should inherit from error', () => { const error = new HttpException('', 400); expect(error instanceof Error).to.be.true; }); describe('when serializing', () => { describe('and "response" parameter is a string', () => { it('should concatenate HttpException with the given message', () => { const responseAsString = 'Some Error'; const error = new HttpException(responseAsString, 400); expect(`${error}`).to.be.eql(`HttpException: ${responseAsString}`); expect(`${error}`.includes('[object Object]')).to.not.be.true; }); }); describe('and "response" parameter is an object', () => { it('should use default message', () => { const responseAsObject = { foo: 'bar' }; const error = new HttpException(responseAsObject, 400); const badRequestError = new BadRequestException(responseAsObject); expect(`${error}`).to.be.eql(`HttpException: Http Exception`); expect(`${badRequestError}`).to.be.eql( `BadRequestException: Bad Request Exception`, ); expect(`${error}`.includes('[object Object]')).to.not.be.true; expect(`${badRequestError}`.includes('[object Object]')).to.not.be.true; }); }); }); describe('createBody', () => { describe('when object has been passed', () => { it('should return expected object', () => { const object = { message: 'test', }; expect(HttpException.createBody(object)).to.be.eql(object); }); }); describe('when string has been passed', () => { it('should return expected object', () => { const error = 'test'; const status = 500; const message = 'error'; expect(HttpException.createBody(message, error, status)).to.be.eql({ error, message, statusCode: status, }); }); }); describe('when nil has been passed', () => { it('should return expected object', () => { const status = 500; const error = 'error'; expect(HttpException.createBody(null, error, status)).to.be.eql({ message: error, statusCode: status, }); }); }); it('should not override pre-defined body if message is array', () => { expect( HttpException.createBody(['a', 'random', 'array'], 'error', 200), ).to.eql({ message: ['a', 'random', 'array'], error: 'error', statusCode: 200, }); }); }); describe('initCause', () => { const errorCause = new Error('An internal error cause'); const customDescription = 'custom description'; it('configures a cause when message is an instance of error', () => { const message = new Error('Some Error'); const error = new HttpException(message, 400); expect(`${error}`).to.be.eql(`HttpException: ${message.message}`); const { cause } = error; expect(cause).to.be.eql(message); }); it('configures a cause when message is a string and the options object is passed', () => { const error = new HttpException(customDescription, 400, { cause: errorCause, }); expect(`${error}`).to.be.eql(`HttpException: ${customDescription}`); const { cause } = error; expect(cause).to.be.eql(errorCause); }); it('configures a cause when using a bult-in exception with options', () => { const builtInErrorClasses = [ BadGatewayException, BadRequestException, ConflictException, ForbiddenException, GatewayTimeoutException, GoneException, HttpVersionNotSupportedException, ImATeapotException, InternalServerErrorException, MethodNotAllowedException, MisdirectedException, NotAcceptableException, NotFoundException, NotImplementedException, PayloadTooLargeException, PreconditionFailedException, RequestTimeoutException, ServiceUnavailableException, UnauthorizedException, UnprocessableEntityException, UnsupportedMediaTypeException, ]; builtInErrorClasses.forEach(ExceptionClass => { const error = new ExceptionClass(customDescription, { cause: errorCause, }); const { cause } = error; expect(cause).to.be.eql(errorCause); }); }); }); });
packages/common/test/exceptions/http.exception.spec.ts
0
https://github.com/nestjs/nest/commit/20abe1df78159aa6d451898e8470285ed64eabe5
[ 0.0001900411443784833, 0.00017169346392620355, 0.000166451238328591, 0.00017128823674283922, 0.000004333195192884887 ]
{ "id": 7, "code_window": [ " this.routesMapper,\n", " this.httpAdapter,\n", " );\n", " await instance.configure(middlewareBuilder);\n", "\n", " if (!(middlewareBuilder instanceof MiddlewareBuilder)) {\n", " return;\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " try {\n", " await instance.configure(middlewareBuilder);\n", " } catch (err) {\n", " if (!this.appOptions.preview) {\n", " throw err;\n", " }\n", " const warningMessage =\n", " `Warning! \"${moduleRef.name}\" module exposes a \"configure\" method that throws an exception in the preview mode` +\n", " ` (possibly due to missing dependencies). Note: you can ignore this message, just be aware that some of those conditional middlewares will not be reflected in your graph.`;\n", " this.logger.warn(warningMessage);\n", " }\n" ], "file_path": "packages/core/middleware/middleware-module.ts", "type": "replace", "edit_start_line_idx": 106 }
import { InjectorDependencyContext } from '../../injector/injector'; import { UNKNOWN_DEPENDENCIES_MESSAGE } from '../messages'; import { RuntimeException } from './runtime.exception'; import { Module } from '../../injector/module'; export class UndefinedDependencyException extends RuntimeException { constructor( type: string, undefinedDependencyContext: InjectorDependencyContext, module?: Module, ) { super( UNKNOWN_DEPENDENCIES_MESSAGE(type, undefinedDependencyContext, module), ); } }
packages/core/errors/exceptions/undefined-dependency.exception.ts
0
https://github.com/nestjs/nest/commit/20abe1df78159aa6d451898e8470285ed64eabe5
[ 0.0001706837210804224, 0.00016837756265886128, 0.00016607140423730016, 0.00016837756265886128, 0.000002306158421561122 ]
{ "id": 7, "code_window": [ " this.routesMapper,\n", " this.httpAdapter,\n", " );\n", " await instance.configure(middlewareBuilder);\n", "\n", " if (!(middlewareBuilder instanceof MiddlewareBuilder)) {\n", " return;\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " try {\n", " await instance.configure(middlewareBuilder);\n", " } catch (err) {\n", " if (!this.appOptions.preview) {\n", " throw err;\n", " }\n", " const warningMessage =\n", " `Warning! \"${moduleRef.name}\" module exposes a \"configure\" method that throws an exception in the preview mode` +\n", " ` (possibly due to missing dependencies). Note: you can ignore this message, just be aware that some of those conditional middlewares will not be reflected in your graph.`;\n", " this.logger.warn(warningMessage);\n", " }\n" ], "file_path": "packages/core/middleware/middleware-module.ts", "type": "replace", "edit_start_line_idx": 106 }
export const MATH_SERVICE = 'MATH_SERVICE';
sample/03-microservices/src/math/math.constants.ts
0
https://github.com/nestjs/nest/commit/20abe1df78159aa6d451898e8470285ed64eabe5
[ 0.00017629354260861874, 0.00017629354260861874, 0.00017629354260861874, 0.00017629354260861874, 0 ]
{ "id": 8, "code_window": [ " this.container,\n", " this.config,\n", " this.injector,\n", " this.httpAdapter,\n", " this.graphInspector,\n", " );\n", " }\n", "\n", " public registerWsModule() {\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " this.appOptions,\n" ], "file_path": "packages/core/nest-application.ts", "type": "add", "edit_start_line_idx": 166 }
import { HttpServer, VersioningType } from '@nestjs/common'; import { RequestMethod } from '@nestjs/common/enums/request-method.enum'; import { MiddlewareConfiguration, NestMiddleware, RouteInfo, } from '@nestjs/common/interfaces/middleware'; import { addLeadingSlash, isUndefined, } from '@nestjs/common/utils/shared.utils'; import { ApplicationConfig } from '../application-config'; import { InvalidMiddlewareException } from '../errors/exceptions/invalid-middleware.exception'; import { RuntimeException } from '../errors/exceptions/runtime.exception'; import { ContextIdFactory } from '../helpers/context-id-factory'; import { ExecutionContextHost } from '../helpers/execution-context-host'; import { STATIC_CONTEXT } from '../injector/constants'; import { NestContainer } from '../injector/container'; import { Injector } from '../injector/injector'; import { InstanceWrapper } from '../injector/instance-wrapper'; import { InstanceToken, Module } from '../injector/module'; import { GraphInspector } from '../inspector/graph-inspector'; import { Entrypoint, MiddlewareEntrypointMetadata, } from '../inspector/interfaces/entrypoint.interface'; import { REQUEST_CONTEXT_ID } from '../router/request/request-constants'; import { RoutePathFactory } from '../router/route-path-factory'; import { RouterExceptionFilters } from '../router/router-exception-filters'; import { RouterProxy } from '../router/router-proxy'; import { isRequestMethodAll, isRouteExcluded } from '../router/utils'; import { MiddlewareBuilder } from './builder'; import { MiddlewareContainer } from './container'; import { MiddlewareResolver } from './resolver'; import { RoutesMapper } from './routes-mapper'; export class MiddlewareModule { private readonly routerProxy = new RouterProxy(); private readonly exceptionFiltersCache = new WeakMap(); private injector: Injector; private routerExceptionFilter: RouterExceptionFilters; private routesMapper: RoutesMapper; private resolver: MiddlewareResolver; private config: ApplicationConfig; private container: NestContainer; private httpAdapter: HttpServer; private graphInspector: GraphInspector; constructor(private readonly routePathFactory: RoutePathFactory) {} public async register( middlewareContainer: MiddlewareContainer, container: NestContainer, config: ApplicationConfig, injector: Injector, httpAdapter: HttpServer, graphInspector: GraphInspector, ) { const appRef = container.getHttpAdapterRef(); this.routerExceptionFilter = new RouterExceptionFilters( container, config, appRef, ); this.routesMapper = new RoutesMapper(container); this.resolver = new MiddlewareResolver(middlewareContainer, injector); this.config = config; this.injector = injector; this.container = container; this.httpAdapter = httpAdapter; this.graphInspector = graphInspector; const modules = container.getModules(); await this.resolveMiddleware(middlewareContainer, modules); } public async resolveMiddleware( middlewareContainer: MiddlewareContainer, modules: Map<string, Module>, ) { const moduleEntries = [...modules.entries()]; const loadMiddlewareConfiguration = async ([moduleName, moduleRef]: [ string, Module, ]) => { await this.loadConfiguration(middlewareContainer, moduleRef, moduleName); await this.resolver.resolveInstances(moduleRef, moduleName); }; await Promise.all(moduleEntries.map(loadMiddlewareConfiguration)); } public async loadConfiguration( middlewareContainer: MiddlewareContainer, moduleRef: Module, moduleKey: string, ) { const { instance } = moduleRef; if (!instance.configure) { return; } const middlewareBuilder = new MiddlewareBuilder( this.routesMapper, this.httpAdapter, ); await instance.configure(middlewareBuilder); if (!(middlewareBuilder instanceof MiddlewareBuilder)) { return; } const config = middlewareBuilder.build(); middlewareContainer.insertConfig(config, moduleKey); } public async registerMiddleware( middlewareContainer: MiddlewareContainer, applicationRef: any, ) { const configs = middlewareContainer.getConfigurations(); const registerAllConfigs = async ( moduleKey: string, middlewareConfig: MiddlewareConfiguration[], ) => { for (const config of middlewareConfig) { await this.registerMiddlewareConfig( middlewareContainer, config, moduleKey, applicationRef, ); } }; const entriesSortedByDistance = [...configs.entries()].sort( ([moduleA], [moduleB]) => { return ( this.container.getModuleByKey(moduleA).distance - this.container.getModuleByKey(moduleB).distance ); }, ); for (const [moduleRef, moduleConfigurations] of entriesSortedByDistance) { await registerAllConfigs(moduleRef, [...moduleConfigurations]); } } public async registerMiddlewareConfig( middlewareContainer: MiddlewareContainer, config: MiddlewareConfiguration, moduleKey: string, applicationRef: any, ) { const { forRoutes } = config; for (const routeInfo of forRoutes) { await this.registerRouteMiddleware( middlewareContainer, routeInfo as RouteInfo, config, moduleKey, applicationRef, ); } } public async registerRouteMiddleware( middlewareContainer: MiddlewareContainer, routeInfo: RouteInfo, config: MiddlewareConfiguration, moduleKey: string, applicationRef: any, ) { const middlewareCollection = [].concat(config.middleware); const moduleRef = this.container.getModuleByKey(moduleKey); for (const metatype of middlewareCollection) { const collection = middlewareContainer.getMiddlewareCollection(moduleKey); const instanceWrapper = collection.get(metatype); if (isUndefined(instanceWrapper)) { throw new RuntimeException(); } if (instanceWrapper.isTransient) { return; } this.graphInspector.insertClassNode( moduleRef, instanceWrapper, 'middleware', ); const middlewareDefinition: Entrypoint<MiddlewareEntrypointMetadata> = { type: 'middleware', methodName: 'use', className: instanceWrapper.name, classNodeId: instanceWrapper.id, metadata: { key: routeInfo.path, path: routeInfo.path, requestMethod: (RequestMethod[routeInfo.method] as keyof typeof RequestMethod) ?? 'ALL', version: routeInfo.version, }, }; this.graphInspector.insertEntrypointDefinition( middlewareDefinition, instanceWrapper.id, ); await this.bindHandler( instanceWrapper, applicationRef, routeInfo, moduleRef, collection, ); } } private async bindHandler( wrapper: InstanceWrapper<NestMiddleware>, applicationRef: HttpServer, routeInfo: RouteInfo, moduleRef: Module, collection: Map<InstanceToken, InstanceWrapper>, ) { const { instance, metatype } = wrapper; if (isUndefined(instance?.use)) { throw new InvalidMiddlewareException(metatype.name); } const isStatic = wrapper.isDependencyTreeStatic(); if (isStatic) { const proxy = await this.createProxy(instance); return this.registerHandler(applicationRef, routeInfo, proxy); } await this.registerHandler( applicationRef, routeInfo, async <TRequest, TResponse>( req: TRequest, res: TResponse, next: () => void, ) => { try { const contextId = ContextIdFactory.getByRequest(req); if (!req[REQUEST_CONTEXT_ID]) { Object.defineProperty(req, REQUEST_CONTEXT_ID, { value: contextId, enumerable: false, writable: false, configurable: false, }); this.container.registerRequestProvider( contextId.getParent ? contextId.payload : req, contextId, ); } const contextInstance = await this.injector.loadPerContext( instance, moduleRef, collection, contextId, ); const proxy = await this.createProxy<TRequest, TResponse>( contextInstance, contextId, ); return proxy(req, res, next); } catch (err) { let exceptionsHandler = this.exceptionFiltersCache.get(instance.use); if (!exceptionsHandler) { exceptionsHandler = this.routerExceptionFilter.create( instance, instance.use, undefined, ); this.exceptionFiltersCache.set(instance.use, exceptionsHandler); } const host = new ExecutionContextHost([req, res, next]); exceptionsHandler.next(err, host); } }, ); } private async createProxy<TRequest = unknown, TResponse = unknown>( instance: NestMiddleware, contextId = STATIC_CONTEXT, ): Promise<(req: TRequest, res: TResponse, next: () => void) => void> { const exceptionsHandler = this.routerExceptionFilter.create( instance, instance.use, undefined, contextId, ); const middleware = instance.use.bind(instance); return this.routerProxy.createProxy(middleware, exceptionsHandler); } private async registerHandler( applicationRef: HttpServer, { path, method, version }: RouteInfo, proxy: <TRequest, TResponse>( req: TRequest, res: TResponse, next: () => void, ) => void, ) { const prefix = this.config.getGlobalPrefix(); const excludedRoutes = this.config.getGlobalPrefixOptions().exclude; if ( (Array.isArray(excludedRoutes) && isRouteExcluded(excludedRoutes, path, method)) || ['*', '/*', '(.*)', '/(.*)'].includes(path) ) { path = addLeadingSlash(path); } else { const basePath = addLeadingSlash(prefix); if (basePath?.endsWith('/') && path?.startsWith('/')) { // strip slash when a wildcard is being used // and global prefix has been set path = path?.slice(1); } path = basePath + path; } const applicationVersioningConfig = this.config.getVersioning(); if (version && applicationVersioningConfig.type === VersioningType.URI) { const versionPrefix = this.routePathFactory.getVersionPrefix( applicationVersioningConfig, ); path = `/${versionPrefix}${version.toString()}${path}`; } const isMethodAll = isRequestMethodAll(method); const requestMethod = RequestMethod[method]; const router = await applicationRef.createMiddlewareFactory(method); router( path, isMethodAll ? proxy : <TRequest, TResponse>( req: TRequest, res: TResponse, next: () => void, ) => { if (applicationRef.getRequestMethod(req) === requestMethod) { return proxy(req, res, next); } return next(); }, ); } }
packages/core/middleware/middleware-module.ts
1
https://github.com/nestjs/nest/commit/20abe1df78159aa6d451898e8470285ed64eabe5
[ 0.013949445448815823, 0.0011523624416440725, 0.00016559354844503105, 0.0001922179653774947, 0.0028500710614025593 ]
{ "id": 8, "code_window": [ " this.container,\n", " this.config,\n", " this.injector,\n", " this.httpAdapter,\n", " this.graphInspector,\n", " );\n", " }\n", "\n", " public registerWsModule() {\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " this.appOptions,\n" ], "file_path": "packages/core/nest-application.ts", "type": "add", "edit_start_line_idx": 166 }
import { Logger } from '@nestjs/common/services/logger.service'; import { loadPackage } from '@nestjs/common/utils/load-package.util'; import { ERROR_EVENT, MESSAGE_EVENT, REDIS_DEFAULT_HOST, REDIS_DEFAULT_PORT, } from '../constants'; import { ReadPacket, RedisOptions, WritePacket } from '../interfaces'; import { ClientProxy } from './client-proxy'; type Redis = any; let redisPackage = {} as any; export class ClientRedis extends ClientProxy { protected readonly logger = new Logger(ClientProxy.name); protected readonly subscriptionsCount = new Map<string, number>(); protected pubClient: Redis; protected subClient: Redis; protected connection: Promise<any>; protected isExplicitlyTerminated = false; constructor(protected readonly options: RedisOptions['options']) { super(); redisPackage = loadPackage('ioredis', ClientRedis.name, () => require('ioredis'), ); this.initializeSerializer(options); this.initializeDeserializer(options); } public getRequestPattern(pattern: string): string { return pattern; } public getReplyPattern(pattern: string): string { return `${pattern}.reply`; } public close() { this.pubClient && this.pubClient.quit(); this.subClient && this.subClient.quit(); this.pubClient = this.subClient = null; this.isExplicitlyTerminated = true; } public async connect(): Promise<any> { if (this.pubClient && this.subClient) { return this.connection; } this.pubClient = this.createClient(); this.subClient = this.createClient(); this.handleError(this.pubClient); this.handleError(this.subClient); this.connection = Promise.all([ this.subClient.connect(), this.pubClient.connect(), ]); await this.connection; this.subClient.on(MESSAGE_EVENT, this.createResponseCallback()); return this.connection; } public createClient(): Redis { return new redisPackage({ host: REDIS_DEFAULT_HOST, port: REDIS_DEFAULT_PORT, ...this.getClientOptions(), lazyConnect: true, }); } public handleError(client: Redis) { client.addListener(ERROR_EVENT, (err: any) => this.logger.error(err)); } public getClientOptions(): Partial<RedisOptions['options']> { const retryStrategy = (times: number) => this.createRetryStrategy(times); return { ...(this.options || {}), retryStrategy, }; } public createRetryStrategy(times: number): undefined | number { if (this.isExplicitlyTerminated) { return undefined; } if ( !this.getOptionsProp(this.options, 'retryAttempts') || times > this.getOptionsProp(this.options, 'retryAttempts') ) { this.logger.error('Retry time exhausted'); return; } return this.getOptionsProp(this.options, 'retryDelay') || 0; } public createResponseCallback(): ( channel: string, buffer: string, ) => Promise<void> { return async (channel: string, buffer: string) => { const packet = JSON.parse(buffer); const { err, response, isDisposed, id } = await this.deserializer.deserialize(packet); const callback = this.routingMap.get(id); if (!callback) { return; } if (isDisposed || err) { return callback({ err, response, isDisposed: true, }); } callback({ err, response, }); }; } protected publish( partialPacket: ReadPacket, callback: (packet: WritePacket) => any, ): () => void { try { const packet = this.assignPacketId(partialPacket); const pattern = this.normalizePattern(partialPacket.pattern); const serializedPacket = this.serializer.serialize(packet); const responseChannel = this.getReplyPattern(pattern); let subscriptionsCount = this.subscriptionsCount.get(responseChannel) || 0; const publishPacket = () => { subscriptionsCount = this.subscriptionsCount.get(responseChannel) || 0; this.subscriptionsCount.set(responseChannel, subscriptionsCount + 1); this.routingMap.set(packet.id, callback); this.pubClient.publish( this.getRequestPattern(pattern), JSON.stringify(serializedPacket), ); }; if (subscriptionsCount <= 0) { this.subClient.subscribe( responseChannel, (err: any) => !err && publishPacket(), ); } else { publishPacket(); } return () => { this.unsubscribeFromChannel(responseChannel); this.routingMap.delete(packet.id); }; } catch (err) { callback({ err }); } } protected dispatchEvent(packet: ReadPacket): Promise<any> { const pattern = this.normalizePattern(packet.pattern); const serializedPacket = this.serializer.serialize(packet); return new Promise<void>((resolve, reject) => this.pubClient.publish(pattern, JSON.stringify(serializedPacket), err => err ? reject(err) : resolve(), ), ); } protected unsubscribeFromChannel(channel: string) { const subscriptionCount = this.subscriptionsCount.get(channel); this.subscriptionsCount.set(channel, subscriptionCount - 1); if (subscriptionCount - 1 <= 0) { this.subClient.unsubscribe(channel); } } }
packages/microservices/client/client-redis.ts
0
https://github.com/nestjs/nest/commit/20abe1df78159aa6d451898e8470285ed64eabe5
[ 0.00017719938477966934, 0.000171813226188533, 0.00016702058201190084, 0.0001718001440167427, 0.0000025496090074739186 ]
{ "id": 8, "code_window": [ " this.container,\n", " this.config,\n", " this.injector,\n", " this.httpAdapter,\n", " this.graphInspector,\n", " );\n", " }\n", "\n", " public registerWsModule() {\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " this.appOptions,\n" ], "file_path": "packages/core/nest-application.ts", "type": "add", "edit_start_line_idx": 166 }
import { SetMetadata } from '../../decorators'; import { CACHE_KEY_METADATA } from '../cache.constants'; /** * Decorator that sets the caching key used to store/retrieve cached items for * Web sockets or Microservice based apps. * * For example: * `@CacheKey('events')` * * @param key string naming the field to be used as a cache key * * @see [Caching](https://docs.nestjs.com/techniques/caching) * * @publicApi */ export const CacheKey = (key: string) => SetMetadata(CACHE_KEY_METADATA, key);
packages/common/cache/decorators/cache-key.decorator.ts
0
https://github.com/nestjs/nest/commit/20abe1df78159aa6d451898e8470285ed64eabe5
[ 0.00017174241656903177, 0.00016924631199799478, 0.00016675022197887301, 0.00016924631199799478, 0.0000024960972950793803 ]
{ "id": 8, "code_window": [ " this.container,\n", " this.config,\n", " this.injector,\n", " this.httpAdapter,\n", " this.graphInspector,\n", " );\n", " }\n", "\n", " public registerWsModule() {\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " this.appOptions,\n" ], "file_path": "packages/core/nest-application.ts", "type": "add", "edit_start_line_idx": 166 }
import { expect } from 'chai'; import * as sinon from 'sinon'; import { ClientTCP } from '../../client/client-tcp'; import { ERROR_EVENT } from '../../constants'; describe('ClientTCP', () => { let client: ClientTCP; let socket; let createSocketStub: sinon.SinonStub; beforeEach(() => { client = new ClientTCP({}); const onFakeCallback = (event, callback) => event !== 'error' && event !== 'close' && callback({}); socket = { connect: sinon.stub(), on: sinon.stub().callsFake(onFakeCallback), netSocket: { addListener: sinon.stub().callsFake(onFakeCallback), removeListener: sinon.spy(), once: sinon.stub().callsFake(onFakeCallback), }, sendMessage: sinon.spy(), end: sinon.spy(), }; createSocketStub = sinon .stub(client, 'createSocket') .callsFake(() => socket); }); afterEach(() => { createSocketStub.restore(); }); describe('publish', () => { let msg; beforeEach(() => { msg = { test: 3 }; client['isConnected'] = true; client['socket'] = socket; }); it('should send message', () => { client['publish'](msg, () => ({})); }); describe('on dispose', () => { it('should remove listener from routing map', () => { client['publish'](msg, () => ({}))(); expect(client['routingMap'].size).to.be.eq(0); }); }); describe('on error', () => { it('should call callback', () => { const callback = sinon.spy(); sinon.stub(client, 'assignPacketId' as any).callsFake(() => { throw new Error(); }); client['publish'](msg, callback); expect(callback.called).to.be.true; expect(callback.getCall(0).args[0].err).to.be.instanceof(Error); }); }); }); describe('handleResponse', () => { let callback; const id = '1'; describe('when disposed', () => { beforeEach(async () => { callback = sinon.spy(); client['routingMap'].set(id, callback); await client.handleResponse({ id, isDisposed: true }); }); it('should emit disposed callback', () => { expect(callback.called).to.be.true; expect( callback.calledWith({ err: undefined, response: undefined, isDisposed: true, }), ).to.be.true; }); }); describe('when not disposed', () => { let buffer; beforeEach(async () => { buffer = { id, err: undefined, response: 'res' }; callback = sinon.spy(); client['routingMap'].set(id, callback); await client.handleResponse(buffer); }); it('should not end server', () => { expect(socket.end.called).to.be.false; }); it('should call callback with error and response data', () => { expect(callback.called).to.be.true; expect( callback.calledWith({ err: buffer.err, response: buffer.response, }), ).to.be.true; }); }); }); describe('connect', () => { let bindEventsSpy: sinon.SinonSpy; let connect$Stub: sinon.SinonStub; beforeEach(async () => { bindEventsSpy = sinon.spy(client, 'bindEvents'); }); afterEach(() => { bindEventsSpy.restore(); }); describe('when is not connected', () => { beforeEach(async () => { client['isConnected'] = false; const source = { subscribe: ({ complete }) => complete(), pipe: () => source, }; connect$Stub = sinon .stub(client, 'connect$' as any) .callsFake(() => source); await client.connect(); }); afterEach(() => { connect$Stub.restore(); }); it('should call "bindEvents" once', async () => { expect(bindEventsSpy.called).to.be.true; }); it('should call "createSocket" once', async () => { expect(createSocketStub.called).to.be.true; }); it('should call "connect$" once', async () => { expect(connect$Stub.called).to.be.true; }); it('should listen on messages', () => { expect(socket.on.called).to.be.true; }); }); describe('when is connected', () => { beforeEach(() => { client['isConnected'] = true; }); it('should not call "createSocket"', () => { expect(createSocketStub.called).to.be.false; }); it('should not call "bindEvents"', () => { expect(bindEventsSpy.called).to.be.false; }); }); }); describe('close', () => { let routingMap; let callback; beforeEach(() => { routingMap = new Map<string, Function>(); callback = sinon.spy(); routingMap.set('some id', callback); (client as any).socket = socket; (client as any).isConnected = true; (client as any).routingMap = routingMap; client.close(); }); it('should end() socket', () => { expect(socket.end.called).to.be.true; }); it('should set "isConnected" to false', () => { expect((client as any).isConnected).to.be.false; }); it('should set "socket" to null', () => { expect((client as any).socket).to.be.null; }); it('should clear out the routing map', () => { expect((client as any).routingMap.size).to.be.eq(0); }); it('should call callbacks', () => { expect( callback.calledWith({ err: sinon.match({ message: 'Connection closed' }), }), ).to.be.true; }); }); describe('bindEvents', () => { it('should bind error event handler', () => { const callback = sinon.stub().callsFake((_, fn) => fn({ code: 'test' })); const emitter = { on: callback, }; client.bindEvents(emitter as any); expect(callback.getCall(0).args[0]).to.be.eql(ERROR_EVENT); }); }); describe('dispatchEvent', () => { const msg = { pattern: 'pattern', data: 'data' }; let sendMessageStub: sinon.SinonStub, internalSocket; beforeEach(() => { sendMessageStub = sinon.stub(); internalSocket = { sendMessage: sendMessageStub, }; (client as any).socket = internalSocket; }); it('should publish packet', async () => { await client['dispatchEvent'](msg); expect(sendMessageStub.called).to.be.true; }); }); });
packages/microservices/test/client/client-tcp.spec.ts
0
https://github.com/nestjs/nest/commit/20abe1df78159aa6d451898e8470285ed64eabe5
[ 0.00017600483261048794, 0.00017423098324798048, 0.0001725378242554143, 0.00017423147801309824, 9.835259788815165e-7 ]
{ "id": 0, "code_window": [ " link = 'link',\n", " code = 'code',\n", " underline = 'underline',\n", "}\n", "\n", "type Roles = OrgUserRoles | ProjectRoles | WorkspaceUserRoles;\n", "\n", "type RolesObj = Partial<Record<Roles, boolean>>;\n", "\n", "type RolesType = RolesObj | string[] | string;\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "export enum NcDataErrorCodes {\n", " NC_ERR_MM_MODEL_NOT_FOUND = 'NC_ERR_MM_MODEL_NOT_FOUND',\n", "}\n", "\n" ], "file_path": "packages/nocodb-sdk/src/lib/globals.ts", "type": "add", "edit_start_line_idx": 125 }
import { RelationTypes } from 'nocodb-sdk'; import type { BaseModelSqlv2 } from '~/db/BaseModelSqlv2'; import type { LinksColumn } from '~/models'; import type { RollupColumn } from '~/models'; import type { XKnex } from '~/db/CustomKnex'; import type { LinkToAnotherRecordColumn } from '~/models'; import type { Knex } from 'knex'; export default async function ({ baseModelSqlv2, knex, // tn, // column, alias, columnOptions, }: { baseModelSqlv2: BaseModelSqlv2; knex: XKnex; alias?: string; columnOptions: RollupColumn | LinksColumn; }): Promise<{ builder: Knex.QueryBuilder | any }> { const relationColumn = await columnOptions.getRelationColumn(); const relationColumnOption: LinkToAnotherRecordColumn = (await relationColumn.getColOptions()) as LinkToAnotherRecordColumn; const rollupColumn = await columnOptions.getRollupColumn(); const childCol = await relationColumnOption.getChildColumn(); const childModel = await childCol?.getModel(); const parentCol = await relationColumnOption.getParentColumn(); const parentModel = await parentCol?.getModel(); const refTableAlias = `__nc_rollup`; switch (relationColumnOption.type) { case RelationTypes.HAS_MANY: return { builder: knex( knex.raw(`?? as ??`, [ baseModelSqlv2.getTnPath(childModel?.table_name), refTableAlias, ]), ) [columnOptions.rollup_function as string]?.( knex.ref(`${refTableAlias}.${rollupColumn.column_name}`), ) .where( knex.ref( `${alias || baseModelSqlv2.getTnPath(parentModel.table_name)}.${ parentCol.column_name }`, ), '=', knex.ref(`${refTableAlias}.${childCol.column_name}`), ), }; case RelationTypes.MANY_TO_MANY: { const mmModel = await relationColumnOption.getMMModel(); const mmChildCol = await relationColumnOption.getMMChildColumn(); const mmParentCol = await relationColumnOption.getMMParentColumn(); return { builder: knex( knex.raw(`?? as ??`, [ baseModelSqlv2.getTnPath(parentModel?.table_name), refTableAlias, ]), ) [columnOptions.rollup_function as string]?.( knex.ref(`${refTableAlias}.${rollupColumn.column_name}`), ) .innerJoin( baseModelSqlv2.getTnPath(mmModel.table_name), knex.ref( `${baseModelSqlv2.getTnPath(mmModel.table_name)}.${ mmParentCol.column_name }`, ), '=', knex.ref(`${refTableAlias}.${parentCol.column_name}`), ) .where( knex.ref( `${baseModelSqlv2.getTnPath(mmModel.table_name)}.${ mmChildCol.column_name }`, ), '=', knex.ref( `${alias || baseModelSqlv2.getTnPath(childModel.table_name)}.${ childCol.column_name }`, ), ), }; } default: throw Error(`Unsupported relation type '${relationColumnOption.type}'`); } }
packages/nocodb/src/db/genRollupSelectv2.ts
1
https://github.com/nocodb/nocodb/commit/04e6529ce3bb892780da3c3268f75bc37d8fdbdb
[ 0.00018096872372552752, 0.0001764367480063811, 0.00017313589341938496, 0.0001763222535373643, 0.0000022317024104268057 ]
{ "id": 0, "code_window": [ " link = 'link',\n", " code = 'code',\n", " underline = 'underline',\n", "}\n", "\n", "type Roles = OrgUserRoles | ProjectRoles | WorkspaceUserRoles;\n", "\n", "type RolesObj = Partial<Record<Roles, boolean>>;\n", "\n", "type RolesType = RolesObj | string[] | string;\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "export enum NcDataErrorCodes {\n", " NC_ERR_MM_MODEL_NOT_FOUND = 'NC_ERR_MM_MODEL_NOT_FOUND',\n", "}\n", "\n" ], "file_path": "packages/nocodb-sdk/src/lib/globals.ts", "type": "add", "edit_start_line_idx": 125 }
<script setup lang="ts"> import { IsPublicInj, inject, ref, storeToRefs, useGlobal, useSharedView, useSmartsheetStoreOrThrow, useViewsStore, } from '#imports' const { isGrid, isGallery, isKanban, isMap } = useSmartsheetStoreOrThrow() const isPublic = inject(IsPublicInj, ref(false)) const { isViewsLoading } = storeToRefs(useViewsStore()) const { isMobileMode } = useGlobal() const { allowCSVDownload } = useSharedView() </script> <template> <div class="nc-table-toolbar py-1 px-2.25 xs:(px-1) flex gap-2 items-center border-b border-gray-200 overflow-hidden xs:(min-h-14) max-h-[var(--topbar-height)] min-h-[var(--topbar-height)] z-7" > <template v-if="isViewsLoading"> <a-skeleton-input :active="true" class="!w-44 !h-4 ml-2 !rounded overflow-hidden" /> </template> <template v-else> <LazySmartsheetToolbarMappedBy v-if="isMap" /> <LazySmartsheetToolbarFieldsMenu v-if="isGrid || isGallery || isKanban || isMap" :show-system-fields="false" /> <LazySmartsheetToolbarStackedBy v-if="isKanban" /> <LazySmartsheetToolbarColumnFilterMenu v-if="isGrid || isGallery || isKanban || isMap" /> <LazySmartsheetToolbarGroupByMenu v-if="isGrid" /> <LazySmartsheetToolbarSortListMenu v-if="isGrid || isGallery || isKanban" /> <template v-if="!isMobileMode"> <LazySmartsheetToolbarRowHeight v-if="isGrid" /> <!-- <LazySmartsheetToolbarQrScannerButton v-if="isMobileMode && (isGrid || isKanban || isGallery)" /> --> <LazySmartsheetToolbarExport v-if="isPublic && allowCSVDownload" /> <div class="flex-1" /> </template> <LazySmartsheetToolbarSearchData v-if="isGrid || isGallery || isKanban" :class="{ 'shrink': !isMobileMode, 'w-full': isMobileMode, }" /> </template> </div> </template> <style scoped> .nc-table-toolbar-mobile { @apply flex-wrap h-auto py-2; } </style>
packages/nc-gui/components/smartsheet/Toolbar.vue
0
https://github.com/nocodb/nocodb/commit/04e6529ce3bb892780da3c3268f75bc37d8fdbdb
[ 0.00017840885266195983, 0.000175598674104549, 0.00017058545199688524, 0.00017609010683372617, 0.0000025048291263374267 ]
{ "id": 0, "code_window": [ " link = 'link',\n", " code = 'code',\n", " underline = 'underline',\n", "}\n", "\n", "type Roles = OrgUserRoles | ProjectRoles | WorkspaceUserRoles;\n", "\n", "type RolesObj = Partial<Record<Roles, boolean>>;\n", "\n", "type RolesType = RolesObj | string[] | string;\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "export enum NcDataErrorCodes {\n", " NC_ERR_MM_MODEL_NOT_FOUND = 'NC_ERR_MM_MODEL_NOT_FOUND',\n", "}\n", "\n" ], "file_path": "packages/nocodb-sdk/src/lib/globals.ts", "type": "add", "edit_start_line_idx": 125 }
import type { Knex } from 'knex'; const up = async (knex: Knex) => { await knex.schema.alterTable('nc_shared_views', (table) => { table.dropColumns('view_name'); }); }; const down = async (knex) => { await knex.schema.alterTable('nc_shared_views', (table) => { table.integer('view_name'); }); }; export { up, down };
packages/nocodb/src/meta/migrations/v1/nc_006_alter_nc_shared_views.ts
0
https://github.com/nocodb/nocodb/commit/04e6529ce3bb892780da3c3268f75bc37d8fdbdb
[ 0.00017838827625382692, 0.00017788952391128987, 0.00017739077156875283, 0.00017788952391128987, 4.987523425370455e-7 ]
{ "id": 0, "code_window": [ " link = 'link',\n", " code = 'code',\n", " underline = 'underline',\n", "}\n", "\n", "type Roles = OrgUserRoles | ProjectRoles | WorkspaceUserRoles;\n", "\n", "type RolesObj = Partial<Record<Roles, boolean>>;\n", "\n", "type RolesType = RolesObj | string[] | string;\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "export enum NcDataErrorCodes {\n", " NC_ERR_MM_MODEL_NOT_FOUND = 'NC_ERR_MM_MODEL_NOT_FOUND',\n", "}\n", "\n" ], "file_path": "packages/nocodb-sdk/src/lib/globals.ts", "type": "add", "edit_start_line_idx": 125 }
import { expect, test } from '@playwright/test'; import { Api, TableListType, TableType } from 'nocodb-sdk'; import { DashboardPage } from '../../../pages/Dashboard'; import { deepCompare } from '../../../tests/utils/objectCompareUtil'; import setup, { unsetup } from '../../../setup'; import { BaseInfoApiUtil, TableInfo } from '../../../tests/utils/baseInfoApiUtil'; import { isEE } from '../../../setup/db'; import { AuditPage } from '../../../pages/Dashboard/ProjectView/Audit'; test.describe('Table Operations', () => { let dashboard: DashboardPage, audit: AuditPage; let context: any; test.beforeEach(async ({ page }) => { context = await setup({ page, isEmptyProject: false }); dashboard = new DashboardPage(page, context.base); audit = dashboard.baseView.dataSources.audit; }); test.afterEach(async () => { await unsetup(context); }); test('Create, and delete table, verify in audit tab, rename City table, update icon and reorder tables', async () => { await dashboard.treeView.createTable({ title: 'tablex', baseTitle: context.base.title }); await dashboard.treeView.verifyTable({ title: 'tablex' }); await dashboard.treeView.deleteTable({ title: 'tablex' }); await dashboard.treeView.verifyTable({ title: 'tablex', exists: false }); if (!isEE()) { // Audit logs in clickhouse; locally wont be accessible await dashboard.treeView.openProject({ title: context.base.title, context }); await dashboard.baseView.tab_dataSources.click(); await dashboard.baseView.dataSources.openAudit({ rowIndex: 0 }); await audit.verifyRow({ index: 0, opType: 'TABLE', opSubtype: 'DELETE', user: `user-${process.env.TEST_PARALLEL_INDEX}@nocodb.com`, }); await audit.verifyRow({ index: 1, opType: 'TABLE', opSubtype: 'CREATE', user: `user-${process.env.TEST_PARALLEL_INDEX}@nocodb.com`, }); await audit.close(); } await dashboard.treeView.renameTable({ title: 'City', newTitle: 'Cityx' }); await dashboard.treeView.verifyTable({ title: 'Cityx' }); await dashboard.treeView.focusTable({ title: 'Actor' }); await dashboard.treeView.verifyTable({ title: 'Actor', index: 0 }); await dashboard.treeView.reorderTables({ sourceTable: 'Actor', destinationTable: 'Address', }); await dashboard.treeView.verifyTable({ title: 'Address', index: 0 }); // verify table icon customization await dashboard.treeView.openTable({ title: 'Address' }); await dashboard.treeView.changeTableIcon({ title: 'Address', icon: 'american-football', iconDisplay: '🏈' }); await dashboard.treeView.verifyTabIcon({ title: 'Address', icon: 'american-football', iconDisplay: '🏈' }); }); test.skip('duplicate_table', async () => { const orginalTableName = 'Actor'; const dupTableName = 'Actor copy'; // verify table icon customization await dashboard.treeView.duplicateTable(orginalTableName, true, true); await dashboard.treeView.verifyTable({ title: dupTableName }); // let baseInfoApiUtil: BaseInfoApiUtil = new BaseInfoApiUtil(context.token); // let originalTable: Promise<TableInfo> = baseInfoApiUtil.extractTableInfo(context.base_id, 'Address'); // let duplicateTable: Promise<TableInfo> = await this.api.dbTable.list(baseId);.extractTableInfo(context.base_id, 'Address copy'); const api: Api<any> = new Api({ baseURL: `http://localhost:8080/`, headers: { 'xc-auth': context.token, }, }); const tables: TableListType = await api.dbTable.list(context.base.id); const originalTable: TableType = tables.list.filter(t => t.title === orginalTableName)[0]; const duplicateTable: TableType = tables.list.filter(t => t.title === dupTableName)[0]; expect( deepCompare( originalTable, duplicateTable, undefined, new Set(['.id', '.table_name', '.title', '.order', '.created_at', '.updated_at']) ) ).toBeTruthy(); // check individual field values where values does not match as per design }); test.skip('duplicate_table_with_no_data_views', async () => { const originalTableName = 'Actor'; const dupTableName = 'Actor copy'; // verify table icon customization await dashboard.treeView.duplicateTable(originalTableName, false, false); await dashboard.treeView.verifyTable({ title: dupTableName }); // let baseInfoApiUtil: BaseInfoApiUtil = new BaseInfoApiUtil(context.token); // let originalTable: Promise<TableInfo> = baseInfoApiUtil.extractTableInfo(context.base_id, 'Address'); // let duplicateTable: Promise<TableInfo> = await this.api.dbTable.list(baseId);.extractTableInfo(context.base_id, 'Address copy'); const api: Api<any> = new Api({ baseURL: `http://localhost:8080/`, headers: { 'xc-auth': context.token, }, }); const tables: TableListType = await api.dbTable.list(context.base.id); const originalTable: TableType = tables.list.filter(t => t.title === originalTableName)[0]; const duplicateTable: TableType = tables.list.filter(t => t.title === dupTableName)[0]; const p: BaseInfoApiUtil = new BaseInfoApiUtil(context.token); const originalTableInfo: TableInfo = await p.extractTableInfo(originalTable, context.base.id); const duplicateTableInfo: TableInfo = await p.extractTableInfo(duplicateTable, context.base.id); expect( deepCompare( originalTableInfo, duplicateTableInfo, new Set(['created_at']), new Set([ '.table.id', '.table.table_name', '.table.title', '.table.order', '.table.created_at', '.table.updated_at', '.views.0.view.ptn', '.views.0.view._ptn', '.views.0.view.ptn._ptn', '.views.0.view.ptn._ptn.ptype.tn', '.views.0.view.tn', '.views.0.view._tn', '.views.0.view.id', '.views.0.view.view.fk_view_id', '.views.0.view.view.updated_at', '.views.0.view.fk_model_id', '.views.0.view.title', '.views.0.view.updated_at', '.views.0.view.fk_view_id', // Mismatch length key: '.firstPageData.list', '.firstPageData.pageInfo', '.views.0.firstPageData', ]) ) ).toBeTruthy(); }); // check individual field values where values does not match as per design });
tests/playwright/tests/db/general/tableOperations.spec.ts
0
https://github.com/nocodb/nocodb/commit/04e6529ce3bb892780da3c3268f75bc37d8fdbdb
[ 0.0001826020161388442, 0.0001773838303051889, 0.00017197855049744248, 0.00017711418331600726, 0.0000024735422812227625 ]
{ "id": 1, "code_window": [ " isVirtualCol,\n", " isLinksOrLTAR,\n", " isCreatedOrLastModifiedTimeCol,\n", " isCreatedOrLastModifiedByCol,\n", " isMMSystemCol\n", "} from '~/lib/UITypes';\n", "export { default as CustomAPI, FileType } from '~/lib/CustomAPI';\n", "export { default as TemplateGenerator } from '~/lib/TemplateGenerator';\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " isMMSystemCol,\n" ], "file_path": "packages/nocodb-sdk/src/lib/index.ts", "type": "replace", "edit_start_line_idx": 18 }
import { RelationTypes } from 'nocodb-sdk'; import type { BaseModelSqlv2 } from '~/db/BaseModelSqlv2'; import type { LinksColumn } from '~/models'; import type { RollupColumn } from '~/models'; import type { XKnex } from '~/db/CustomKnex'; import type { LinkToAnotherRecordColumn } from '~/models'; import type { Knex } from 'knex'; export default async function ({ baseModelSqlv2, knex, // tn, // column, alias, columnOptions, }: { baseModelSqlv2: BaseModelSqlv2; knex: XKnex; alias?: string; columnOptions: RollupColumn | LinksColumn; }): Promise<{ builder: Knex.QueryBuilder | any }> { const relationColumn = await columnOptions.getRelationColumn(); const relationColumnOption: LinkToAnotherRecordColumn = (await relationColumn.getColOptions()) as LinkToAnotherRecordColumn; const rollupColumn = await columnOptions.getRollupColumn(); const childCol = await relationColumnOption.getChildColumn(); const childModel = await childCol?.getModel(); const parentCol = await relationColumnOption.getParentColumn(); const parentModel = await parentCol?.getModel(); const refTableAlias = `__nc_rollup`; switch (relationColumnOption.type) { case RelationTypes.HAS_MANY: return { builder: knex( knex.raw(`?? as ??`, [ baseModelSqlv2.getTnPath(childModel?.table_name), refTableAlias, ]), ) [columnOptions.rollup_function as string]?.( knex.ref(`${refTableAlias}.${rollupColumn.column_name}`), ) .where( knex.ref( `${alias || baseModelSqlv2.getTnPath(parentModel.table_name)}.${ parentCol.column_name }`, ), '=', knex.ref(`${refTableAlias}.${childCol.column_name}`), ), }; case RelationTypes.MANY_TO_MANY: { const mmModel = await relationColumnOption.getMMModel(); const mmChildCol = await relationColumnOption.getMMChildColumn(); const mmParentCol = await relationColumnOption.getMMParentColumn(); return { builder: knex( knex.raw(`?? as ??`, [ baseModelSqlv2.getTnPath(parentModel?.table_name), refTableAlias, ]), ) [columnOptions.rollup_function as string]?.( knex.ref(`${refTableAlias}.${rollupColumn.column_name}`), ) .innerJoin( baseModelSqlv2.getTnPath(mmModel.table_name), knex.ref( `${baseModelSqlv2.getTnPath(mmModel.table_name)}.${ mmParentCol.column_name }`, ), '=', knex.ref(`${refTableAlias}.${parentCol.column_name}`), ) .where( knex.ref( `${baseModelSqlv2.getTnPath(mmModel.table_name)}.${ mmChildCol.column_name }`, ), '=', knex.ref( `${alias || baseModelSqlv2.getTnPath(childModel.table_name)}.${ childCol.column_name }`, ), ), }; } default: throw Error(`Unsupported relation type '${relationColumnOption.type}'`); } }
packages/nocodb/src/db/genRollupSelectv2.ts
1
https://github.com/nocodb/nocodb/commit/04e6529ce3bb892780da3c3268f75bc37d8fdbdb
[ 0.0001817893353290856, 0.00017177252448163927, 0.00016235094517469406, 0.00017147748440038413, 0.000004878023901255801 ]
{ "id": 1, "code_window": [ " isVirtualCol,\n", " isLinksOrLTAR,\n", " isCreatedOrLastModifiedTimeCol,\n", " isCreatedOrLastModifiedByCol,\n", " isMMSystemCol\n", "} from '~/lib/UITypes';\n", "export { default as CustomAPI, FileType } from '~/lib/CustomAPI';\n", "export { default as TemplateGenerator } from '~/lib/TemplateGenerator';\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " isMMSystemCol,\n" ], "file_path": "packages/nocodb-sdk/src/lib/index.ts", "type": "replace", "edit_start_line_idx": 18 }
import { nanoid } from 'nanoid'; import NcPluginMgrv2 from '~/helpers/NcPluginMgrv2'; import Noco from '~/Noco'; import NocoCache from '~/cache/NocoCache'; import { CacheGetType, CacheScope } from '~/utils/globals'; function roundExpiry(date) { const msInHour = 10 * 60 * 1000; return new Date(Math.ceil(date.getTime() / msInHour) * msInHour); } const DEFAULT_EXPIRE_SECONDS = isNaN( parseInt(process.env.NC_ATTACHMENT_EXPIRE_SECONDS), ) ? 2 * 60 * 60 : parseInt(process.env.NC_ATTACHMENT_EXPIRE_SECONDS); export default class PresignedUrl { path: string; url: string; expires_at: string; constructor(data: Partial<PresignedUrl>) { Object.assign(this, data); } private static async add(param: { path: string; url: string; expires_at: Date; expiresInSeconds?: number; }) { const { path, url, expires_at, expiresInSeconds = DEFAULT_EXPIRE_SECONDS, } = param; await NocoCache.setExpiring( `${CacheScope.PRESIGNED_URL}:path:${path}`, { path, url, expires_at, }, expiresInSeconds, ); await NocoCache.setExpiring( `${CacheScope.PRESIGNED_URL}:url:${decodeURIComponent(url)}`, { path, url, expires_at, }, expiresInSeconds, ); } private static async delete(param: { path: string; url: string }) { const { path, url } = param; await NocoCache.del(`${CacheScope.PRESIGNED_URL}:path:${path}`); await NocoCache.del(`${CacheScope.PRESIGNED_URL}:url:${url}`); } public static async getPath(url: string, _ncMeta = Noco.ncMeta) { const urlData = url && (await NocoCache.get( `${CacheScope.PRESIGNED_URL}:url:${url}`, CacheGetType.TYPE_OBJECT, )); if (!urlData) { return null; } // if present, check if the expiry date is greater than now if ( urlData && new Date(urlData.expires_at).getTime() < new Date().getTime() ) { // if not, delete the url await this.delete({ path: urlData.path, url: urlData.url }); return null; } return urlData?.path; } public static async getSignedUrl( param: { path: string; expireSeconds?: number; s3?: boolean; }, _ncMeta = Noco.ncMeta, ) { const { path, expireSeconds = DEFAULT_EXPIRE_SECONDS, s3 = false } = param; const expireAt = roundExpiry( new Date(new Date().getTime() + expireSeconds * 1000), ); // at least expireSeconds from now // calculate the expiry time in seconds considering rounding const expiresInSeconds = Math.ceil( (expireAt.getTime() - new Date().getTime()) / 1000, ); let tempUrl; const url = await NocoCache.get( `${CacheScope.PRESIGNED_URL}:path:${path}`, CacheGetType.TYPE_OBJECT, ); if (url) { // if present, check if the expiry date is greater than now if (new Date(url.expires_at).getTime() > new Date().getTime()) { // if greater, return the url return url.url; } else { // if not, delete the url await this.delete({ path: url.path, url: url.url }); } } if (s3) { // if not present, create a new url const storageAdapter = await NcPluginMgrv2.storageAdapter(); tempUrl = await (storageAdapter as any).getSignedUrl( path, expiresInSeconds, ); await this.add({ path: path, url: tempUrl, expires_at: expireAt, expiresInSeconds, }); } else { // if not present, create a new url tempUrl = `dltemp/${nanoid(16)}/${expireAt.getTime()}/${path}`; await this.add({ path: path, url: tempUrl, expires_at: expireAt, expiresInSeconds, }); } // return the url return tempUrl; } }
packages/nocodb/src/models/PresignedUrl.ts
0
https://github.com/nocodb/nocodb/commit/04e6529ce3bb892780da3c3268f75bc37d8fdbdb
[ 0.0005029113963246346, 0.0001932194863911718, 0.00016614774358458817, 0.0001734318648232147, 0.00007999972876859829 ]
{ "id": 1, "code_window": [ " isVirtualCol,\n", " isLinksOrLTAR,\n", " isCreatedOrLastModifiedTimeCol,\n", " isCreatedOrLastModifiedByCol,\n", " isMMSystemCol\n", "} from '~/lib/UITypes';\n", "export { default as CustomAPI, FileType } from '~/lib/CustomAPI';\n", "export { default as TemplateGenerator } from '~/lib/TemplateGenerator';\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " isMMSystemCol,\n" ], "file_path": "packages/nocodb-sdk/src/lib/index.ts", "type": "replace", "edit_start_line_idx": 18 }
import { SettingsPage } from '.'; import { defaultBaseName } from '../../../constants'; import BasePage from '../../Base'; import { AclPage } from './Acl'; import { SettingsErdPage } from './Erd'; import { MetaDataPage } from '../ProjectView/Metadata'; export class DataSourcesPage extends BasePage { private readonly settings: SettingsPage; readonly erd: SettingsErdPage; readonly acl: AclPage; readonly metaData: MetaDataPage; constructor(settings: SettingsPage) { super(settings.rootPage); this.settings = settings; this.erd = new SettingsErdPage(this); this.acl = new AclPage(this); this.metaData = new MetaDataPage(this); } get() { return this.settings.get().locator(`[data-testid="nc-settings-subtab-Data Sources"]`); } async openErd({ dataSourceName }: { dataSourceName: string }) { await this.get().locator('.ds-table-row', { hasText: dataSourceName }).locator('button:has-text("ERD")').click(); } async openAcl({ dataSourceName = defaultBaseName }: { dataSourceName?: string } = {}) { await this.get().locator('.ds-table-row', { hasText: dataSourceName }).locator('button:has-text("UI ACL")').click(); } async openMetaSync({ dataSourceName = defaultBaseName }: { dataSourceName?: string } = {}) { await this.get() .locator('.ds-table-row', { hasText: dataSourceName }) .locator('button:has-text("Sync Metadata")') .click(); } }
tests/playwright/pages/Dashboard/Settings/DataSources.ts
0
https://github.com/nocodb/nocodb/commit/04e6529ce3bb892780da3c3268f75bc37d8fdbdb
[ 0.00017611142538953573, 0.0001746273774188012, 0.00017293592100031674, 0.00017444134573452175, 0.000001142613200499909 ]
{ "id": 1, "code_window": [ " isVirtualCol,\n", " isLinksOrLTAR,\n", " isCreatedOrLastModifiedTimeCol,\n", " isCreatedOrLastModifiedByCol,\n", " isMMSystemCol\n", "} from '~/lib/UITypes';\n", "export { default as CustomAPI, FileType } from '~/lib/CustomAPI';\n", "export { default as TemplateGenerator } from '~/lib/TemplateGenerator';\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " isMMSystemCol,\n" ], "file_path": "packages/nocodb-sdk/src/lib/index.ts", "type": "replace", "edit_start_line_idx": 18 }
import { test } from '@playwright/test'; import { DashboardPage } from '../../../pages/Dashboard'; import setup, { unsetup } from '../../../setup'; test.describe.skip('Super user', () => { let dashboard: DashboardPage; let context: any; test.beforeEach(async ({ page }) => { context = await setup({ page, isEmptyProject: true, isSuperUser: true }); dashboard = new DashboardPage(page, context.base); }); test.afterEach(async () => { await unsetup(context); }); // fix me! test('AppStore access', async () => { await dashboard.closeTab({ title: 'Team & Auth' }); await dashboard.rootPage.goto('/#/account/apps'); await dashboard.rootPage.waitForLoadState('load'); const appPage = await dashboard.rootPage; // Access slack card const card = await appPage.locator('.nc-app-store-card-Slack'); await card.click(); await card.locator('.nc-app-store-card-install').click(); // Configure slack let slackModal = await appPage.locator('.nc-modal-plugin-install'); await slackModal.locator('[placeholder="Channel Name"]').fill('Test Channel'); await slackModal.locator('[placeholder="Webhook URL"]').fill('http://test.com'); await slackModal.locator('button:has-text("Save")').click(); await dashboard.verifyToast({ message: 'Successfully installed' }); // Modify configuration await card.click(); await card.locator('.nc-app-store-card-edit').click(); slackModal = appPage.locator('.nc-modal-plugin-install'); await slackModal.locator('[placeholder="Channel Name"]').fill('Test Channel 2'); await slackModal.locator('[placeholder="Webhook URL"]').fill('http://test2.com'); await slackModal.locator('button:has-text("Save")').click(); await dashboard.verifyToast({ message: 'Successfully installed' }); // Uninstall await card.click(); await card.locator('.nc-app-store-card-reset').click(); slackModal = appPage.locator('.nc-modal-plugin-uninstall'); await slackModal.locator('button:has-text("Confirm")').click(); await dashboard.verifyToast({ message: 'Plugin uninstalled successfully' }); }); });
tests/playwright/tests/db/usersAccounts/rolesSuperUser.spec.ts
0
https://github.com/nocodb/nocodb/commit/04e6529ce3bb892780da3c3268f75bc37d8fdbdb
[ 0.00017796950123738497, 0.0001758801518008113, 0.0001744616311043501, 0.00017557668616063893, 0.0000010900329243668239 ]
{ "id": 2, "code_window": [ "import { RelationTypes } from 'nocodb-sdk';\n", "import type { BaseModelSqlv2 } from '~/db/BaseModelSqlv2';\n", "import type { LinksColumn } from '~/models';\n", "import type { RollupColumn } from '~/models';\n" ], "labels": [ "replace", "keep", "keep", "keep" ], "after_edit": [ "import { NcDataErrorCodes, RelationTypes } from 'nocodb-sdk';\n" ], "file_path": "packages/nocodb/src/db/genRollupSelectv2.ts", "type": "replace", "edit_start_line_idx": 0 }
export * from '~/lib/XcUIBuilder'; export * from '~/lib/XcNotification'; export * from '~/lib/Api'; export * from '~/lib/columnRules'; export * from '~/lib/sqlUi'; export * from '~/lib/globals'; export * from '~/lib/helperFunctions'; export * from '~/lib/enums'; export * from '~/lib/formulaHelpers'; export { default as UITypes, UITypesName, numericUITypes, isNumericCol, isVirtualCol, isLinksOrLTAR, isCreatedOrLastModifiedTimeCol, isCreatedOrLastModifiedByCol, isMMSystemCol } from '~/lib/UITypes'; export { default as CustomAPI, FileType } from '~/lib/CustomAPI'; export { default as TemplateGenerator } from '~/lib/TemplateGenerator'; export * from '~/lib/passwordHelpers'; export * from '~/lib/mergeSwaggerSchema'; export * from '~/lib/dateTimeHelper';
packages/nocodb-sdk/src/lib/index.ts
1
https://github.com/nocodb/nocodb/commit/04e6529ce3bb892780da3c3268f75bc37d8fdbdb
[ 0.00018812826601788402, 0.00017739442409947515, 0.00017188086349051446, 0.00017217414279002696, 0.000007590916993649444 ]
{ "id": 2, "code_window": [ "import { RelationTypes } from 'nocodb-sdk';\n", "import type { BaseModelSqlv2 } from '~/db/BaseModelSqlv2';\n", "import type { LinksColumn } from '~/models';\n", "import type { RollupColumn } from '~/models';\n" ], "labels": [ "replace", "keep", "keep", "keep" ], "after_edit": [ "import { NcDataErrorCodes, RelationTypes } from 'nocodb-sdk';\n" ], "file_path": "packages/nocodb/src/db/genRollupSelectv2.ts", "type": "replace", "edit_start_line_idx": 0 }
<template> <div /> </template>
packages/nc-gui/components/cmd-k/index.vue
0
https://github.com/nocodb/nocodb/commit/04e6529ce3bb892780da3c3268f75bc37d8fdbdb
[ 0.00017428140563424677, 0.00017428140563424677, 0.00017428140563424677, 0.00017428140563424677, 0 ]
{ "id": 2, "code_window": [ "import { RelationTypes } from 'nocodb-sdk';\n", "import type { BaseModelSqlv2 } from '~/db/BaseModelSqlv2';\n", "import type { LinksColumn } from '~/models';\n", "import type { RollupColumn } from '~/models';\n" ], "labels": [ "replace", "keep", "keep", "keep" ], "after_edit": [ "import { NcDataErrorCodes, RelationTypes } from 'nocodb-sdk';\n" ], "file_path": "packages/nocodb/src/db/genRollupSelectv2.ts", "type": "replace", "edit_start_line_idx": 0 }
/* tslint:disable:prefer-const */ import colors from 'colors'; import fs from 'fs'; import glob from 'glob'; import jsonfile from 'jsonfile'; import path from 'path'; import Util from '../util/Util'; import Table from 'cli-table3'; class PermissionsMgr { public static async set(args) { if (Util.isProjectGraphql()) { try { if (args._.length < 4) { console.warn('Invalid arguments for : xc permissions.set'); return; } // @ts-ignore let [_, models, users, ...resolvers] = args._; models = models.split('.'); users = users.split('.'); /* get all policies */ const policiesPath = path.join( process.cwd(), 'server', PermissionsMgr.getPolicyPath(), '**', '*.policy.js' ); glob.sync(policiesPath).forEach(file => { const modelName = path.basename(file).split('.')[0]; if (models.includes(modelName) || models[0] === '$') { const filePermissions = require(file); const roles = this.extractUniqueGqlPolicyRoles(filePermissions); if (users[0] === '$') { for (const [route, rolesObj] of Object.entries(filePermissions)) { if (resolvers[0] === '$=1') { const permObj = roles.reduce((obj, role) => { obj[role] = true; return obj; }, {}); Object.assign(rolesObj, permObj); console.log( `Setting Permissions for model:${modelName} roles:${roles.join( ', ' )} resolver: ${route}` ); } else if (resolvers[0] === '$=0') { const permObj = roles.reduce((obj, role) => { obj[role] = false; return obj; }, {}); Object.assign(rolesObj, permObj); console.log( `Setting Permissions for model:${modelName} roles:${roles.join( ', ' )} resolver: ${route}` ); } else { resolvers.forEach(permission => { const permTuple = permission.split('='); if (route === permTuple[0]) { const permObj = roles.reduce((obj, role) => { const val = !!(permTuple.length === 1 ? 1 : +permTuple[1] || 0); obj[role] = val; return obj; }, {}); Object.assign(rolesObj, permObj); console.log( `Setting Permissions for model:${modelName} roles:${roles.join( ', ' )} , resolver: ${route}` ); } }); } } } else { for (const [route, rolesObj] of Object.entries(filePermissions)) { resolvers.forEach(permission => { const permTuple = permission.split('='); if (route === permTuple[0] || permTuple[0] === '$') { const permObj = users.reduce((obj, role) => { const val = !!(permTuple.length === 1 ? 1 : +permTuple[1] || 0); obj[role] = val; return obj; }, {}); Object.assign(rolesObj, permObj); console.log( `Setting Permissions for model:${modelName} roles:${users} , resolver: ${route}` ); } }); } } const policyFileContent = `module.exports = ${JSON.stringify( filePermissions, null, 2 )};\n`; fs.writeFileSync(file, policyFileContent); } }); } catch (e) { console.error(`Error in xc permissions.set`, e); } } else { try { if (args._.length < 4) { console.warn('Invalid arguments for : xc permissions.set'); return; } // @ts-ignore let [_, models, users, ...permissions] = args._; models = models.split('.'); users = users.split('.'); /* get all policies */ const policiesPath = path.join( process.cwd(), 'server', PermissionsMgr.getPolicyPath(), '**', '*.routes.js' ); glob.sync(policiesPath).forEach(file => { const modelName = path.basename(file).split('.')[0]; if (models.includes(modelName) || models[0] === '$') { const routesList: Route[] = require(file); const roles = this.extractUniqueRoles(routesList); if (users[0] === '$') { for (const route of routesList) { if (permissions[0] === '$=1') { const permObj = roles.reduce((obj, role) => { obj[role] = true; return obj; }, {}); Object.assign(route.acl, permObj); console.log( `Setting Permissions for model:${modelName} roles:${roles.join( ', ' )} method: ${route.type}=true, route: ${route.path}` ); } else if (permissions[0] === '$=0') { const permObj = roles.reduce((obj, role) => { obj[role] = false; return obj; }, {}); Object.assign(route.acl, permObj); console.log( `Setting Permissions for model:${modelName} roles:${roles.join( ', ' )} method: ${route.type}=false, route: ${route.path}` ); } else { permissions.forEach(permission => { const permTuple = permission.split('='); const val = !!(permTuple.length === 1 ? 1 : +permTuple[1] || 0); const permObj = roles.reduce((obj, role) => { obj[role] = val; return obj; }, {}); if (route.type === permTuple[0]) { Object.assign(route.acl, permObj); console.log( `Setting Permissions for model:${modelName} roles:${roles.join( ', ' )} method: ${permTuple[0]}=${val}, route: ${route.path}` ); } }); } } } else { for (const route of routesList) { permissions.forEach(permission => { const permTuple = permission.split('='); const val = !!(permTuple.length === 1 ? 1 : +permTuple[1] || 0); const permObj = users.reduce((obj, role) => { obj[role] = val; return obj; }, {}); if (route.type === permTuple[0]) { Object.assign(route.acl, permObj); console.log( `Setting Permissions for model:${modelName} roles:${users.join( ', ' )} method: ${permTuple[0]}=${val}, route: ${route.path}` ); } else if (permTuple[0] === '*') { Object.assign(route.acl, permObj); console.log( `Setting Permissions for model:${modelName} roles:${users.join( ', ' )} method: ${route.type}=${val}, route: ${route.path}` ); } }); } } const policyFileContent = `module.exports = ${JSON.stringify( routesList, null, 2 )};\n`; fs.writeFileSync(file, policyFileContent); } }); } catch (e) { console.error(`Error in xc permissions.set`, e); } } } public static async get(args) { if (Util.isProjectGraphql()) { try { if (args._.length < 2) { console.warn('Invalid arguments for : xc permissions.get'); return; } let { 1: models } = args._; models = models.split('.'); /* get all policies */ const policiesPath = path.join( process.cwd(), 'server', PermissionsMgr.getPolicyPath(), '**', '*.policy.js' ); // instantiate let rows: any[] = []; let roles: any[] = []; glob.sync(policiesPath).forEach(file => { // let filePermissions = require(file); const modelName = path.basename(file).split('.')[0]; if (models.includes(modelName)) { const filePermissions = require(file); roles = this.extractUniqueGqlPolicyRoles(filePermissions); rows.push([ { colSpan: roles.length + 1, content: colors.green(file), hAlign: 'center' } ]); for (const [route, methods] of Object.entries(filePermissions)) { const row: any[] = [{ content: route, vAlign: 'center' }]; for (const role of roles) { row.push(methods[role] ? colors.green('✔') : colors.red('x')); } rows.push(row); } } }); const table = new Table({ head: ['Route', ...roles] }); table.push(...rows); console.log(table.toString()); } catch (e) { console.error(`Error in xc permissions.get`, e); } } else { try { if (args._.length < 2) { console.warn('Invalid arguments for : xc permissions.get'); return; } let { 1: models } = args._; models = models.split('.'); /* get all policies */ const policiesPath = path.join( process.cwd(), 'server', PermissionsMgr.getPolicyPath(), '**', '*.routes.js' ); // instantiate const table = new Table({ head: ['Route', 'Role', 'GET', 'POST', 'PUT', 'DELETE', 'PATCH'] }); glob .sync(policiesPath) .sort(this.sortFiles) .forEach(file => { const modelName = path.basename(file).split('.')[0]; if (models.includes(modelName)) { const routesList: Route[] = require(file); const groupedRoutes = this.groupRoutes(routesList); // extract unique roles const roles = this.extractUniqueRoles(routesList); table.push([ { colSpan: 7, content: colors.green(file), hAlign: 'center' } ]); for (const [routePath, methods] of Object.entries( groupedRoutes )) { let i = 0; for (const role of roles) { { table.push([ ...(i++ ? [] : [ { content: routePath, rowSpan: roles.length, vAlign: 'center' } ]), role, methods?.get?.acl?.[role] ? colors.green('✔') : colors.red('x'), methods?.post?.acl?.[role] ? colors.green('✔') : colors.red('x'), methods?.put?.acl?.[role] ? colors.green('✔') : colors.red('x'), methods?.delete?.acl?.[role] ? colors.green('✔') : colors.red('x'), methods?.patch?.acl?.[role] ? colors.green('✔') : colors.red('x') ] as any); } } } } }); console.log(table.toString()); } catch (e) { console.error(`Error in xc permissions.get`, e); } } } public static async userAdd(args) { if (Util.isProjectGraphql()) { try { if (args._.length < 2) { console.warn('Invalid arguments for : xc permissions.userAdd'); return; } const { 1: user } = args._; /* get all policies */ const policiesPath = path.join( process.cwd(), 'server', PermissionsMgr.getPolicyPath(), '**', '*.policy.js' ); glob.sync(policiesPath).forEach(file => { const modelName = path.basename(file).split('.')[0]; const filePermissions = require(file); const roles = this.extractUniqueGqlPolicyRoles(filePermissions); if (roles.includes(user)) { console.warn(`${user} already exist in ${modelName} policy`); return; } for (const roles1 of Object.values(filePermissions)) { roles1[user] = true; } console.log( `Adding new role permission for model:${modelName} roles:${user}` ); const policyFileContent = `module.exports = ${JSON.stringify( filePermissions, null, 2 )};\n`; fs.writeFileSync(file, policyFileContent); }); } catch (e) { console.error(`Error in xc permissions.user.add`, e); } } else { try { if (args._.length < 2) { console.warn('Invalid arguments for : xc permissions.userAdd'); return; } const { 1: user } = args._; /* get all policies */ const policiesPath = path.join( process.cwd(), 'server', PermissionsMgr.getPolicyPath(), '**', '*.routes.js' ); glob.sync(policiesPath).forEach(file => { const modelName = path.basename(file).split('.')[0]; const routes: Route[] = require(file); const roles = this.extractUniqueRoles(routes); if (roles.includes(user)) { console.warn(`${user} already exist in ${modelName} policy`); return; } for (const route of routes) { route.acl[user] = true; } console.log( `Adding new role permission for model:${modelName} roles:${user}` ); const policyFileContent = `module.exports = ${JSON.stringify( routes, null, 2 )};\n`; fs.writeFileSync(file, policyFileContent); }); } catch (e) { console.error(`Error in xc permissions.user.add`, e); } } } public static async userDelete(args) { if (Util.isProjectGraphql()) { try { if (args._.length < 2) { console.warn('Invalid arguments for : xc permissions.userAdd'); return; } const { 1: user } = args._; /* get all policies */ const policiesPath = path.join( process.cwd(), 'server', PermissionsMgr.getPolicyPath(), '**', '*.policy.js' ); glob.sync(policiesPath).forEach(file => { const modelName = path.basename(file).split('.')[0]; const filePermissions = require(file); const roles = this.extractUniqueGqlPolicyRoles(filePermissions); if (!roles.includes(user)) { console.warn(`${user} not exist in ${modelName} policy`); return; } for (const roles1 of Object.values(filePermissions)) { delete roles1[user]; } console.log( `Deleting user permission for model:${modelName} roles:${user}` ); const policyFileContent = `module.exports = ${JSON.stringify( filePermissions, null, 2 )};\n`; fs.writeFileSync(file, policyFileContent); }); } catch (e) { console.error(`Error in xc permissions.user.delete`, e); } } else { try { if (args._.length < 2) { console.warn('Invalid arguments for : xc permissions.userAdd'); return; } const { 1: user } = args._; /* get all policies */ const policiesPath = path.join( process.cwd(), 'server', PermissionsMgr.getPolicyPath(), '**', '*.routes.js' ); glob.sync(policiesPath).forEach(file => { const modelName = path.basename(file).split('.')[0]; const routes: Route[] = require(file); const roles = this.extractUniqueRoles(routes); if (!roles.includes(user)) { console.warn(`${user} not exist in ${modelName} policy`); return; } for (const route of routes) { delete route.acl[user]; } console.log( `Deleting user permission for model:${modelName} roles:${user}` ); const policyFileContent = `module.exports = ${JSON.stringify( routes, null, 2 )};\n`; fs.writeFileSync(file, policyFileContent); }); } catch (e) { console.error(`Error in xc permissions.user.delete`, e); } } } public static async userRename(args) { if (Util.isProjectGraphql()) { try { if (args._.length < 3) { console.warn('Invalid arguments for : xc permissions.userAdd'); return; } const { 1: oldUser, 2: newUser } = args._; /* get all policies */ const policiesPath = path.join( process.cwd(), 'server', PermissionsMgr.getPolicyPath(), '**', '*.policy.js' ); glob.sync(policiesPath).forEach(file => { const modelName = path.basename(file).split('.')[0]; const filePermissions = require(file); const roles = this.extractUniqueGqlPolicyRoles(filePermissions); if (!roles.includes(oldUser)) { console.warn(`${oldUser} not exist in ${modelName} policy`); return; } if (roles.includes(newUser)) { console.warn(`${newUser} is already exist in ${modelName} policy`); return; } for (const roles1 of Object.values(filePermissions)) { roles1[newUser] = roles1[oldUser]; delete roles1[oldUser]; } console.log( `Renaming user permission ${oldUser} to ${newUser} for model:${modelName}` ); const policyFileContent = `module.exports = ${JSON.stringify( filePermissions, null, 2 )};\n`; fs.writeFileSync(file, policyFileContent); }); } catch (e) { console.error(`Error in xc permissions.user.delete`, e); } } else { try { if (args._.length < 3) { console.warn('Invalid arguments for : xc permissions.userAdd'); return; } const { 1: oldUser, 2: newUser } = args._; /* get all policies */ const policiesPath = path.join( process.cwd(), 'server', PermissionsMgr.getPolicyPath(), '**', '*.routes.js' ); glob.sync(policiesPath).forEach(file => { const modelName = path.basename(file).split('.')[0]; const routes: Route[] = require(file); const roles = this.extractUniqueRoles(routes); if (!roles.includes(oldUser)) { console.warn(`${oldUser} not exist in ${modelName} policy`); return; } if (roles.includes(newUser)) { console.warn(`${newUser} is already exist in ${modelName} policy`); return; } for (const route of routes) { route.acl[newUser] = route.acl[oldUser]; delete route.acl[oldUser]; } console.log( `Renaming user permission ${oldUser} to ${newUser} for model:${modelName}` ); const policyFileContent = `module.exports = ${JSON.stringify( routes, null, 2 )};\n`; fs.writeFileSync(file, policyFileContent); }); } catch (e) { console.error(`Error in xc permissions.user.delete`, e); } } } public static getPolicyPath() { const projectConfig = jsonfile.readFileSync( path.join(process.cwd(), 'config.xc.json') ); return projectConfig.meta.projectType === 'rest' ? 'routers' : 'resolvers'; } private static extractUniqueGqlPolicyRoles(filePermissions) { return Object.values(filePermissions) .flatMap(roles1 => Object.keys(roles1)) .filter((v, i, arr) => arr.indexOf(v) === i); } private static extractUniqueRoles(routesList: Route[]) { const roles = routesList .flatMap(route => Object.keys(route.acl)) .filter((v, i, arr) => arr.indexOf(v) === i); return roles; } private static groupRoutes(routes: Route[]): GroupedRoutes { const groupedRoutes: GroupedRoutes = {}; for (const route of routes) { groupedRoutes[route.path] = groupedRoutes[route.path] || {}; groupedRoutes[route.path][route.type] = route; } return groupedRoutes; } private static sortFiles(file1: string, file2: string): number { return ( ((file1.indexOf('.bt.') > -1 ? 1 : 0) || (file1.indexOf('.hm.') > -1 ? 2 : 0)) - ((file2.indexOf('.bt.') > -1 ? 1 : 0) || (file2.indexOf('.hm.') > -1 ? 2 : 0)) ); } } export default PermissionsMgr; export interface Route { type: string; path: string; acl: { [key: string]: boolean; }; } type httpMethods = 'get' | 'post' | 'patch' | 'put' | 'delete'; export interface GroupedRoutes { [key: string]: { [key in httpMethods]?: { type: string; path: string; acl: { [key: string]: boolean; }; }; }; }
packages/nc-cli/src/lib/mgr/PermissionsMgr.ts
0
https://github.com/nocodb/nocodb/commit/04e6529ce3bb892780da3c3268f75bc37d8fdbdb
[ 0.00039764956454746425, 0.00017437493079341948, 0.00016393812256865203, 0.00017154029046650976, 0.000025767030820134096 ]
{ "id": 2, "code_window": [ "import { RelationTypes } from 'nocodb-sdk';\n", "import type { BaseModelSqlv2 } from '~/db/BaseModelSqlv2';\n", "import type { LinksColumn } from '~/models';\n", "import type { RollupColumn } from '~/models';\n" ], "labels": [ "replace", "keep", "keep", "keep" ], "after_edit": [ "import { NcDataErrorCodes, RelationTypes } from 'nocodb-sdk';\n" ], "file_path": "packages/nocodb/src/db/genRollupSelectv2.ts", "type": "replace", "edit_start_line_idx": 0 }
########### # Builder ########### FROM node:18.12.1-alpine as builder WORKDIR /usr/src/app # install node-gyp dependencies RUN apk add --no-cache python3 make g++ # install pnpm RUN corepack enable && corepack prepare pnpm@latest --activate # Copy application dependency manifests to the container image. COPY ./package.json ./package.json COPY ./docker/nc-gui/ ./docker/nc-gui/ COPY ./docker/main.js ./docker/index.js COPY ./docker/start-local.sh /usr/src/appEntry/start.sh COPY src/public/ ./docker/public/ # for pnpm to generate a flat node_modules without symlinks # so that modclean could work as expected RUN echo "node-linker=hoisted" > .npmrc # install production dependencies, # reduce node_module size with modclean & removing sqlite deps, # package built code into app.tar.gz & add execute permission to start.sh RUN pnpm uninstall nocodb-sdk RUN pnpm install --prod --shamefully-hoist --reporter=silent \ && pnpm dlx modclean --patterns="default:*" --ignore="nc-lib-gui/**,dayjs/**,express-status-monitor/**,@azure/msal-node/dist/**" --run \ && rm -rf ./node_modules/sqlite3/deps \ && tar -czf ../appEntry/app.tar.gz ./* \ && chmod +x /usr/src/appEntry/start.sh ########## # Runner ########## FROM alpine:3.18 WORKDIR /usr/src/app ENV NC_DOCKER 0.6 ENV NODE_ENV production ENV PORT 8080 ENV NC_TOOL_DIR=/usr/app/data/ RUN apk --update --no-cache add \ nodejs \ tar \ dumb-init \ curl \ jq # Copy packaged production code & main entry file COPY --from=builder /usr/src/appEntry/ /usr/src/appEntry/ EXPOSE 8080 ENTRYPOINT ["/usr/bin/dumb-init", "--"] # Start Nocodb CMD ["/usr/src/appEntry/start.sh"]
packages/nocodb/Dockerfile.local
0
https://github.com/nocodb/nocodb/commit/04e6529ce3bb892780da3c3268f75bc37d8fdbdb
[ 0.00020458121434785426, 0.0001740444713504985, 0.00016296606918331236, 0.00016906901146285236, 0.000014010673112352379 ]
{ "id": 3, "code_window": [ " const mmModel = await relationColumnOption.getMMModel();\n", " const mmChildCol = await relationColumnOption.getMMChildColumn();\n", " const mmParentCol = await relationColumnOption.getMMParentColumn();\n", "\n", " return {\n", " builder: knex(\n", " knex.raw(`?? as ??`, [\n", " baseModelSqlv2.getTnPath(parentModel?.table_name),\n", " refTableAlias,\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " if (!mmModel) {\n", " return this.dbDriver.raw(`?`, [\n", " NcDataErrorCodes.NC_ERR_MM_MODEL_NOT_FOUND,\n", " ]);\n", " }\n", "\n" ], "file_path": "packages/nocodb/src/db/genRollupSelectv2.ts", "type": "add", "edit_start_line_idx": 58 }
export * from '~/lib/XcUIBuilder'; export * from '~/lib/XcNotification'; export * from '~/lib/Api'; export * from '~/lib/columnRules'; export * from '~/lib/sqlUi'; export * from '~/lib/globals'; export * from '~/lib/helperFunctions'; export * from '~/lib/enums'; export * from '~/lib/formulaHelpers'; export { default as UITypes, UITypesName, numericUITypes, isNumericCol, isVirtualCol, isLinksOrLTAR, isCreatedOrLastModifiedTimeCol, isCreatedOrLastModifiedByCol, isMMSystemCol } from '~/lib/UITypes'; export { default as CustomAPI, FileType } from '~/lib/CustomAPI'; export { default as TemplateGenerator } from '~/lib/TemplateGenerator'; export * from '~/lib/passwordHelpers'; export * from '~/lib/mergeSwaggerSchema'; export * from '~/lib/dateTimeHelper';
packages/nocodb-sdk/src/lib/index.ts
1
https://github.com/nocodb/nocodb/commit/04e6529ce3bb892780da3c3268f75bc37d8fdbdb
[ 0.000176129411556758, 0.0001717099075904116, 0.00016485326341353357, 0.0001741470186971128, 0.000004915455065201968 ]
{ "id": 3, "code_window": [ " const mmModel = await relationColumnOption.getMMModel();\n", " const mmChildCol = await relationColumnOption.getMMChildColumn();\n", " const mmParentCol = await relationColumnOption.getMMParentColumn();\n", "\n", " return {\n", " builder: knex(\n", " knex.raw(`?? as ??`, [\n", " baseModelSqlv2.getTnPath(parentModel?.table_name),\n", " refTableAlias,\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " if (!mmModel) {\n", " return this.dbDriver.raw(`?`, [\n", " NcDataErrorCodes.NC_ERR_MM_MODEL_NOT_FOUND,\n", " ]);\n", " }\n", "\n" ], "file_path": "packages/nocodb/src/db/genRollupSelectv2.ts", "type": "add", "edit_start_line_idx": 58 }
<script lang="ts" setup> import type { ViewType } from 'nocodb-sdk' import { ViewTypes } from 'nocodb-sdk' import type { SortableEvent } from 'sortablejs' import Sortable from 'sortablejs' import type { Menu as AntMenu } from 'ant-design-vue' import { extractSdkResponseErrorMsg, isDefaultBase, message, onMounted, parseProp, ref, resolveComponent, useApi, useCommandPalette, useDialog, useNuxtApp, useUndoRedo, viewTypeAlias, watch, } from '#imports' interface Emits { (event: 'openModal', data: { type: ViewTypes; title?: string; copyViewId?: string; groupingFieldColumnId?: string }): void (event: 'deleted'): void } const emits = defineEmits<Emits>() const base = inject(ProjectInj)! const table = inject(SidebarTableInj)! const { isLeftSidebarOpen } = storeToRefs(useSidebarStore()) const { activeTableId } = storeToRefs(useTablesStore()) const { isUIAllowed } = useRoles() const { isMobileMode } = useGlobal() const { $e } = useNuxtApp() const { t } = useI18n() const { viewsByTable, activeView, allRecentViews } = storeToRefs(useViewsStore()) const { navigateToTable } = useTablesStore() const views = computed(() => viewsByTable.value.get(table.value.id!)?.filter((v) => !v.is_default) ?? []) const { api } = useApi() const { refreshCommandPalette } = useCommandPalette() const { addUndo, defineModelScope } = useUndoRedo() const { navigateToView, loadViews, removeFromRecentViews } = useViewsStore() /** Selected view(s) for menu */ const selected = ref<string[]>([]) /** dragging renamable view items */ const dragging = ref(false) const menuRef = ref<typeof AntMenu>() const isMarked = ref<string | false>(false) /** Watch currently active view, so we can mark it in the menu */ watch(activeView, (nextActiveView) => { if (nextActiveView && nextActiveView.id) { selected.value = [nextActiveView.id] } }) /** shortly mark an item after sorting */ function markItem(id: string) { isMarked.value = id setTimeout(() => { isMarked.value = false }, 300) } const isDefaultSource = computed(() => { const source = base.value?.sources?.find((b) => b.id === table.value.source_id) if (!source) return false return isDefaultBase(source) }) /** validate view title */ function validate(view: ViewType) { if (!view.title || view.title.trim().length < 0) { return t('msg.error.viewNameRequired') } if (views.value.some((v) => v.title === view.title && v.id !== view.id)) { return t('msg.error.viewNameDuplicate') } return true } let sortable: Sortable function onSortStart(evt: SortableEvent) { evt.stopImmediatePropagation() evt.preventDefault() dragging.value = true } async function onSortEnd(evt: SortableEvent, undo = false) { if (!undo) { evt.stopImmediatePropagation() evt.preventDefault() dragging.value = false } if (views.value.length < 2) return const { newIndex = 0, oldIndex = 0 } = evt if (newIndex === oldIndex) return if (!undo) { addUndo({ redo: { fn: async () => { const ord = sortable.toArray() const temp = ord.splice(oldIndex, 1) ord.splice(newIndex, 0, temp[0]) sortable.sort(ord) await onSortEnd(evt, true) }, args: [], }, undo: { fn: async () => { const ord = sortable.toArray() const temp = ord.splice(newIndex, 1) ord.splice(oldIndex, 0, temp[0]) sortable.sort(ord) await onSortEnd({ ...evt, oldIndex: newIndex, newIndex: oldIndex }, true) }, args: [], }, scope: defineModelScope({ view: activeView.value }), }) } const children = evt.to.children as unknown as HTMLLIElement[] const previousEl = children[newIndex - 1] const nextEl = children[newIndex + 1] const currentItem = views.value.find((v) => v.id === evt.item.id) if (!currentItem || !currentItem.id) return // set default order value as 0 if item not found const previousItem = (previousEl ? views.value.find((v) => v.id === previousEl.id) ?? { order: 0 } : { order: 0 }) as ViewType const nextItem = (nextEl ? views.value.find((v) => v.id === nextEl.id) : {}) as ViewType let nextOrder: number // set new order value based on the new order of the items if (views.value.length - 1 === newIndex) { nextOrder = parseFloat(String(previousItem.order)) + 1 } else if (newIndex === 0) { nextOrder = parseFloat(String(nextItem.order)) / 2 } else { nextOrder = (parseFloat(String(previousItem.order)) + parseFloat(String(nextItem.order))) / 2 } const _nextOrder = !isNaN(Number(nextOrder)) ? nextOrder : oldIndex currentItem.order = _nextOrder await api.dbView.update(currentItem.id, { order: _nextOrder }) markItem(currentItem.id) $e('a:view:reorder') } const initSortable = (el: HTMLElement) => { if (sortable) sortable.destroy() if (isMobileMode.value) return sortable = new Sortable(el, { // handle: '.nc-drag-icon', ghostClass: 'ghost', onStart: onSortStart, onEnd: onSortEnd, }) } onMounted(() => menuRef.value && initSortable(menuRef.value.$el)) /** Navigate to view by changing url param */ async function changeView(view: ViewType) { await navigateToView({ view, tableId: table.value.id!, baseId: base.value.id!, hardReload: view.type === ViewTypes.FORM && selected.value[0] === view.id, doNotSwitchTab: true, }) if (isMobileMode.value) { isLeftSidebarOpen.value = false } } /** Rename a view */ async function onRename(view: ViewType, originalTitle?: string, undo = false) { try { await api.dbView.update(view.id!, { title: view.title, order: view.order, }) navigateToView({ view, tableId: table.value.id!, baseId: base.value.id!, hardReload: view.type === ViewTypes.FORM && selected.value[0] === view.id, }) refreshCommandPalette() if (!undo) { addUndo({ redo: { fn: (v: ViewType, title: string) => { const tempTitle = v.title v.title = title onRename(v, tempTitle, true) }, args: [view, view.title], }, undo: { fn: (v: ViewType, title: string) => { const tempTitle = v.title v.title = title onRename(v, tempTitle, true) }, args: [view, originalTitle], }, scope: defineModelScope({ view: activeView.value }), }) } // update view name in recent views allRecentViews.value = allRecentViews.value.map((rv) => { if (rv.viewId === view.id && rv.tableID === view.fk_model_id) { rv.viewName = view.title } return rv }) // View renamed successfully // message.success(t('msg.success.viewRenamed')) } catch (e: any) { message.error(await extractSdkResponseErrorMsg(e)) } } /** Open delete modal */ function openDeleteDialog(view: ViewType) { const isOpen = ref(true) const { close } = useDialog(resolveComponent('DlgViewDelete'), { 'modelValue': isOpen, 'view': view, 'onUpdate:modelValue': closeDialog, 'onDeleted': async () => { closeDialog() emits('deleted') removeFromRecentViews({ viewId: view.id, tableId: view.fk_model_id, baseId: base.value.id }) refreshCommandPalette() if (activeView.value?.id === view.id) { navigateToTable({ tableId: table.value.id!, baseId: base.value.id!, }) } await loadViews({ tableId: table.value.id!, force: true, }) const activeNonDefaultViews = viewsByTable.value.get(table.value.id!)?.filter((v) => !v.is_default) ?? [] table.value.meta = { ...(table.value.meta as object), hasNonDefaultViews: activeNonDefaultViews.length > 1, } }, }) function closeDialog() { isOpen.value = false close(1000) } } const setIcon = async (icon: string, view: ViewType) => { try { // modify the icon property in meta view.meta = { ...parseProp(view.meta), icon, } api.dbView.update(view.id as string, { meta: view.meta, }) $e('a:view:icon:sidebar', { icon }) } catch (e: any) { message.error(await extractSdkResponseErrorMsg(e)) } } function onOpenModal({ title = '', type, copyViewId, groupingFieldColumnId, }: { title?: string type: ViewTypes copyViewId?: string groupingFieldColumnId?: string }) { const isOpen = ref(true) const { close } = useDialog(resolveComponent('DlgViewCreate'), { 'modelValue': isOpen, title, type, 'tableId': table.value.id, 'selectedViewId': copyViewId, groupingFieldColumnId, 'views': views, 'onUpdate:modelValue': closeDialog, 'onCreated': async (view: ViewType) => { closeDialog() refreshCommandPalette() await loadViews({ force: true, tableId: table.value.id!, }) navigateToView({ view, tableId: table.value.id!, baseId: base.value.id!, hardReload: view.type === ViewTypes.FORM && selected.value[0] === view.id, }) $e('a:view:create', { view: view.type }) }, }) function closeDialog() { isOpen.value = false close(1000) } } </script> <template> <a-menu ref="menuRef" :class="{ dragging }" class="nc-views-menu flex flex-col w-full !border-r-0 !bg-inherit" :selected-keys="selected" > <DashboardTreeViewCreateViewBtn v-if="isUIAllowed('viewCreateOrEdit')" :class="{ '!pl-18 !xs:(pl-19.75)': isDefaultSource, '!pl-23.5 !xs:(pl-27)': !isDefaultSource, }" :align-left-level="isDefaultSource ? 1 : 2" > <div role="button" class="nc-create-view-btn flex flex-row items-center cursor-pointer rounded-md w-full" :class="{ 'text-brand-500 hover:text-brand-600': activeTableId === table.id, 'text-gray-500 hover:text-brand-500': activeTableId !== table.id, }" > <div class="flex flex-row items-center pl-1.25 !py-1.5 text-inherit"> <GeneralIcon icon="plus" /> <div class="pl-1.75"> {{ $t('general.createEntity', { entity: $t('objects.view'), }) }} </div> </div> </div> </DashboardTreeViewCreateViewBtn> <template v-if="views.length"> <DashboardTreeViewViewsNode v-for="view of views" :id="view.id" :key="view.id" :view="view" :on-validate="validate" :table="table" class="nc-view-item !rounded-md !px-0.75 !py-0.5 w-full transition-all ease-in duration-100" :class="{ 'bg-gray-200': isMarked === view.id, 'active': activeView?.id === view.id, [`nc-${view.type ? viewTypeAlias[view.type] : undefined || view.type}-view-item`]: true, }" :data-view-id="view.id" @change-view="changeView" @open-modal="onOpenModal" @delete="openDeleteDialog" @rename="onRename" @select-icon="setIcon($event, view)" /> </template> </a-menu> </template> <style lang="scss"> .nc-views-menu { .ghost, .ghost > * { @apply !pointer-events-none; } &.dragging { .nc-icon { @apply !hidden; } .nc-view-icon { @apply !block; } } .ant-menu-item:not(.sortable-chosen) { @apply color-transition; } .ant-menu-title-content { @apply !w-full; } .sortable-chosen { @apply !bg-gray-200; } .active { @apply !bg-primary-selected font-medium; } } </style>
packages/nc-gui/components/dashboard/TreeView/ViewsList.vue
0
https://github.com/nocodb/nocodb/commit/04e6529ce3bb892780da3c3268f75bc37d8fdbdb
[ 0.00017721561016514897, 0.0001728361239656806, 0.00016733429220039397, 0.0001731421798467636, 0.0000022470849216915667 ]
{ "id": 3, "code_window": [ " const mmModel = await relationColumnOption.getMMModel();\n", " const mmChildCol = await relationColumnOption.getMMChildColumn();\n", " const mmParentCol = await relationColumnOption.getMMParentColumn();\n", "\n", " return {\n", " builder: knex(\n", " knex.raw(`?? as ??`, [\n", " baseModelSqlv2.getTnPath(parentModel?.table_name),\n", " refTableAlias,\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " if (!mmModel) {\n", " return this.dbDriver.raw(`?`, [\n", " NcDataErrorCodes.NC_ERR_MM_MODEL_NOT_FOUND,\n", " ]);\n", " }\n", "\n" ], "file_path": "packages/nocodb/src/db/genRollupSelectv2.ts", "type": "add", "edit_start_line_idx": 58 }
import BaseGqlXcTsSchema from './BaseGqlXcTsSchema'; class GqlXcTsSchemaMysql extends BaseGqlXcTsSchema { /** * * @param dir * @param filename * @param ct * @param ctx.tn * @param ctx.columns * @param ctx.relations */ constructor({ dir, filename, ctx }) { super({ dir, filename, ctx }); } /*/!** * * @param args * @param args.columns * @param args.relations * @returns {string} * @private *!/ _renderColumns(args) { let str = ''; str += ` ${this._getInputType(args)}\r\n ${this._getQuery(args)},\r\n ${this._getMutation(args)}\r\n ${this._getType(args)}\r\n ` str += ''; return str; } _getInputType(args) { let str = `input ${args.tn_camelize}Input { \r\n` for (let i = 0; i < args.columns.length; ++i) { if (args.columns[i]._cn.split(' ').length > 1) { // str += `\t\t${args.columns[i]._cn}: ${this._getGraphqlType(args.columns[i])},\r\n`; } else { str += `\t\t${args.columns[i]._cn}: ${this._getGraphqlType(args.columns[i])},\r\n`; } } str += `\t}`; return str; } _getQuery(args) { let str = `type Query { \r\n` str += `\t\t${args.tn_camelize}List(where: String,condition:Condition${args.tn_camelize}, limit: Int, offset: Int, sort: String, conditionGraph: String): [${args.tn_camelize}]\r\n` str += `\t\t${args.tn_camelize}Read(id:String!): ${args.tn_camelize}\r\n` str += `\t\t${args.tn_camelize}Exists(id: String!): Boolean\r\n` str += `\t\t${args.tn_camelize}FindOne(where: String!,condition:Condition${args.tn_camelize}): ${args.tn_camelize}\r\n` str += `\t\t${args.tn_camelize}Count(where: String!,condition:Condition${args.tn_camelize},conditionGraph: String): Int\r\n` str += `\t\t${args.tn_camelize}Distinct(column_name: String, where: String,condition:Condition${args.tn_camelize}, limit: Int, offset: Int, sort: String): [${args.tn_camelize}]\r\n` str += `\t\t${args.tn_camelize}GroupBy(fields: String, having: String, limit: Int, offset: Int, sort: String): [${args.tn_camelize}GroupBy]\r\n` str += `\t\t${args.tn_camelize}Aggregate(column_name: String!, having: String, limit: Int, offset: Int, sort: String, func: String!): [${args.tn_camelize}Aggregate]\r\n` str += `\t\t${args.tn_camelize}Distribution(min: Int, max: Int, step: Int, steps: String, column_name: String!): [distribution]\r\n` str += `\t}\r\n` return str; } _getMutation(args) { if (args.type === 'view') return ''; let str = `type Mutation { \r\n` str += `\t\t${args.tn_camelize}Create(data:${args.tn_camelize}Input): ${args.tn_camelize}\r\n` str += `\t\t${args.tn_camelize}Update(id:String,data:${args.tn_camelize}Input): Int\r\n` //${args.tn_camelize}\r\n` str += `\t\t${args.tn_camelize}Delete(id:String): Int\r\n`//${args.tn_camelize}\r\n` str += `\t\t${args.tn_camelize}CreateBulk(data: [${args.tn_camelize}Input]): [Int]\r\n` str += `\t\t${args.tn_camelize}UpdateBulk(data: [${args.tn_camelize}Input]): [Int]\r\n` str += `\t\t${args.tn_camelize}DeleteBulk(data: [${args.tn_camelize}Input]): [Int]\r\n` str += `\t},\r\n` return str; } _getType(args) { let str = `type ${args.tn_camelize} { \r\n` let strWhere = `input Condition${args.tn_camelize} { \r\n` for (let i = 0; i < args.columns.length; ++i) { // todo: handle column name contains whitespace if (args.columns[i]._cn.split(' ').length > 1) { // str += `\t\t${args.columns[i]._cn}: ${this._getGraphqlType(args.columns[i])},\r\n`; } else { str += `\t\t${args.columns[i]._cn}: ${this._getGraphqlType(args.columns[i])},\r\n`; strWhere += `\t\t${args.columns[i]._cn}: ${this._getGraphqlConditionType(args.columns[i])},\r\n`; } } let hasManyRelations = args.relations.filter(r => r.rtn === args.tn); if (hasManyRelations.length > 1) hasManyRelations = lodash.uniqBy(hasManyRelations, function (e) { return [e.tn, e.rtn].join(); }); str += hasManyRelations.length ? `\r\n` : ``; // cityList in Country for (let i = 0; i < hasManyRelations.length; ++i) { let childTable = inflection.camelize(hasManyRelations[i]._tn) str += `\t\t${childTable}List: [${childTable}]\r\n`; strWhere += `\t\t${childTable}List: Condition${childTable}\r\n`; str += `\t\t${childTable}Count: Int\r\n`; } str+= this.generateManyToManyTypeProps(args); let belongsToRelations = args.relations.filter(r => r.tn === args.tn); if (belongsToRelations.length > 1) belongsToRelations = lodash.uniqBy(belongsToRelations, function (e) { return [e.tn, e.rtn].join(); }); str += belongsToRelations.length ? `\r\n` : ``; // Country withi city - this is reverse for (let i = 0; i < belongsToRelations.length; ++i) { let parentTable = inflection.camelize(belongsToRelations[i]._rtn) str += `\t\t${parentTable}Read(id:String): ${parentTable}\r\n`; strWhere += `\t\t${parentTable}Read: Condition${parentTable}\r\n`; } str += `\t}\r\n` const grpFields = Object.assign({}, GROUPBY_DEFAULT_COLS); str += `type ${args.tn_camelize}GroupBy { \r\n` for (let i = 0; i < args.columns.length; ++i) { if (args.columns[i]._cn in grpFields) { grpFields[args.columns[i]._cn] = `\t\t# ${args.columns[i]._cn} - clashes with column in table\r\n`; } else { // todo: handle column name contains whitespace if (args.columns[i]._cn.split(' ').length > 1) { // str += `\t\t${args.columns[i]._cn}: ${this._getGraphqlType(args.columns[i])},\r\n`; } else { str += `\t\t${args.columns[i]._cn}: ${this._getGraphqlType(args.columns[i])},\r\n`; } } } str += Object.values(grpFields).join(''); str += `\t}\r\n` const aggFields = Object.assign({}, AGG_DEFAULT_COLS); str += `type ${args.tn_camelize}Aggregate { \r\n` for (let i = 0; i < args.columns.length; ++i) { if (args.columns[i]._cn in aggFields) { aggFields[args.columns[i]._cn] = `\t\t# ${args.columns[i]._cn} - clashes with column in table\r\n`; } else { // todo: handle column name contains whitespace if (args.columns[i]._cn.split(' ').length > 1) { // str += `\t\t${args.columns[i]._cn}: ${this._getGraphqlType(args.columns[i])},\r\n`; } else { str += `\t\t${args.columns[i]._cn}: ${this._getGraphqlType(args.columns[i])},\r\n`; } } } str += Object.values(aggFields).join(''); str += `\t}\r\n` strWhere += ` _or:[Condition${args.tn_camelize}] _not:Condition${args.tn_camelize} _and:[Condition${args.tn_camelize}] \t}\r\n` return `${str}\r\n\r\n${strWhere}`; } */ protected _getGraphqlType(columnObj): string { switch (columnObj.dt) { case 'tinyint': case 'smallint': case 'mediumint': case 'bigint': case 'serial': case 'int': return 'Int'; break; case 'float': case 'decimal': case 'double': case 'real': return 'Float'; break; case 'bit': case 'boolean': return 'Boolean'; case 'date': case 'datetime': case 'timestamp': case 'time': case 'year': return 'String'; break; case 'char': case 'varchar': case 'nchar': case 'text': case 'tinytext': case 'mediumtext': case 'longtext': case 'binary': case 'varbinary': case 'blob': case 'tinyblob': case 'mediumblob': case 'longblob': case 'enum': return 'String'; break; case 'set': return 'JSON'; break; case 'geometry': case 'point': case 'linestring': case 'polygon': case 'multipoint': case 'multilinestring': case 'multipolygon': case 'json': default: return 'JSON'; break; } } protected _getGraphqlConditionType(columnObj): any { switch (this._getGraphqlType(columnObj.dt)) { case 'Int': return 'ConditionInt'; case 'Float': return 'ConditionFloat'; case 'Boolean': return 'ConditionBoolean'; case 'String': case 'JSON': return 'ConditionString'; case '[String]': return 'ConditionString'; } } /*getString() { return this._renderColumns(this.ctx); }*/ } export default GqlXcTsSchemaMysql;
packages/nocodb/src/db/sql-mgr/code/gql-schema/xc-ts/GqlXcTsSchemaMysql.ts
0
https://github.com/nocodb/nocodb/commit/04e6529ce3bb892780da3c3268f75bc37d8fdbdb
[ 0.00017547031166031957, 0.00017101030971389264, 0.00016465908265672624, 0.00017125690646935254, 0.0000029075051770632854 ]
{ "id": 3, "code_window": [ " const mmModel = await relationColumnOption.getMMModel();\n", " const mmChildCol = await relationColumnOption.getMMChildColumn();\n", " const mmParentCol = await relationColumnOption.getMMParentColumn();\n", "\n", " return {\n", " builder: knex(\n", " knex.raw(`?? as ??`, [\n", " baseModelSqlv2.getTnPath(parentModel?.table_name),\n", " refTableAlias,\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " if (!mmModel) {\n", " return this.dbDriver.raw(`?`, [\n", " NcDataErrorCodes.NC_ERR_MM_MODEL_NOT_FOUND,\n", " ]);\n", " }\n", "\n" ], "file_path": "packages/nocodb/src/db/genRollupSelectv2.ts", "type": "add", "edit_start_line_idx": 58 }
<script setup lang="ts"> import { Tooltip as ATooltip, Empty } from 'ant-design-vue' import type { AuditType } from 'nocodb-sdk' import { timeAgo } from 'nocodb-sdk' import { ProjectIdInj, h, iconMap, onMounted, storeToRefs, useBase, useGlobal, useI18n, useNuxtApp } from '#imports' const { $api } = useNuxtApp() const { base } = storeToRefs(useBase()) const _projectId = inject(ProjectIdInj, undefined) const baseId = computed(() => _projectId.value ?? base.value?.id) const { t } = useI18n() const isLoading = ref(false) const audits = ref<null | Array<AuditType>>(null) const totalRows = ref(0) const currentPage = ref(1) const currentLimit = ref(25) const { appInfo } = useGlobal() async function loadAudits(page = currentPage.value, limit = currentLimit.value) { try { if (!base.value?.id) return isLoading.value = true const { list, pageInfo } = await $api.base.auditList(baseId.value, { offset: limit * (page - 1), limit, }) audits.value = list totalRows.value = pageInfo.totalRows ?? 0 } catch (e) { console.error(e) } finally { isLoading.value = false } } onMounted(async () => { if (audits.value === null) { await loadAudits(currentPage.value, currentLimit.value) } }) const tableHeaderRenderer = (label: string) => () => h('div', { class: 'text-gray-500' }, label) const columns = [ { // Operation Type title: tableHeaderRenderer(t('labels.operationType')), dataIndex: 'op_type', key: 'op_type', }, { // Operation sub-type title: tableHeaderRenderer(t('labels.operationSubType')), dataIndex: 'op_sub_type', key: 'op_sub_type', }, { // Description title: tableHeaderRenderer(t('labels.description')), dataIndex: 'description', key: 'description', customRender: (value: { text: string }) => h('pre', {}, value.text), }, { // User title: tableHeaderRenderer(t('objects.user')), dataIndex: 'user', key: 'user', customRender: (value: { text: string }) => h('div', {}, value.text || 'Shared base'), }, { // Created title: tableHeaderRenderer(t('labels.created')), dataIndex: 'created_at', key: 'created_at', sort: 'desc', customRender: (value: { text: string }) => h(ATooltip, { placement: 'bottom', title: h('span', {}, value.text) }, () => timeAgo(value.text)), width: '10%', }, ] </script> <template> <div class="flex flex-col gap-4 w-full"> <div v-if="!appInfo.auditEnabled" class="text-red-500">Audit logs are currently disabled by administrators.</div> <div class="flex flex-row justify-end items-center"> <a-button class="self-start !rounded-md" @click="loadAudits"> <!-- Reload --> <div class="flex items-center gap-2 text-gray-600 font-light"> <component :is="iconMap.reload" :class="{ 'animate-infinite animate-spin !text-success': isLoading }" /> {{ $t('general.reload') }} </div> </a-button> </div> <a-table class="nc-audit-table w-full" size="small" :data-source="audits ?? []" :columns="columns" :pagination="false" :loading="isLoading" data-testid="audit-tab-table" > <template #emptyText> <a-empty :image="Empty.PRESENTED_IMAGE_SIMPLE" :description="$t('labels.noData')" /> </template> </a-table> <div class="flex flex-row justify-center items-center"> <a-pagination v-model:current="currentPage" v-model:page-size="currentLimit" :total="+totalRows" show-less-items @change="loadAudits" /> </div> </div> </template> <style lang="scss"> .nc-audit-table pre { display: table; table-layout: fixed; width: 100%; white-space: break-spaces; font-size: unset; font-family: unset; } </style>
packages/nc-gui/components/dashboard/settings/AuditTab.vue
0
https://github.com/nocodb/nocodb/commit/04e6529ce3bb892780da3c3268f75bc37d8fdbdb
[ 0.000965713057667017, 0.00022469479881692678, 0.00016334193060174584, 0.00017271806427743286, 0.00019806335330940783 ]
{ "id": 0, "code_window": [ "\t\tthis.isBuilt = false;\n", "\t}\n", "\n", "\tprivate registerListeners(): void {\n", "\t\tthis.toDispose.push(this.debugService.onDidChangeState(() => {\n", "\t\t\tthis.onDebugStateChange();\n", "\t\t}));\n", "\t\tthis.toDispose.push(this.actionBar.actionRunner.addListener2(events.EventType.RUN, (e: any) => {\n", "\t\t\t// check for error\n", "\t\t\tif (e.error && !errors.isPromiseCanceledError(e.error)) {\n", "\t\t\t\tthis.messageService.show(severity.Error, e.error);\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tthis.toDispose.push(this.debugService.getViewModel().onDidFocusStackFrame(() => {\n", "\t\t\tthis.update();\n" ], "file_path": "src/vs/workbench/parts/debug/browser/debugActionsWidget.ts", "type": "replace", "edit_start_line_idx": 73 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import lifecycle = require('vs/base/common/lifecycle'); import errors = require('vs/base/common/errors'); import * as strings from 'vs/base/common/strings'; import severity from 'vs/base/common/severity'; import builder = require('vs/base/browser/builder'); import dom = require('vs/base/browser/dom'); import { StandardMouseEvent } from 'vs/base/browser/mouseEvent'; import actions = require('vs/base/common/actions'); import events = require('vs/base/common/events'); import actionbar = require('vs/base/browser/ui/actionbar/actionbar'); import { IPartService } from 'vs/workbench/services/part/common/partService'; import wbext = require('vs/workbench/common/contributions'); import debug = require('vs/workbench/parts/debug/common/debug'); import { PauseAction, ContinueAction, StepBackAction, StopAction, DisconnectAction, StepOverAction, StepIntoAction, StepOutAction, RestartAction } from 'vs/workbench/parts/debug/browser/debugActions'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { IStorageService, StorageScope } from 'vs/platform/storage/common/storage'; import { IMessageService } from 'vs/platform/message/common/message'; import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry'; import IDebugService = debug.IDebugService; const $ = builder.$; const DEBUG_ACTIONS_WIDGET_POSITION_KEY = 'debug.actionswidgetposition'; export class DebugActionsWidget implements wbext.IWorkbenchContribution { private static ID = 'debug.actionsWidget'; private $el: builder.Builder; private dragArea: builder.Builder; private toDispose: lifecycle.IDisposable[]; private actionBar: actionbar.ActionBar; private actions: actions.IAction[]; private pauseAction: PauseAction; private continueAction: ContinueAction; private stepBackAction: StepBackAction; private stopAction: StopAction; private disconnectAction: DisconnectAction; private isVisible: boolean; private isBuilt: boolean; constructor( @IMessageService private messageService: IMessageService, @ITelemetryService private telemetryService: ITelemetryService, @IDebugService private debugService: IDebugService, @IInstantiationService private instantiationService: IInstantiationService, @IPartService private partService: IPartService, @IStorageService private storageService: IStorageService ) { this.$el = $().div().addClass('debug-actions-widget'); this.dragArea = $().div().addClass('drag-area'); this.$el.append(this.dragArea); const actionBarContainter = $().div().addClass('.action-bar-container'); this.$el.append(actionBarContainter); this.toDispose = []; this.actionBar = new actionbar.ActionBar(actionBarContainter, { orientation: actionbar.ActionsOrientation.HORIZONTAL }); this.toDispose.push(this.actionBar); this.registerListeners(); this.hide(); this.isBuilt = false; } private registerListeners(): void { this.toDispose.push(this.debugService.onDidChangeState(() => { this.onDebugStateChange(); })); this.toDispose.push(this.actionBar.actionRunner.addListener2(events.EventType.RUN, (e: any) => { // check for error if (e.error && !errors.isPromiseCanceledError(e.error)) { this.messageService.show(severity.Error, e.error); } // log in telemetry if (this.telemetryService) { this.telemetryService.publicLog('workbenchActionExecuted', { id: e.action.id, from: 'debugActionsWidget' }); } })); $(window).on(dom.EventType.RESIZE, () => this.setXCoordinate(), this.toDispose); this.dragArea.on(dom.EventType.MOUSE_UP, (event: MouseEvent) => { const mouseClickEvent = new StandardMouseEvent(event); if (mouseClickEvent.detail === 2) { // double click on debug bar centers it again #8250 this.setXCoordinate(0.5 * window.innerWidth); } }); this.dragArea.on(dom.EventType.MOUSE_DOWN, (event: MouseEvent) => { const $window = $(window); this.dragArea.addClass('dragged'); $window.on('mousemove', (e: MouseEvent) => { const mouseMoveEvent = new StandardMouseEvent(e); // Prevent default to stop editor selecting text #8524 mouseMoveEvent.preventDefault(); this.setXCoordinate(mouseMoveEvent.posx); }).once('mouseup', (e: MouseEvent) => { const mouseMoveEvent = new StandardMouseEvent(e); this.storageService.store(DEBUG_ACTIONS_WIDGET_POSITION_KEY, mouseMoveEvent.posx / window.innerWidth, StorageScope.WORKSPACE); this.dragArea.removeClass('dragged'); $window.off('mousemove'); }); }); } private setXCoordinate(x?: number): void { if (!this.isVisible) { return; } if (!x) { x = parseFloat(this.storageService.get(DEBUG_ACTIONS_WIDGET_POSITION_KEY, StorageScope.WORKSPACE, '0.5')) * window.innerWidth; } const halfWidgetWidth = this.$el.getHTMLElement().clientWidth / 2; x = x + halfWidgetWidth - 16; // take into account half the size of the widget x = Math.max(148, x); // do not allow the widget to overflow on the left x = Math.min(x, window.innerWidth - halfWidgetWidth - 10); // do not allow the widget to overflow on the right this.$el.style('left', `${x}px`); } public getId(): string { return DebugActionsWidget.ID; } private onDebugStateChange(): void { const state = this.debugService.state; if (state === debug.State.Disabled || state === debug.State.Inactive) { return this.hide(); } this.actionBar.clear(); this.actionBar.push(this.getActions(this.instantiationService, this.debugService.state), { icon: true, label: false }); this.show(); } private show(): void { if (this.isVisible) { return; } if (!this.isBuilt) { this.isBuilt = true; this.$el.build(builder.withElementById(this.partService.getWorkbenchElementId()).getHTMLElement()); } this.isVisible = true; this.$el.show(); this.setXCoordinate(); } private hide(): void { this.isVisible = false; this.$el.hide(); } private getActions(instantiationService: IInstantiationService, state: debug.State): actions.IAction[] { if (!this.actions) { this.continueAction = instantiationService.createInstance(ContinueAction, ContinueAction.ID, ContinueAction.LABEL); this.pauseAction = instantiationService.createInstance(PauseAction, PauseAction.ID, PauseAction.LABEL); this.stopAction = instantiationService.createInstance(StopAction, StopAction.ID, StopAction.LABEL); this.disconnectAction = instantiationService.createInstance(DisconnectAction, DisconnectAction.ID, DisconnectAction.LABEL); this.actions = [ this.continueAction, instantiationService.createInstance(StepOverAction, StepOverAction.ID, StepOverAction.LABEL), instantiationService.createInstance(StepIntoAction, StepIntoAction.ID, StepIntoAction.LABEL), instantiationService.createInstance(StepOutAction, StepOutAction.ID, StepOutAction.LABEL), instantiationService.createInstance(RestartAction, RestartAction.ID, RestartAction.LABEL), this.stopAction ]; this.actions.forEach(a => { this.toDispose.push(a); }); this.toDispose.push(this.pauseAction); this.toDispose.push(this.disconnectAction); } this.actions[0] = state === debug.State.Running ? this.pauseAction : this.continueAction; const process = this.debugService.getViewModel().focusedProcess; this.actions[5] = (process && !strings.equalsIgnoreCase(process.session.configuration.type, 'extensionHost') && process.session.requestType === debug.SessionRequestType.ATTACH) ? this.disconnectAction : this.stopAction; if (process && process.session.configuration.capabilities.supportsStepBack) { if (!this.stepBackAction) { this.stepBackAction = instantiationService.createInstance(StepBackAction, StepBackAction.ID, StepBackAction.LABEL); this.toDispose.push(this.stepBackAction); } // Return a copy of this.actions containing stepBackAction return [...this.actions.slice(0, 4), this.stepBackAction, ...this.actions.slice(4)]; } else { return this.actions; } } public dispose(): void { this.toDispose = lifecycle.dispose(this.toDispose); if (this.$el) { this.$el.destroy(); delete this.$el; } } }
src/vs/workbench/parts/debug/browser/debugActionsWidget.ts
1
https://github.com/microsoft/vscode/commit/318bafe3a8822a8dd40d91e555d9377a84b34e07
[ 0.9988447427749634, 0.0911049172282219, 0.00016058975597843528, 0.000177707479451783, 0.28662997484207153 ]
{ "id": 0, "code_window": [ "\t\tthis.isBuilt = false;\n", "\t}\n", "\n", "\tprivate registerListeners(): void {\n", "\t\tthis.toDispose.push(this.debugService.onDidChangeState(() => {\n", "\t\t\tthis.onDebugStateChange();\n", "\t\t}));\n", "\t\tthis.toDispose.push(this.actionBar.actionRunner.addListener2(events.EventType.RUN, (e: any) => {\n", "\t\t\t// check for error\n", "\t\t\tif (e.error && !errors.isPromiseCanceledError(e.error)) {\n", "\t\t\t\tthis.messageService.show(severity.Error, e.error);\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tthis.toDispose.push(this.debugService.getViewModel().onDidFocusStackFrame(() => {\n", "\t\t\tthis.update();\n" ], "file_path": "src/vs/workbench/parts/debug/browser/debugActionsWidget.ts", "type": "replace", "edit_start_line_idx": 73 }
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16"><style type="text/css">.st0{opacity:0;fill:#262626;} .st1{fill:#262626;} .st2{fill:#C5C5C5;}</style><g id="outline"><rect class="st0" width="16" height="16"/><path class="st1" d="M16 4.022v-3.022h-16.014v3.022h3.046l-3.043 7.945h-.004v.01l.015 1.023h-.014v1.991h16.014v-3.023h-1v-7.946h1zm-5.914 5.301c0 .233-.023.441-.066.595-.047.164-.099.247-.127.284l-.078.069-.151.026-.115-.017-.139-.137c-.031-.078-.112-.332-.112-.566 0-.254.091-.561.126-.656l.069-.141.109-.082.178-.027c.077 0 .117.014.177.056l.087.179.051.237-.009.18zm-3.695-5.301v2.893l-1.116-2.893h1.116zm-3.026 7.02h1.573l.351.926h-2.254l.33-.926zm8.635-4.354c-.206-.2-.431-.38-.695-.512-.396-.198-.853-.298-1.355-.298-.215 0-.423.02-.621.058v-1.914h2.671v2.666z"/></g><g id="icon_x5F_bg"><rect x="13" y="4" class="st2" width="1" height="8"/><path class="st2" d="M11.225 8.387c-.078-.299-.199-.562-.36-.786s-.365-.401-.609-.53-.534-.193-.866-.193c-.198 0-.38.024-.547.073-.165.049-.316.117-.453.205-.136.088-.257.194-.365.318l-.179.258v-3.154h-.893v7.422h.893v-.575l.126.175c.087.102.189.19.304.269.117.078.249.14.398.186.149.046.314.068.498.068.353 0 .666-.071.937-.212.272-.143.499-.338.682-.586.183-.25.321-.543.414-.879.093-.338.14-.703.14-1.097-.001-.342-.04-.663-.12-.962zm-1.479-.607c.151.071.282.176.39.314.109.14.194.313.255.517.051.174.082.371.089.587l-.007.125c0 .327-.033.62-.1.869-.067.246-.161.453-.278.614-.117.162-.26.285-.421.366-.322.162-.76.166-1.069.015-.153-.075-.286-.175-.393-.296-.085-.096-.156-.216-.218-.367 0 0-.179-.447-.179-.947 0-.5.179-1.002.179-1.002.062-.177.136-.318.224-.43.114-.143.256-.259.424-.345.168-.086.365-.129.587-.129.19 0 .364.037.517.109z"/><rect x=".987" y="2" class="st2" width="14.013" height="1.023"/><rect x=".987" y="12.968" class="st2" width="14.013" height="1.023"/><path class="st2" d="M1.991 12.031l.728-2.031h2.219l.778 2.031h1.082l-2.485-7.158h-.941l-2.441 7.086-.025.072h1.085zm1.827-5.609h.022l.914 2.753h-1.841l.905-2.753z"/></g></svg>
src/vs/base/browser/ui/findinput/whole-word-dark.svg
0
https://github.com/microsoft/vscode/commit/318bafe3a8822a8dd40d91e555d9377a84b34e07
[ 0.00016550782311242074, 0.00016550782311242074, 0.00016550782311242074, 0.00016550782311242074, 0 ]
{ "id": 0, "code_window": [ "\t\tthis.isBuilt = false;\n", "\t}\n", "\n", "\tprivate registerListeners(): void {\n", "\t\tthis.toDispose.push(this.debugService.onDidChangeState(() => {\n", "\t\t\tthis.onDebugStateChange();\n", "\t\t}));\n", "\t\tthis.toDispose.push(this.actionBar.actionRunner.addListener2(events.EventType.RUN, (e: any) => {\n", "\t\t\t// check for error\n", "\t\t\tif (e.error && !errors.isPromiseCanceledError(e.error)) {\n", "\t\t\t\tthis.messageService.show(severity.Error, e.error);\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tthis.toDispose.push(this.debugService.getViewModel().onDidFocusStackFrame(() => {\n", "\t\t\tthis.update();\n" ], "file_path": "src/vs/workbench/parts/debug/browser/debugActionsWidget.ts", "type": "replace", "edit_start_line_idx": 73 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ // Do not edit this file. It is machine generated. { "evaluateMathExpression": "Emmet: Mathematischen Ausdruck auswerten" }
i18n/deu/src/vs/workbench/parts/emmet/node/actions/evaluateMath.i18n.json
0
https://github.com/microsoft/vscode/commit/318bafe3a8822a8dd40d91e555d9377a84b34e07
[ 0.00017415483307559043, 0.00017415483307559043, 0.00017415483307559043, 0.00017415483307559043, 0 ]
{ "id": 0, "code_window": [ "\t\tthis.isBuilt = false;\n", "\t}\n", "\n", "\tprivate registerListeners(): void {\n", "\t\tthis.toDispose.push(this.debugService.onDidChangeState(() => {\n", "\t\t\tthis.onDebugStateChange();\n", "\t\t}));\n", "\t\tthis.toDispose.push(this.actionBar.actionRunner.addListener2(events.EventType.RUN, (e: any) => {\n", "\t\t\t// check for error\n", "\t\t\tif (e.error && !errors.isPromiseCanceledError(e.error)) {\n", "\t\t\t\tthis.messageService.show(severity.Error, e.error);\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\tthis.toDispose.push(this.debugService.getViewModel().onDidFocusStackFrame(() => {\n", "\t\t\tthis.update();\n" ], "file_path": "src/vs/workbench/parts/debug/browser/debugActionsWidget.ts", "type": "replace", "edit_start_line_idx": 73 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ // Do not edit this file. It is machine generated. { "extensionsInstalled": "正在安裝擴充功能 '{0}'...", "hint": "'{0}' 現在是擴充功能。要加以安裝嗎?", "later": "稍後", "no": "否", "yes": "是" }
i18n/cht/src/vs/workbench/parts/extensions/electron-browser/extensionsAssistant.i18n.json
0
https://github.com/microsoft/vscode/commit/318bafe3a8822a8dd40d91e555d9377a84b34e07
[ 0.00017302400374319404, 0.00017288322851527482, 0.0001727424532873556, 0.00017288322851527482, 1.4077522791922092e-7 ]
{ "id": 1, "code_window": [ "\tpublic getId(): string {\n", "\t\treturn DebugActionsWidget.ID;\n", "\t}\n", "\n", "\tprivate onDebugStateChange(): void {\n", "\t\tconst state = this.debugService.state;\n", "\t\tif (state === debug.State.Disabled || state === debug.State.Inactive) {\n", "\t\t\treturn this.hide();\n", "\t\t}\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tprivate update(): void {\n" ], "file_path": "src/vs/workbench/parts/debug/browser/debugActionsWidget.ts", "type": "replace", "edit_start_line_idx": 134 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import lifecycle = require('vs/base/common/lifecycle'); import errors = require('vs/base/common/errors'); import * as strings from 'vs/base/common/strings'; import severity from 'vs/base/common/severity'; import builder = require('vs/base/browser/builder'); import dom = require('vs/base/browser/dom'); import { StandardMouseEvent } from 'vs/base/browser/mouseEvent'; import actions = require('vs/base/common/actions'); import events = require('vs/base/common/events'); import actionbar = require('vs/base/browser/ui/actionbar/actionbar'); import { IPartService } from 'vs/workbench/services/part/common/partService'; import wbext = require('vs/workbench/common/contributions'); import debug = require('vs/workbench/parts/debug/common/debug'); import { PauseAction, ContinueAction, StepBackAction, StopAction, DisconnectAction, StepOverAction, StepIntoAction, StepOutAction, RestartAction } from 'vs/workbench/parts/debug/browser/debugActions'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { IStorageService, StorageScope } from 'vs/platform/storage/common/storage'; import { IMessageService } from 'vs/platform/message/common/message'; import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry'; import IDebugService = debug.IDebugService; const $ = builder.$; const DEBUG_ACTIONS_WIDGET_POSITION_KEY = 'debug.actionswidgetposition'; export class DebugActionsWidget implements wbext.IWorkbenchContribution { private static ID = 'debug.actionsWidget'; private $el: builder.Builder; private dragArea: builder.Builder; private toDispose: lifecycle.IDisposable[]; private actionBar: actionbar.ActionBar; private actions: actions.IAction[]; private pauseAction: PauseAction; private continueAction: ContinueAction; private stepBackAction: StepBackAction; private stopAction: StopAction; private disconnectAction: DisconnectAction; private isVisible: boolean; private isBuilt: boolean; constructor( @IMessageService private messageService: IMessageService, @ITelemetryService private telemetryService: ITelemetryService, @IDebugService private debugService: IDebugService, @IInstantiationService private instantiationService: IInstantiationService, @IPartService private partService: IPartService, @IStorageService private storageService: IStorageService ) { this.$el = $().div().addClass('debug-actions-widget'); this.dragArea = $().div().addClass('drag-area'); this.$el.append(this.dragArea); const actionBarContainter = $().div().addClass('.action-bar-container'); this.$el.append(actionBarContainter); this.toDispose = []; this.actionBar = new actionbar.ActionBar(actionBarContainter, { orientation: actionbar.ActionsOrientation.HORIZONTAL }); this.toDispose.push(this.actionBar); this.registerListeners(); this.hide(); this.isBuilt = false; } private registerListeners(): void { this.toDispose.push(this.debugService.onDidChangeState(() => { this.onDebugStateChange(); })); this.toDispose.push(this.actionBar.actionRunner.addListener2(events.EventType.RUN, (e: any) => { // check for error if (e.error && !errors.isPromiseCanceledError(e.error)) { this.messageService.show(severity.Error, e.error); } // log in telemetry if (this.telemetryService) { this.telemetryService.publicLog('workbenchActionExecuted', { id: e.action.id, from: 'debugActionsWidget' }); } })); $(window).on(dom.EventType.RESIZE, () => this.setXCoordinate(), this.toDispose); this.dragArea.on(dom.EventType.MOUSE_UP, (event: MouseEvent) => { const mouseClickEvent = new StandardMouseEvent(event); if (mouseClickEvent.detail === 2) { // double click on debug bar centers it again #8250 this.setXCoordinate(0.5 * window.innerWidth); } }); this.dragArea.on(dom.EventType.MOUSE_DOWN, (event: MouseEvent) => { const $window = $(window); this.dragArea.addClass('dragged'); $window.on('mousemove', (e: MouseEvent) => { const mouseMoveEvent = new StandardMouseEvent(e); // Prevent default to stop editor selecting text #8524 mouseMoveEvent.preventDefault(); this.setXCoordinate(mouseMoveEvent.posx); }).once('mouseup', (e: MouseEvent) => { const mouseMoveEvent = new StandardMouseEvent(e); this.storageService.store(DEBUG_ACTIONS_WIDGET_POSITION_KEY, mouseMoveEvent.posx / window.innerWidth, StorageScope.WORKSPACE); this.dragArea.removeClass('dragged'); $window.off('mousemove'); }); }); } private setXCoordinate(x?: number): void { if (!this.isVisible) { return; } if (!x) { x = parseFloat(this.storageService.get(DEBUG_ACTIONS_WIDGET_POSITION_KEY, StorageScope.WORKSPACE, '0.5')) * window.innerWidth; } const halfWidgetWidth = this.$el.getHTMLElement().clientWidth / 2; x = x + halfWidgetWidth - 16; // take into account half the size of the widget x = Math.max(148, x); // do not allow the widget to overflow on the left x = Math.min(x, window.innerWidth - halfWidgetWidth - 10); // do not allow the widget to overflow on the right this.$el.style('left', `${x}px`); } public getId(): string { return DebugActionsWidget.ID; } private onDebugStateChange(): void { const state = this.debugService.state; if (state === debug.State.Disabled || state === debug.State.Inactive) { return this.hide(); } this.actionBar.clear(); this.actionBar.push(this.getActions(this.instantiationService, this.debugService.state), { icon: true, label: false }); this.show(); } private show(): void { if (this.isVisible) { return; } if (!this.isBuilt) { this.isBuilt = true; this.$el.build(builder.withElementById(this.partService.getWorkbenchElementId()).getHTMLElement()); } this.isVisible = true; this.$el.show(); this.setXCoordinate(); } private hide(): void { this.isVisible = false; this.$el.hide(); } private getActions(instantiationService: IInstantiationService, state: debug.State): actions.IAction[] { if (!this.actions) { this.continueAction = instantiationService.createInstance(ContinueAction, ContinueAction.ID, ContinueAction.LABEL); this.pauseAction = instantiationService.createInstance(PauseAction, PauseAction.ID, PauseAction.LABEL); this.stopAction = instantiationService.createInstance(StopAction, StopAction.ID, StopAction.LABEL); this.disconnectAction = instantiationService.createInstance(DisconnectAction, DisconnectAction.ID, DisconnectAction.LABEL); this.actions = [ this.continueAction, instantiationService.createInstance(StepOverAction, StepOverAction.ID, StepOverAction.LABEL), instantiationService.createInstance(StepIntoAction, StepIntoAction.ID, StepIntoAction.LABEL), instantiationService.createInstance(StepOutAction, StepOutAction.ID, StepOutAction.LABEL), instantiationService.createInstance(RestartAction, RestartAction.ID, RestartAction.LABEL), this.stopAction ]; this.actions.forEach(a => { this.toDispose.push(a); }); this.toDispose.push(this.pauseAction); this.toDispose.push(this.disconnectAction); } this.actions[0] = state === debug.State.Running ? this.pauseAction : this.continueAction; const process = this.debugService.getViewModel().focusedProcess; this.actions[5] = (process && !strings.equalsIgnoreCase(process.session.configuration.type, 'extensionHost') && process.session.requestType === debug.SessionRequestType.ATTACH) ? this.disconnectAction : this.stopAction; if (process && process.session.configuration.capabilities.supportsStepBack) { if (!this.stepBackAction) { this.stepBackAction = instantiationService.createInstance(StepBackAction, StepBackAction.ID, StepBackAction.LABEL); this.toDispose.push(this.stepBackAction); } // Return a copy of this.actions containing stepBackAction return [...this.actions.slice(0, 4), this.stepBackAction, ...this.actions.slice(4)]; } else { return this.actions; } } public dispose(): void { this.toDispose = lifecycle.dispose(this.toDispose); if (this.$el) { this.$el.destroy(); delete this.$el; } } }
src/vs/workbench/parts/debug/browser/debugActionsWidget.ts
1
https://github.com/microsoft/vscode/commit/318bafe3a8822a8dd40d91e555d9377a84b34e07
[ 0.9991441965103149, 0.13782276213169098, 0.0001658974651945755, 0.00018457285477779806, 0.34205737709999084 ]
{ "id": 1, "code_window": [ "\tpublic getId(): string {\n", "\t\treturn DebugActionsWidget.ID;\n", "\t}\n", "\n", "\tprivate onDebugStateChange(): void {\n", "\t\tconst state = this.debugService.state;\n", "\t\tif (state === debug.State.Disabled || state === debug.State.Inactive) {\n", "\t\t\treturn this.hide();\n", "\t\t}\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tprivate update(): void {\n" ], "file_path": "src/vs/workbench/parts/debug/browser/debugActionsWidget.ts", "type": "replace", "edit_start_line_idx": 134 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ declare function run(): void; declare function suite(name: string, fn: (err?) => void); declare function test(name: string, fn: (done?: (err?) => void) => void); declare function suiteSetup(fn: (done?: (err?) => void) => void); declare function suiteTeardown(fn: (done?: (err?) => void) => void); declare function setup(fn: (done?: (err?) => void) => void); declare function teardown(fn: (done?: (err?) => void) => void);
extensions/vscode-colorize-tests/typings/mocha.d.ts
0
https://github.com/microsoft/vscode/commit/318bafe3a8822a8dd40d91e555d9377a84b34e07
[ 0.00017848782590590417, 0.00017701671458780766, 0.00017554560326971114, 0.00017701671458780766, 0.0000014711113180965185 ]
{ "id": 1, "code_window": [ "\tpublic getId(): string {\n", "\t\treturn DebugActionsWidget.ID;\n", "\t}\n", "\n", "\tprivate onDebugStateChange(): void {\n", "\t\tconst state = this.debugService.state;\n", "\t\tif (state === debug.State.Disabled || state === debug.State.Inactive) {\n", "\t\t\treturn this.hide();\n", "\t\t}\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tprivate update(): void {\n" ], "file_path": "src/vs/workbench/parts/debug/browser/debugActionsWidget.ts", "type": "replace", "edit_start_line_idx": 134 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ // Do not edit this file. It is machine generated. { "badConfigFile": "Git {0}", "cancel": "취소", "cantOpen": "이 Git 리소스를 열 수 없습니다.", "cantOpenResource": "이 Git 리소스를 열 수 없습니다.", "changesFromIndex": "{0}(index)", "changesFromIndexDesc": "{0} - 인덱스 변경 내용", "changesFromTree": "{0}({1})", "changesFromTreeDesc": "{0} - {1} 변경 내용", "checkNativeConsole": "git 작업을 실행하는 동안 문제가 발생했습니다. 출력을 검토하거나 콘솔을 사용하여 리포지토리의 상태를 확인하세요.", "configureUsernameEmail": "git 사용자 이름 및 메일을 구성하세요.", "download": "다운로드", "gitIndexChanges": "{0}(index) ↔ {1}", "gitIndexChangesDesc": "{0} - 인덱스 변경 내용", "gitIndexChangesRenamed": "{0} ← {1}", "gitIndexChangesRenamedDesc": "{0} - 이름 바꿈 - 인덱스 변경 내용", "gitMergeChanges": "{0}(병합) ↔ {1}", "gitMergeChangesDesc": "{0} - 변경 내용 병합", "neverShowAgain": "다시 표시 안 함", "showOutput": "출력 표시", "unmergedChanges": "변경 내용을 커밋하기 전에 먼저 병합되지 않은 변경 내용을 확인해야 합니다.", "updateGit": "Git {0}이(가) 설치된 것 같습니다. Code는 2.0.0 이하의 Git에서 최적으로 작동합니다.", "workingTreeChanges": "{0} (HEAD) ↔ {1}", "workingTreeChangesDesc": "{0} - 작업 트리 변경 내용" }
i18n/kor/src/vs/workbench/parts/git/browser/gitServices.i18n.json
0
https://github.com/microsoft/vscode/commit/318bafe3a8822a8dd40d91e555d9377a84b34e07
[ 0.000175598164787516, 0.00017063198902178556, 0.00016521928773727268, 0.00017085522995330393, 0.0000047566777539032046 ]
{ "id": 1, "code_window": [ "\tpublic getId(): string {\n", "\t\treturn DebugActionsWidget.ID;\n", "\t}\n", "\n", "\tprivate onDebugStateChange(): void {\n", "\t\tconst state = this.debugService.state;\n", "\t\tif (state === debug.State.Disabled || state === debug.State.Inactive) {\n", "\t\t\treturn this.hide();\n", "\t\t}\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\tprivate update(): void {\n" ], "file_path": "src/vs/workbench/parts/debug/browser/debugActionsWidget.ts", "type": "replace", "edit_start_line_idx": 134 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ // Do not edit this file. It is machine generated. { "close": "Chiudi", "neverShowAgain": "Non visualizzare più questo messaggio", "reallyRecommended": "È consigliabile installare l'estensione '{0}'.", "showRecommendations": "Mostra gli elementi consigliati", "workspaceRecommended": "Per questa area di lavoro sono disponibili estensioni consigliate." }
i18n/ita/src/vs/workbench/parts/extensions/electron-browser/extensionTipsService.i18n.json
0
https://github.com/microsoft/vscode/commit/318bafe3a8822a8dd40d91e555d9377a84b34e07
[ 0.00017606660549063236, 0.00017543746798764914, 0.00017480833048466593, 0.00017543746798764914, 6.291375029832125e-7 ]
{ "id": 2, "code_window": [ "\n", "\tpublic getProcesses(): Process[] {\n", "\t\treturn this.processes;\n", "\t}\n", "\n", "\tpublic addProcess(name: string, session: debug.ISession & debug.ITreeElement): void {\n", "\t\tthis.processes.push(new Process(name, session));\n", "\t}\n", "\n", "\tpublic removeProcess(id: string): void {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ "\tpublic addProcess(name: string, session: debug.ISession & debug.ITreeElement): Process {\n", "\t\tconst process = new Process(name, session);\n", "\t\tthis.processes.push(process);\n", "\n", "\t\treturn process;\n" ], "file_path": "src/vs/workbench/parts/debug/common/debugModel.ts", "type": "replace", "edit_start_line_idx": 663 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import lifecycle = require('vs/base/common/lifecycle'); import errors = require('vs/base/common/errors'); import * as strings from 'vs/base/common/strings'; import severity from 'vs/base/common/severity'; import builder = require('vs/base/browser/builder'); import dom = require('vs/base/browser/dom'); import { StandardMouseEvent } from 'vs/base/browser/mouseEvent'; import actions = require('vs/base/common/actions'); import events = require('vs/base/common/events'); import actionbar = require('vs/base/browser/ui/actionbar/actionbar'); import { IPartService } from 'vs/workbench/services/part/common/partService'; import wbext = require('vs/workbench/common/contributions'); import debug = require('vs/workbench/parts/debug/common/debug'); import { PauseAction, ContinueAction, StepBackAction, StopAction, DisconnectAction, StepOverAction, StepIntoAction, StepOutAction, RestartAction } from 'vs/workbench/parts/debug/browser/debugActions'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { IStorageService, StorageScope } from 'vs/platform/storage/common/storage'; import { IMessageService } from 'vs/platform/message/common/message'; import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry'; import IDebugService = debug.IDebugService; const $ = builder.$; const DEBUG_ACTIONS_WIDGET_POSITION_KEY = 'debug.actionswidgetposition'; export class DebugActionsWidget implements wbext.IWorkbenchContribution { private static ID = 'debug.actionsWidget'; private $el: builder.Builder; private dragArea: builder.Builder; private toDispose: lifecycle.IDisposable[]; private actionBar: actionbar.ActionBar; private actions: actions.IAction[]; private pauseAction: PauseAction; private continueAction: ContinueAction; private stepBackAction: StepBackAction; private stopAction: StopAction; private disconnectAction: DisconnectAction; private isVisible: boolean; private isBuilt: boolean; constructor( @IMessageService private messageService: IMessageService, @ITelemetryService private telemetryService: ITelemetryService, @IDebugService private debugService: IDebugService, @IInstantiationService private instantiationService: IInstantiationService, @IPartService private partService: IPartService, @IStorageService private storageService: IStorageService ) { this.$el = $().div().addClass('debug-actions-widget'); this.dragArea = $().div().addClass('drag-area'); this.$el.append(this.dragArea); const actionBarContainter = $().div().addClass('.action-bar-container'); this.$el.append(actionBarContainter); this.toDispose = []; this.actionBar = new actionbar.ActionBar(actionBarContainter, { orientation: actionbar.ActionsOrientation.HORIZONTAL }); this.toDispose.push(this.actionBar); this.registerListeners(); this.hide(); this.isBuilt = false; } private registerListeners(): void { this.toDispose.push(this.debugService.onDidChangeState(() => { this.onDebugStateChange(); })); this.toDispose.push(this.actionBar.actionRunner.addListener2(events.EventType.RUN, (e: any) => { // check for error if (e.error && !errors.isPromiseCanceledError(e.error)) { this.messageService.show(severity.Error, e.error); } // log in telemetry if (this.telemetryService) { this.telemetryService.publicLog('workbenchActionExecuted', { id: e.action.id, from: 'debugActionsWidget' }); } })); $(window).on(dom.EventType.RESIZE, () => this.setXCoordinate(), this.toDispose); this.dragArea.on(dom.EventType.MOUSE_UP, (event: MouseEvent) => { const mouseClickEvent = new StandardMouseEvent(event); if (mouseClickEvent.detail === 2) { // double click on debug bar centers it again #8250 this.setXCoordinate(0.5 * window.innerWidth); } }); this.dragArea.on(dom.EventType.MOUSE_DOWN, (event: MouseEvent) => { const $window = $(window); this.dragArea.addClass('dragged'); $window.on('mousemove', (e: MouseEvent) => { const mouseMoveEvent = new StandardMouseEvent(e); // Prevent default to stop editor selecting text #8524 mouseMoveEvent.preventDefault(); this.setXCoordinate(mouseMoveEvent.posx); }).once('mouseup', (e: MouseEvent) => { const mouseMoveEvent = new StandardMouseEvent(e); this.storageService.store(DEBUG_ACTIONS_WIDGET_POSITION_KEY, mouseMoveEvent.posx / window.innerWidth, StorageScope.WORKSPACE); this.dragArea.removeClass('dragged'); $window.off('mousemove'); }); }); } private setXCoordinate(x?: number): void { if (!this.isVisible) { return; } if (!x) { x = parseFloat(this.storageService.get(DEBUG_ACTIONS_WIDGET_POSITION_KEY, StorageScope.WORKSPACE, '0.5')) * window.innerWidth; } const halfWidgetWidth = this.$el.getHTMLElement().clientWidth / 2; x = x + halfWidgetWidth - 16; // take into account half the size of the widget x = Math.max(148, x); // do not allow the widget to overflow on the left x = Math.min(x, window.innerWidth - halfWidgetWidth - 10); // do not allow the widget to overflow on the right this.$el.style('left', `${x}px`); } public getId(): string { return DebugActionsWidget.ID; } private onDebugStateChange(): void { const state = this.debugService.state; if (state === debug.State.Disabled || state === debug.State.Inactive) { return this.hide(); } this.actionBar.clear(); this.actionBar.push(this.getActions(this.instantiationService, this.debugService.state), { icon: true, label: false }); this.show(); } private show(): void { if (this.isVisible) { return; } if (!this.isBuilt) { this.isBuilt = true; this.$el.build(builder.withElementById(this.partService.getWorkbenchElementId()).getHTMLElement()); } this.isVisible = true; this.$el.show(); this.setXCoordinate(); } private hide(): void { this.isVisible = false; this.$el.hide(); } private getActions(instantiationService: IInstantiationService, state: debug.State): actions.IAction[] { if (!this.actions) { this.continueAction = instantiationService.createInstance(ContinueAction, ContinueAction.ID, ContinueAction.LABEL); this.pauseAction = instantiationService.createInstance(PauseAction, PauseAction.ID, PauseAction.LABEL); this.stopAction = instantiationService.createInstance(StopAction, StopAction.ID, StopAction.LABEL); this.disconnectAction = instantiationService.createInstance(DisconnectAction, DisconnectAction.ID, DisconnectAction.LABEL); this.actions = [ this.continueAction, instantiationService.createInstance(StepOverAction, StepOverAction.ID, StepOverAction.LABEL), instantiationService.createInstance(StepIntoAction, StepIntoAction.ID, StepIntoAction.LABEL), instantiationService.createInstance(StepOutAction, StepOutAction.ID, StepOutAction.LABEL), instantiationService.createInstance(RestartAction, RestartAction.ID, RestartAction.LABEL), this.stopAction ]; this.actions.forEach(a => { this.toDispose.push(a); }); this.toDispose.push(this.pauseAction); this.toDispose.push(this.disconnectAction); } this.actions[0] = state === debug.State.Running ? this.pauseAction : this.continueAction; const process = this.debugService.getViewModel().focusedProcess; this.actions[5] = (process && !strings.equalsIgnoreCase(process.session.configuration.type, 'extensionHost') && process.session.requestType === debug.SessionRequestType.ATTACH) ? this.disconnectAction : this.stopAction; if (process && process.session.configuration.capabilities.supportsStepBack) { if (!this.stepBackAction) { this.stepBackAction = instantiationService.createInstance(StepBackAction, StepBackAction.ID, StepBackAction.LABEL); this.toDispose.push(this.stepBackAction); } // Return a copy of this.actions containing stepBackAction return [...this.actions.slice(0, 4), this.stepBackAction, ...this.actions.slice(4)]; } else { return this.actions; } } public dispose(): void { this.toDispose = lifecycle.dispose(this.toDispose); if (this.$el) { this.$el.destroy(); delete this.$el; } } }
src/vs/workbench/parts/debug/browser/debugActionsWidget.ts
1
https://github.com/microsoft/vscode/commit/318bafe3a8822a8dd40d91e555d9377a84b34e07
[ 0.0006159336771816015, 0.00019463524222373962, 0.00016482558567076921, 0.000172417116118595, 0.00009266143024433404 ]
{ "id": 2, "code_window": [ "\n", "\tpublic getProcesses(): Process[] {\n", "\t\treturn this.processes;\n", "\t}\n", "\n", "\tpublic addProcess(name: string, session: debug.ISession & debug.ITreeElement): void {\n", "\t\tthis.processes.push(new Process(name, session));\n", "\t}\n", "\n", "\tpublic removeProcess(id: string): void {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ "\tpublic addProcess(name: string, session: debug.ISession & debug.ITreeElement): Process {\n", "\t\tconst process = new Process(name, session);\n", "\t\tthis.processes.push(process);\n", "\n", "\t\treturn process;\n" ], "file_path": "src/vs/workbench/parts/debug/common/debugModel.ts", "type": "replace", "edit_start_line_idx": 663 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; import URI from 'vs/base/common/uri'; import { IDisposable, dispose } from 'vs/base/common/lifecycle'; import { TPromise } from 'vs/base/common/winjs.base'; import { IThreadService } from 'vs/workbench/services/thread/common/threadService'; import { ISingleEditOperation, ISelection, IRange, IEditor, EditorType, ICommonCodeEditor, ICommonDiffEditor, IDecorationRenderOptions, IDecorationOptions } from 'vs/editor/common/editorCommon'; import { ICodeEditorService } from 'vs/editor/common/services/codeEditorService'; import { IWorkbenchEditorService } from 'vs/workbench/services/editor/common/editorService'; import { IEditorGroupService } from 'vs/workbench/services/group/common/groupService'; import { Position as EditorPosition } from 'vs/platform/editor/common/editor'; import { IModelService } from 'vs/editor/common/services/modelService'; import { MainThreadEditorsTracker, TextEditorRevealType, MainThreadTextEditor, IApplyEditsOptions, ITextEditorConfigurationUpdate } from 'vs/workbench/api/node/mainThreadEditorsTracker'; import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry'; import { IEventService } from 'vs/platform/event/common/event'; import { equals as arrayEquals } from 'vs/base/common/arrays'; import { equals as objectEquals } from 'vs/base/common/objects'; import { ExtHostContext, MainThreadEditorsShape, ExtHostEditorsShape, ITextEditorPositionData } from './extHost.protocol'; export class MainThreadEditors extends MainThreadEditorsShape { private _proxy: ExtHostEditorsShape; private _workbenchEditorService: IWorkbenchEditorService; private _telemetryService: ITelemetryService; private _editorTracker: MainThreadEditorsTracker; private _toDispose: IDisposable[]; private _textEditorsListenersMap: { [editorId: string]: IDisposable[]; }; private _textEditorsMap: { [editorId: string]: MainThreadTextEditor; }; private _activeTextEditor: string; private _visibleEditors: string[]; private _editorPositionData: ITextEditorPositionData; constructor( @IThreadService threadService: IThreadService, @IWorkbenchEditorService workbenchEditorService: IWorkbenchEditorService, @IEditorGroupService editorGroupService: IEditorGroupService, @ITelemetryService telemetryService: ITelemetryService, @ICodeEditorService editorService: ICodeEditorService, @IEventService eventService: IEventService, @IModelService modelService: IModelService ) { super(); this._proxy = threadService.get(ExtHostContext.ExtHostEditors); this._workbenchEditorService = workbenchEditorService; this._telemetryService = telemetryService; this._toDispose = []; this._textEditorsListenersMap = Object.create(null); this._textEditorsMap = Object.create(null); this._activeTextEditor = null; this._visibleEditors = []; this._editorPositionData = null; this._editorTracker = new MainThreadEditorsTracker(editorService, modelService); this._toDispose.push(this._editorTracker); this._toDispose.push(this._editorTracker.onTextEditorAdd((textEditor) => this._onTextEditorAdd(textEditor))); this._toDispose.push(this._editorTracker.onTextEditorRemove((textEditor) => this._onTextEditorRemove(textEditor))); this._toDispose.push(this._editorTracker.onDidUpdateTextEditors(() => this._updateActiveAndVisibleTextEditors())); this._toDispose.push(this._editorTracker.onChangedFocusedTextEditor((focusedTextEditorId) => this._updateActiveAndVisibleTextEditors())); this._toDispose.push(editorGroupService.onEditorsChanged(() => this._updateActiveAndVisibleTextEditors())); this._toDispose.push(editorGroupService.onEditorsMoved(() => this._updateActiveAndVisibleTextEditors())); } public dispose(): void { Object.keys(this._textEditorsListenersMap).forEach((editorId) => { dispose(this._textEditorsListenersMap[editorId]); }); this._textEditorsListenersMap = Object.create(null); this._toDispose = dispose(this._toDispose); } private _onTextEditorAdd(textEditor: MainThreadTextEditor): void { let id = textEditor.getId(); let toDispose: IDisposable[] = []; toDispose.push(textEditor.onConfigurationChanged((opts) => { this._proxy.$acceptOptionsChanged(id, opts); })); toDispose.push(textEditor.onSelectionChanged((event) => { this._proxy.$acceptSelectionsChanged(id, event); })); this._proxy.$acceptTextEditorAdd({ id: id, document: textEditor.getModel().uri, options: textEditor.getConfiguration(), selections: textEditor.getSelections(), editorPosition: this._findEditorPosition(textEditor) }); this._textEditorsListenersMap[id] = toDispose; this._textEditorsMap[id] = textEditor; } private _onTextEditorRemove(textEditor: MainThreadTextEditor): void { let id = textEditor.getId(); dispose(this._textEditorsListenersMap[id]); delete this._textEditorsListenersMap[id]; delete this._textEditorsMap[id]; this._proxy.$acceptTextEditorRemove(id); } private _updateActiveAndVisibleTextEditors(): void { // active and visible editors let visibleEditors = this._editorTracker.getVisibleTextEditorIds(); let activeEditor = this._findActiveTextEditorId(); if (activeEditor !== this._activeTextEditor || !arrayEquals(this._visibleEditors, visibleEditors, (a, b) => a === b)) { this._activeTextEditor = activeEditor; this._visibleEditors = visibleEditors; this._proxy.$acceptActiveEditorAndVisibleEditors(this._activeTextEditor, this._visibleEditors); } // editor columns let editorPositionData = this._getTextEditorPositionData(); if (!objectEquals(this._editorPositionData, editorPositionData)) { this._editorPositionData = editorPositionData; this._proxy.$acceptEditorPositionData(this._editorPositionData); } } private _findActiveTextEditorId(): string { let focusedTextEditorId = this._editorTracker.getFocusedTextEditorId(); if (focusedTextEditorId) { return focusedTextEditorId; } let activeEditor = this._workbenchEditorService.getActiveEditor(); if (!activeEditor) { return null; } let editor = <IEditor>activeEditor.getControl(); // Substitute for (editor instanceof ICodeEditor) if (!editor || typeof editor.getEditorType !== 'function') { // Not a text editor... return null; } if (editor.getEditorType() === EditorType.ICodeEditor) { return this._editorTracker.findTextEditorIdFor(<ICommonCodeEditor>editor); } // Must be a diff editor => use the modified side return this._editorTracker.findTextEditorIdFor((<ICommonDiffEditor>editor).getModifiedEditor()); } private _findEditorPosition(editor: MainThreadTextEditor): EditorPosition { for (let workbenchEditor of this._workbenchEditorService.getVisibleEditors()) { if (editor.matches(workbenchEditor)) { return workbenchEditor.position; } } } private _getTextEditorPositionData(): ITextEditorPositionData { let result: ITextEditorPositionData = Object.create(null); for (let workbenchEditor of this._workbenchEditorService.getVisibleEditors()) { let editor = <IEditor>workbenchEditor.getControl(); // Substitute for (editor instanceof ICodeEditor) if (!editor || typeof editor.getEditorType !== 'function') { // Not a text editor... continue; } if (editor.getEditorType() === EditorType.ICodeEditor) { let id = this._editorTracker.findTextEditorIdFor(<ICommonCodeEditor>editor); if (id) { result[id] = workbenchEditor.position; } } } return result; } // --- from extension host process $tryShowTextDocument(resource: URI, position: EditorPosition, preserveFocus: boolean): TPromise<string> { const input = { resource, options: { preserveFocus, pinned: true } }; return this._workbenchEditorService.openEditor(input, position).then(editor => { if (!editor) { return; } return new TPromise<void>(c => { // not very nice but the way it is: changes to the editor state aren't // send to the ext host as they happen but stuff is delayed a little. in // order to provide the real editor on #openTextEditor we need to sync on // that update let subscription: IDisposable; let handle: number; function contd() { subscription.dispose(); clearTimeout(handle); c(undefined); } subscription = this._editorTracker.onDidUpdateTextEditors(() => { contd(); }); handle = setTimeout(() => { contd(); }, 1000); }).then(() => { // find the editor we have just opened and return the // id we have assigned to it. for (let id in this._textEditorsMap) { if (this._textEditorsMap[id].matches(editor)) { return id; } } }); }); } $tryShowEditor(id: string, position: EditorPosition): TPromise<void> { // check how often this is used this._telemetryService.publicLog('api.deprecated', { function: 'TextEditor.show' }); let mainThreadEditor = this._textEditorsMap[id]; if (mainThreadEditor) { let model = mainThreadEditor.getModel(); return this._workbenchEditorService.openEditor({ resource: model.uri, options: { preserveFocus: false } }, position).then(() => { return; }); } } $tryHideEditor(id: string): TPromise<void> { // check how often this is used this._telemetryService.publicLog('api.deprecated', { function: 'TextEditor.hide' }); let mainThreadEditor = this._textEditorsMap[id]; if (mainThreadEditor) { let editors = this._workbenchEditorService.getVisibleEditors(); for (let editor of editors) { if (mainThreadEditor.matches(editor)) { return this._workbenchEditorService.closeEditor(editor.position, editor.input).then(() => { return; }); } } } } $trySetSelections(id: string, selections: ISelection[]): TPromise<any> { if (!this._textEditorsMap[id]) { return TPromise.wrapError('TextEditor disposed'); } this._textEditorsMap[id].setSelections(selections); return TPromise.as(null); } $trySetDecorations(id: string, key: string, ranges: IDecorationOptions[]): TPromise<any> { if (!this._textEditorsMap[id]) { return TPromise.wrapError('TextEditor disposed'); } this._textEditorsMap[id].setDecorations(key, ranges); return TPromise.as(null); } $tryRevealRange(id: string, range: IRange, revealType: TextEditorRevealType): TPromise<any> { if (!this._textEditorsMap[id]) { return TPromise.wrapError('TextEditor disposed'); } this._textEditorsMap[id].revealRange(range, revealType); } $trySetOptions(id: string, options: ITextEditorConfigurationUpdate): TPromise<any> { if (!this._textEditorsMap[id]) { return TPromise.wrapError('TextEditor disposed'); } this._textEditorsMap[id].setConfiguration(options); return TPromise.as(null); } $tryApplyEdits(id: string, modelVersionId: number, edits: ISingleEditOperation[], opts: IApplyEditsOptions): TPromise<boolean> { if (!this._textEditorsMap[id]) { return TPromise.wrapError('TextEditor disposed'); } return TPromise.as(this._textEditorsMap[id].applyEdits(modelVersionId, edits, opts)); } $registerTextEditorDecorationType(key: string, options: IDecorationRenderOptions): void { this._editorTracker.registerTextEditorDecorationType(key, options); } $removeTextEditorDecorationType(key: string): void { this._editorTracker.removeTextEditorDecorationType(key); } }
src/vs/workbench/api/node/mainThreadEditors.ts
0
https://github.com/microsoft/vscode/commit/318bafe3a8822a8dd40d91e555d9377a84b34e07
[ 0.00017644642503000796, 0.00017196504632011056, 0.0001649433543207124, 0.00017217471031472087, 0.0000028961585485376418 ]
{ "id": 2, "code_window": [ "\n", "\tpublic getProcesses(): Process[] {\n", "\t\treturn this.processes;\n", "\t}\n", "\n", "\tpublic addProcess(name: string, session: debug.ISession & debug.ITreeElement): void {\n", "\t\tthis.processes.push(new Process(name, session));\n", "\t}\n", "\n", "\tpublic removeProcess(id: string): void {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ "\tpublic addProcess(name: string, session: debug.ISession & debug.ITreeElement): Process {\n", "\t\tconst process = new Process(name, session);\n", "\t\tthis.processes.push(process);\n", "\n", "\t\treturn process;\n" ], "file_path": "src/vs/workbench/parts/debug/common/debugModel.ts", "type": "replace", "edit_start_line_idx": 663 }
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16"><path fill="#1E1E1E" d="M4.222 0h-2.222v.479c-.526.648-.557 1.57-.043 2.269l.043.059v3.203l-.4.296-.053.053c-.353.352-.547.822-.547 1.321s.194.967.549 1.32c.134.134.288.236.451.322v6.678h14v-16h-11.778z"/><path fill="#E8E8E8" d="M10.798 7l-1.83-2h6.032v2h-4.202zm-2.292-6h-3.207l1.337 1.52 1.87-1.52zm-5.506 8.531v1.469h12v-2h-10.813l-.024.021c-.3.299-.716.479-1.163.51zm0 5.469h12v-2h-12v2zm3.323-8h.631l-.347-.266-.284.266zm8.677-4v-2h-3.289l-1.743 2h5.032z"/><path fill="#F48771" d="M7.246 4.6l2.856-3.277-.405-.002-3.176 2.581-2.607-2.962c-.336-.221-.786-.2-1.082.096-.308.306-.319.779-.069 1.12l2.83 2.444-3.339 2.466c-.339.338-.339.887 0 1.225.339.337.888.337 1.226 0l3.063-2.867 3.33 2.555h.466l-3.093-3.379z"/></svg>
src/vs/workbench/parts/extensions/electron-browser/media/clear-inverse.svg
0
https://github.com/microsoft/vscode/commit/318bafe3a8822a8dd40d91e555d9377a84b34e07
[ 0.00019840050663333386, 0.00019840050663333386, 0.00019840050663333386, 0.00019840050663333386, 0 ]
{ "id": 2, "code_window": [ "\n", "\tpublic getProcesses(): Process[] {\n", "\t\treturn this.processes;\n", "\t}\n", "\n", "\tpublic addProcess(name: string, session: debug.ISession & debug.ITreeElement): void {\n", "\t\tthis.processes.push(new Process(name, session));\n", "\t}\n", "\n", "\tpublic removeProcess(id: string): void {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ "\tpublic addProcess(name: string, session: debug.ISession & debug.ITreeElement): Process {\n", "\t\tconst process = new Process(name, session);\n", "\t\tthis.processes.push(process);\n", "\n", "\t\treturn process;\n" ], "file_path": "src/vs/workbench/parts/debug/common/debugModel.ts", "type": "replace", "edit_start_line_idx": 663 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ // Do not edit this file. It is machine generated. { "extensionDescription.activationEvents1": "la propiedad `{0}` se puede omitir o debe ser de tipo \"string[]\"", "extensionDescription.activationEvents2": "las propiedades `{0}` y `{1}` deben especificarse u omitirse conjuntamente", "extensionDescription.empty": "Se obtuvo una descripción vacía de la extensión.", "extensionDescription.engines": "la propiedad `{0}` es obligatoria y debe ser de tipo \"object\"", "extensionDescription.engines.vscode": "la propiedad `{0}` es obligatoria y debe ser de tipo \"string\"", "extensionDescription.extensionDependencies": "la propiedad `{0}` se puede omitir o debe ser de tipo \"string[]\"", "extensionDescription.main1": "la propiedad `{0}` se puede omitir o debe ser de tipo \"string\"", "extensionDescription.main2": "Se esperaba que \"main\" ({0}) se hubiera incluido en la carpeta de la extensión ({1}). Esto puede hacer que la extensión no sea portátil.", "extensionDescription.main3": "las propiedades `{0}` y `{1}` deben especificarse u omitirse conjuntamente", "extensionDescription.name": "la propiedad `{0}` es obligatoria y debe ser de tipo \"string\"", "extensionDescription.publisher": "la propiedad `{0}` es obligatoria y debe ser de tipo \"string\"", "extensionDescription.version": "la propiedad `{0}` es obligatoria y debe ser de tipo \"string\"", "vscode.extension.activationEvents": "Eventos de activación de la extensión VS Code.", "vscode.extension.badges": "Matriz de distintivos que se muestran en la barra lateral de la página de extensiones de Marketplace.", "vscode.extension.badges.description": "Descripción del distintivo.", "vscode.extension.badges.href": "Vínculo del distintivo.", "vscode.extension.badges.url": "URL de la imagen del distintivo.", "vscode.extension.categories": "Categorías que usa la galería de VS Code para clasificar la extensión.", "vscode.extension.contributes": "Todas las contribuciones de la extensión VS Code representadas por este paquete.", "vscode.extension.displayName": "Nombre para mostrar de la extensión que se usa en la galería de VS Code.", "vscode.extension.extensionDependencies": "Dependencias a otras extensiones. El identificador de una extensión siempre es ${publisher}.${name}. Por ejemplo: vscode.csharp.", "vscode.extension.galleryBanner": "Banner usado en VS Code Marketplace.", "vscode.extension.galleryBanner.color": "Color del banner en el encabezado de página de VS Code Marketplace.", "vscode.extension.galleryBanner.theme": "Tema de color de la fuente que se usa en el banner.", "vscode.extension.icon": "Ruta de acceso a un icono de 128 x 128 píxeles.", "vscode.extension.preview": "Establece la extensión que debe marcarse como versión preliminar en Marketplace.", "vscode.extension.publisher": "El publicador de la extensión VS Code.", "vscode.extension.scripts.prepublish": "Script que se ejecuta antes de publicar el paquete como extensión VS Code." }
i18n/esn/src/vs/platform/extensions/common/extensionsRegistry.i18n.json
0
https://github.com/microsoft/vscode/commit/318bafe3a8822a8dd40d91e555d9377a84b34e07
[ 0.00017390192078892142, 0.0001695837127044797, 0.0001656791428104043, 0.00016937690088525414, 0.000002914585820690263 ]
{ "id": 3, "code_window": [ "\t\t\t}\n", "\n", "\t\t\tconst session = this.instantiationService.createInstance(RawDebugSession, sessionId, configuration.debugServer, adapter, this.customTelemetryService);\n", "\t\t\tthis.model.addProcess(configuration.name, session);\n", "\t\t\tthis.toDisposeOnSessionEnd[session.getId()] = [];\n", "\t\t\tif (client) {\n", "\t\t\t\tthis.toDisposeOnSessionEnd[session.getId()].push(client);\n", "\t\t\t}\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tconst process = this.model.addProcess(configuration.name, session);\n", "\n", "\t\t\tif (!this.viewModel.focusedProcess) {\n", "\t\t\t\tthis.viewModel.setFocusedStackFrame(null, process);\n", "\t\t\t}\n" ], "file_path": "src/vs/workbench/parts/debug/electron-browser/debugService.ts", "type": "replace", "edit_start_line_idx": 634 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as nls from 'vs/nls'; import * as lifecycle from 'vs/base/common/lifecycle'; import { guessMimeTypes } from 'vs/base/common/mime'; import Event, { Emitter } from 'vs/base/common/event'; import * as paths from 'vs/base/common/paths'; import * as strings from 'vs/base/common/strings'; import { generateUuid } from 'vs/base/common/uuid'; import uri from 'vs/base/common/uri'; import { Action } from 'vs/base/common/actions'; import { first, distinct } from 'vs/base/common/arrays'; import { isObject, isUndefinedOrNull } from 'vs/base/common/types'; import * as errors from 'vs/base/common/errors'; import severity from 'vs/base/common/severity'; import { TPromise } from 'vs/base/common/winjs.base'; import * as aria from 'vs/base/browser/ui/aria/aria'; import { Client as TelemetryClient } from 'vs/base/parts/ipc/node/ipc.cp'; import { ICodeEditor } from 'vs/editor/browser/editorBrowser'; import { IContextKeyService, IContextKey } from 'vs/platform/contextkey/common/contextkey'; import { IMarkerService } from 'vs/platform/markers/common/markers'; import { ILifecycleService } from 'vs/platform/lifecycle/common/lifecycle'; import { IExtensionService } from 'vs/platform/extensions/common/extensions'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { IFileService, FileChangesEvent, FileChangeType, EventType } from 'vs/platform/files/common/files'; import { IEventService } from 'vs/platform/event/common/event'; import { IMessageService, CloseAction } from 'vs/platform/message/common/message'; import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry'; import { TelemetryService } from 'vs/platform/telemetry/common/telemetryService'; import { TelemetryAppenderClient } from 'vs/platform/telemetry/common/telemetryIpc'; import { IStorageService, StorageScope } from 'vs/platform/storage/common/storage'; import { IEditorGroupService } from 'vs/workbench/services/group/common/groupService'; import { asFileEditorInput } from 'vs/workbench/common/editor'; import * as debug from 'vs/workbench/parts/debug/common/debug'; import { RawDebugSession } from 'vs/workbench/parts/debug/electron-browser/rawDebugSession'; import { Model, ExceptionBreakpoint, FunctionBreakpoint, Breakpoint, Expression } from 'vs/workbench/parts/debug/common/debugModel'; import { DebugStringEditorInput, DebugErrorEditorInput } from 'vs/workbench/parts/debug/browser/debugEditorInputs'; import { ViewModel } from 'vs/workbench/parts/debug/common/debugViewModel'; import * as debugactions from 'vs/workbench/parts/debug/browser/debugActions'; import { ConfigurationManager } from 'vs/workbench/parts/debug/node/debugConfigurationManager'; import { Source } from 'vs/workbench/parts/debug/common/debugSource'; import { ITaskService, TaskEvent, TaskType, TaskServiceEvents, ITaskSummary } from 'vs/workbench/parts/tasks/common/taskService'; import { TaskError, TaskErrors } from 'vs/workbench/parts/tasks/common/taskSystem'; import { VIEWLET_ID as EXPLORER_VIEWLET_ID } from 'vs/workbench/parts/files/common/files'; import { IViewletService } from 'vs/workbench/services/viewlet/common/viewletService'; import { IPanelService } from 'vs/workbench/services/panel/common/panelService'; import { IPartService } from 'vs/workbench/services/part/common/partService'; import { ITextFileService } from 'vs/workbench/services/textfile/common/textfiles'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace'; import { IWorkbenchEditorService } from 'vs/workbench/services/editor/common/editorService'; import { IWindowService, IBroadcast } from 'vs/workbench/services/window/electron-browser/windowService'; import { ILogEntry, EXTENSION_LOG_BROADCAST_CHANNEL, EXTENSION_ATTACH_BROADCAST_CHANNEL, EXTENSION_TERMINATE_BROADCAST_CHANNEL } from 'vs/workbench/services/extensions/electron-browser/extensionHost'; import { ipcRenderer as ipc } from 'electron'; const DEBUG_BREAKPOINTS_KEY = 'debug.breakpoint'; const DEBUG_BREAKPOINTS_ACTIVATED_KEY = 'debug.breakpointactivated'; const DEBUG_FUNCTION_BREAKPOINTS_KEY = 'debug.functionbreakpoint'; const DEBUG_EXCEPTION_BREAKPOINTS_KEY = 'debug.exceptionbreakpoint'; const DEBUG_WATCH_EXPRESSIONS_KEY = 'debug.watchexpressions'; const DEBUG_SELECTED_CONFIG_NAME_KEY = 'debug.selectedconfigname'; export class DebugService implements debug.IDebugService { public _serviceBrand: any; private sessionStates: { [id: string]: debug.State }; private _onDidChangeState: Emitter<void>; private model: Model; private viewModel: ViewModel; private configurationManager: ConfigurationManager; private customTelemetryService: ITelemetryService; private lastTaskEvent: TaskEvent; private toDispose: lifecycle.IDisposable[]; private toDisposeOnSessionEnd: { [id: string]: lifecycle.IDisposable[] }; private inDebugMode: IContextKey<boolean>; private breakpointsToSendOnResourceSaved: { [uri: string]: boolean }; constructor( @IStorageService private storageService: IStorageService, @IWorkbenchEditorService private editorService: IWorkbenchEditorService, @ITextFileService private textFileService: ITextFileService, @IViewletService private viewletService: IViewletService, @IPanelService private panelService: IPanelService, @IFileService private fileService: IFileService, @IMessageService private messageService: IMessageService, @IPartService private partService: IPartService, @IWindowService private windowService: IWindowService, @ITelemetryService private telemetryService: ITelemetryService, @IWorkspaceContextService private contextService: IWorkspaceContextService, @IContextKeyService contextKeyService: IContextKeyService, @IEditorGroupService private editorGroupService: IEditorGroupService, @IEventService eventService: IEventService, @ILifecycleService lifecycleService: ILifecycleService, @IInstantiationService private instantiationService: IInstantiationService, @IExtensionService private extensionService: IExtensionService, @IMarkerService private markerService: IMarkerService, @ITaskService private taskService: ITaskService, @IConfigurationService private configurationService: IConfigurationService ) { this.toDispose = []; this.toDisposeOnSessionEnd = {}; this.breakpointsToSendOnResourceSaved = {}; this._onDidChangeState = new Emitter<void>(); this.sessionStates = {}; this.configurationManager = this.instantiationService.createInstance(ConfigurationManager); this.inDebugMode = debug.CONTEXT_IN_DEBUG_MODE.bindTo(contextKeyService); this.model = new Model(this.loadBreakpoints(), this.storageService.getBoolean(DEBUG_BREAKPOINTS_ACTIVATED_KEY, StorageScope.WORKSPACE, true), this.loadFunctionBreakpoints(), this.loadExceptionBreakpoints(), this.loadWatchExpressions()); this.toDispose.push(this.model); this.viewModel = new ViewModel(this.storageService.get(DEBUG_SELECTED_CONFIG_NAME_KEY, StorageScope.WORKSPACE, null)); this.registerListeners(eventService, lifecycleService); } private registerListeners(eventService: IEventService, lifecycleService: ILifecycleService): void { this.toDispose.push(eventService.addListener2(EventType.FILE_CHANGES, (e: FileChangesEvent) => this.onFileChanges(e))); if (this.taskService) { this.toDispose.push(this.taskService.addListener2(TaskServiceEvents.Active, (e: TaskEvent) => { this.lastTaskEvent = e; })); this.toDispose.push(this.taskService.addListener2(TaskServiceEvents.Inactive, (e: TaskEvent) => { if (e.type === TaskType.SingleRun) { this.lastTaskEvent = null; } })); this.toDispose.push(this.taskService.addListener2(TaskServiceEvents.Terminated, (e: TaskEvent) => { this.lastTaskEvent = null; })); } lifecycleService.onShutdown(this.store, this); lifecycleService.onShutdown(this.dispose, this); this.toDispose.push(this.windowService.onBroadcast(this.onBroadcast, this)); } private onBroadcast(broadcast: IBroadcast): void { // attach: PH is ready to be attached to // TODO@Isidor this is a hack to just get any 'extensionHost' session. // Optimally the broadcast would contain the id of the session // We are only intersted if we have an active debug session for extensionHost const session = <RawDebugSession>this.model.getProcesses().map(p => p.session).filter(s => s.configuration.type === 'extensionHost').pop(); if (broadcast.channel === EXTENSION_ATTACH_BROADCAST_CHANNEL) { this.rawAttach(session, broadcast.payload.port); return; } if (broadcast.channel === EXTENSION_TERMINATE_BROADCAST_CHANNEL) { this.onSessionEnd(session); return; } // from this point on we require an active session if (!session) { return; } // a plugin logged output, show it inside the REPL if (broadcast.channel === EXTENSION_LOG_BROADCAST_CHANNEL) { let extensionOutput: ILogEntry = broadcast.payload; let sev = extensionOutput.severity === 'warn' ? severity.Warning : extensionOutput.severity === 'error' ? severity.Error : severity.Info; let args: any[] = []; try { let parsed = JSON.parse(extensionOutput.arguments); args.push(...Object.getOwnPropertyNames(parsed).map(o => parsed[o])); } catch (error) { args.push(extensionOutput.arguments); } // add output for each argument logged let simpleVals: any[] = []; for (let i = 0; i < args.length; i++) { let a = args[i]; // undefined gets printed as 'undefined' if (typeof a === 'undefined') { simpleVals.push('undefined'); } // null gets printed as 'null' else if (a === null) { simpleVals.push('null'); } // objects & arrays are special because we want to inspect them in the REPL else if (isObject(a) || Array.isArray(a)) { // flush any existing simple values logged if (simpleVals.length) { this.logToRepl(simpleVals.join(' '), sev); simpleVals = []; } // show object this.logToRepl(a, sev); } // string: watch out for % replacement directive // string substitution and formatting @ https://developer.chrome.com/devtools/docs/console else if (typeof a === 'string') { let buf = ''; for (let j = 0, len = a.length; j < len; j++) { if (a[j] === '%' && (a[j + 1] === 's' || a[j + 1] === 'i' || a[j + 1] === 'd')) { i++; // read over substitution buf += !isUndefinedOrNull(args[i]) ? args[i] : ''; // replace j++; // read over directive } else { buf += a[j]; } } simpleVals.push(buf); } // number or boolean is joined together else { simpleVals.push(a); } } // flush simple values if (simpleVals.length) { this.logToRepl(simpleVals.join(' '), sev); } } } private registerSessionListeners(session: RawDebugSession): void { this.toDisposeOnSessionEnd[session.getId()].push(session); this.toDisposeOnSessionEnd[session.getId()].push(session.onDidInitialize(event => { aria.status(nls.localize('debuggingStarted', "Debugging started.")); const sendConfigurationDone = () => { if (session && session.configuration.capabilities.supportsConfigurationDoneRequest) { session.configurationDone().done(null, e => { // Disconnect the debug session on configuration done error #10596 if (session) { session.disconnect().done(null, errors.onUnexpectedError); } this.messageService.show(severity.Error, e.message); }); } }; const process = this.model.getProcesses().filter(p => p.getId() === session.getId()).pop(); this.sendAllBreakpoints(process).done(sendConfigurationDone, sendConfigurationDone); })); this.toDisposeOnSessionEnd[session.getId()].push(session.onDidStop(event => { this.setStateAndEmit(session.getId(), debug.State.Stopped); const threadId = event.body.threadId; session.threads().then(response => { if (!response || !response.body || !response.body.threads) { return; } const rawThread = response.body.threads.filter(t => t.id === threadId).pop(); this.model.rawUpdate({ sessionId: session.getId(), thread: rawThread, threadId, stoppedDetails: event.body, allThreadsStopped: event.body.allThreadsStopped }); const process = this.model.getProcesses().filter(p => p.getId() === session.getId()).pop(); const thread = process && process.getThread(threadId); if (thread) { thread.getCallStack().then(callStack => { if (callStack.length > 0) { // focus first stack frame from top that has source location const stackFrameToFocus = first(callStack, sf => sf.source && sf.source.available, callStack[0]); this.setFocusedStackFrameAndEvaluate(stackFrameToFocus).done(null, errors.onUnexpectedError); this.windowService.getWindow().focus(); aria.alert(nls.localize('debuggingPaused', "Debugging paused, reason {0}, {1} {2}", event.body.reason, stackFrameToFocus.source ? stackFrameToFocus.source.name : '', stackFrameToFocus.lineNumber)); return this.openOrRevealSource(stackFrameToFocus.source, stackFrameToFocus.lineNumber, false, false); } else { this.setFocusedStackFrameAndEvaluate(null).done(null, errors.onUnexpectedError); } }); } }, errors.onUnexpectedError); })); this.toDisposeOnSessionEnd[session.getId()].push(session.onDidThread(event => { if (event.body.reason === 'started') { session.threads().done(response => { if (response && response.body && response.body.threads) { response.body.threads.forEach(thread => this.model.rawUpdate({ sessionId: session.getId(), threadId: thread.id, thread })); } }, errors.onUnexpectedError); } else if (event.body.reason === 'exited') { this.model.clearThreads(session.getId(), true, event.body.threadId); } })); this.toDisposeOnSessionEnd[session.getId()].push(session.onDidTerminateDebugee(event => { aria.status(nls.localize('debuggingStopped', "Debugging stopped.")); if (session && session.getId() === event.body.sessionId) { if (event.body && typeof event.body.restart === 'boolean' && event.body.restart) { const process = this.model.getProcesses().filter(p => p.getId() === session.getId()).pop(); this.restartProcess(process).done(null, err => this.messageService.show(severity.Error, err.message)); } else { session.disconnect().done(null, errors.onUnexpectedError); } } })); this.toDisposeOnSessionEnd[session.getId()].push(session.onDidContinued(event => { this.transitionToRunningState(session, event.body.allThreadsContinued ? undefined : event.body.threadId); })); this.toDisposeOnSessionEnd[session.getId()].push(session.onDidOutput(event => { if (event.body && event.body.category === 'telemetry') { // only log telemetry events from debug adapter if the adapter provided the telemetry key // and the user opted in telemetry if (this.customTelemetryService && this.telemetryService.isOptedIn) { this.customTelemetryService.publicLog(event.body.output, event.body.data); } } else if (event.body && typeof event.body.output === 'string' && event.body.output.length > 0) { this.onOutput(event); } })); this.toDisposeOnSessionEnd[session.getId()].push(session.onDidBreakpoint(event => { const id = event.body && event.body.breakpoint ? event.body.breakpoint.id : undefined; const breakpoint = this.model.getBreakpoints().filter(bp => bp.idFromAdapter === id).pop(); if (breakpoint) { this.model.updateBreakpoints({ [breakpoint.getId()]: event.body.breakpoint }); } else { const functionBreakpoint = this.model.getFunctionBreakpoints().filter(bp => bp.idFromAdapter === id).pop(); if (functionBreakpoint) { this.model.updateFunctionBreakpoints({ [functionBreakpoint.getId()]: event.body.breakpoint }); } } })); this.toDisposeOnSessionEnd[session.getId()].push(session.onDidExitAdapter(event => { // 'Run without debugging' mode VSCode must terminate the extension host. More details: #3905 if (session && session.configuration.type === 'extensionHost' && this.sessionStates[session.getId()] === debug.State.RunningNoDebug) { ipc.send('vscode:closeExtensionHostWindow', this.contextService.getWorkspace().resource.fsPath); } if (session && session.getId() === event.body.sessionId) { this.onSessionEnd(session); } })); } private onOutput(event: DebugProtocol.OutputEvent): void { const outputSeverity = event.body.category === 'stderr' ? severity.Error : event.body.category === 'console' ? severity.Warning : severity.Info; this.appendReplOutput(event.body.output, outputSeverity); } private loadBreakpoints(): Breakpoint[] { let result: Breakpoint[]; try { result = JSON.parse(this.storageService.get(DEBUG_BREAKPOINTS_KEY, StorageScope.WORKSPACE, '[]')).map((breakpoint: any) => { return new Breakpoint(uri.parse(breakpoint.uri.external || breakpoint.source.uri.external), breakpoint.desiredLineNumber || breakpoint.lineNumber, breakpoint.enabled, breakpoint.condition, breakpoint.hitCondition); }); } catch (e) { } return result || []; } private loadFunctionBreakpoints(): FunctionBreakpoint[] { let result: FunctionBreakpoint[]; try { result = JSON.parse(this.storageService.get(DEBUG_FUNCTION_BREAKPOINTS_KEY, StorageScope.WORKSPACE, '[]')).map((fb: any) => { return new FunctionBreakpoint(fb.name, fb.enabled, fb.hitCondition); }); } catch (e) { } return result || []; } private loadExceptionBreakpoints(): ExceptionBreakpoint[] { let result: ExceptionBreakpoint[]; try { result = JSON.parse(this.storageService.get(DEBUG_EXCEPTION_BREAKPOINTS_KEY, StorageScope.WORKSPACE, '[]')).map((exBreakpoint: any) => { return new ExceptionBreakpoint(exBreakpoint.filter || exBreakpoint.name, exBreakpoint.label, exBreakpoint.enabled); }); } catch (e) { } return result || []; } private loadWatchExpressions(): Expression[] { let result: Expression[]; try { result = JSON.parse(this.storageService.get(DEBUG_WATCH_EXPRESSIONS_KEY, StorageScope.WORKSPACE, '[]')).map((watchStoredData: { name: string, id: string }) => { return new Expression(watchStoredData.name, false, watchStoredData.id); }); } catch (e) { } return result || []; } public get state(): debug.State { if (!this.contextService.getWorkspace()) { return debug.State.Disabled; } const focusedProcess = this.viewModel.focusedProcess; if (focusedProcess) { return this.sessionStates[focusedProcess.getId()]; } const processes = this.model.getProcesses(); if (processes.length > 0) { return this.sessionStates[processes[0].getId()]; } return debug.State.Inactive; } public get onDidChangeState(): Event<void> { return this._onDidChangeState.event; } private setStateAndEmit(sessionId: string, newState: debug.State): void { this.sessionStates[sessionId] = newState; this._onDidChangeState.fire(); } public get enabled(): boolean { return !!this.contextService.getWorkspace(); } public setFocusedStackFrameAndEvaluate(focusedStackFrame: debug.IStackFrame): TPromise<void> { const processes = this.model.getProcesses(); const process = focusedStackFrame ? focusedStackFrame.thread.process : processes.length ? processes[0] : null; if (process && !focusedStackFrame) { const thread = process.getAllThreads().pop(); const callStack = thread ? thread.getCachedCallStack() : null; focusedStackFrame = callStack && callStack.length ? callStack[0] : null; } this.viewModel.setFocusedStackFrame(focusedStackFrame, process); this._onDidChangeState.fire(); return this.model.evaluateWatchExpressions(process, focusedStackFrame); } public enableOrDisableBreakpoints(enable: boolean, breakpoint?: debug.IEnablement): TPromise<void> { if (breakpoint) { this.model.setEnablement(breakpoint, enable); if (breakpoint instanceof Breakpoint) { return this.sendBreakpoints(breakpoint.uri); } else if (breakpoint instanceof FunctionBreakpoint) { return this.sendFunctionBreakpoints(); } return this.sendExceptionBreakpoints(); } this.model.enableOrDisableAllBreakpoints(enable); return this.sendAllBreakpoints(); } public addBreakpoints(uri: uri, rawBreakpoints: debug.IRawBreakpoint[]): TPromise<void> { this.model.addBreakpoints(uri, rawBreakpoints); rawBreakpoints.forEach(rbp => aria.status(nls.localize('breakpointAdded', "Added breakpoint, line {0}, file {1}", rbp.lineNumber, uri.fsPath))); return this.sendBreakpoints(uri); } public removeBreakpoints(id?: string): TPromise<any> { const toRemove = this.model.getBreakpoints().filter(bp => !id || bp.getId() === id); toRemove.forEach(bp => aria.status(nls.localize('breakpointRemoved', "Removed breakpoint, line {0}, file {1}", bp.lineNumber, bp.uri.fsPath))); const urisToClear = distinct(toRemove, bp => bp.uri.toString()).map(bp => bp.uri); this.model.removeBreakpoints(toRemove); return TPromise.join(urisToClear.map(uri => this.sendBreakpoints(uri))); } public setBreakpointsActivated(activated: boolean): TPromise<void> { this.model.setBreakpointsActivated(activated); return this.sendAllBreakpoints(); } public addFunctionBreakpoint(): void { this.model.addFunctionBreakpoint(''); } public renameFunctionBreakpoint(id: string, newFunctionName: string): TPromise<void> { this.model.updateFunctionBreakpoints({ [id]: { name: newFunctionName } }); return this.sendFunctionBreakpoints(); } public removeFunctionBreakpoints(id?: string): TPromise<void> { this.model.removeFunctionBreakpoints(id); return this.sendFunctionBreakpoints(); } public addReplExpression(name: string): TPromise<void> { this.telemetryService.publicLog('debugService/addReplExpression'); return this.model.addReplExpression(this.viewModel.focusedProcess, this.viewModel.focusedStackFrame, name) // Evaluate all watch expressions again since repl evaluation might have changed some. .then(() => this.setFocusedStackFrameAndEvaluate(this.viewModel.focusedStackFrame)); } public logToRepl(value: string | { [key: string]: any }, severity?: severity): void { this.model.logToRepl(value, severity); } public appendReplOutput(value: string, severity?: severity): void { this.model.appendReplOutput(value, severity); } public removeReplExpressions(): void { this.model.removeReplExpressions(); } public addWatchExpression(name: string): TPromise<void> { return this.model.addWatchExpression(this.viewModel.focusedProcess, this.viewModel.focusedStackFrame, name); } public renameWatchExpression(id: string, newName: string): TPromise<void> { return this.model.renameWatchExpression(this.viewModel.focusedProcess, this.viewModel.focusedStackFrame, id, newName); } public removeWatchExpressions(id?: string): void { this.model.removeWatchExpressions(id); } public createProcess(configurationOrName: debug.IConfig | string): TPromise<any> { this.removeReplExpressions(); const sessionId = generateUuid(); this.setStateAndEmit(sessionId, debug.State.Initializing); return this.textFileService.saveAll() // make sure all dirty files are saved .then(() => this.configurationService.reloadConfiguration() // make sure configuration is up to date .then(() => this.extensionService.onReady() .then(() => this.configurationManager.getConfiguration(configurationOrName) .then(configuration => { if (!configuration) { return this.configurationManager.openConfigFile(false).then(openend => { if (openend) { this.messageService.show(severity.Info, nls.localize('NewLaunchConfig', "Please set up the launch configuration file for your application.")); } }); } if (configuration.silentlyAbort) { return; } if (strings.equalsIgnoreCase(configuration.type, 'composite') && configuration.configurationNames) { return TPromise.join(configuration.configurationNames.map(name => this.createProcess(name))); } if (!this.configurationManager.getAdapter(configuration.type)) { return configuration.type ? TPromise.wrapError(new Error(nls.localize('debugTypeNotSupported', "Configured debug type '{0}' is not supported.", configuration.type))) : TPromise.wrapError(errors.create(nls.localize('debugTypeMissing', "Missing property 'type' for the chosen launch configuration."), { actions: [this.instantiationService.createInstance(debugactions.ConfigureAction, debugactions.ConfigureAction.ID, debugactions.ConfigureAction.LABEL), CloseAction] })); } return this.runPreLaunchTask(configuration.preLaunchTask).then((taskSummary: ITaskSummary) => { const errorCount = configuration.preLaunchTask ? this.markerService.getStatistics().errors : 0; const successExitCode = taskSummary && taskSummary.exitCode === 0; const failureExitCode = taskSummary && taskSummary.exitCode !== undefined && taskSummary.exitCode !== 0; if (successExitCode || (errorCount === 0 && !failureExitCode)) { return this.doCreateProcess(sessionId, configuration); } this.messageService.show(severity.Error, { message: errorCount > 1 ? nls.localize('preLaunchTaskErrors', "Build errors have been detected during preLaunchTask '{0}'.", configuration.preLaunchTask) : errorCount === 1 ? nls.localize('preLaunchTaskError', "Build error has been detected during preLaunchTask '{0}'.", configuration.preLaunchTask) : nls.localize('preLaunchTaskExitCode', "The preLaunchTask '{0}' terminated with exit code {1}.", configuration.preLaunchTask, taskSummary.exitCode), actions: [new Action('debug.continue', nls.localize('debugAnyway', "Debug Anyway"), null, true, () => { this.messageService.hideAll(); return this.doCreateProcess(sessionId, configuration); }), CloseAction] }); }, (err: TaskError) => { if (err.code !== TaskErrors.NotConfigured) { throw err; } this.messageService.show(err.severity, { message: err.message, actions: [this.taskService.configureAction(), CloseAction] }); }); })))); } private doCreateProcess(sessionId: string, configuration: debug.IConfig): TPromise<any> { return this.telemetryService.getTelemetryInfo().then(info => { const telemetryInfo: { [key: string]: string } = Object.create(null); telemetryInfo['common.vscodemachineid'] = info.machineId; telemetryInfo['common.vscodesessionid'] = info.sessionId; return telemetryInfo; }).then(data => { const adapter = this.configurationManager.getAdapter(configuration.type); const { aiKey, type } = adapter; const publisher = adapter.extensionDescription.publisher; this.customTelemetryService = null; let client: TelemetryClient; if (aiKey) { client = new TelemetryClient( uri.parse(require.toUrl('bootstrap')).fsPath, { serverName: 'Debug Telemetry', timeout: 1000 * 60 * 5, args: [`${publisher}.${type}`, JSON.stringify(data), aiKey], env: { ELECTRON_RUN_AS_NODE: 1, PIPE_LOGGING: 'true', AMD_ENTRYPOINT: 'vs/workbench/parts/debug/node/telemetryApp' } } ); const channel = client.getChannel('telemetryAppender'); const appender = new TelemetryAppenderClient(channel); this.customTelemetryService = new TelemetryService({ appender }, this.configurationService); } const session = this.instantiationService.createInstance(RawDebugSession, sessionId, configuration.debugServer, adapter, this.customTelemetryService); this.model.addProcess(configuration.name, session); this.toDisposeOnSessionEnd[session.getId()] = []; if (client) { this.toDisposeOnSessionEnd[session.getId()].push(client); } this.registerSessionListeners(session); return session.initialize({ adapterID: configuration.type, pathFormat: 'path', linesStartAt1: true, columnsStartAt1: true, supportsVariableType: true, // #8858 supportsVariablePaging: true, // #9537 supportsRunInTerminalRequest: true // #10574 }).then((result: DebugProtocol.InitializeResponse) => { if (session.disconnected) { return TPromise.wrapError(new Error(nls.localize('debugAdapterCrash', "Debug adapter process has terminated unexpectedly"))); } this.model.setExceptionBreakpoints(session.configuration.capabilities.exceptionBreakpointFilters); return configuration.request === 'attach' ? session.attach(configuration) : session.launch(configuration); }).then((result: DebugProtocol.Response) => { if (session.disconnected) { return TPromise.as(null); } if (configuration.internalConsoleOptions === 'openOnSessionStart' || (!this.viewModel.changedWorkbenchViewState && configuration.internalConsoleOptions !== 'neverOpen')) { this.panelService.openPanel(debug.REPL_ID, false).done(undefined, errors.onUnexpectedError); } if (!this.viewModel.changedWorkbenchViewState && !this.partService.isSideBarHidden()) { // We only want to change the workbench view state on the first debug session #5738 and if the side bar is not hidden this.viewModel.changedWorkbenchViewState = true; this.viewletService.openViewlet(debug.VIEWLET_ID); } // Do not change status bar to orange if we are just running without debug. if (!configuration.noDebug) { this.partService.addClass('debugging'); } this.extensionService.activateByEvent(`onDebug:${configuration.type}`).done(null, errors.onUnexpectedError); this.inDebugMode.set(true); this.transitionToRunningState(session); this.telemetryService.publicLog('debugSessionStart', { type: configuration.type, breakpointCount: this.model.getBreakpoints().length, exceptionBreakpoints: this.model.getExceptionBreakpoints(), watchExpressionsCount: this.model.getWatchExpressions().length, extensionName: `${adapter.extensionDescription.publisher}.${adapter.extensionDescription.name}`, isBuiltin: adapter.extensionDescription.isBuiltin }); }).then(undefined, (error: any) => { if (error instanceof Error && error.message === 'Canceled') { // Do not show 'canceled' error messages to the user #7906 return TPromise.as(null); } this.telemetryService.publicLog('debugMisconfiguration', { type: configuration ? configuration.type : undefined }); this.setStateAndEmit(session.getId(), debug.State.Inactive); if (!session.disconnected) { session.disconnect().done(null, errors.onUnexpectedError); } // Show the repl if some error got logged there #5870 if (this.model.getReplElements().length > 0) { this.panelService.openPanel(debug.REPL_ID, false).done(undefined, errors.onUnexpectedError); } const configureAction = this.instantiationService.createInstance(debugactions.ConfigureAction, debugactions.ConfigureAction.ID, debugactions.ConfigureAction.LABEL); const actions = (error.actions && error.actions.length) ? error.actions.concat([configureAction]) : [CloseAction, configureAction]; return TPromise.wrapError(errors.create(error.message, { actions })); }); }); } private runPreLaunchTask(taskName: string): TPromise<ITaskSummary> { if (!taskName) { return TPromise.as(null); } // run a task before starting a debug session return this.taskService.tasks().then(descriptions => { const filteredTasks = descriptions.filter(task => task.name === taskName); if (filteredTasks.length !== 1) { return TPromise.wrapError(errors.create(nls.localize('DebugTaskNotFound', "Could not find the preLaunchTask \'{0}\'.", taskName), { actions: [ this.instantiationService.createInstance(debugactions.ConfigureAction, debugactions.ConfigureAction.ID, debugactions.ConfigureAction.LABEL), this.taskService.configureAction(), CloseAction ] })); } // task is already running - nothing to do. if (this.lastTaskEvent && this.lastTaskEvent.taskName === taskName) { return TPromise.as(null); } if (this.lastTaskEvent) { // there is a different task running currently. return TPromise.wrapError(errors.create(nls.localize('differentTaskRunning', "There is a task {0} running. Can not run pre launch task {1}.", this.lastTaskEvent.taskName, taskName))); } // no task running, execute the preLaunchTask. const taskPromise = this.taskService.run(filteredTasks[0].id).then(result => { this.lastTaskEvent = null; return result; }, err => { this.lastTaskEvent = null; }); if (filteredTasks[0].isWatching) { return new TPromise((c, e) => this.taskService.addOneTimeDisposableListener(TaskServiceEvents.Inactive, () => c(null))); } return taskPromise; }); } private rawAttach(session: RawDebugSession, port: number): TPromise<any> { if (session) { return session.attach({ port }); } const sessionId = generateUuid(); this.setStateAndEmit(sessionId, debug.State.Initializing); return this.configurationManager.getConfiguration(this.viewModel.selectedConfigurationName).then(config => this.doCreateProcess(sessionId, config) ); } public restartProcess(process: debug.IProcess): TPromise<any> { return process ? process.session.disconnect(true).then(() => new TPromise<void>((c, e) => { setTimeout(() => { this.createProcess(process.name).then(() => c(null), err => e(err)); }, 300); }) ) : this.createProcess(this.viewModel.selectedConfigurationName); } private onSessionEnd(session: RawDebugSession): void { if (session) { const bpsExist = this.model.getBreakpoints().length > 0; this.telemetryService.publicLog('debugSessionStop', { type: session.configuration.type, success: session.emittedStopped || !bpsExist, sessionLengthInSeconds: session.getLengthInSeconds(), breakpointCount: this.model.getBreakpoints().length, watchExpressionsCount: this.model.getWatchExpressions().length }); } try { this.toDisposeOnSessionEnd[session.getId()] = lifecycle.dispose(this.toDisposeOnSessionEnd[session.getId()]); } catch (e) { // an internal module might be open so the dispose can throw -> ignore and continue with stop session. } this.model.removeProcess(session.getId()); this.setFocusedStackFrameAndEvaluate(null).done(null, errors.onUnexpectedError); this.setStateAndEmit(session.getId(), debug.State.Inactive); if (this.model.getProcesses().length === 0) { this.partService.removeClass('debugging'); // set breakpoints back to unverified since the session ended. const data: { [id: string]: { line: number, verified: boolean } } = {}; this.model.getBreakpoints().forEach(bp => { data[bp.getId()] = { line: bp.lineNumber, verified: false }; }); this.model.updateBreakpoints(data); this.inDebugMode.reset(); if (!this.partService.isSideBarHidden() && this.configurationService.getConfiguration<debug.IDebugConfiguration>('debug').openExplorerOnEnd) { this.viewletService.openViewlet(EXPLORER_VIEWLET_ID).done(null, errors.onUnexpectedError); } } } public getModel(): debug.IModel { return this.model; } public getViewModel(): debug.IViewModel { return this.viewModel; } public openOrRevealSource(sourceOrUri: Source | uri, lineNumber: number, preserveFocus: boolean, sideBySide: boolean): TPromise<any> { const visibleEditors = this.editorService.getVisibleEditors(); const uri = sourceOrUri instanceof Source ? sourceOrUri.uri : sourceOrUri; const source = sourceOrUri instanceof Source ? sourceOrUri : null; for (let i = 0; i < visibleEditors.length; i++) { const fileInput = asFileEditorInput(visibleEditors[i].input); if ((fileInput && fileInput.getResource().toString() === uri.toString()) || (visibleEditors[i].input instanceof DebugStringEditorInput && (<DebugStringEditorInput>visibleEditors[i].input).getResource().toString() === uri.toString())) { const control = <ICodeEditor>visibleEditors[i].getControl(); if (control) { control.revealLineInCenterIfOutsideViewport(lineNumber); control.setSelection({ startLineNumber: lineNumber, startColumn: 1, endLineNumber: lineNumber, endColumn: 1 }); this.editorGroupService.activateGroup(i); if (!preserveFocus) { this.editorGroupService.focusGroup(i); } } return TPromise.as(null); } } const process = this.viewModel.focusedProcess; if (process && source && source.inMemory) { // internal module if (source.reference !== 0 && source.available) { return process.session.source({ sourceReference: source.reference }).then(response => { const mime = response && response.body && response.body.mimeType ? response.body.mimeType : guessMimeTypes(source.name)[0]; const inputValue = response && response.body ? response.body.content : ''; return this.getDebugStringEditorInput(process, source, inputValue, mime); }, (err: DebugProtocol.ErrorResponse) => { // Display the error from debug adapter using a temporary editor #8836 return this.getDebugErrorEditorInput(process, source, err.message); }).then(editorInput => { return this.editorService.openEditor(editorInput, { preserveFocus, selection: { startLineNumber: lineNumber, startColumn: 1, endLineNumber: lineNumber, endColumn: 1 } }, sideBySide); }); } return this.sourceIsUnavailable(process, source, sideBySide); } if (Source.isInMemory(uri)) { return TPromise.as(null); } return this.fileService.resolveFile(uri).then(() => this.editorService.openEditor({ resource: uri, options: { selection: { startLineNumber: lineNumber, startColumn: 1, endLineNumber: lineNumber, endColumn: 1 }, preserveFocus: preserveFocus } }, sideBySide), err => this.sourceIsUnavailable(process, source, sideBySide) ); } private sourceIsUnavailable(process: debug.IProcess, source: Source, sideBySide: boolean): TPromise<any> { this.model.sourceIsUnavailable(source); const editorInput = this.getDebugErrorEditorInput(process, source, nls.localize('debugSourceNotAvailable', "Source {0} is not available.", source.name)); return this.editorService.openEditor(editorInput, { preserveFocus: true }, sideBySide); } public getConfigurationManager(): debug.IConfigurationManager { return this.configurationManager; } private transitionToRunningState(session: RawDebugSession, threadId?: number): void { this.model.clearThreads(session.getId(), false, threadId); this.setStateAndEmit(session.getId(), session.requestType === debug.SessionRequestType.LAUNCH_NO_DEBUG ? debug.State.RunningNoDebug : debug.State.Running); this.setFocusedStackFrameAndEvaluate(null).done(null, errors.onUnexpectedError); } private getDebugStringEditorInput(process: debug.IProcess, source: Source, value: string, mtype: string): DebugStringEditorInput { const result = this.instantiationService.createInstance(DebugStringEditorInput, source.name, source.uri, source.origin, value, mtype, void 0); this.toDisposeOnSessionEnd[process.getId()].push(result); return result; } private getDebugErrorEditorInput(process: debug.IProcess, source: Source, value: string): DebugErrorEditorInput { const result = this.instantiationService.createInstance(DebugErrorEditorInput, source.name, value); this.toDisposeOnSessionEnd[process.getId()].push(result); return result; } private sendAllBreakpoints(process?: debug.IProcess): TPromise<any> { return TPromise.join(distinct(this.model.getBreakpoints(), bp => bp.uri.toString()).map(bp => this.sendBreakpoints(bp.uri, false, process))) .then(() => this.sendFunctionBreakpoints(process)) // send exception breakpoints at the end since some debug adapters rely on the order .then(() => this.sendExceptionBreakpoints(process)); } private sendBreakpoints(modelUri: uri, sourceModified = false, targetProcess?: debug.IProcess): TPromise<void> { const sendBreakpointsToProcess = (process: debug.IProcess): TPromise<void> => { const session = <RawDebugSession>process.session; if (!session.readyForBreakpoints) { return TPromise.as(null); } if (this.textFileService.isDirty(modelUri)) { // Only send breakpoints for a file once it is not dirty #8077 this.breakpointsToSendOnResourceSaved[modelUri.toString()] = true; return TPromise.as(null); } const breakpointsToSend = distinct( this.model.getBreakpoints().filter(bp => this.model.areBreakpointsActivated() && bp.enabled && bp.uri.toString() === modelUri.toString()), bp => `${bp.desiredLineNumber}` ); let rawSource: DebugProtocol.Source; for (let t of process.getAllThreads()) { for (let sf of t.getCachedCallStack()) { if (sf.source.uri.toString() === modelUri.toString()) { rawSource = sf.source.raw; break; } } } rawSource = rawSource || { path: paths.normalize(modelUri.fsPath, true), name: paths.basename(modelUri.fsPath) }; return session.setBreakpoints({ source: rawSource, lines: breakpointsToSend.map(bp => bp.desiredLineNumber), breakpoints: breakpointsToSend.map(bp => ({ line: bp.desiredLineNumber, condition: bp.condition, hitCondition: bp.hitCondition })), sourceModified }).then(response => { if (!response || !response.body) { return; } const data: { [id: string]: { line?: number, verified: boolean } } = {}; for (let i = 0; i < breakpointsToSend.length; i++) { data[breakpointsToSend[i].getId()] = response.body.breakpoints[i]; } this.model.updateBreakpoints(data); }); }; return this.sendToOneOrAllProcesses(targetProcess, sendBreakpointsToProcess); } private sendFunctionBreakpoints(targetProcess?: debug.IProcess): TPromise<void> { const sendFunctionBreakpointsToProcess = (process: debug.IProcess): TPromise<void> => { const session = <RawDebugSession>process.session; if (!session.readyForBreakpoints || !session.configuration.capabilities.supportsFunctionBreakpoints) { return TPromise.as(null); } const breakpointsToSend = this.model.getFunctionBreakpoints().filter(fbp => fbp.enabled && this.model.areBreakpointsActivated()); return session.setFunctionBreakpoints({ breakpoints: breakpointsToSend }).then(response => { if (!response || !response.body) { return; } const data: { [id: string]: { name?: string, verified?: boolean } } = {}; for (let i = 0; i < breakpointsToSend.length; i++) { data[breakpointsToSend[i].getId()] = response.body.breakpoints[i]; } this.model.updateFunctionBreakpoints(data); }); }; return this.sendToOneOrAllProcesses(targetProcess, sendFunctionBreakpointsToProcess); } private sendExceptionBreakpoints(targetProcess?: debug.IProcess): TPromise<void> { const sendExceptionBreakpointsToProcess = (process: debug.IProcess): TPromise<any> => { const session = <RawDebugSession>process.session; if (!session.readyForBreakpoints || this.model.getExceptionBreakpoints().length === 0) { return TPromise.as(null); } const enabledExceptionBps = this.model.getExceptionBreakpoints().filter(exb => exb.enabled); return session.setExceptionBreakpoints({ filters: enabledExceptionBps.map(exb => exb.filter) }); }; return this.sendToOneOrAllProcesses(targetProcess, sendExceptionBreakpointsToProcess); } private sendToOneOrAllProcesses(process: debug.IProcess, send: (process: debug.IProcess) => TPromise<void>): TPromise<void> { if (process) { return send(process); } return TPromise.join(this.model.getProcesses().map(p => send(p))).then(() => void 0); } private onFileChanges(fileChangesEvent: FileChangesEvent): void { this.model.removeBreakpoints(this.model.getBreakpoints().filter(bp => fileChangesEvent.contains(bp.uri, FileChangeType.DELETED))); fileChangesEvent.getUpdated().forEach(event => { if (this.breakpointsToSendOnResourceSaved[event.resource.toString()]) { this.breakpointsToSendOnResourceSaved[event.resource.toString()] = false; this.sendBreakpoints(event.resource, true).done(null, errors.onUnexpectedError); } }); } private store(): void { this.storageService.store(DEBUG_BREAKPOINTS_KEY, JSON.stringify(this.model.getBreakpoints()), StorageScope.WORKSPACE); this.storageService.store(DEBUG_BREAKPOINTS_ACTIVATED_KEY, this.model.areBreakpointsActivated() ? 'true' : 'false', StorageScope.WORKSPACE); this.storageService.store(DEBUG_FUNCTION_BREAKPOINTS_KEY, JSON.stringify(this.model.getFunctionBreakpoints()), StorageScope.WORKSPACE); this.storageService.store(DEBUG_EXCEPTION_BREAKPOINTS_KEY, JSON.stringify(this.model.getExceptionBreakpoints()), StorageScope.WORKSPACE); this.storageService.store(DEBUG_SELECTED_CONFIG_NAME_KEY, this.viewModel.selectedConfigurationName, StorageScope.WORKSPACE); this.storageService.store(DEBUG_WATCH_EXPRESSIONS_KEY, JSON.stringify(this.model.getWatchExpressions().map(we => ({ name: we.name, id: we.getId() }))), StorageScope.WORKSPACE); } public dispose(): void { Object.keys(this.toDisposeOnSessionEnd).forEach(key => lifecycle.dispose(this.toDisposeOnSessionEnd[key])); this.toDispose = lifecycle.dispose(this.toDispose); } }
src/vs/workbench/parts/debug/electron-browser/debugService.ts
1
https://github.com/microsoft/vscode/commit/318bafe3a8822a8dd40d91e555d9377a84b34e07
[ 0.9982688426971436, 0.07472812384366989, 0.0001630357000976801, 0.00017951462359633297, 0.2315746694803238 ]
{ "id": 3, "code_window": [ "\t\t\t}\n", "\n", "\t\t\tconst session = this.instantiationService.createInstance(RawDebugSession, sessionId, configuration.debugServer, adapter, this.customTelemetryService);\n", "\t\t\tthis.model.addProcess(configuration.name, session);\n", "\t\t\tthis.toDisposeOnSessionEnd[session.getId()] = [];\n", "\t\t\tif (client) {\n", "\t\t\t\tthis.toDisposeOnSessionEnd[session.getId()].push(client);\n", "\t\t\t}\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tconst process = this.model.addProcess(configuration.name, session);\n", "\n", "\t\t\tif (!this.viewModel.focusedProcess) {\n", "\t\t\t\tthis.viewModel.setFocusedStackFrame(null, process);\n", "\t\t\t}\n" ], "file_path": "src/vs/workbench/parts/debug/electron-browser/debugService.ts", "type": "replace", "edit_start_line_idx": 634 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ // Do not edit this file. It is machine generated. { "label": "Gehe zu Zeile..." }
i18n/deu/src/vs/editor/contrib/quickOpen/browser/gotoLine.contribution.i18n.json
0
https://github.com/microsoft/vscode/commit/318bafe3a8822a8dd40d91e555d9377a84b34e07
[ 0.00017619357095099986, 0.00017619357095099986, 0.00017619357095099986, 0.00017619357095099986, 0 ]
{ "id": 3, "code_window": [ "\t\t\t}\n", "\n", "\t\t\tconst session = this.instantiationService.createInstance(RawDebugSession, sessionId, configuration.debugServer, adapter, this.customTelemetryService);\n", "\t\t\tthis.model.addProcess(configuration.name, session);\n", "\t\t\tthis.toDisposeOnSessionEnd[session.getId()] = [];\n", "\t\t\tif (client) {\n", "\t\t\t\tthis.toDisposeOnSessionEnd[session.getId()].push(client);\n", "\t\t\t}\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tconst process = this.model.addProcess(configuration.name, session);\n", "\n", "\t\t\tif (!this.viewModel.focusedProcess) {\n", "\t\t\t\tthis.viewModel.setFocusedStackFrame(null, process);\n", "\t\t\t}\n" ], "file_path": "src/vs/workbench/parts/debug/electron-browser/debugService.ts", "type": "replace", "edit_start_line_idx": 634 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ // Do not edit this file. It is machine generated. { "copyMarker": "Copia" }
i18n/ita/src/vs/workbench/parts/markers/electron-browser/markersElectronContributions.i18n.json
0
https://github.com/microsoft/vscode/commit/318bafe3a8822a8dd40d91e555d9377a84b34e07
[ 0.0001767744543030858, 0.0001767744543030858, 0.0001767744543030858, 0.0001767744543030858, 0 ]
{ "id": 3, "code_window": [ "\t\t\t}\n", "\n", "\t\t\tconst session = this.instantiationService.createInstance(RawDebugSession, sessionId, configuration.debugServer, adapter, this.customTelemetryService);\n", "\t\t\tthis.model.addProcess(configuration.name, session);\n", "\t\t\tthis.toDisposeOnSessionEnd[session.getId()] = [];\n", "\t\t\tif (client) {\n", "\t\t\t\tthis.toDisposeOnSessionEnd[session.getId()].push(client);\n", "\t\t\t}\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\tconst process = this.model.addProcess(configuration.name, session);\n", "\n", "\t\t\tif (!this.viewModel.focusedProcess) {\n", "\t\t\t\tthis.viewModel.setFocusedStackFrame(null, process);\n", "\t\t\t}\n" ], "file_path": "src/vs/workbench/parts/debug/electron-browser/debugService.ts", "type": "replace", "edit_start_line_idx": 634 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ // Do not edit this file. It is machine generated. { "dirtyFiles": "{0} archivos no guardados" }
i18n/esn/src/vs/workbench/parts/files/browser/fileTracker.i18n.json
0
https://github.com/microsoft/vscode/commit/318bafe3a8822a8dd40d91e555d9377a84b34e07
[ 0.00017598990234546363, 0.00017598990234546363, 0.00017598990234546363, 0.00017598990234546363, 0 ]
{ "id": 0, "code_window": [ " display: 'flex',\n", " flexWrap: 'wrap',\n", " },\n", " input: {\n", " margin: theme.spacing.unit,\n", " },\n", "}));\n", "\n", "class TextFields extends Component {\n", " state = {\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " width: 200,\n" ], "file_path": "docs/src/pages/component-demos/text-fields/TextFields.js", "type": "add", "edit_start_line_idx": 14 }
// @flow import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { withStyles, createStyleSheet } from 'material-ui/styles'; import TextField from 'material-ui/TextField'; const styleSheet = createStyleSheet('TextFields', theme => ({ container: { display: 'flex', flexWrap: 'wrap', }, input: { margin: theme.spacing.unit, }, })); class TextFields extends Component { state = { name: 'Cat in the Hat', }; render() { const classes = this.props.classes; return ( <div className={classes.container}> <TextField id="name" label="Name" className={classes.input} value={this.state.name} onChange={event => this.setState({ name: event.target.value })} /> <TextField id="uncontrolled" label="Uncontrolled" defaultValue="foo" className={classes.input} /> <TextField required id="required" label="Required" defaultValue="Hello World" className={classes.input} /> <TextField error id="error" label="Error" defaultValue="Hello World" className={classes.input} /> <TextField id="password" label="Password" className={classes.input} type="password" /> <TextField id="multiline-flexible" label="Multiline" multiline rowsMax="4" defaultValue="Default Value" className={classes.input} /> <TextField id="multiline-static" label="Multiline" multiline rows="4" defaultValue="Default Value" className={classes.input} /> </div> ); } } TextFields.propTypes = { classes: PropTypes.object.isRequired, }; export default withStyles(styleSheet)(TextFields);
docs/src/pages/component-demos/text-fields/TextFields.js
1
https://github.com/mui/material-ui/commit/2611239179c1457b8e5fd9513d2d32b67b8e90f2
[ 0.9989945292472839, 0.4436090290546417, 0.00016671602497808635, 0.00016971291915979236, 0.49578264355659485 ]
{ "id": 0, "code_window": [ " display: 'flex',\n", " flexWrap: 'wrap',\n", " },\n", " input: {\n", " margin: theme.spacing.unit,\n", " },\n", "}));\n", "\n", "class TextFields extends Component {\n", " state = {\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " width: 200,\n" ], "file_path": "docs/src/pages/component-demos/text-fields/TextFields.js", "type": "add", "edit_start_line_idx": 14 }
<svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 48 48"><path d="M44 11.44l-9.19-7.71-2.57 3.06 9.19 7.71L44 11.44zM15.76 6.78l-2.57-3.06L4 11.43l2.57 3.06 9.19-7.71zM25 16h-3v12l9.49 5.71L33 31.24l-8-4.74V16zm-1.01-8C14.04 8 6 16.06 6 26s8.04 18 17.99 18S42 35.94 42 26 33.94 8 23.99 8zM24 40c-7.73 0-14-6.27-14-14s6.27-14 14-14 14 6.27 14 14-6.26 14-14 14z"/></svg>
packages/material-ui-icons/test/fixtures/material-design-icons/svg/action/svg/production/ic_alarm_48px.svg
0
https://github.com/mui/material-ui/commit/2611239179c1457b8e5fd9513d2d32b67b8e90f2
[ 0.00016903495998121798, 0.00016903495998121798, 0.00016903495998121798, 0.00016903495998121798, 0 ]
{ "id": 0, "code_window": [ " display: 'flex',\n", " flexWrap: 'wrap',\n", " },\n", " input: {\n", " margin: theme.spacing.unit,\n", " },\n", "}));\n", "\n", "class TextFields extends Component {\n", " state = {\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " width: 200,\n" ], "file_path": "docs/src/pages/component-demos/text-fields/TextFields.js", "type": "add", "edit_start_line_idx": 14 }
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from 'material-ui/SvgIcon'; let NavigateBefore = (props) => ( <SvgIcon {...props}> <path d="M15.41 7.41L14 6l-6 6 6 6 1.41-1.41L10.83 12z"/> </SvgIcon> ); NavigateBefore = pure(NavigateBefore); NavigateBefore.muiName = 'SvgIcon'; export default NavigateBefore;
packages/material-ui-icons/src/NavigateBefore.js
0
https://github.com/mui/material-ui/commit/2611239179c1457b8e5fd9513d2d32b67b8e90f2
[ 0.00017345001106150448, 0.00017221184680238366, 0.0001709736679913476, 0.00017221184680238366, 0.0000012381715350784361 ]
{ "id": 0, "code_window": [ " display: 'flex',\n", " flexWrap: 'wrap',\n", " },\n", " input: {\n", " margin: theme.spacing.unit,\n", " },\n", "}));\n", "\n", "class TextFields extends Component {\n", " state = {\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " width: 200,\n" ], "file_path": "docs/src/pages/component-demos/text-fields/TextFields.js", "type": "add", "edit_start_line_idx": 14 }
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from 'material-ui/SvgIcon'; let BatteryCharging50 = (props) => ( <SvgIcon {...props}> <path d="M14.47 13.5L11 20v-5.5H9l.53-1H7v7.17C7 21.4 7.6 22 8.33 22h7.33c.74 0 1.34-.6 1.34-1.33V13.5h-2.53z"/><path fillOpacity=".3" d="M15.67 4H14V2h-4v2H8.33C7.6 4 7 4.6 7 5.33v8.17h2.53L13 7v5.5h2l-.53 1H17V5.33C17 4.6 16.4 4 15.67 4z"/> </SvgIcon> ); BatteryCharging50 = pure(BatteryCharging50); BatteryCharging50.muiName = 'SvgIcon'; export default BatteryCharging50;
packages/material-ui-icons/src/BatteryCharging50.js
0
https://github.com/mui/material-ui/commit/2611239179c1457b8e5fd9513d2d32b67b8e90f2
[ 0.00018321715469937772, 0.00017717565060593188, 0.00017113414651248604, 0.00017717565060593188, 0.0000060415040934458375 ]
{ "id": 1, "code_window": [ " multiline\n", " rows=\"4\"\n", " defaultValue=\"Default Value\"\n", " className={classes.input}\n", " />\n", " </div>\n", " );\n", " }\n", "}\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " <TextField\n", " id=\"date\"\n", " label=\"From date\"\n", " type=\"date\"\n", " defaultValue=\"2017-05-24\"\n", " className={classes.input}\n", " />\n" ], "file_path": "docs/src/pages/component-demos/text-fields/TextFields.js", "type": "add", "edit_start_line_idx": 71 }
// @flow weak import React, { Component } from 'react'; import PropTypes from 'prop-types'; import classNames from 'classnames'; import { createStyleSheet } from 'jss-theme-reactor'; import withStyles from '../styles/withStyles'; import Textarea from './Textarea'; function isDirty(obj) { return obj && obj.value && obj.value.length > 0; } export const styleSheet = createStyleSheet('MuiInput', theme => ({ wrapper: { // Mimics the default input display property used by browsers for an input. display: 'inline-block', position: 'relative', fontFamily: theme.typography.fontFamily, }, formControl: { marginTop: 10, marginBottom: 10, }, inkbar: { '&:after': { backgroundColor: theme.palette.primary[500], left: 0, bottom: -2, // Doing the other way around crash on IE11 "''" https://github.com/cssinjs/jss/issues/242 content: '""', height: 2, position: 'absolute', right: 0, transform: 'scaleX(0)', transition: theme.transitions.create('transform', { duration: theme.transitions.duration.shorter, easing: theme.transitions.easing.easeOut, }), }, '&$focused:after': { transform: 'scaleX(1)', }, }, focused: {}, error: { '&:after': { backgroundColor: theme.palette.error[500], transform: 'scaleX(1)', // error is always underlined in red }, }, input: { font: 'inherit', padding: '6px 0', border: 0, display: 'block', verticalAlign: 'middle', whiteSpace: 'normal', background: 'none', margin: 0, // Reset for Safari color: theme.palette.text.primary, width: '100%', '&:focus': { outline: 0, }, '&::-webkit-search-decoration': { // Remove the padding when type=search. appearance: 'none', }, }, singleline: { appearance: 'textfield', // Improve type search style. }, multiline: { resize: 'none', padding: 0, }, multilineWrapper: { padding: '6px 0', }, disabled: { color: theme.palette.text.disabled, }, underline: { borderBottom: `1px solid ${theme.palette.text.divider}`, '&$disabled': { borderBottomStyle: 'dotted', }, }, })); class Input extends Component { static defaultProps = { disabled: false, type: 'text', disableUnderline: false, multiline: false, }; state = { focused: false, }; componentWillMount() { if (this.isControlled()) { this.checkDirty(this.props); } } componentDidMount() { if (!this.isControlled()) { this.checkDirty(this.input); } } componentWillUpdate(nextProps) { if (this.isControlled()) { this.checkDirty(nextProps); } } // Holds the input reference input = null; handleFocus = event => { this.setState({ focused: true }); if (this.props.onFocus) { this.props.onFocus(event); } }; handleBlur = event => { this.setState({ focused: false }); if (this.props.onBlur) { this.props.onBlur(event); } }; handleChange = event => { if (!this.isControlled()) { this.checkDirty(this.input); } if (this.props.onChange) { this.props.onChange(event); } }; handleRefInput = node => { this.input = node; if (this.props.inputRef) { this.props.inputRef(node); } }; handleRefTextarea = node => { this.input = node; if (this.props.inputRef) { this.props.inputRef(node); } }; isControlled() { return typeof this.props.value === 'string'; } checkDirty(obj) { const { muiFormControl } = this.context; if (isDirty(obj)) { if (muiFormControl && muiFormControl.onDirty) { muiFormControl.onDirty(); } if (this.props.onDirty) { this.props.onDirty(); } return; } if (muiFormControl && muiFormControl.onClean) { muiFormControl.onClean(); } if (this.props.onClean) { this.props.onClean(); } } render() { const { classes, className: classNameProp, component, defaultValue, disabled, disableUnderline, error: errorProp, id, inputClassName: inputClassNameProp, inputProps: inputPropsProp, inputRef, // eslint-disable-line no-unused-vars multiline, onBlur, // eslint-disable-line no-unused-vars onFocus, // eslint-disable-line no-unused-vars onChange, // eslint-disable-line no-unused-vars onKeyDown, onKeyUp, placeholder, name, rows, rowsMax, type, value, ...other } = this.props; const { muiFormControl } = this.context; let error = errorProp; if (typeof error === 'undefined' && muiFormControl) { error = muiFormControl.error; } const wrapperClassName = classNames( classes.wrapper, { [classes.disabled]: disabled, [classes.error]: error, [classes.focused]: this.state.focused, [classes.formControl]: muiFormControl, [classes.inkbar]: !disableUnderline, [classes.multilineWrapper]: multiline, [classes.underline]: !disableUnderline, }, classNameProp, ); const inputClassName = classNames( classes.input, { [classes.disabled]: disabled, [classes.singleline]: !multiline, [classes.multiline]: multiline, }, inputClassNameProp, ); const required = muiFormControl && muiFormControl.required === true; let InputComponent = 'input'; let inputProps = { ref: this.handleRefInput, ...inputPropsProp, }; if (component) { inputProps = { rowsMax, ...inputProps, }; InputComponent = component; } else if (multiline) { if (rows && !rowsMax) { inputProps = { ...inputProps, }; InputComponent = 'textarea'; } else { inputProps = { rowsMax, textareaRef: this.handleRefTextarea, ...inputProps, ref: null, }; InputComponent = Textarea; } } return ( <div className={wrapperClassName} {...other}> <InputComponent className={inputClassName} onBlur={this.handleBlur} onFocus={this.handleFocus} onChange={this.handleChange} onKeyUp={onKeyUp} onKeyDown={onKeyDown} disabled={disabled} aria-required={required ? true : undefined} value={value} id={id} name={name} defaultValue={defaultValue} placeholder={placeholder} type={type} rows={rows} {...inputProps} /> </div> ); } } Input.propTypes = { /** * Useful to extend the style applied to components. */ classes: PropTypes.object.isRequired, /** * The CSS class name of the wrapper element. */ className: PropTypes.string, /** * The component used for the root node. * Either a string to use a DOM element or a component. * It's an `input` by default. */ component: PropTypes.oneOfType([PropTypes.string, PropTypes.func]), /** * The default value of the `Input` element. */ defaultValue: PropTypes.string, /** * If `true`, the input will be disabled. */ disabled: PropTypes.bool, /** * If `true`, the input will not have an underline. */ disableUnderline: PropTypes.bool, /** * If `true`, the input will indicate an error. */ error: PropTypes.bool, /* * @ignore */ id: PropTypes.string, /** * The CSS class name of the input element. */ inputClassName: PropTypes.string, /** * Properties applied to the `input` element. */ inputProps: PropTypes.object, /** * Use that property to pass a ref callback to the native input component. */ inputRef: PropTypes.func, /** * If `true`, a textarea element will be rendered. */ multiline: PropTypes.bool, /** * @ignore */ name: PropTypes.string, /** * @ignore */ onBlur: PropTypes.func, /** * @ignore */ onChange: PropTypes.func, /** * @ignore */ onClean: PropTypes.func, /** * @ignore */ onDirty: PropTypes.func, /** * @ignore */ onFocus: PropTypes.func, /** * @ignore */ onKeyDown: PropTypes.func, /** * @ignore */ onKeyUp: PropTypes.func, /** * @ignore */ placeholder: PropTypes.string, /** * Number of rows to display when multiline option is set to true. */ rows: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), /** * Maxium number of rows to display when multiline option is set to true. */ rowsMax: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), /** * Type of the input element. It should be a valid HTML5 input type. */ type: PropTypes.string, /** * The input value, required for a controlled component. */ value: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), }; Input.contextTypes = { muiFormControl: PropTypes.object, }; export default withStyles(styleSheet)(Input);
src/Input/Input.js
1
https://github.com/mui/material-ui/commit/2611239179c1457b8e5fd9513d2d32b67b8e90f2
[ 0.03065767139196396, 0.0018983538029715419, 0.0001610605395399034, 0.00017625396139919758, 0.005490269046276808 ]
{ "id": 1, "code_window": [ " multiline\n", " rows=\"4\"\n", " defaultValue=\"Default Value\"\n", " className={classes.input}\n", " />\n", " </div>\n", " );\n", " }\n", "}\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " <TextField\n", " id=\"date\"\n", " label=\"From date\"\n", " type=\"date\"\n", " defaultValue=\"2017-05-24\"\n", " className={classes.input}\n", " />\n" ], "file_path": "docs/src/pages/component-demos/text-fields/TextFields.js", "type": "add", "edit_start_line_idx": 71 }
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from 'material-ui/SvgIcon'; let OpenInNew = (props) => ( <SvgIcon {...props}> <path d="M19 19H5V5h7V3H5c-1.11 0-2 .9-2 2v14c0 1.1.89 2 2 2h14c1.1 0 2-.9 2-2v-7h-2v7zM14 3v2h3.59l-9.83 9.83 1.41 1.41L19 6.41V10h2V3h-7z"/> </SvgIcon> ); OpenInNew = pure(OpenInNew); OpenInNew.muiName = 'SvgIcon'; export default OpenInNew;
packages/material-ui-icons/src/OpenInNew.js
0
https://github.com/mui/material-ui/commit/2611239179c1457b8e5fd9513d2d32b67b8e90f2
[ 0.00017302481865044683, 0.00016891019186004996, 0.00016479557962156832, 0.00016891019186004996, 0.000004114619514439255 ]
{ "id": 1, "code_window": [ " multiline\n", " rows=\"4\"\n", " defaultValue=\"Default Value\"\n", " className={classes.input}\n", " />\n", " </div>\n", " );\n", " }\n", "}\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " <TextField\n", " id=\"date\"\n", " label=\"From date\"\n", " type=\"date\"\n", " defaultValue=\"2017-05-24\"\n", " className={classes.input}\n", " />\n" ], "file_path": "docs/src/pages/component-demos/text-fields/TextFields.js", "type": "add", "edit_start_line_idx": 71 }
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from 'material-ui/SvgIcon'; let AirlineSeatLegroomExtra = (props) => ( <SvgIcon {...props}> <path d="M4 12V3H2v9c0 2.76 2.24 5 5 5h6v-2H7c-1.66 0-3-1.34-3-3zm18.83 5.24c-.38-.72-1.29-.97-2.03-.63l-1.09.5-3.41-6.98c-.34-.68-1.03-1.12-1.79-1.12L11 9V3H5v8c0 1.66 1.34 3 3 3h7l3.41 7 3.72-1.7c.77-.36 1.1-1.3.7-2.06z"/> </SvgIcon> ); AirlineSeatLegroomExtra = pure(AirlineSeatLegroomExtra); AirlineSeatLegroomExtra.muiName = 'SvgIcon'; export default AirlineSeatLegroomExtra;
packages/material-ui-icons/src/AirlineSeatLegroomExtra.js
0
https://github.com/mui/material-ui/commit/2611239179c1457b8e5fd9513d2d32b67b8e90f2
[ 0.0001651130005484447, 0.0001650944905122742, 0.00016507598047610372, 0.0001650944905122742, 1.8510036170482635e-8 ]
{ "id": 1, "code_window": [ " multiline\n", " rows=\"4\"\n", " defaultValue=\"Default Value\"\n", " className={classes.input}\n", " />\n", " </div>\n", " );\n", " }\n", "}\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " <TextField\n", " id=\"date\"\n", " label=\"From date\"\n", " type=\"date\"\n", " defaultValue=\"2017-05-24\"\n", " className={classes.input}\n", " />\n" ], "file_path": "docs/src/pages/component-demos/text-fields/TextFields.js", "type": "add", "edit_start_line_idx": 71 }
// @flow weak const path = require('path'); const webpack = require('webpack'); const packageJson = require('./package.json'); const packageJsonSrc = require('../package.json'); const excludedDeps = ['lodash', 'recompose', 'object-assign', 'material-ui-icons', 'babel-runtime']; const deps = [ 'react-hot-loader/index', 'react-hot-loader/patch', 'eventsource-polyfill', 'webpack-dev-server/client', 'react-addons-perf', 'webpack/hot/log-apply-result', 'webpack-dev-server/client/index', ] .concat(Object.keys(packageJson.dependencies)) .concat(Object.keys(packageJsonSrc.dependencies)) .concat(Object.keys(packageJsonSrc.peerDependencies)) .filter(dep => { return excludedDeps.indexOf(dep) === -1; }); module.exports = { devtool: 'inline-source-map', entry: { lib: deps, }, output: { filename: 'dll.bundle.js', path: path.join(__dirname, 'build'), library: 'dll', }, plugins: [ new webpack.DllPlugin({ name: 'dll', path: 'build/dll.manifest.json', }), ], };
docs/webpack.dll.config.js
0
https://github.com/mui/material-ui/commit/2611239179c1457b8e5fd9513d2d32b67b8e90f2
[ 0.00017754492000676692, 0.00017534857033751905, 0.00017268018564209342, 0.00017515086801722646, 0.000001795470893739548 ]
{ "id": 2, "code_window": [ " input: {\n", " font: 'inherit',\n", " padding: '6px 0',\n", " border: 0,\n", " display: 'block',\n", " verticalAlign: 'middle',\n", " whiteSpace: 'normal',\n", " background: 'none',\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " boxSizing: 'content-box',\n" ], "file_path": "src/Input/Input.js", "type": "add", "edit_start_line_idx": 56 }
// @flow weak import React, { Component } from 'react'; import PropTypes from 'prop-types'; import classNames from 'classnames'; import { createStyleSheet } from 'jss-theme-reactor'; import withStyles from '../styles/withStyles'; import Textarea from './Textarea'; function isDirty(obj) { return obj && obj.value && obj.value.length > 0; } export const styleSheet = createStyleSheet('MuiInput', theme => ({ wrapper: { // Mimics the default input display property used by browsers for an input. display: 'inline-block', position: 'relative', fontFamily: theme.typography.fontFamily, }, formControl: { marginTop: 10, marginBottom: 10, }, inkbar: { '&:after': { backgroundColor: theme.palette.primary[500], left: 0, bottom: -2, // Doing the other way around crash on IE11 "''" https://github.com/cssinjs/jss/issues/242 content: '""', height: 2, position: 'absolute', right: 0, transform: 'scaleX(0)', transition: theme.transitions.create('transform', { duration: theme.transitions.duration.shorter, easing: theme.transitions.easing.easeOut, }), }, '&$focused:after': { transform: 'scaleX(1)', }, }, focused: {}, error: { '&:after': { backgroundColor: theme.palette.error[500], transform: 'scaleX(1)', // error is always underlined in red }, }, input: { font: 'inherit', padding: '6px 0', border: 0, display: 'block', verticalAlign: 'middle', whiteSpace: 'normal', background: 'none', margin: 0, // Reset for Safari color: theme.palette.text.primary, width: '100%', '&:focus': { outline: 0, }, '&::-webkit-search-decoration': { // Remove the padding when type=search. appearance: 'none', }, }, singleline: { appearance: 'textfield', // Improve type search style. }, multiline: { resize: 'none', padding: 0, }, multilineWrapper: { padding: '6px 0', }, disabled: { color: theme.palette.text.disabled, }, underline: { borderBottom: `1px solid ${theme.palette.text.divider}`, '&$disabled': { borderBottomStyle: 'dotted', }, }, })); class Input extends Component { static defaultProps = { disabled: false, type: 'text', disableUnderline: false, multiline: false, }; state = { focused: false, }; componentWillMount() { if (this.isControlled()) { this.checkDirty(this.props); } } componentDidMount() { if (!this.isControlled()) { this.checkDirty(this.input); } } componentWillUpdate(nextProps) { if (this.isControlled()) { this.checkDirty(nextProps); } } // Holds the input reference input = null; handleFocus = event => { this.setState({ focused: true }); if (this.props.onFocus) { this.props.onFocus(event); } }; handleBlur = event => { this.setState({ focused: false }); if (this.props.onBlur) { this.props.onBlur(event); } }; handleChange = event => { if (!this.isControlled()) { this.checkDirty(this.input); } if (this.props.onChange) { this.props.onChange(event); } }; handleRefInput = node => { this.input = node; if (this.props.inputRef) { this.props.inputRef(node); } }; handleRefTextarea = node => { this.input = node; if (this.props.inputRef) { this.props.inputRef(node); } }; isControlled() { return typeof this.props.value === 'string'; } checkDirty(obj) { const { muiFormControl } = this.context; if (isDirty(obj)) { if (muiFormControl && muiFormControl.onDirty) { muiFormControl.onDirty(); } if (this.props.onDirty) { this.props.onDirty(); } return; } if (muiFormControl && muiFormControl.onClean) { muiFormControl.onClean(); } if (this.props.onClean) { this.props.onClean(); } } render() { const { classes, className: classNameProp, component, defaultValue, disabled, disableUnderline, error: errorProp, id, inputClassName: inputClassNameProp, inputProps: inputPropsProp, inputRef, // eslint-disable-line no-unused-vars multiline, onBlur, // eslint-disable-line no-unused-vars onFocus, // eslint-disable-line no-unused-vars onChange, // eslint-disable-line no-unused-vars onKeyDown, onKeyUp, placeholder, name, rows, rowsMax, type, value, ...other } = this.props; const { muiFormControl } = this.context; let error = errorProp; if (typeof error === 'undefined' && muiFormControl) { error = muiFormControl.error; } const wrapperClassName = classNames( classes.wrapper, { [classes.disabled]: disabled, [classes.error]: error, [classes.focused]: this.state.focused, [classes.formControl]: muiFormControl, [classes.inkbar]: !disableUnderline, [classes.multilineWrapper]: multiline, [classes.underline]: !disableUnderline, }, classNameProp, ); const inputClassName = classNames( classes.input, { [classes.disabled]: disabled, [classes.singleline]: !multiline, [classes.multiline]: multiline, }, inputClassNameProp, ); const required = muiFormControl && muiFormControl.required === true; let InputComponent = 'input'; let inputProps = { ref: this.handleRefInput, ...inputPropsProp, }; if (component) { inputProps = { rowsMax, ...inputProps, }; InputComponent = component; } else if (multiline) { if (rows && !rowsMax) { inputProps = { ...inputProps, }; InputComponent = 'textarea'; } else { inputProps = { rowsMax, textareaRef: this.handleRefTextarea, ...inputProps, ref: null, }; InputComponent = Textarea; } } return ( <div className={wrapperClassName} {...other}> <InputComponent className={inputClassName} onBlur={this.handleBlur} onFocus={this.handleFocus} onChange={this.handleChange} onKeyUp={onKeyUp} onKeyDown={onKeyDown} disabled={disabled} aria-required={required ? true : undefined} value={value} id={id} name={name} defaultValue={defaultValue} placeholder={placeholder} type={type} rows={rows} {...inputProps} /> </div> ); } } Input.propTypes = { /** * Useful to extend the style applied to components. */ classes: PropTypes.object.isRequired, /** * The CSS class name of the wrapper element. */ className: PropTypes.string, /** * The component used for the root node. * Either a string to use a DOM element or a component. * It's an `input` by default. */ component: PropTypes.oneOfType([PropTypes.string, PropTypes.func]), /** * The default value of the `Input` element. */ defaultValue: PropTypes.string, /** * If `true`, the input will be disabled. */ disabled: PropTypes.bool, /** * If `true`, the input will not have an underline. */ disableUnderline: PropTypes.bool, /** * If `true`, the input will indicate an error. */ error: PropTypes.bool, /* * @ignore */ id: PropTypes.string, /** * The CSS class name of the input element. */ inputClassName: PropTypes.string, /** * Properties applied to the `input` element. */ inputProps: PropTypes.object, /** * Use that property to pass a ref callback to the native input component. */ inputRef: PropTypes.func, /** * If `true`, a textarea element will be rendered. */ multiline: PropTypes.bool, /** * @ignore */ name: PropTypes.string, /** * @ignore */ onBlur: PropTypes.func, /** * @ignore */ onChange: PropTypes.func, /** * @ignore */ onClean: PropTypes.func, /** * @ignore */ onDirty: PropTypes.func, /** * @ignore */ onFocus: PropTypes.func, /** * @ignore */ onKeyDown: PropTypes.func, /** * @ignore */ onKeyUp: PropTypes.func, /** * @ignore */ placeholder: PropTypes.string, /** * Number of rows to display when multiline option is set to true. */ rows: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), /** * Maxium number of rows to display when multiline option is set to true. */ rowsMax: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), /** * Type of the input element. It should be a valid HTML5 input type. */ type: PropTypes.string, /** * The input value, required for a controlled component. */ value: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), }; Input.contextTypes = { muiFormControl: PropTypes.object, }; export default withStyles(styleSheet)(Input);
src/Input/Input.js
1
https://github.com/mui/material-ui/commit/2611239179c1457b8e5fd9513d2d32b67b8e90f2
[ 0.9608780741691589, 0.02323613315820694, 0.000163618620717898, 0.0001725541369523853, 0.14643694460391998 ]
{ "id": 2, "code_window": [ " input: {\n", " font: 'inherit',\n", " padding: '6px 0',\n", " border: 0,\n", " display: 'block',\n", " verticalAlign: 'middle',\n", " whiteSpace: 'normal',\n", " background: 'none',\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " boxSizing: 'content-box',\n" ], "file_path": "src/Input/Input.js", "type": "add", "edit_start_line_idx": 56 }
# TableRow Will automatically set dynamic row height based on the material table element parent (head, body, etc). ## Props | Name | Type | Default | Description | |:-----|:-----|:--------|:------------| | children | node | | Should be valid `<tr>` children such as `TableCell`. | | classes | object | | Useful to extend the style applied to components. | | hover | bool | false | If `true`, the table row will shade on hover. | | selected | bool | false | If `true`, the table row will have the selected shading. | Any other properties supplied will be spread to the root element. ## Classes You can overrides all the class names injected by Material-UI thanks to the `classes` property. This property accepts the following keys: - `root` - `head` - `footer` - `hover` - `selected` Have a look at [overriding with class names](/customization/overrides#overriding-with-class-names) section for more detail. If using the `overrides` key of the theme as documented [here](/customization/themes#customizing-all-instances-of-a-component-type), you need to use the following style sheet name: `MuiTableRow`.
docs/src/pages/component-api/Table/TableRow.md
0
https://github.com/mui/material-ui/commit/2611239179c1457b8e5fd9513d2d32b67b8e90f2
[ 0.0001752768293954432, 0.00017074031347874552, 0.00016823981422930956, 0.00016972229059319943, 0.00000276535797638644 ]