prefix
stringlengths 82
32.6k
| middle
stringlengths 5
470
| suffix
stringlengths 0
81.2k
| file_path
stringlengths 6
168
| repo_name
stringlengths 16
77
| context
listlengths 5
5
| lang
stringclasses 4
values | ground_truth
stringlengths 5
470
|
---|---|---|---|---|---|---|---|
import { useEffect, useLayoutEffect, useRef } from 'react';
import { PlayIcon } from '@heroicons/react/24/outline';
import MonacoEditor from '@monaco-editor/react';
import { editor } from 'monaco-editor';
import useFile from '../hooks/useFile';
import useFilesMutations from '../hooks/useFilesMutations';
import Button from './Button';
import K from './Hotkey';
interface EditorProps {
onRunCode?: (code: string) => void;
showRunButton?: boolean;
}
interface CoreEditorProps extends EditorProps {
onSave: (content: string) => void;
onChange: (value: string) => void;
value: string;
}
const CoreEditor = (props: CoreEditorProps): JSX.Element => {
const ref = useRef<editor.IStandaloneCodeEditor>();
const handleShortcut = (e: KeyboardEvent) => {
const isMod = navigator.platform.startsWith('Mac') ? e.metaKey : e.ctrlKey;
if (isMod && e.key === 's') {
e.preventDefault();
const content = ref.current?.getValue();
if (content !== undefined) props.onSave(content);
}
if (e.key === 'F5') {
e.preventDefault();
saveThenRunCode();
}
};
useEffect(() => {
window.addEventListener('keydown', handleShortcut);
return () => window.removeEventListener('keydown', handleShortcut);
}, [handleShortcut]);
const saveThenRunCode = () => {
const content = ref.current?.getValue() ?? '';
props.onSave(content);
props.onRunCode?.(content);
};
return (
<section className="windowed h-full w-full">
<MonacoEditor
defaultLanguage="python"
onChange={(value) =>
value !== undefined ? props.onChange(value) : null
}
onMount={(editor) => (ref.current = editor)}
options={{
fontSize: 14,
fontFamily: 'monospace',
smoothScrolling: true,
cursorSmoothCaretAnimation: 'on',
minimap: { enabled: false },
}}
theme="vs-dark"
value={props.value}
/>
{props.showRunButton && (
<div className="absolute bottom-3 right-3 space-x-2">
<Button icon={PlayIcon} onClick={saveThenRunCode}>
Run
<K className="ml-2 text-blue-900/60 ring-blue-900/60" of="F5" />
</Button>
</div>
)}
</section>
);
};
const Editor = (props: EditorProps): JSX.Element | null => {
const { update, save } = useFilesMutations();
|
const { name, content } = useFile.Selected();
|
useLayoutEffect(() => {
document.title = `${name ? `${name} | ` : ''}Glide`;
}, [name]);
if (name === undefined || content === undefined) return null;
return (
<CoreEditor
{...props}
onChange={update}
onSave={(newContent) => save(name, newContent)}
value={content}
/>
);
};
export default Editor;
|
src/components/Editor.tsx
|
NUSSOC-glide-3ab6925
|
[
{
"filename": "src/components/FileName.tsx",
"retrieved_chunk": " type=\"text\"\n value={newFileName ?? props.initialValue}\n />\n );\n};\nconst FileName = (): JSX.Element => {\n const name = useFile.SelectedName();\n const unsaved = useFile.IsUnsavedOf(name);\n const existingNames = useFile.NamesSet();\n const { rename } = useFilesMutations();",
"score": 0.8666998147964478
},
{
"filename": "src/components/FileName.tsx",
"retrieved_chunk": " const [newFileName, setNewFileName] = useState<string>();\n const [editing, setEditing] = useState(false);\n return !editing ? (\n <div\n className=\"min-w-0 rounded-lg p-2 hover:bg-slate-800\"\n onClick={() => setEditing(true)}\n >\n <p className=\"text-md overflow-hidden overflow-ellipsis whitespace-nowrap\">\n {props.initialValue}\n </p>",
"score": 0.8534219264984131
},
{
"filename": "src/components/FileUploader.tsx",
"retrieved_chunk": "import { ChangeEventHandler, ComponentProps } from 'react';\nimport Button from './Button';\ninterface FileUploaderProps extends ComponentProps<typeof Button> {\n onUpload?: (name: string, content: string | null) => void;\n}\nconst FileUploader = (props: FileUploaderProps): JSX.Element => {\n const { onUpload: onUploadFile, ...buttonProps } = props;\n const handleUpload: ChangeEventHandler<HTMLInputElement> = (e) => {\n e.preventDefault();\n const files = e.target.files;",
"score": 0.8515033721923828
},
{
"filename": "src/components/FileItem.tsx",
"retrieved_chunk": "const FileItem = (props: FileItemProps): JSX.Element => {\n const { select, destroy } = useFilesMutations();\n const selectedFileName = useFile.SelectedName();\n const buttonRef = useRef<HTMLButtonElement>(null);\n useLayoutEffect(() => {\n if (props.name !== selectedFileName) return;\n buttonRef.current?.focus();\n }, [props.name, selectedFileName]);\n return (\n <div className=\"flex items-center space-x-2\">",
"score": 0.8496590256690979
},
{
"filename": "src/components/Library.tsx",
"retrieved_chunk": " onClose: () => void;\n}\nconst Library = (props: LibraryProps): JSX.Element => {\n const files = useFile.NamesWithUnsaved();\n const { draft, create } = useFilesMutations();\n return (\n <Transition appear as={Fragment} show={props.open}>\n <Dialog className=\"relative z-40\" onClose={props.onClose}>\n <Transition.Child\n as={Fragment}",
"score": 0.8427507877349854
}
] |
typescript
|
const { name, content } = useFile.Selected();
|
import { Fragment } from 'react';
import { Dialog, Transition } from '@headlessui/react';
import { ArrowUpTrayIcon, PlusIcon } from '@heroicons/react/24/outline';
import useFile from '../hooks/useFile';
import useFilesMutations from '../hooks/useFilesMutations';
import Button from './Button';
import FileItem from './FileItem';
import FileUploader from './FileUploader';
interface LibraryProps {
open: boolean;
onClose: () => void;
}
const Library = (props: LibraryProps): JSX.Element => {
const files = useFile.NamesWithUnsaved();
const { draft, create } = useFilesMutations();
return (
<Transition appear as={Fragment} show={props.open}>
<Dialog className="relative z-40" onClose={props.onClose}>
<Transition.Child
as={Fragment}
enter="ease-out duration-100"
enterFrom="opacity-0"
enterTo="opacity-100"
leave="ease-in duration-100"
leaveFrom="opacity-100"
leaveTo="opacity-0"
>
<div className="fixed inset-0 bg-black bg-opacity-25" />
</Transition.Child>
<div className="fixed inset-0 overflow-y-auto">
<div className="flex min-h-full items-start justify-center px-4 py-10 text-center">
<Transition.Child
as={Fragment}
enter="ease-out duration-100"
enterFrom="opacity-0 scale-95"
enterTo="opacity-100 scale-100"
leave="ease-in duration-100"
leaveFrom="opacity-100 scale-100"
leaveTo="opacity-0 scale-95"
>
<Dialog.Panel className="w-full max-w-md transform overflow-hidden rounded-2xl bg-slate-800 p-5 text-left align-middle shadow-xl ring-2 ring-slate-700 transition-all">
<div className="flex justify-between">
<Dialog.Title
as="h3"
className="text-lg font-medium leading-6 text-white"
>
Library
</Dialog.Title>
<p className="select-none text-sm text-slate-600">
{__VERSION__}
</p>
</div>
<div className="mt-6 flex flex-col space-y-2">
{files.map(({ name, unsaved }) => (
|
<FileItem
key={name}
|
name={name}
onClick={props.onClose}
unsaved={unsaved}
/>
))}
</div>
<div className="mt-10 space-x-2">
<Button
icon={PlusIcon}
onClick={() => {
draft(true);
props.onClose();
}}
>
New File
</Button>
<FileUploader
icon={ArrowUpTrayIcon}
onUpload={(name, content) => {
if (content === null) return;
create(name, content);
props.onClose();
}}
>
Upload
</FileUploader>
</div>
</Dialog.Panel>
</Transition.Child>
</div>
</div>
</Dialog>
</Transition>
);
};
export default Library;
|
src/components/Library.tsx
|
NUSSOC-glide-3ab6925
|
[
{
"filename": "src/components/FileItem.tsx",
"retrieved_chunk": "const FileItem = (props: FileItemProps): JSX.Element => {\n const { select, destroy } = useFilesMutations();\n const selectedFileName = useFile.SelectedName();\n const buttonRef = useRef<HTMLButtonElement>(null);\n useLayoutEffect(() => {\n if (props.name !== selectedFileName) return;\n buttonRef.current?.focus();\n }, [props.name, selectedFileName]);\n return (\n <div className=\"flex items-center space-x-2\">",
"score": 0.8508130311965942
},
{
"filename": "src/components/FileItem.tsx",
"retrieved_chunk": "import { useLayoutEffect, useRef } from 'react';\nimport { ArrowRightIcon, TrashIcon } from '@heroicons/react/24/outline';\nimport useFile from '../hooks/useFile';\nimport useFilesMutations from '../hooks/useFilesMutations';\nimport UnsavedBadge from './UnsavedBadge';\ninterface FileItemProps {\n name: string;\n onClick?: () => void;\n unsaved?: boolean;\n}",
"score": 0.8303703665733337
},
{
"filename": "src/components/Navigator.tsx",
"retrieved_chunk": " Save <K of=\"Mod+S\" />\n </Item>\n )}\n <Item\n className=\"text-slate-400\"\n icon={BuildingLibraryIcon}\n onClick={() => setOpenLibrary(true)}\n >\n Library <K of=\"Mod+O\" />\n </Item>",
"score": 0.8254187703132629
},
{
"filename": "src/hooks/useFile.ts",
"retrieved_chunk": "import { getState } from '../store';\nimport { getSelectedFile, getSelectedFileName } from '../store/filesSlice';\nimport { useAppSelector } from '../store/hooks';\nconst Selected = () => useAppSelector(getSelectedFile);\nconst SelectedName = () => useAppSelector(getSelectedFileName);\nconst NamesSet = () =>\n useAppSelector(({ files, vault }) => new Set(files.list.concat(vault.list)));\nconst NamesWithUnsaved = () =>\n useAppSelector(({ files, vault }) =>\n files.list.map((name) => {",
"score": 0.8215848207473755
},
{
"filename": "src/components/Navigator.tsx",
"retrieved_chunk": "import { useEffect, useState } from 'react';\nimport { BuildingLibraryIcon } from '@heroicons/react/24/outline';\nimport useFile from '../hooks/useFile';\nimport FileName from './FileName';\nimport K from './Hotkey';\nimport Item from './Item';\nimport Library from './Library';\nconst isMac = navigator.platform.startsWith('Mac');\nconst Navigator = (): JSX.Element => {\n const [openLibrary, setOpenLibrary] = useState(true);",
"score": 0.8206046223640442
}
] |
typescript
|
<FileItem
key={name}
|
import { useState } from 'react';
import { Transition } from '@headlessui/react';
import useFile from '../hooks/useFile';
import useFilesMutations from '../hooks/useFilesMutations';
import UnsavedBadge from './UnsavedBadge';
interface RenamableInputProps {
initialValue: string;
onConfirm: (value: string) => void;
}
const RenamableInput = (props: RenamableInputProps): JSX.Element => {
const [newFileName, setNewFileName] = useState<string>();
const [editing, setEditing] = useState(false);
return !editing ? (
<div
className="min-w-0 rounded-lg p-2 hover:bg-slate-800"
onClick={() => setEditing(true)}
>
<p className="text-md overflow-hidden overflow-ellipsis whitespace-nowrap">
{props.initialValue}
</p>
</div>
) : (
<input
autoFocus
className="w-fit rounded-lg bg-slate-800 bg-transparent p-2 outline-none ring-2 ring-slate-600"
onBlur={() => {
let newName = newFileName?.trim();
setEditing(false);
setNewFileName(undefined);
if (
!newName ||
newName === props.initialValue ||
newName.startsWith('.') ||
newName.endsWith('.')
)
return;
/**
* @see https://en.wikipedia.org/wiki/Filename#Reserved_characters_and_words
*/
newName = newName.replace(/[/\\?%*:|"<>]/g, '_');
props.onConfirm(newName);
}}
onChange={(e) => setNewFileName(e.target.value)}
onFocus={(e) => {
const name = e.target.value;
const extensionLength = name.split('.').pop()?.length ?? 0;
e.target.setSelectionRange(0, name.length - extensionLength - 1);
}}
onKeyDown={(e) => {
if (e.key === 'Enter') {
e.preventDefault();
e.currentTarget.blur();
}
if (e.key === 'Escape') {
e.preventDefault();
setEditing(false);
setNewFileName(undefined);
}
}}
placeholder={props.initialValue}
type="text"
value={newFileName ?? props.initialValue}
/>
);
};
const FileName = (): JSX.Element => {
const name = useFile.SelectedName();
|
const unsaved = useFile.IsUnsavedOf(name);
|
const existingNames = useFile.NamesSet();
const { rename } = useFilesMutations();
return (
<div className="flex min-w-0 items-center space-x-3">
{name && (
<RenamableInput
initialValue={name}
onConfirm={(newName) => {
if (!name) return;
if (existingNames.has(newName)) return;
rename(name, newName);
}}
/>
)}
<Transition
enter="transition-transform origin-left duration-75"
enterFrom="scale-0"
enterTo="scale-100"
leave="transition-transform origin-left duration-150"
leaveFrom="scale-100"
leaveTo="scale-0"
show={Boolean(name && unsaved)}
>
<UnsavedBadge />
</Transition>
</div>
);
};
export default FileName;
|
src/components/FileName.tsx
|
NUSSOC-glide-3ab6925
|
[
{
"filename": "src/components/FileItem.tsx",
"retrieved_chunk": "const FileItem = (props: FileItemProps): JSX.Element => {\n const { select, destroy } = useFilesMutations();\n const selectedFileName = useFile.SelectedName();\n const buttonRef = useRef<HTMLButtonElement>(null);\n useLayoutEffect(() => {\n if (props.name !== selectedFileName) return;\n buttonRef.current?.focus();\n }, [props.name, selectedFileName]);\n return (\n <div className=\"flex items-center space-x-2\">",
"score": 0.8741168975830078
},
{
"filename": "src/components/FileUploader.tsx",
"retrieved_chunk": "import { ChangeEventHandler, ComponentProps } from 'react';\nimport Button from './Button';\ninterface FileUploaderProps extends ComponentProps<typeof Button> {\n onUpload?: (name: string, content: string | null) => void;\n}\nconst FileUploader = (props: FileUploaderProps): JSX.Element => {\n const { onUpload: onUploadFile, ...buttonProps } = props;\n const handleUpload: ChangeEventHandler<HTMLInputElement> = (e) => {\n e.preventDefault();\n const files = e.target.files;",
"score": 0.8659545183181763
},
{
"filename": "src/hooks/useFile.ts",
"retrieved_chunk": "import { getState } from '../store';\nimport { getSelectedFile, getSelectedFileName } from '../store/filesSlice';\nimport { useAppSelector } from '../store/hooks';\nconst Selected = () => useAppSelector(getSelectedFile);\nconst SelectedName = () => useAppSelector(getSelectedFileName);\nconst NamesSet = () =>\n useAppSelector(({ files, vault }) => new Set(files.list.concat(vault.list)));\nconst NamesWithUnsaved = () =>\n useAppSelector(({ files, vault }) =>\n files.list.map((name) => {",
"score": 0.8513239026069641
},
{
"filename": "src/components/FileItem.tsx",
"retrieved_chunk": "import { useLayoutEffect, useRef } from 'react';\nimport { ArrowRightIcon, TrashIcon } from '@heroicons/react/24/outline';\nimport useFile from '../hooks/useFile';\nimport useFilesMutations from '../hooks/useFilesMutations';\nimport UnsavedBadge from './UnsavedBadge';\ninterface FileItemProps {\n name: string;\n onClick?: () => void;\n unsaved?: boolean;\n}",
"score": 0.843134880065918
},
{
"filename": "src/components/Library.tsx",
"retrieved_chunk": " New File\n </Button>\n <FileUploader\n icon={ArrowUpTrayIcon}\n onUpload={(name, content) => {\n if (content === null) return;\n create(name, content);\n props.onClose();\n }}\n >",
"score": 0.8410099148750305
}
] |
typescript
|
const unsaved = useFile.IsUnsavedOf(name);
|
import { Fragment } from 'react';
import { Dialog, Transition } from '@headlessui/react';
import { ArrowUpTrayIcon, PlusIcon } from '@heroicons/react/24/outline';
import useFile from '../hooks/useFile';
import useFilesMutations from '../hooks/useFilesMutations';
import Button from './Button';
import FileItem from './FileItem';
import FileUploader from './FileUploader';
interface LibraryProps {
open: boolean;
onClose: () => void;
}
const Library = (props: LibraryProps): JSX.Element => {
const files = useFile.NamesWithUnsaved();
const { draft, create } = useFilesMutations();
return (
<Transition appear as={Fragment} show={props.open}>
<Dialog className="relative z-40" onClose={props.onClose}>
<Transition.Child
as={Fragment}
enter="ease-out duration-100"
enterFrom="opacity-0"
enterTo="opacity-100"
leave="ease-in duration-100"
leaveFrom="opacity-100"
leaveTo="opacity-0"
>
<div className="fixed inset-0 bg-black bg-opacity-25" />
</Transition.Child>
<div className="fixed inset-0 overflow-y-auto">
<div className="flex min-h-full items-start justify-center px-4 py-10 text-center">
<Transition.Child
as={Fragment}
enter="ease-out duration-100"
enterFrom="opacity-0 scale-95"
enterTo="opacity-100 scale-100"
leave="ease-in duration-100"
leaveFrom="opacity-100 scale-100"
leaveTo="opacity-0 scale-95"
>
<Dialog.Panel className="w-full max-w-md transform overflow-hidden rounded-2xl bg-slate-800 p-5 text-left align-middle shadow-xl ring-2 ring-slate-700 transition-all">
<div className="flex justify-between">
<Dialog.Title
as="h3"
className="text-lg font-medium leading-6 text-white"
>
Library
</Dialog.Title>
<p className="select-none text-sm text-slate-600">
{__VERSION__}
</p>
</div>
<div className="mt-6 flex flex-col space-y-2">
{files.map(({ name, unsaved }) => (
<FileItem
key={name}
name={name}
onClick={props.onClose}
unsaved={unsaved}
/>
))}
</div>
<div className="mt-10 space-x-2">
<
|
Button
icon={PlusIcon}
|
onClick={() => {
draft(true);
props.onClose();
}}
>
New File
</Button>
<FileUploader
icon={ArrowUpTrayIcon}
onUpload={(name, content) => {
if (content === null) return;
create(name, content);
props.onClose();
}}
>
Upload
</FileUploader>
</div>
</Dialog.Panel>
</Transition.Child>
</div>
</div>
</Dialog>
</Transition>
);
};
export default Library;
|
src/components/Library.tsx
|
NUSSOC-glide-3ab6925
|
[
{
"filename": "src/components/FileItem.tsx",
"retrieved_chunk": " {props.name}\n </p>\n <div className=\"flex items-center space-x-3 pl-2\">\n {props.unsaved && <UnsavedBadge className=\"group-hover:hidden\" />}\n <div className=\"hidden animate-pulse items-center space-x-1 text-xs opacity-70 group-hover:flex\">\n <p>Open</p>\n <ArrowRightIcon className=\"h-4\" />\n </div>\n </div>\n </button>",
"score": 0.9089362025260925
},
{
"filename": "src/components/FileItem.tsx",
"retrieved_chunk": " <button\n ref={buttonRef}\n className=\"group flex w-full min-w-0 select-none flex-row items-center justify-between rounded-lg bg-slate-700 p-3 text-slate-100 transition-transform hover:bg-slate-600 focus:outline-none focus:ring-2 focus:ring-sky-500 active:scale-95\"\n onClick={() => {\n select(props.name);\n props.onClick?.();\n }}\n tabIndex={1}\n >\n <p className=\"overflow-hidden overflow-ellipsis whitespace-nowrap opacity-90\">",
"score": 0.8558250069618225
},
{
"filename": "src/components/FileItem.tsx",
"retrieved_chunk": " <div\n className=\"flex h-9 w-9 shrink-0 items-center justify-center rounded-lg bg-red-600/20 text-red-400 transition-transform hover:scale-110 active:scale-95\"\n onClick={() => destroy(props.name)}\n role=\"button\"\n >\n <TrashIcon className=\"h-5\" />\n </div>\n </div>\n );\n};",
"score": 0.8537243008613586
},
{
"filename": "src/components/Terminal.tsx",
"retrieved_chunk": " }}\n onClickRestart={props.onRestart}\n />\n </div>\n {props.showStopButton && (\n <div className=\"absolute right-3 top-3 z-20 space-x-2 opacity-50 hover:opacity-100\">\n <Button icon={StopIcon} onClick={props.onStop}>\n Stop\n </Button>\n </div>",
"score": 0.8517687320709229
},
{
"filename": "src/components/FileName.tsx",
"retrieved_chunk": " />\n )}\n <Transition\n enter=\"transition-transform origin-left duration-75\"\n enterFrom=\"scale-0\"\n enterTo=\"scale-100\"\n leave=\"transition-transform origin-left duration-150\"\n leaveFrom=\"scale-100\"\n leaveTo=\"scale-0\"\n show={Boolean(name && unsaved)}",
"score": 0.8487992286682129
}
] |
typescript
|
Button
icon={PlusIcon}
|
import {
ComponentRef,
forwardRef,
useEffect,
useImperativeHandle,
useLayoutEffect,
useRef,
} from 'react';
import { StopIcon } from '@heroicons/react/24/outline';
import { slate, yellow } from 'tailwindcss/colors';
import { Terminal as Xterm } from 'xterm';
import { CanvasAddon } from 'xterm-addon-canvas';
import { FitAddon } from 'xterm-addon-fit';
import { WebglAddon } from 'xterm-addon-webgl';
import Button from './Button';
import Prompt from './Prompt';
import TerminalMenu from './TerminalMenu';
import 'xterm/css/xterm.css';
interface TerminalRef {
append: (result?: string) => void;
write: (result?: string) => void;
error: (result?: string) => void;
system: (result?: string) => void;
}
interface TerminalProps {
onStop?: () => void;
onReturn?: (line: string) => void;
onRestart?: () => void;
showStopButton?: boolean;
}
const isASCIIPrintable = (character: string): boolean =>
character >= String.fromCharCode(32) && character <= String.fromCharCode(126);
const isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
/**
* @see https://github.com/xtermjs/xterm.js/pull/4255
*/
const getSafariVersion = (): number => {
if (!isSafari) return 0;
const majorVersion = navigator.userAgent.match(/Version\/(\d+)/);
if (majorVersion === null || majorVersion.length < 2) return 0;
return parseInt(majorVersion[1]);
};
const isWebGL2Compatible = (): boolean => {
const context = document.createElement('canvas').getContext('webgl2');
const isWebGL2Available = Boolean(context);
return isWebGL2Available && (isSafari ? getSafariVersion() >= 16 : true);
};
const Terminal = forwardRef<TerminalRef, TerminalProps>(
(props, ref): JSX.Element => {
const xtermRef = useRef<Xterm>();
const fitAddonRef = useRef<FitAddon>();
const terminalRef = useRef<HTMLDivElement>(null);
const containerRef = useRef<HTMLDivElement>(null);
const promptRef = useRef<ComponentRef<typeof Prompt>>(null);
useLayoutEffect(() => {
const container = containerRef.current;
if (!container) return;
const resizeObserver = new ResizeObserver(() =>
fitAddonRef.current?.fit(),
);
resizeObserver.observe(container);
return () => resizeObserver.disconnect();
}, []);
useEffect(() => {
const terminal = terminalRef.current;
if (!terminal) return;
const xterm = new Xterm({
cursorBlink: false,
cursorStyle: 'underline',
fontFamily: 'monospace',
fontSize: 14,
theme: { background: slate[900], cursor: yellow[400] },
disableStdin: true,
});
const fitAddon = new FitAddon();
xterm.loadAddon(fitAddon);
if (isWebGL2Compatible()) {
xterm.loadAddon(new WebglAddon());
} else {
xterm.loadAddon(new CanvasAddon());
}
xterm.onKey(({ key }) => {
if (!(isASCIIPrintable(key) || key >= '\u00a0')) return;
|
promptRef.current?.focusWith(key);
|
});
xterm.open(terminal);
fitAddon.fit();
xtermRef.current = xterm;
fitAddonRef.current = fitAddon;
return () => xterm.dispose();
}, []);
const write = (text: string, line = true) => {
const trimmed = text.replace(/\n/g, '\r\n');
const xterm = xtermRef.current;
if (!xterm) return;
const writer = (text: string) =>
line ? xterm.writeln(text) : xterm.write(text);
try {
writer(trimmed);
} catch (error) {
if (!(error instanceof Error)) throw error;
console.log('oops', error.message);
xterm.clear();
writer(trimmed);
}
};
useImperativeHandle(ref, () => ({
append: (result?: string) => write(result ?? ''),
write: (result?: string) => write(result ?? '', false),
error: (result?: string) =>
write('\u001b[31m' + (result ?? '') + '\u001b[0m'),
system: (result?: string) =>
write('\u001b[33m' + (result ?? '') + '\u001b[0m'),
}));
return (
<section ref={containerRef} className="relative h-full w-full">
<div ref={terminalRef} className="windowed h-full" />
<div className="absolute bottom-0 left-0 z-40 flex w-full space-x-2 px-2 pb-2">
<Prompt
ref={promptRef}
onReturn={(input) => {
props.onReturn?.(input);
xtermRef.current?.scrollToBottom();
}}
/>
<TerminalMenu
onClickClearConsole={() => xtermRef.current?.clear()}
onClickForceStop={() => {
props.onStop?.();
xtermRef.current?.scrollToBottom();
}}
onClickRestart={props.onRestart}
/>
</div>
{props.showStopButton && (
<div className="absolute right-3 top-3 z-20 space-x-2 opacity-50 hover:opacity-100">
<Button icon={StopIcon} onClick={props.onStop}>
Stop
</Button>
</div>
)}
</section>
);
},
);
Terminal.displayName = 'Terminal';
export default Terminal;
|
src/components/Terminal.tsx
|
NUSSOC-glide-3ab6925
|
[
{
"filename": "src/components/Prompt.tsx",
"retrieved_chunk": "const Prompt = forwardRef<PromptRef, PromptProps>((props, ref): JSX.Element => {\n const [{ dirty, command }, setCommand] = useState({\n dirty: false,\n command: '',\n });\n const inputRef = useRef<HTMLInputElement>(null);\n const history = useCommandHistory();\n useImperativeHandle(ref, () => ({\n focusWith: (key) => {\n if (key)",
"score": 0.8248623013496399
},
{
"filename": "src/components/Editor.tsx",
"retrieved_chunk": " };\n useEffect(() => {\n window.addEventListener('keydown', handleShortcut);\n return () => window.removeEventListener('keydown', handleShortcut);\n }, [handleShortcut]);\n const saveThenRunCode = () => {\n const content = ref.current?.getValue() ?? '';\n props.onSave(content);\n props.onRunCode?.(content);\n };",
"score": 0.8230460286140442
},
{
"filename": "src/components/Prompt.tsx",
"retrieved_chunk": "import { forwardRef, useImperativeHandle, useRef, useState } from 'react';\nimport { ChevronRightIcon } from '@heroicons/react/24/outline';\nimport produce from 'immer';\nimport useCommandHistory from '../hooks/useCommandHistory';\ninterface PromptRef {\n focusWith: (key?: string) => void;\n}\ninterface PromptProps {\n onReturn?: (command: string) => void;\n}",
"score": 0.8182628154754639
},
{
"filename": "src/components/Navigator.tsx",
"retrieved_chunk": " onClick={() => {\n window.dispatchEvent(\n new KeyboardEvent('keydown', {\n key: 's',\n metaKey: isMac,\n ctrlKey: !isMac,\n }),\n );\n }}\n >",
"score": 0.8150635957717896
},
{
"filename": "src/components/Editor.tsx",
"retrieved_chunk": " const isMod = navigator.platform.startsWith('Mac') ? e.metaKey : e.ctrlKey;\n if (isMod && e.key === 's') {\n e.preventDefault();\n const content = ref.current?.getValue();\n if (content !== undefined) props.onSave(content);\n }\n if (e.key === 'F5') {\n e.preventDefault();\n saveThenRunCode();\n }",
"score": 0.8110660314559937
}
] |
typescript
|
promptRef.current?.focusWith(key);
|
import {
ComponentRef,
forwardRef,
useEffect,
useImperativeHandle,
useLayoutEffect,
useRef,
} from 'react';
import { StopIcon } from '@heroicons/react/24/outline';
import { slate, yellow } from 'tailwindcss/colors';
import { Terminal as Xterm } from 'xterm';
import { CanvasAddon } from 'xterm-addon-canvas';
import { FitAddon } from 'xterm-addon-fit';
import { WebglAddon } from 'xterm-addon-webgl';
import Button from './Button';
import Prompt from './Prompt';
import TerminalMenu from './TerminalMenu';
import 'xterm/css/xterm.css';
interface TerminalRef {
append: (result?: string) => void;
write: (result?: string) => void;
error: (result?: string) => void;
system: (result?: string) => void;
}
interface TerminalProps {
onStop?: () => void;
onReturn?: (line: string) => void;
onRestart?: () => void;
showStopButton?: boolean;
}
const isASCIIPrintable = (character: string): boolean =>
character >= String.fromCharCode(32) && character <= String.fromCharCode(126);
const isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
/**
* @see https://github.com/xtermjs/xterm.js/pull/4255
*/
const getSafariVersion = (): number => {
if (!isSafari) return 0;
const majorVersion = navigator.userAgent.match(/Version\/(\d+)/);
if (majorVersion === null || majorVersion.length < 2) return 0;
return parseInt(majorVersion[1]);
};
const isWebGL2Compatible = (): boolean => {
const context = document.createElement('canvas').getContext('webgl2');
const isWebGL2Available = Boolean(context);
return isWebGL2Available && (isSafari ? getSafariVersion() >= 16 : true);
};
const Terminal = forwardRef<TerminalRef, TerminalProps>(
(props, ref): JSX.Element => {
const xtermRef = useRef<Xterm>();
const fitAddonRef = useRef<FitAddon>();
const terminalRef = useRef<HTMLDivElement>(null);
const containerRef = useRef<HTMLDivElement>(null);
|
const promptRef = useRef<ComponentRef<typeof Prompt>>(null);
|
useLayoutEffect(() => {
const container = containerRef.current;
if (!container) return;
const resizeObserver = new ResizeObserver(() =>
fitAddonRef.current?.fit(),
);
resizeObserver.observe(container);
return () => resizeObserver.disconnect();
}, []);
useEffect(() => {
const terminal = terminalRef.current;
if (!terminal) return;
const xterm = new Xterm({
cursorBlink: false,
cursorStyle: 'underline',
fontFamily: 'monospace',
fontSize: 14,
theme: { background: slate[900], cursor: yellow[400] },
disableStdin: true,
});
const fitAddon = new FitAddon();
xterm.loadAddon(fitAddon);
if (isWebGL2Compatible()) {
xterm.loadAddon(new WebglAddon());
} else {
xterm.loadAddon(new CanvasAddon());
}
xterm.onKey(({ key }) => {
if (!(isASCIIPrintable(key) || key >= '\u00a0')) return;
promptRef.current?.focusWith(key);
});
xterm.open(terminal);
fitAddon.fit();
xtermRef.current = xterm;
fitAddonRef.current = fitAddon;
return () => xterm.dispose();
}, []);
const write = (text: string, line = true) => {
const trimmed = text.replace(/\n/g, '\r\n');
const xterm = xtermRef.current;
if (!xterm) return;
const writer = (text: string) =>
line ? xterm.writeln(text) : xterm.write(text);
try {
writer(trimmed);
} catch (error) {
if (!(error instanceof Error)) throw error;
console.log('oops', error.message);
xterm.clear();
writer(trimmed);
}
};
useImperativeHandle(ref, () => ({
append: (result?: string) => write(result ?? ''),
write: (result?: string) => write(result ?? '', false),
error: (result?: string) =>
write('\u001b[31m' + (result ?? '') + '\u001b[0m'),
system: (result?: string) =>
write('\u001b[33m' + (result ?? '') + '\u001b[0m'),
}));
return (
<section ref={containerRef} className="relative h-full w-full">
<div ref={terminalRef} className="windowed h-full" />
<div className="absolute bottom-0 left-0 z-40 flex w-full space-x-2 px-2 pb-2">
<Prompt
ref={promptRef}
onReturn={(input) => {
props.onReturn?.(input);
xtermRef.current?.scrollToBottom();
}}
/>
<TerminalMenu
onClickClearConsole={() => xtermRef.current?.clear()}
onClickForceStop={() => {
props.onStop?.();
xtermRef.current?.scrollToBottom();
}}
onClickRestart={props.onRestart}
/>
</div>
{props.showStopButton && (
<div className="absolute right-3 top-3 z-20 space-x-2 opacity-50 hover:opacity-100">
<Button icon={StopIcon} onClick={props.onStop}>
Stop
</Button>
</div>
)}
</section>
);
},
);
Terminal.displayName = 'Terminal';
export default Terminal;
|
src/components/Terminal.tsx
|
NUSSOC-glide-3ab6925
|
[
{
"filename": "src/pages/IDEPage.tsx",
"retrieved_chunk": "import { ComponentRef, useRef, useState } from 'react';\nimport Between from '../components/Between';\nimport Editor from '../components/Editor';\nimport Navigator from '../components/Navigator';\nimport Terminal from '../components/Terminal';\nimport useFile from '../hooks/useFile';\nimport useInterpreter from '../hooks/useInterpreter';\nconst IDEPage = (): JSX.Element => {\n const consoleRef = useRef<ComponentRef<typeof Terminal>>(null);\n const [running, setRunning] = useState(false);",
"score": 0.8426340818405151
},
{
"filename": "src/components/Prompt.tsx",
"retrieved_chunk": "const Prompt = forwardRef<PromptRef, PromptProps>((props, ref): JSX.Element => {\n const [{ dirty, command }, setCommand] = useState({\n dirty: false,\n command: '',\n });\n const inputRef = useRef<HTMLInputElement>(null);\n const history = useCommandHistory();\n useImperativeHandle(ref, () => ({\n focusWith: (key) => {\n if (key)",
"score": 0.8398687839508057
},
{
"filename": "src/components/TerminalMenu.tsx",
"retrieved_chunk": " {props.children}\n </Menu.Item>\n);\nconst TerminalMenu = (props: TerminalMenuProps): JSX.Element => {\n return (\n <Menu as=\"div\" className=\"relative inline-block text-left\">\n <Menu.Button className=\"rounded-md bg-slate-500 bg-opacity-20 p-2 transition-transform hover:bg-opacity-30 active:scale-95\">\n <Bars3Icon aria-hidden=\"true\" className=\"h-5 w-5\" />\n </Menu.Button>\n <Transition",
"score": 0.8325586915016174
},
{
"filename": "src/components/Between.tsx",
"retrieved_chunk": " const { by: sizes } = props;\n const oneRef = useRef<HTMLDivElement>(null);\n const twoRef = useRef<HTMLDivElement>(null);\n const [direction, setDirection] = useState<Direction>('vertical');\n useLayoutEffect(() => {\n const resizeObserver = new ResizeObserver((entries) => {\n if (!entries.length) return;\n const { width } = entries[0].contentRect;\n setDirection(width >= 1024 ? 'horizontal' : 'vertical');\n });",
"score": 0.8261919021606445
},
{
"filename": "src/components/Editor.tsx",
"retrieved_chunk": " showRunButton?: boolean;\n}\ninterface CoreEditorProps extends EditorProps {\n onSave: (content: string) => void;\n onChange: (value: string) => void;\n value: string;\n}\nconst CoreEditor = (props: CoreEditorProps): JSX.Element => {\n const ref = useRef<editor.IStandaloneCodeEditor>();\n const handleShortcut = (e: KeyboardEvent) => {",
"score": 0.8218213319778442
}
] |
typescript
|
const promptRef = useRef<ComponentRef<typeof Prompt>>(null);
|
import { useEffect, useState } from 'react';
import { BuildingLibraryIcon } from '@heroicons/react/24/outline';
import useFile from '../hooks/useFile';
import FileName from './FileName';
import K from './Hotkey';
import Item from './Item';
import Library from './Library';
const isMac = navigator.platform.startsWith('Mac');
const Navigator = (): JSX.Element => {
const [openLibrary, setOpenLibrary] = useState(true);
const name = useFile.SelectedName();
const handleShortcut = (e: KeyboardEvent) => {
const isMod = isMac ? e.metaKey : e.ctrlKey;
if (isMod && e.key === 'o') {
e.preventDefault();
setOpenLibrary(true);
}
};
useEffect(() => {
window.addEventListener('keydown', handleShortcut);
return () => window.removeEventListener('keydown', handleShortcut);
}, [handleShortcut]);
return (
<>
<nav className="flex items-center justify-between space-x-2">
<FileName />
<div className="flex flex-row items-center space-x-2">
{name && (
<Item
className="text-slate-400"
onClick={() => {
window.dispatchEvent(
new KeyboardEvent('keydown', {
key: 's',
metaKey: isMac,
ctrlKey: !isMac,
}),
);
}}
>
Save <K of="Mod+S" />
</Item>
)}
<Item
className="text-slate-400"
icon={BuildingLibraryIcon}
onClick={() => setOpenLibrary(true)}
>
Library <K of="Mod+O" />
</Item>
</div>
</nav>
<
|
Library onClose={() => setOpenLibrary(false)} open={openLibrary} />
</>
);
|
};
export default Navigator;
|
src/components/Navigator.tsx
|
NUSSOC-glide-3ab6925
|
[
{
"filename": "src/components/Library.tsx",
"retrieved_chunk": " onClose: () => void;\n}\nconst Library = (props: LibraryProps): JSX.Element => {\n const files = useFile.NamesWithUnsaved();\n const { draft, create } = useFilesMutations();\n return (\n <Transition appear as={Fragment} show={props.open}>\n <Dialog className=\"relative z-40\" onClose={props.onClose}>\n <Transition.Child\n as={Fragment}",
"score": 0.8679001331329346
},
{
"filename": "src/components/Library.tsx",
"retrieved_chunk": "import { Fragment } from 'react';\nimport { Dialog, Transition } from '@headlessui/react';\nimport { ArrowUpTrayIcon, PlusIcon } from '@heroicons/react/24/outline';\nimport useFile from '../hooks/useFile';\nimport useFilesMutations from '../hooks/useFilesMutations';\nimport Button from './Button';\nimport FileItem from './FileItem';\nimport FileUploader from './FileUploader';\ninterface LibraryProps {\n open: boolean;",
"score": 0.8531232476234436
},
{
"filename": "src/components/Library.tsx",
"retrieved_chunk": " <Dialog.Panel className=\"w-full max-w-md transform overflow-hidden rounded-2xl bg-slate-800 p-5 text-left align-middle shadow-xl ring-2 ring-slate-700 transition-all\">\n <div className=\"flex justify-between\">\n <Dialog.Title\n as=\"h3\"\n className=\"text-lg font-medium leading-6 text-white\"\n >\n Library\n </Dialog.Title>\n <p className=\"select-none text-sm text-slate-600\">\n {__VERSION__}",
"score": 0.8283975124359131
},
{
"filename": "src/components/TerminalMenu.tsx",
"retrieved_chunk": " as={Fragment}\n enter=\"transition ease-out duration-100\"\n enterFrom=\"transform opacity-0 scale-95\"\n enterTo=\"transform opacity-100 scale-100\"\n leave=\"transition ease-in duration-75\"\n leaveFrom=\"transform opacity-100 scale-100\"\n leaveTo=\"transform opacity-0 scale-95\"\n >\n <Menu.Items className=\"absolute bottom-11 right-0 z-40 origin-bottom-right divide-y-2 divide-slate-700 rounded-md bg-slate-800 shadow-2xl ring-2 ring-slate-700\">\n <div className=\"px-1 py-1\">",
"score": 0.8248074054718018
},
{
"filename": "src/components/Library.tsx",
"retrieved_chunk": "};\nexport default Library;",
"score": 0.820874810218811
}
] |
typescript
|
Library onClose={() => setOpenLibrary(false)} open={openLibrary} />
</>
);
|
import { Fragment } from 'react';
import { Dialog, Transition } from '@headlessui/react';
import { ArrowUpTrayIcon, PlusIcon } from '@heroicons/react/24/outline';
import useFile from '../hooks/useFile';
import useFilesMutations from '../hooks/useFilesMutations';
import Button from './Button';
import FileItem from './FileItem';
import FileUploader from './FileUploader';
interface LibraryProps {
open: boolean;
onClose: () => void;
}
const Library = (props: LibraryProps): JSX.Element => {
const files = useFile.NamesWithUnsaved();
const { draft, create } = useFilesMutations();
return (
<Transition appear as={Fragment} show={props.open}>
<Dialog className="relative z-40" onClose={props.onClose}>
<Transition.Child
as={Fragment}
enter="ease-out duration-100"
enterFrom="opacity-0"
enterTo="opacity-100"
leave="ease-in duration-100"
leaveFrom="opacity-100"
leaveTo="opacity-0"
>
<div className="fixed inset-0 bg-black bg-opacity-25" />
</Transition.Child>
<div className="fixed inset-0 overflow-y-auto">
<div className="flex min-h-full items-start justify-center px-4 py-10 text-center">
<Transition.Child
as={Fragment}
enter="ease-out duration-100"
enterFrom="opacity-0 scale-95"
enterTo="opacity-100 scale-100"
leave="ease-in duration-100"
leaveFrom="opacity-100 scale-100"
leaveTo="opacity-0 scale-95"
>
<Dialog.Panel className="w-full max-w-md transform overflow-hidden rounded-2xl bg-slate-800 p-5 text-left align-middle shadow-xl ring-2 ring-slate-700 transition-all">
<div className="flex justify-between">
<Dialog.Title
as="h3"
className="text-lg font-medium leading-6 text-white"
>
Library
</Dialog.Title>
<p className="select-none text-sm text-slate-600">
{__VERSION__}
</p>
</div>
<div className="mt-6 flex flex-col space-y-2">
{files.map(({ name, unsaved }) => (
<FileItem
key={name}
name={name}
onClick={props.onClose}
unsaved={unsaved}
/>
))}
</div>
<div className="mt-10 space-x-2">
<Button
icon={PlusIcon}
onClick={() => {
draft(true);
props.onClose();
}}
>
New File
</Button>
<FileUploader
icon={ArrowUpTrayIcon}
onUpload={
|
(name, content) => {
|
if (content === null) return;
create(name, content);
props.onClose();
}}
>
Upload
</FileUploader>
</div>
</Dialog.Panel>
</Transition.Child>
</div>
</div>
</Dialog>
</Transition>
);
};
export default Library;
|
src/components/Library.tsx
|
NUSSOC-glide-3ab6925
|
[
{
"filename": "src/components/FileUploader.tsx",
"retrieved_chunk": " if (!files?.length) return;\n const file = Array.from(files)[0];\n const reader = new FileReader();\n reader.onload = ({ target }) =>\n props.onUpload?.(file.name, target?.result as string);\n reader.readAsText(file);\n e.target.value = '';\n };\n return (\n <Button",
"score": 0.8486144542694092
},
{
"filename": "src/components/FileName.tsx",
"retrieved_chunk": " props.onConfirm(newName);\n }}\n onChange={(e) => setNewFileName(e.target.value)}\n onFocus={(e) => {\n const name = e.target.value;\n const extensionLength = name.split('.').pop()?.length ?? 0;\n e.target.setSelectionRange(0, name.length - extensionLength - 1);\n }}\n onKeyDown={(e) => {\n if (e.key === 'Enter') {",
"score": 0.8440549969673157
},
{
"filename": "src/components/FileUploader.tsx",
"retrieved_chunk": "import { ChangeEventHandler, ComponentProps } from 'react';\nimport Button from './Button';\ninterface FileUploaderProps extends ComponentProps<typeof Button> {\n onUpload?: (name: string, content: string | null) => void;\n}\nconst FileUploader = (props: FileUploaderProps): JSX.Element => {\n const { onUpload: onUploadFile, ...buttonProps } = props;\n const handleUpload: ChangeEventHandler<HTMLInputElement> = (e) => {\n e.preventDefault();\n const files = e.target.files;",
"score": 0.8435920476913452
},
{
"filename": "src/components/FileName.tsx",
"retrieved_chunk": " type=\"text\"\n value={newFileName ?? props.initialValue}\n />\n );\n};\nconst FileName = (): JSX.Element => {\n const name = useFile.SelectedName();\n const unsaved = useFile.IsUnsavedOf(name);\n const existingNames = useFile.NamesSet();\n const { rename } = useFilesMutations();",
"score": 0.8420159816741943
},
{
"filename": "src/components/FileName.tsx",
"retrieved_chunk": " e.preventDefault();\n e.currentTarget.blur();\n }\n if (e.key === 'Escape') {\n e.preventDefault();\n setEditing(false);\n setNewFileName(undefined);\n }\n }}\n placeholder={props.initialValue}",
"score": 0.8419439792633057
}
] |
typescript
|
(name, content) => {
|
import {
ComponentRef,
forwardRef,
useEffect,
useImperativeHandle,
useLayoutEffect,
useRef,
} from 'react';
import { StopIcon } from '@heroicons/react/24/outline';
import { slate, yellow } from 'tailwindcss/colors';
import { Terminal as Xterm } from 'xterm';
import { CanvasAddon } from 'xterm-addon-canvas';
import { FitAddon } from 'xterm-addon-fit';
import { WebglAddon } from 'xterm-addon-webgl';
import Button from './Button';
import Prompt from './Prompt';
import TerminalMenu from './TerminalMenu';
import 'xterm/css/xterm.css';
interface TerminalRef {
append: (result?: string) => void;
write: (result?: string) => void;
error: (result?: string) => void;
system: (result?: string) => void;
}
interface TerminalProps {
onStop?: () => void;
onReturn?: (line: string) => void;
onRestart?: () => void;
showStopButton?: boolean;
}
const isASCIIPrintable = (character: string): boolean =>
character >= String.fromCharCode(32) && character <= String.fromCharCode(126);
const isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
/**
* @see https://github.com/xtermjs/xterm.js/pull/4255
*/
const getSafariVersion = (): number => {
if (!isSafari) return 0;
const majorVersion = navigator.userAgent.match(/Version\/(\d+)/);
if (majorVersion === null || majorVersion.length < 2) return 0;
return parseInt(majorVersion[1]);
};
const isWebGL2Compatible = (): boolean => {
const context = document.createElement('canvas').getContext('webgl2');
const isWebGL2Available = Boolean(context);
return isWebGL2Available && (isSafari ? getSafariVersion() >= 16 : true);
};
const Terminal = forwardRef<TerminalRef, TerminalProps>(
(props, ref): JSX.Element => {
const xtermRef = useRef<Xterm>();
const fitAddonRef = useRef<FitAddon>();
const terminalRef = useRef<HTMLDivElement>(null);
const containerRef = useRef<HTMLDivElement>(null);
const promptRef = useRef<ComponentRef<typeof Prompt>>(null);
useLayoutEffect(() => {
const container = containerRef.current;
if (!container) return;
const resizeObserver = new ResizeObserver(() =>
fitAddonRef.current?.fit(),
);
resizeObserver.observe(container);
return () => resizeObserver.disconnect();
}, []);
useEffect(() => {
const terminal = terminalRef.current;
if (!terminal) return;
const xterm = new Xterm({
cursorBlink: false,
cursorStyle: 'underline',
fontFamily: 'monospace',
fontSize: 14,
theme: { background: slate[900], cursor: yellow[400] },
disableStdin: true,
});
const fitAddon = new FitAddon();
xterm.loadAddon(fitAddon);
if (isWebGL2Compatible()) {
xterm.loadAddon(new WebglAddon());
} else {
xterm.loadAddon(new CanvasAddon());
}
xterm.onKey(({ key }) => {
if (!(isASCIIPrintable(key) || key >= '\u00a0')) return;
promptRef.current?.focusWith(key);
});
xterm.open(terminal);
fitAddon.fit();
xtermRef.current = xterm;
fitAddonRef.current = fitAddon;
return () => xterm.dispose();
}, []);
const write = (text: string, line = true) => {
const trimmed = text.replace(/\n/g, '\r\n');
const xterm = xtermRef.current;
if (!xterm) return;
const writer = (text: string) =>
line ? xterm.writeln(text) : xterm.write(text);
try {
writer(trimmed);
} catch (error) {
if (!(error instanceof Error)) throw error;
console.log('oops', error.message);
xterm.clear();
writer(trimmed);
}
};
useImperativeHandle(ref, () => ({
append: (result?: string) => write(result ?? ''),
write: (result?: string) => write(result ?? '', false),
error: (result?: string) =>
write('\u001b[31m' + (result ?? '') + '\u001b[0m'),
system: (result?: string) =>
write('\u001b[33m' + (result ?? '') + '\u001b[0m'),
}));
return (
<section ref={containerRef} className="relative h-full w-full">
<div ref={terminalRef} className="windowed h-full" />
<div className="absolute bottom-0 left-0 z-40 flex w-full space-x-2 px-2 pb-2">
|
<Prompt
ref={promptRef}
|
onReturn={(input) => {
props.onReturn?.(input);
xtermRef.current?.scrollToBottom();
}}
/>
<TerminalMenu
onClickClearConsole={() => xtermRef.current?.clear()}
onClickForceStop={() => {
props.onStop?.();
xtermRef.current?.scrollToBottom();
}}
onClickRestart={props.onRestart}
/>
</div>
{props.showStopButton && (
<div className="absolute right-3 top-3 z-20 space-x-2 opacity-50 hover:opacity-100">
<Button icon={StopIcon} onClick={props.onStop}>
Stop
</Button>
</div>
)}
</section>
);
},
);
Terminal.displayName = 'Terminal';
export default Terminal;
|
src/components/Terminal.tsx
|
NUSSOC-glide-3ab6925
|
[
{
"filename": "src/pages/IDEPage.tsx",
"retrieved_chunk": " <Terminal\n ref={consoleRef}\n onRestart={interpreter.restart}\n onReturn={interpreter.execute}\n onStop={interpreter.stop}\n showStopButton={running}\n />\n }\n />\n </main>",
"score": 0.8640785813331604
},
{
"filename": "src/components/Editor.tsx",
"retrieved_chunk": " return (\n <section className=\"windowed h-full w-full\">\n <MonacoEditor\n defaultLanguage=\"python\"\n onChange={(value) =>\n value !== undefined ? props.onChange(value) : null\n }\n onMount={(editor) => (ref.current = editor)}\n options={{\n fontSize: 14,",
"score": 0.8449398279190063
},
{
"filename": "src/components/Prompt.tsx",
"retrieved_chunk": "const Prompt = forwardRef<PromptRef, PromptProps>((props, ref): JSX.Element => {\n const [{ dirty, command }, setCommand] = useState({\n dirty: false,\n command: '',\n });\n const inputRef = useRef<HTMLInputElement>(null);\n const history = useCommandHistory();\n useImperativeHandle(ref, () => ({\n focusWith: (key) => {\n if (key)",
"score": 0.8395189046859741
},
{
"filename": "src/pages/IDEPage.tsx",
"retrieved_chunk": " <main className=\"h-screen w-screen bg-slate-900 p-3 text-white\">\n <Between\n by={[70, 30]}\n first={\n <div className=\"flex h-full flex-col space-y-3\">\n <Navigator />\n <Editor onRunCode={interpreter.run} showRunButton={!running} />\n </div>\n }\n second={",
"score": 0.8375899195671082
},
{
"filename": "src/pages/IDEPage.tsx",
"retrieved_chunk": " const interpreter = useInterpreter({\n write: (text: string) => consoleRef.current?.write(text),\n writeln: (text: string) => consoleRef.current?.append(text),\n error: (text: string) => consoleRef.current?.error(text),\n system: (text: string) => consoleRef.current?.system(text),\n exports: useFile.Exports,\n lock: () => setRunning(true),\n unlock: () => setRunning(false),\n });\n return (",
"score": 0.8367468118667603
}
] |
typescript
|
<Prompt
ref={promptRef}
|
import { createCollectionRef } from './createCollectionRef'
import { firestore } from 'firebase-admin'
import { serverTimestamp } from './serverTimestamp'
/**
* Adds a new document to the specified collection in Firestore. If an ID is provided, the document will be set with that ID; otherwise, an ID will be automatically generated.
*
* @param db - The instance of the Firestore database to interact with.
* @param collectionPath - The path of the collection where the document will be added or set.
* @param params - The data of the document to be added or set.
* @param id - Optional. If provided, the document will be set with this ID. If not, an ID will be automatically generated by Firestore.
*
* @returns A reference to the added or set document.
*
* @throws Throws an exception if any error occurs during the document addition or setting process.
*
* @example
* ```typescript
* import { firestore } from 'firebase-admin'
* import { add } from '@skeet-framework/firestore'
*
* const db = firestore();
* const data: User = {
* name: "John Doe",
* age: 30
* };
*
* async function run() {
* try {
* const path = 'Users';
* // Example without providing an ID:
* const docRef1 = await add<User>(db, path, data);
* console.log(`Document added with ID: ${docRef1.id}`);
*
* // Example with providing an ID:
* const customID = 'custom_user_id';
* const docRef2 = await add<User>(db, path, data, customID);
* console.log(`Document set with ID: ${docRef2.id}`);
* } catch (error) {
* console.error(`Error processing document: ${error}`);
* }
* }
*
* run();
* ```
*/
export const addCollectionItem = async <T extends firestore.DocumentData>(
db: firestore.Firestore,
collectionPath: string,
params: T,
id?: string
) => {
try {
|
const collectionRef = createCollectionRef<T>(db, collectionPath)
if (id) {
|
const docRef = collectionRef.doc(id)
await docRef.set({
...params,
createdAt: serverTimestamp(),
updatedAt: serverTimestamp(),
})
return docRef
} else {
const data = await collectionRef.add({
...params,
createdAt: serverTimestamp(),
updatedAt: serverTimestamp(),
})
if (!data) {
throw new Error('no data')
}
return data
}
} catch (error) {
throw new Error(`Error adding document: ${error}`)
}
}
|
src/lib/addCollectionItem.ts
|
elsoul-skeet-firestore-8c637de
|
[
{
"filename": "src/lib/addCollectionItem.d.ts",
"retrieved_chunk": " * run();\n * ```\n */\nexport declare const addCollectionItem: <T extends firestore.DocumentData>(db: firestore.Firestore, collectionPath: string, params: T, id?: string) => Promise<any>;",
"score": 0.9251904487609863
},
{
"filename": "src/lib/updateCollectionItem.ts",
"retrieved_chunk": " */\nexport const updateCollectionItem = async <T extends firestore.DocumentData>(\n db: firestore.Firestore,\n collectionPath: string,\n docId: string,\n params: firestore.UpdateData<T>\n): Promise<boolean> => {\n try {\n const docRef = db\n .collection(collectionPath)",
"score": 0.9215347766876221
},
{
"filename": "src/lib/addCollectionItem.d.ts",
"retrieved_chunk": "import { firestore } from 'firebase-admin';\n/**\n * Adds a new document to the specified collection in Firestore. If an ID is provided, the document will be set with that ID; otherwise, an ID will be automatically generated.\n *\n * @param db - The instance of the Firestore database to interact with.\n * @param collectionPath - The path of the collection where the document will be added or set.\n * @param params - The data of the document to be added or set.\n * @param id - Optional. If provided, the document will be set with this ID. If not, an ID will be automatically generated by Firestore.\n *\n * @returns A reference to the added or set document.",
"score": 0.8845641016960144
},
{
"filename": "src/lib/createCollectionRef.ts",
"retrieved_chunk": "import { firestore } from 'firebase-admin'\nimport { createFirestoreDataConverter } from './createFirestoreDataConverter'\nimport { DocumentData } from 'firebase/firestore'\nexport const createCollectionRef = <T extends DocumentData>(\n db: firestore.Firestore,\n collectionPath: string\n) => {\n return db\n .collection(collectionPath)\n .withConverter(createFirestoreDataConverter<T>())",
"score": 0.8791183233261108
},
{
"filename": "src/lib/updateCollectionItem.d.ts",
"retrieved_chunk": " * }\n * } catch (error) {\n * console.error(`Error updating document: ${error}`);\n * }\n * }\n *\n * run();\n * ```\n */\nexport declare const updateCollectionItem: <T extends firestore.DocumentData>(db: firestore.Firestore, collectionPath: string, docId: string, params: firestore.UpdateData<T>) => Promise<boolean>;",
"score": 0.8680663704872131
}
] |
typescript
|
const collectionRef = createCollectionRef<T>(db, collectionPath)
if (id) {
|
import {
ComponentRef,
forwardRef,
useEffect,
useImperativeHandle,
useLayoutEffect,
useRef,
} from 'react';
import { StopIcon } from '@heroicons/react/24/outline';
import { slate, yellow } from 'tailwindcss/colors';
import { Terminal as Xterm } from 'xterm';
import { CanvasAddon } from 'xterm-addon-canvas';
import { FitAddon } from 'xterm-addon-fit';
import { WebglAddon } from 'xterm-addon-webgl';
import Button from './Button';
import Prompt from './Prompt';
import TerminalMenu from './TerminalMenu';
import 'xterm/css/xterm.css';
interface TerminalRef {
append: (result?: string) => void;
write: (result?: string) => void;
error: (result?: string) => void;
system: (result?: string) => void;
}
interface TerminalProps {
onStop?: () => void;
onReturn?: (line: string) => void;
onRestart?: () => void;
showStopButton?: boolean;
}
const isASCIIPrintable = (character: string): boolean =>
character >= String.fromCharCode(32) && character <= String.fromCharCode(126);
const isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
/**
* @see https://github.com/xtermjs/xterm.js/pull/4255
*/
const getSafariVersion = (): number => {
if (!isSafari) return 0;
const majorVersion = navigator.userAgent.match(/Version\/(\d+)/);
if (majorVersion === null || majorVersion.length < 2) return 0;
return parseInt(majorVersion[1]);
};
const isWebGL2Compatible = (): boolean => {
const context = document.createElement('canvas').getContext('webgl2');
const isWebGL2Available = Boolean(context);
return isWebGL2Available && (isSafari ? getSafariVersion() >= 16 : true);
};
const Terminal = forwardRef<TerminalRef, TerminalProps>(
(props, ref): JSX.Element => {
const xtermRef = useRef<Xterm>();
const fitAddonRef = useRef<FitAddon>();
const terminalRef = useRef<HTMLDivElement>(null);
const containerRef = useRef<HTMLDivElement>(null);
const promptRef = useRef<ComponentRef<typeof Prompt>>(null);
useLayoutEffect(() => {
const container = containerRef.current;
if (!container) return;
const resizeObserver = new ResizeObserver(() =>
fitAddonRef.current?.fit(),
);
resizeObserver.observe(container);
return () => resizeObserver.disconnect();
}, []);
useEffect(() => {
const terminal = terminalRef.current;
if (!terminal) return;
const xterm = new Xterm({
cursorBlink: false,
cursorStyle: 'underline',
fontFamily: 'monospace',
fontSize: 14,
theme: { background: slate[900], cursor: yellow[400] },
disableStdin: true,
});
const fitAddon = new FitAddon();
xterm.loadAddon(fitAddon);
if (isWebGL2Compatible()) {
xterm.loadAddon(new WebglAddon());
} else {
xterm.loadAddon(new CanvasAddon());
}
xterm.onKey(({ key }) => {
if (!(isASCIIPrintable(key) || key >= '\u00a0')) return;
promptRef.current?.focusWith(key);
});
xterm.open(terminal);
fitAddon.fit();
xtermRef.current = xterm;
fitAddonRef.current = fitAddon;
return () => xterm.dispose();
}, []);
const write = (text: string, line = true) => {
const trimmed = text.replace(/\n/g, '\r\n');
const xterm = xtermRef.current;
if (!xterm) return;
const writer = (text: string) =>
line ? xterm.writeln(text) : xterm.write(text);
try {
writer(trimmed);
} catch (error) {
if (!(error instanceof Error)) throw error;
console.log('oops', error.message);
xterm.clear();
writer(trimmed);
}
};
useImperativeHandle(ref, () => ({
append: (result?: string) => write(result ?? ''),
write: (result?: string) => write(result ?? '', false),
error: (result?: string) =>
write('\u001b[31m' + (result ?? '') + '\u001b[0m'),
system: (result?: string) =>
write('\u001b[33m' + (result ?? '') + '\u001b[0m'),
}));
return (
<section ref={containerRef} className="relative h-full w-full">
<div ref={terminalRef} className="windowed h-full" />
<div className="absolute bottom-0 left-0 z-40 flex w-full space-x-2 px-2 pb-2">
<Prompt
ref={promptRef}
onReturn={(input) => {
props.onReturn?.(input);
xtermRef.current?.scrollToBottom();
}}
/>
<TerminalMenu
onClickClearConsole={() => xtermRef.current?.clear()}
onClickForceStop={() => {
props.onStop?.();
xtermRef.current?.scrollToBottom();
}}
onClickRestart={props.onRestart}
/>
</div>
{props.showStopButton && (
<div className="absolute right-3 top-3 z-20 space-x-2 opacity-50 hover:opacity-100">
<
|
Button icon={StopIcon} onClick={props.onStop}>
Stop
</Button>
</div>
)}
|
</section>
);
},
);
Terminal.displayName = 'Terminal';
export default Terminal;
|
src/components/Terminal.tsx
|
NUSSOC-glide-3ab6925
|
[
{
"filename": "src/components/FileItem.tsx",
"retrieved_chunk": " {props.name}\n </p>\n <div className=\"flex items-center space-x-3 pl-2\">\n {props.unsaved && <UnsavedBadge className=\"group-hover:hidden\" />}\n <div className=\"hidden animate-pulse items-center space-x-1 text-xs opacity-70 group-hover:flex\">\n <p>Open</p>\n <ArrowRightIcon className=\"h-4\" />\n </div>\n </div>\n </button>",
"score": 0.883905291557312
},
{
"filename": "src/components/Editor.tsx",
"retrieved_chunk": " fontFamily: 'monospace',\n smoothScrolling: true,\n cursorSmoothCaretAnimation: 'on',\n minimap: { enabled: false },\n }}\n theme=\"vs-dark\"\n value={props.value}\n />\n {props.showRunButton && (\n <div className=\"absolute bottom-3 right-3 space-x-2\">",
"score": 0.8636257648468018
},
{
"filename": "src/components/FileItem.tsx",
"retrieved_chunk": " <div\n className=\"flex h-9 w-9 shrink-0 items-center justify-center rounded-lg bg-red-600/20 text-red-400 transition-transform hover:scale-110 active:scale-95\"\n onClick={() => destroy(props.name)}\n role=\"button\"\n >\n <TrashIcon className=\"h-5\" />\n </div>\n </div>\n );\n};",
"score": 0.8549631834030151
},
{
"filename": "src/components/TerminalMenu.tsx",
"retrieved_chunk": " <MenuHeader>Interpreter</MenuHeader>\n <MenuItem icon={ArrowPathIcon} onClick={props.onClickRestart}>\n Restart\n </MenuItem>\n <MenuItem icon={StopIcon} onClick={props.onClickForceStop}>\n Force stop\n </MenuItem>\n </div>\n <div className=\"px-1 py-1\">\n <MenuHeader>Console</MenuHeader>",
"score": 0.8548918962478638
},
{
"filename": "src/components/Item.tsx",
"retrieved_chunk": " } ${props.className ?? ''}`}\n role=\"button\"\n >\n {Icon && (\n <Icon\n className={`w-5 flex-shrink-0 opacity-80 ${\n !selected ? 'group-hover:opacity-90' : ''\n } ${iconClassName ?? ''}`}\n />\n )}",
"score": 0.8475760221481323
}
] |
typescript
|
Button icon={StopIcon} onClick={props.onStop}>
Stop
</Button>
</div>
)}
|
import { createCollectionRef } from './createCollectionRef'
import { firestore } from 'firebase-admin'
import { serverTimestamp } from './serverTimestamp'
/**
* Adds multiple documents to the specified collection in Firestore.
* This function supports batched writes, and if the number of items exceeds the maximum batch size (500),
* it will split the items into multiple batches and write them sequentially.
*
* @param db - The instance of the Firestore database to use.
* @param collectionPath - The path of the collection to which the documents will be added.
* @param items - An array of document data to be added.
*
* @returns An array of WriteResult arrays corresponding to each batch.
*
* @throws Throws an exception with an error message if an error occurs.
*
* @example
* ```typescript
* import { firestore } from 'firebase-admin'
* import { adds } from '@skeet-framework/firestore'
*
* const db = firestore();
* const users: User[] = [
* { name: "John Doe", age: 30 },
* { name: "Jane Smith", age: 25 },
* // ... more users ...
* ];
*
* async function run() {
* try {
* const path = 'Users'
* const results = await adds<User>(db, path, users);
* console.log(`Added ${users.length} users in ${results.length} batches.`);
* } catch (error) {
* console.error(`Error adding documents: ${error}`);
* }
* }
*
* run();
* ```
*/
export const addMultipleCollectionItems = async <
T extends firestore.DocumentData
>(
db: firestore.Firestore,
collectionPath: string,
items: T[]
): Promise<firestore.WriteResult[][]> => {
const MAX_BATCH_SIZE = 500
const chunkedItems =
items.length > 500 ? chunkArray(items, MAX_BATCH_SIZE) : [items]
const batchResults: firestore.WriteResult[][] = []
for (const chunk of chunkedItems) {
try {
const batch = db.batch()
const
|
collectionRef = createCollectionRef<T>(db, collectionPath)
chunk.forEach((item) => {
|
const docRef = collectionRef.doc()
batch.set(docRef, {
...item,
createdAt: serverTimestamp(),
updatedAt: serverTimestamp(),
})
})
const writeResults = await batch.commit()
batchResults.push(writeResults)
} catch (error) {
throw new Error(`Error adding a batch of documents: ${error}`)
}
}
return batchResults
}
/**
* Helper function to divide an array into chunks of a specified size.
*
* @param array - The array to be divided.
* @param size - The size of each chunk.
*
* @returns An array of chunked arrays.
*/
function chunkArray<T>(array: T[], size: number): T[][] {
const chunked = []
let index = 0
while (index < array.length) {
chunked.push(array.slice(index, size + index))
index += size
}
return chunked
}
|
src/lib/addMultipleCollectionItems.ts
|
elsoul-skeet-firestore-8c637de
|
[
{
"filename": "src/lib/addMultipleCollectionItems.d.ts",
"retrieved_chunk": " * console.log(`Added ${users.length} users in ${results.length} batches.`);\n * } catch (error) {\n * console.error(`Error adding documents: ${error}`);\n * }\n * }\n *\n * run();\n * ```\n */\nexport declare const addMultipleCollectionItems: <T extends firestore.DocumentData>(db: firestore.Firestore, collectionPath: string, items: T[]) => Promise<firestore.WriteResult[][]>;",
"score": 0.8634732961654663
},
{
"filename": "src/lib/addMultipleCollectionItems.d.ts",
"retrieved_chunk": "import { firestore } from 'firebase-admin';\n/**\n * Adds multiple documents to the specified collection in Firestore.\n * This function supports batched writes, and if the number of items exceeds the maximum batch size (500),\n * it will split the items into multiple batches and write them sequentially.\n *\n * @param db - The instance of the Firestore database to use.\n * @param collectionPath - The path of the collection to which the documents will be added.\n * @param items - An array of document data to be added.\n *",
"score": 0.8432146310806274
},
{
"filename": "src/lib/updateCollectionItem.ts",
"retrieved_chunk": " */\nexport const updateCollectionItem = async <T extends firestore.DocumentData>(\n db: firestore.Firestore,\n collectionPath: string,\n docId: string,\n params: firestore.UpdateData<T>\n): Promise<boolean> => {\n try {\n const docRef = db\n .collection(collectionPath)",
"score": 0.8280400037765503
},
{
"filename": "src/lib/queryCollectionItems.ts",
"retrieved_chunk": " */\nexport const queryCollectionItems = async <T extends firestore.DocumentData>(\n db: firestore.Firestore,\n collectionPath: string,\n conditions: QueryCondition[]\n): Promise<T[]> => {\n try {\n let query: firestore.Query = db\n .collection(collectionPath)\n .withConverter(createFirestoreDataConverter<T>())",
"score": 0.8241263628005981
},
{
"filename": "src/lib/addCollectionItem.ts",
"retrieved_chunk": ") => {\n try {\n const collectionRef = createCollectionRef<T>(db, collectionPath)\n if (id) {\n const docRef = collectionRef.doc(id)\n await docRef.set({\n ...params,\n createdAt: serverTimestamp(),\n updatedAt: serverTimestamp(),\n })",
"score": 0.820785403251648
}
] |
typescript
|
collectionRef = createCollectionRef<T>(db, collectionPath)
chunk.forEach((item) => {
|
import { persistor } from '../store';
import { filesActions } from '../store/filesSlice';
import { useAppDispatch } from '../store/hooks';
import { vaultActions } from '../store/vaultSlice';
interface UseFilesMutationsHook {
/**
* For performance reasons, the caller should ensure that the new
* name is not already in use in *both* the files and vault stores.
*/
rename: (from: string, to: string) => void;
save: (name: string, content: string) => void;
destroy: (name: string) => void;
draft: (autoSelect?: boolean) => void;
select: (name: string) => void;
update: (content: string) => void;
create: (name: string, content: string) => void;
}
const useFilesMutations = (): UseFilesMutationsHook => {
const dispatch = useAppDispatch();
return {
save: (name: string, content: string) => {
dispatch(filesActions.updateSelected(content));
dispatch(vaultActions.save({ name, content }));
persistor.flush();
},
rename: (from: string, to: string) => {
if (from === to) return;
dispatch(filesActions.rename({ from, to }));
dispatch(vaultActions.rename({ from, to }));
persistor.flush();
},
destroy: (name: string) => {
dispatch(filesActions.destroy(name));
dispatch(vaultActions.destroy(name));
persistor.flush();
},
draft: (autoSelect?: boolean) => {
|
dispatch(filesActions.draft(autoSelect));
|
},
select: (name: string) => {
dispatch(filesActions.select(name));
},
update: (content: string) => {
dispatch(filesActions.updateSelected(content));
},
create: (name: string, content: string) => {
dispatch(filesActions.create({ name, content }));
dispatch(vaultActions.save({ name, content }));
persistor.flush();
},
};
};
export default useFilesMutations;
|
src/hooks/useFilesMutations.ts
|
NUSSOC-glide-3ab6925
|
[
{
"filename": "src/store/filesSlice.ts",
"retrieved_chunk": " if (state.selected === name) state.selected = undefined;\n },\n select: (state, action: PayloadAction<string>) => {\n const name = action.payload;\n if (state.files[name] === undefined) return;\n state.selected = name;\n },\n rename: (state, action: PayloadAction<{ from: string; to: string }>) => {\n const { from: oldName, to: newName } = action.payload;\n const isOldNameExist = state.files[oldName] !== undefined;",
"score": 0.8792659044265747
},
{
"filename": "src/store/filesSlice.ts",
"retrieved_chunk": " state.selected = newName;\n },\n updateSelected: (state, action: PayloadAction<string>) => {\n if (state.selected === undefined) return;\n state.files[state.selected] = action.payload;\n },\n destroy: (state, action: PayloadAction<string>) => {\n const name = action.payload;\n delete state.files[name];\n state.list = state.list.filter((file) => file !== name);",
"score": 0.8779714703559875
},
{
"filename": "src/store/vaultSlice.ts",
"retrieved_chunk": " const { name, content } = action.payload;\n if (state.files[name] === undefined) state.list.push(name);\n state.files[name] = content;\n },\n destroy: (state, action: PayloadAction<string>) => {\n const name = action.payload;\n delete state.files[name];\n state.list = state.list.filter((file) => file !== name);\n },\n rename: (state, action: PayloadAction<{ from: string; to: string }>) => {",
"score": 0.8697714805603027
},
{
"filename": "src/store/vaultSlice.ts",
"retrieved_chunk": " const { from: oldName, to: newName } = action.payload;\n const isOldNameExist = state.files[oldName] !== undefined;\n const isNewNameExist = state.files[newName] !== undefined;\n if (!isOldNameExist || isNewNameExist) return;\n state.files[newName] = state.files[oldName];\n delete state.files[oldName];\n state.list = state.list.map((name) =>\n name === oldName ? newName : name,\n );\n },",
"score": 0.8555957674980164
},
{
"filename": "src/store/filesSlice.ts",
"retrieved_chunk": " state.list,\n (counter) => `untitled-${counter + 1}.py`,\n );\n state.files[name] = '';\n state.list.push(name);\n const select = action.payload;\n if (select) state.selected = name;\n },\n create: (\n state,",
"score": 0.8524751663208008
}
] |
typescript
|
dispatch(filesActions.draft(autoSelect));
|
import Express from "express";
import { ErrorCodes } from "../const/errors";
import { sendErrorResponse, sendJSONResponse, isURL } from "../utils";
import dns from "node:dns";
import EmailCache from "../models/EmailCache";
import RateLimiter from "../models/RateLimiter";
const RATE_TIMEOUT = 5000;
const RATE_LIMITER = new RateLimiter(5, RATE_TIMEOUT); // Throttle the requests to prevent overload
function validateEmailSyntax(email: string): boolean {
const regex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
const maxDomainLength = 255;
const maxLocalPartLength = 64;
const maxEmailLength = maxLocalPartLength + 1 + maxDomainLength;
if (email.length > maxEmailLength) {
return false;
}
const [localPart, domain] = email.split("@");
if (localPart?.length > maxLocalPartLength || domain?.length > maxDomainLength) {
return false;
}
return regex.test(email);
}
function validateEmailDomain(email: string): Promise<boolean> {
if (!validateEmailSyntax(email)) return Promise.resolve(false);
const [mail, tld] = email.split("@");
if (!tld || !isURL(tld)) return Promise.resolve(false);
return new Promise((resolve, reject) => {
dns.resolve(tld, "MX", (err, addresses) => {
if (err) resolve(false);
resolve(addresses?.length > 0)
})
})
}
export default async function (req: Express.Request, res: Express.Response) {
const queryEmail = req.query?.email;
if (RATE_LIMITER.checkIfTimedOut(req)) {
sendErrorResponse(res, {
error: {
code: ErrorCodes.TOO_MANY_REQUESTS,
details: {
retry_after: `${RATE_TIMEOUT} ms`
},
message: "Too many requests. Please try again later",
},
status: 429
});
RATE_LIMITER.resetRequest(req);
return;
}
RATE_LIMITER.logRequest(req);
if (!queryEmail || queryEmail?.length === 0) {
sendErrorResponse(res, {
error: {
code: ErrorCodes.BAD_INPUT,
message: "email is a required argument",
},
status: 400
});
return;
}
|
const cachedEmailData = await EmailCache.getEmail(queryEmail as string);
|
let emailChecks;
if (cachedEmailData?.length) {
emailChecks = cachedEmailData;
} else {
emailChecks = [
validateEmailSyntax(queryEmail as string),
await validateEmailDomain(queryEmail as string)
]
}
emailChecks = emailChecks as Array<boolean>;
const response = {
data: {
email: queryEmail as string,
valid: emailChecks.every(e => e),
format_valid: emailChecks[0],
domain_valid: emailChecks[1],
},
status: 200
}
if (!cachedEmailData?.length) {
await EmailCache.pushEmail(queryEmail as string, emailChecks as Array<boolean>);
}
sendJSONResponse(res, response)
}
|
src/routes/EmailValidate.ts
|
Aadv1k-ZapMail-fd3be91
|
[
{
"filename": "src/models/EmailCache.ts",
"retrieved_chunk": "\t\t\treturn email;\n\t\t} catch (err) {\n\t\t\tthrow err;\n\t\t}\n\t}\n\tasync getEmail(email: string): Promise<Array<boolean> | null> {\n\t\ttry {\n\t\t\tconst resp = await this.client.get(email)\n\t\t\treturn JSON.parse(resp ?? \"[]\");\n\t\t} catch (err) {",
"score": 0.8205031752586365
},
{
"filename": "src/routes/EmailSend.ts",
"retrieved_chunk": "\t\t\t\t\t\t\t\tmessage: \"Bad input\",\n\t\t\t\t\t\t\t\tdetails: ajv.errors,\n\t\t\t\t\t\t},\n\t\t\t\t\t\tstatus: 400\n\t\t\t\t})\n\t\t\t\treturn;\n\t\t}\n\t\ttry {\n\t\t\t\tconst receivedMailId = await sendMail(body);\n\t\t\t\tsendJSONResponse(res, {",
"score": 0.8098524808883667
},
{
"filename": "src/models/EmailCache.ts",
"retrieved_chunk": "import { createClient } from \"redis\";\nimport { REDIS_CONFIG } from \"../const/vars\";\nclass EmailCache {\n\tclient: any;\n\tconstructor() {\n\t\tthis.client = createClient({\n\t\t\tsocket: {\n\t\t\t\thost: REDIS_CONFIG.host,\n\t\t\t\tport: REDIS_CONFIG.port,\n\t\t\t},",
"score": 0.8080339431762695
},
{
"filename": "src/server.ts",
"retrieved_chunk": "});\n(async () => {\n await EmailCache.init();\n\t\tapp.get(\"/\", (req, res) => {\n\t\t\t\tconsole.log(path.join(__dirname, \"./public/index.html\"))\n\t\t\t\tres.sendFile(path.join(__dirname, \"../public/index.html\"))\n\t\t})\n app.get(\"/api/v1/email/validate\", routeEmailValidate)\n\t\tapp.post(\"/api/v1/email/send\", routeEmailSend)\n})();",
"score": 0.8077432513237
},
{
"filename": "src/routes/EmailSend.ts",
"retrieved_chunk": "\t\t\t\t\t\t},\n\t\t\t\t\t\tstatus: 400\n\t\t\t\t})\n\t\t\t\treturn;\n\t\t}\n\t\tconst isMailValid = ajv.validate(mailSchema, body);\n\t\tif (!isMailValid) {\n\t\t\t\tsendErrorResponse(res, {\n\t\t\t\t\t\terror: {\n\t\t\t\t\t\t\t\tcode: ErrorCodes.BAD_INPUT,",
"score": 0.806708037853241
}
] |
typescript
|
const cachedEmailData = await EmailCache.getEmail(queryEmail as string);
|
import Express from "express";
import { ErrorCodes } from "../const/errors";
import { sendErrorResponse, sendJSONResponse, isURL } from "../utils";
import dns from "node:dns";
import EmailCache from "../models/EmailCache";
import RateLimiter from "../models/RateLimiter";
const RATE_TIMEOUT = 5000;
const RATE_LIMITER = new RateLimiter(5, RATE_TIMEOUT); // Throttle the requests to prevent overload
function validateEmailSyntax(email: string): boolean {
const regex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
const maxDomainLength = 255;
const maxLocalPartLength = 64;
const maxEmailLength = maxLocalPartLength + 1 + maxDomainLength;
if (email.length > maxEmailLength) {
return false;
}
const [localPart, domain] = email.split("@");
if (localPart?.length > maxLocalPartLength || domain?.length > maxDomainLength) {
return false;
}
return regex.test(email);
}
function validateEmailDomain(email: string): Promise<boolean> {
if (!validateEmailSyntax(email)) return Promise.resolve(false);
const [mail, tld] = email.split("@");
if (!tld || !isURL(tld)) return Promise.resolve(false);
return new Promise((resolve, reject) => {
dns.resolve(tld, "MX", (err, addresses) => {
if (err) resolve(false);
resolve(addresses?.length > 0)
})
})
}
export default async function (req: Express.Request, res: Express.Response) {
const queryEmail = req.query?.email;
if (RATE_LIMITER.checkIfTimedOut(req)) {
sendErrorResponse(res, {
error: {
code: ErrorCodes.TOO_MANY_REQUESTS,
details: {
retry_after: `${RATE_TIMEOUT} ms`
},
message: "Too many requests. Please try again later",
},
status: 429
});
RATE_LIMITER.resetRequest(req);
return;
}
RATE_LIMITER.logRequest(req);
if (!queryEmail || queryEmail?.length === 0) {
sendErrorResponse(res, {
error: {
code: ErrorCodes.BAD_INPUT,
message: "email is a required argument",
},
status: 400
});
return;
}
const
|
cachedEmailData = await EmailCache.getEmail(queryEmail as string);
|
let emailChecks;
if (cachedEmailData?.length) {
emailChecks = cachedEmailData;
} else {
emailChecks = [
validateEmailSyntax(queryEmail as string),
await validateEmailDomain(queryEmail as string)
]
}
emailChecks = emailChecks as Array<boolean>;
const response = {
data: {
email: queryEmail as string,
valid: emailChecks.every(e => e),
format_valid: emailChecks[0],
domain_valid: emailChecks[1],
},
status: 200
}
if (!cachedEmailData?.length) {
await EmailCache.pushEmail(queryEmail as string, emailChecks as Array<boolean>);
}
sendJSONResponse(res, response)
}
|
src/routes/EmailValidate.ts
|
Aadv1k-ZapMail-fd3be91
|
[
{
"filename": "src/models/EmailCache.ts",
"retrieved_chunk": "\t\t\treturn email;\n\t\t} catch (err) {\n\t\t\tthrow err;\n\t\t}\n\t}\n\tasync getEmail(email: string): Promise<Array<boolean> | null> {\n\t\ttry {\n\t\t\tconst resp = await this.client.get(email)\n\t\t\treturn JSON.parse(resp ?? \"[]\");\n\t\t} catch (err) {",
"score": 0.8220049738883972
},
{
"filename": "src/routes/EmailSend.ts",
"retrieved_chunk": "\t\t\t\t\t\t},\n\t\t\t\t\t\tstatus: 400\n\t\t\t\t})\n\t\t\t\treturn;\n\t\t}\n\t\tconst isMailValid = ajv.validate(mailSchema, body);\n\t\tif (!isMailValid) {\n\t\t\t\tsendErrorResponse(res, {\n\t\t\t\t\t\terror: {\n\t\t\t\t\t\t\t\tcode: ErrorCodes.BAD_INPUT,",
"score": 0.8208126425743103
},
{
"filename": "src/server.ts",
"retrieved_chunk": "});\n(async () => {\n await EmailCache.init();\n\t\tapp.get(\"/\", (req, res) => {\n\t\t\t\tconsole.log(path.join(__dirname, \"./public/index.html\"))\n\t\t\t\tres.sendFile(path.join(__dirname, \"../public/index.html\"))\n\t\t})\n app.get(\"/api/v1/email/validate\", routeEmailValidate)\n\t\tapp.post(\"/api/v1/email/send\", routeEmailSend)\n})();",
"score": 0.8139864206314087
},
{
"filename": "src/routes/EmailSend.ts",
"retrieved_chunk": "\t\t\t\t\t\t\t\tmessage: \"Bad input\",\n\t\t\t\t\t\t\t\tdetails: ajv.errors,\n\t\t\t\t\t\t},\n\t\t\t\t\t\tstatus: 400\n\t\t\t\t})\n\t\t\t\treturn;\n\t\t}\n\t\ttry {\n\t\t\t\tconst receivedMailId = await sendMail(body);\n\t\t\t\tsendJSONResponse(res, {",
"score": 0.811290979385376
},
{
"filename": "src/models/EmailCache.ts",
"retrieved_chunk": "import { createClient } from \"redis\";\nimport { REDIS_CONFIG } from \"../const/vars\";\nclass EmailCache {\n\tclient: any;\n\tconstructor() {\n\t\tthis.client = createClient({\n\t\t\tsocket: {\n\t\t\t\thost: REDIS_CONFIG.host,\n\t\t\t\tport: REDIS_CONFIG.port,\n\t\t\t},",
"score": 0.809785783290863
}
] |
typescript
|
cachedEmailData = await EmailCache.getEmail(queryEmail as string);
|
import { firestore } from 'firebase-admin'
import { createFirestoreDataConverter } from './createFirestoreDataConverter'
/**
* Represents a condition for querying Firestore collections.
*/
type QueryCondition = {
field?: string
operator?: firestore.WhereFilterOp
value?: any
orderDirection?: firestore.OrderByDirection // "asc" or "desc"
limit?: number
}
/**
* Queries the specified collection in Firestore based on the provided conditions
* and returns an array of documents that match the conditions.
*
* @param db - The instance of the Firestore database to use.
* @param collectionPath - The path of the collection to be queried.
* @param conditions - An array of conditions to apply to the query.
*
* @returns An array of documents from the collection that match the conditions.
*
* @throws Throws an exception with an error message if an error occurs.
*
* @example
* ```typescript
* import { firestore } from 'firebase-admin'
* import { query } from '@skeet-framework/firestore'
* const db = firestore();
*
* // Simple query to get users over 25 years old
* const simpleConditions: QueryCondition[] = [
* { field: "age", operator: ">", value: 25 }
* ];
*
* // Advanced query to get users over 25 years old, ordered by their names
* const advancedConditions: QueryCondition[] = [
* { field: "age", operator: ">", value: 25 },
* { field: "name", orderDirection: "asc" }
* ];
*
* // Query to get users over 25 years old and limit the results to 5
* const limitedConditions: QueryCondition[] = [
* { field: "age", operator: ">", value: 25 },
* { limit: 5 }
* ];
*
* async function run() {
* try {
* const path = 'Users';
*
* // Using the simple conditions
* const usersByAge = await query<User>(db, path, simpleConditions);
* console.log(`Found ${usersByAge.length} users over 25 years old.`);
*
* // Using the advanced conditions
* const orderedUsers = await query<User>(db, path, advancedConditions);
* console.log(`Found ${orderedUsers.length} users over 25 years old, ordered by name.`);
*
* // Using the limited conditions
* const limitedUsers = await query<User>(db, path, limitedConditions);
* console.log(`Found ${limitedUsers.length} users over 25 years old, limited to 5.`);
*
* } catch (error) {
* console.error(`Error querying collection: ${error}`);
* }
* }
*
* run();
* ```
*/
export const queryCollectionItems = async <T extends firestore.DocumentData>(
db: firestore.Firestore,
collectionPath: string,
conditions: QueryCondition[]
): Promise<T[]> => {
try {
let query: firestore.Query = db
.collection(collectionPath)
|
.withConverter(createFirestoreDataConverter<T>())
for (const condition of conditions) {
|
if (
condition.field &&
condition.operator &&
condition.value !== undefined
) {
query = query.where(
condition.field,
condition.operator,
condition.value
)
}
if (condition.field && condition.orderDirection) {
query = query.orderBy(condition.field, condition.orderDirection)
}
if (condition.limit !== undefined) {
query = query.limit(condition.limit)
}
}
const snapshot = await query.get()
return snapshot.docs.map((doc) => ({
id: doc.id,
...(doc.data() as T),
}))
} catch (error) {
throw new Error(`Error querying collection: ${error}`)
}
}
|
src/lib/queryCollectionItems.ts
|
elsoul-skeet-firestore-8c637de
|
[
{
"filename": "src/lib/queryCollectionItems.d.ts",
"retrieved_chunk": "export declare const queryCollectionItems: <T extends firestore.DocumentData>(db: firestore.Firestore, collectionPath: string, conditions: QueryCondition[]) => Promise<T[]>;\nexport {};",
"score": 0.9411983489990234
},
{
"filename": "src/lib/addMultipleCollectionItems.ts",
"retrieved_chunk": " */\nexport const addMultipleCollectionItems = async <\n T extends firestore.DocumentData\n>(\n db: firestore.Firestore,\n collectionPath: string,\n items: T[]\n): Promise<firestore.WriteResult[][]> => {\n const MAX_BATCH_SIZE = 500\n const chunkedItems =",
"score": 0.8566860556602478
},
{
"filename": "src/lib/getCollectionItem.ts",
"retrieved_chunk": " * run();\n * ```\n */\nexport const getCollectionItem = async <T>(\n db: firestore.Firestore,\n collectionPath: string,\n docId: string\n): Promise<T> => {\n const dataRef = db\n .collection(collectionPath)",
"score": 0.8544266223907471
},
{
"filename": "src/lib/updateCollectionItem.ts",
"retrieved_chunk": " */\nexport const updateCollectionItem = async <T extends firestore.DocumentData>(\n db: firestore.Firestore,\n collectionPath: string,\n docId: string,\n params: firestore.UpdateData<T>\n): Promise<boolean> => {\n try {\n const docRef = db\n .collection(collectionPath)",
"score": 0.8491373062133789
},
{
"filename": "src/lib/createCollectionRef.ts",
"retrieved_chunk": "import { firestore } from 'firebase-admin'\nimport { createFirestoreDataConverter } from './createFirestoreDataConverter'\nimport { DocumentData } from 'firebase/firestore'\nexport const createCollectionRef = <T extends DocumentData>(\n db: firestore.Firestore,\n collectionPath: string\n) => {\n return db\n .collection(collectionPath)\n .withConverter(createFirestoreDataConverter<T>())",
"score": 0.8417545557022095
}
] |
typescript
|
.withConverter(createFirestoreDataConverter<T>())
for (const condition of conditions) {
|
import Express from "express";
import { ErrorCodes } from "../const/errors";
import { sendErrorResponse, sendJSONResponse, isURL } from "../utils";
import { MAIL_CONFIG } from "../const/vars";
import nodemailer from "nodemailer"
;
import mailSchema from "../const/mailSchema";
import { Mail } from "../const/email";
import RateLimiter from "../models/RateLimiter";
const RATE_TIMEOUT = 20_000;
const RATE_LIMITER = new RateLimiter(1, RATE_TIMEOUT); // Throttle the requests to prevent overload
import Ajv from "ajv";
const ajv = new Ajv({ allErrors: true });
ajv.addFormat('email', {
type: 'string',
validate: (value: string) => {
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return emailRegex.test(value);
},
});
const transporter = nodemailer.createTransport({
maxConnections: 2,
pool: true,
service: "hotmail",
auth: {
user: MAIL_CONFIG.address,
pass: MAIL_CONFIG.password
}
});
function sendMail(blob: Mail): Promise<string> {
const toEmails = blob.to.map(e => e.email);
const fromEmail = blob.from;
const body = `Forwarded via Zap<https://github.com/aadv1k/zap> originally by ${fromEmail}\n` + blob.body.content;
return new Promise((resolve, reject) => {
transporter.sendMail({
from: MAIL_CONFIG.address,
to: toEmails,
subject: blob.subject,
html: body
}, (error: any, info: any) => {
if (error) reject(error);
resolve(info.messageId);
})
})
}
export default async function (req: Express.Request, res: Express.Response) {
if (RATE_LIMITER.checkIfTimedOut(req)) {
sendErrorResponse(res, {
error: {
code: ErrorCodes.TOO_MANY_REQUESTS,
details: {
retry_after: `${RATE_TIMEOUT} ms`
},
message: "Too many requests. Please try again later",
},
status: 429
});
RATE_LIMITER.resetRequest(req);
return;
}
RATE_LIMITER.logRequest(req);
let body: Mail;
try {
body = req.body;
} catch (err) {
console.log("DEBUG LOG >>>>> ", err)
sendErrorResponse(res, {
error: {
code: ErrorCodes.BAD_INPUT,
message: "Invalid JSON data",
},
status: 400
})
return;
}
|
const isMailValid = ajv.validate(mailSchema, body);
|
if (!isMailValid) {
sendErrorResponse(res, {
error: {
code: ErrorCodes.BAD_INPUT,
message: "Bad input",
details: ajv.errors,
},
status: 400
})
return;
}
try {
const receivedMailId = await sendMail(body);
sendJSONResponse(res, {
data: {
messageId: receivedMailId,
},
status: 200,
}, 200)
} catch (error) {
sendErrorResponse(res, {
error: {
code: ErrorCodes.INTERNAL_ERROR,
message: "Internall error while sending mail",
details: error,
},
status: 500
})
}
}
|
src/routes/EmailSend.ts
|
Aadv1k-ZapMail-fd3be91
|
[
{
"filename": "src/routes/EmailValidate.ts",
"retrieved_chunk": "\t\tif (!queryEmail || queryEmail?.length === 0) {\n\t\t\t\tsendErrorResponse(res, {\n\t\t\t\t\t\terror: {\n\t\t\t\t\t\t\t\tcode: ErrorCodes.BAD_INPUT,\n\t\t\t\t\t\t\t\tmessage: \"email is a required argument\",\n\t\t\t\t\t\t},\n\t\t\t\t\t\tstatus: 400\n\t\t\t\t});\n\t\t\t\treturn;\n\t\t}",
"score": 0.8477197885513306
},
{
"filename": "src/routes/EmailValidate.ts",
"retrieved_chunk": "import Express from \"express\";\nimport { ErrorCodes } from \"../const/errors\";\nimport { sendErrorResponse, sendJSONResponse, isURL } from \"../utils\";\nimport dns from \"node:dns\";\nimport EmailCache from \"../models/EmailCache\";\nimport RateLimiter from \"../models/RateLimiter\";\nconst RATE_TIMEOUT = 5000;\nconst RATE_LIMITER = new RateLimiter(5, RATE_TIMEOUT); // Throttle the requests to prevent overload \nfunction validateEmailSyntax(email: string): boolean {\n const regex = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/;",
"score": 0.8194218873977661
},
{
"filename": "src/server.ts",
"retrieved_chunk": "app.use((err: any, req: any, res: any, next: any) => {\n if (err instanceof SyntaxError) \n\t\t\t\tsendErrorResponse(res as express.Response, {\n\t\t\t\t\t\terror: {\n\t\t\t\t\t\t\t\tcode: ErrorCodes.BAD_INPUT,\n\t\t\t\t\t\t\t\tmessage: \"Bad JSON input\"\n\t\t\t\t\t\t},\n\t\t\t\t\t\tstatus: 400\n\t\t\t\t})\n return;",
"score": 0.8125141859054565
},
{
"filename": "src/routes/EmailValidate.ts",
"retrieved_chunk": "\t\temailChecks = emailChecks as Array<boolean>;\n\t\tconst response = {\n\t\t\t\tdata: {\n\t\t\t\t\t\temail: queryEmail as string,\n\t\t\t\t\t\tvalid: emailChecks.every(e => e),\n\t\t\t\t\t\tformat_valid: emailChecks[0],\n\t\t\t\t\t\tdomain_valid: emailChecks[1],\n\t\t\t\t},\n\t\t\t\tstatus: 200\n\t\t}",
"score": 0.8062256574630737
},
{
"filename": "src/routes/EmailValidate.ts",
"retrieved_chunk": "\t\tif (!cachedEmailData?.length) {\n\t\t\t\tawait EmailCache.pushEmail(queryEmail as string, emailChecks as Array<boolean>);\n\t\t}\n\t\tsendJSONResponse(res, response)\n}",
"score": 0.7911904454231262
}
] |
typescript
|
const isMailValid = ajv.validate(mailSchema, body);
|
import { Request, response, Response } from "express"
import Product from "../models/product"
import { IProduct } from "../types"
type CreateProductRequestType = Pick<
IProduct,
"image" | "name" | "description" | "price"
>
export const createProduct = async (request: Request, response: Response) => {
try {
const { image, name, price, description }: CreateProductRequestType =
request.body
const product = await Product.create({
image,
name,
price,
description,
})
response.send(product)
} catch (error) {
console.log("error in createProduct", error)
response.send({
message: "Something went wrong while creating product",
})
throw error
}
}
export const getProducts = async (request: Request, response: Response) => {
try {
const products = await Product.find({})
response.send(products)
} catch (error) {
console.log("error in getProducts", error)
response.send({ message: "Something went wrong in get products" })
throw error
}
}
export const getProductById = async (request: Request, response: Response) => {
try {
const { id } = request.params
|
const product = await Product.findById(id)
response.send(product)
} catch (error) {
|
console.log("error in getProductById", error)
response.send({
message: "Something went wrong while fetching the product",
})
throw error
}
}
|
src/controller/product.ts
|
omkhetwal-komorebi-backend-production-8f46fde
|
[
{
"filename": "src/routes/product.ts",
"retrieved_chunk": "import express from \"express\"\nimport {\n createProduct,\n getProductById,\n getProducts,\n} from \"../controller/product\"\nconst productRoutes = express.Router()\nproductRoutes.get(\"/\", getProducts)\nproductRoutes.get(\"/:id\", getProductById)\nproductRoutes.post(\"/\", createProduct)",
"score": 0.8634323477745056
},
{
"filename": "src/controller/order.ts",
"retrieved_chunk": " console.log(\"error in createOrder\", error)\n response.send({\n message: \"Something went wrong in create order\",\n })\n throw error\n }\n}",
"score": 0.8490182161331177
},
{
"filename": "src/server.ts",
"retrieved_chunk": "connectToDatabase()\napp.get(\"/ping\", (request, response) => {\n response.send(\"pong\")\n})\napp.post(\"/webhook\", express.raw({ type: \"application/json\" }), webhookHandler)\napp.use(express.json())\napp.use(\"/products\", productRoutes)\napp.use(\"/orders\", orderRoutes)\nconst PORT = process.env.PORT || 3000\napp.listen(PORT, () => {",
"score": 0.8270696401596069
},
{
"filename": "src/models/product.ts",
"retrieved_chunk": "import mongoose, { Schema } from \"mongoose\"\nimport { IProduct } from \"../types\"\nconst productSchema = new Schema<IProduct>(\n {\n name: {\n type: String,\n required: true,\n },\n image: {\n type: String,",
"score": 0.8239067792892456
},
{
"filename": "src/controller/order.ts",
"retrieved_chunk": " orderItems,\n totalPrice,\n paymentIntentId: paymentIntent.id,\n paymentStatus: \"pending\",\n paymentDetails: {},\n })\n response.send({\n clientSecret: paymentIntent.client_secret,\n })\n } catch (error) {",
"score": 0.8234147429466248
}
] |
typescript
|
const product = await Product.findById(id)
response.send(product)
} catch (error) {
|
import {
loadPyodide,
PyodideInterface,
PyProxy,
PyProxyAwaitable,
PyProxyCallable,
PyProxyDict,
} from 'pyodide';
import consoleScript from '../assets/console.py';
/**
* @see https://pyodide.org/en/stable/usage/api/python-api/console.html#pyodide.console.ConsoleFuture.syntax_check
*/
type SyntaxCheck = 'syntax-error' | 'incomplete' | 'complete';
interface Message<T extends Record<string, unknown>> {
type: keyof T;
payload: any;
}
interface RunExportableData {
code: string;
exports?: { name: string; content: string }[];
}
let pyodide: PyodideInterface;
let interruptBuffer: Uint8Array | null;
let await_fut: PyProxyCallable;
let repr_shorten: PyProxyCallable;
let pyconsole: PyProxy;
let clear_console: PyProxyCallable;
let create_console: PyProxyCallable;
const PS1 = '\u001b[32;1m>>> \u001b[0m' as const;
const PS2 = '\u001b[32m... \u001b[0m' as const;
const RUN_CODE = '\u001b[3m\u001b[32m<run code>\u001b[0m' as const;
const post = {
write: (text: string) => postMessage({ type: 'write', payload: text }),
writeln: (line: string) => postMessage({ type: 'writeln', payload: line }),
error: (message: string) => postMessage({ type: 'error', payload: message }),
system: (message: string) =>
postMessage({ type: 'system', payload: message }),
lock: () => postMessage({ type: 'lock' }),
unlock: () => postMessage({ type: 'unlock' }),
prompt: (newLine = true) => post.write(`${newLine ? '\n' : ''}${PS1}`),
promptPending: () => post.write(PS2),
};
const setUpConsole = (globals?: PyProxyDict) => {
pyconsole?.destroy();
pyconsole = create_console(globals);
};
const setUpREPLEnvironment = () => {
const globals = pyodide.globals.get('dict')();
pyodide.
|
runPython(consoleScript, { globals });
|
repr_shorten = globals.get('repr_shorten');
await_fut = globals.get('await_fut');
create_console = globals.get('create_console');
clear_console = globals.get('clear_console');
setUpConsole();
return globals.get('BANNER') as string;
};
const preparePyodide = async () => {
const newPyodide = await loadPyodide();
newPyodide.setStdout({ batched: post.writeln });
newPyodide.setStderr({ batched: post.error });
pyodide = newPyodide;
if (interruptBuffer) pyodide.setInterruptBuffer(interruptBuffer);
/**
* Replaces Pyodide's `js` import with a stub `object`. This must also be
* paired with some `del sys.modules['js']` in Pyodide's initialisation.
*/
pyodide.registerJsModule('js', {});
const banner = setUpREPLEnvironment();
post.writeln(banner);
post.prompt(false);
post.unlock();
return newPyodide;
};
const prepareExports = (exports?: { name: string; content: string }[]) => {
let newExports = new Set<string>();
exports?.forEach(({ name, content }) => {
pyodide.FS.writeFile(name, content, { encoding: 'utf-8' });
newExports.add(name);
});
const oldExports = pyodide.FS.readdir('.') as string[];
oldExports.forEach((name) => {
if (name === '.' || name === '..' || newExports.has(name)) return;
pyodide.FS.unlink(name);
});
};
/**
* Pyodide may sometimes not catch `RecursionError`s and excessively
* recursive code spills as JavaScript `RangeError`, causing Pyodide to
* fatally crash. We need to restart Pyodide in this case.
* @see https://github.com/pyodide/pyodide/issues/951
*/
const handleRangeErrorAndRestartPyodide = async (error: unknown) => {
if (!(error instanceof RangeError)) return;
post.system(
'\nOops, something happened and we have to restart the interpreter. ' +
"Don't worry, it's not your fault. " +
'You may continue once you see the prompt again.\n',
);
await preparePyodide();
};
const listeners = {
initialize: async (newInterruptBuffer?: Uint8Array) => {
pyodide ??= await preparePyodide();
if (!newInterruptBuffer) return;
pyodide.setInterruptBuffer(newInterruptBuffer);
interruptBuffer = newInterruptBuffer;
},
run: async ({ code, exports }: RunExportableData) => {
pyodide ??= await preparePyodide();
post.writeln(RUN_CODE);
try {
post.lock();
prepareExports(exports);
await pyodide.loadPackagesFromImports(code);
const globals = pyodide.globals.get('dict')();
/**
* `await pyodide.runPythonAsync(code)` is not used because it raises
* an uncatchable `PythonError` when Pyodide emits a `KeyboardInterrupt`.
* @see https://github.com/pyodide/pyodide/issues/2141
*/
const result = pyodide.runPython(code, { globals });
setUpConsole(globals);
post.writeln(result?.toString());
} catch (error) {
if (!(error instanceof Error)) throw error;
post.error(error.message);
handleRangeErrorAndRestartPyodide(error);
} finally {
post.prompt();
post.unlock();
}
},
replClear: async () => {
try {
clear_console(pyconsole);
await await_fut(pyconsole.push(''));
} finally {
post.error('\nKeyboardInterrupt');
post.prompt();
}
},
replInput: async ({ code, exports }: RunExportableData) => {
post.writeln(code);
const future = pyconsole.push(code) as PyProxy;
const status = future.syntax_check as SyntaxCheck;
switch (status) {
case 'syntax-error':
post.error(future.formatted_error.trimEnd());
post.prompt();
return;
case 'incomplete':
post.promptPending();
return;
case 'complete':
break;
default:
throw new Error(`Unexpected type: ${status}`);
}
prepareExports(exports);
const wrapped = await_fut(future) as PyProxyAwaitable;
try {
const [value] = await wrapped;
if (value !== undefined) {
const repr = repr_shorten.callKwargs(value, {
separator: '\n<long output truncated>\n',
}) as string;
post.writeln(repr);
}
if (pyodide.isPyProxy(value)) value.destroy();
} catch (error) {
if (!(error instanceof Error)) throw error;
const message = future.formatted_error || error.message;
post.error(message.trimEnd());
handleRangeErrorAndRestartPyodide(error);
} finally {
post.prompt();
future.destroy();
wrapped.destroy();
}
},
};
onmessage = async (event: MessageEvent<Message<typeof listeners>>) => {
listeners[event.data.type]?.(event.data.payload);
};
|
src/workers/interpreter.worker.ts
|
NUSSOC-glide-3ab6925
|
[
{
"filename": "src/hooks/useInterpreter.ts",
"retrieved_chunk": " resetInterruptBuffer();\n workerRef.current?.postMessage({\n type: 'replInput',\n payload: { code, exports: callbacks.exports?.() },\n });\n },\n restart: () => {\n callbacks.system('\\nOkies! Restarting interpreter...\\n');\n restartInterpreter();\n },",
"score": 0.8065182566642761
},
{
"filename": "src/hooks/useInterpreter.ts",
"retrieved_chunk": "import { useEffect, useRef } from 'react';\ninterface Interpreter {\n run: (code: string) => void;\n stop: () => void;\n execute: (command: string) => void;\n restart: () => void;\n}\ninterface Callbacks {\n write: (text: string) => void;\n writeln: (text: string) => void;",
"score": 0.788843035697937
},
{
"filename": "src/hooks/useInterpreter.ts",
"retrieved_chunk": " interruptBufferRef.current[0] = 2;\n workerRef.current?.postMessage({ type: 'replClear' });\n } else {\n callbacks.system(\n \"\\nDue to browser incompatibility, we can't stop your code execution gracefully. Instead, we'll restart the interpreter for you. Hold on yah...\\n\",\n );\n restartInterpreter();\n }\n },\n execute: (code) => {",
"score": 0.7879922986030579
},
{
"filename": "src/pages/IDEPage.tsx",
"retrieved_chunk": " const interpreter = useInterpreter({\n write: (text: string) => consoleRef.current?.write(text),\n writeln: (text: string) => consoleRef.current?.append(text),\n error: (text: string) => consoleRef.current?.error(text),\n system: (text: string) => consoleRef.current?.system(text),\n exports: useFile.Exports,\n lock: () => setRunning(true),\n unlock: () => setRunning(false),\n });\n return (",
"score": 0.7877865433692932
},
{
"filename": "src/components/Terminal.tsx",
"retrieved_chunk": " write: (result?: string) => void;\n error: (result?: string) => void;\n system: (result?: string) => void;\n}\ninterface TerminalProps {\n onStop?: () => void;\n onReturn?: (line: string) => void;\n onRestart?: () => void;\n showStopButton?: boolean;\n}",
"score": 0.7784908413887024
}
] |
typescript
|
runPython(consoleScript, { globals });
|
import EventEmitter from 'events'
import { ModelID } from '../types'
import { WindowAiProvider } from '../types/declarations'
export type Data = {
model?: ModelID
provider?: WindowAiProvider
}
type EventMap = {
change: Data
disconnect: undefined
error: Error
}
type EventKey<T extends EventMap> = string & keyof T
type EventReceiver<T> = (params: T) => void
interface IEmitter<T extends EventMap> {
on<K extends EventKey<T>>(eventName: K, fn: EventReceiver<T[K]>): void
off<K extends EventKey<T>>(eventName: K, fn: EventReceiver<T[K]>): void
emit<K extends EventKey<T>>(
eventName: K,
...params: T[K] extends undefined ? [undefined?] : [T[K]]
): void
}
export abstract class Emitter implements IEmitter<EventMap> {
private emitter = new EventEmitter()
on<K extends EventKey<EventMap>>(
eventName: K,
fn: EventReceiver<EventMap[K]>,
): void {
this.emitter.on(eventName, fn)
}
off<K extends EventKey<EventMap>>(
eventName: K,
fn: EventReceiver<EventMap[K]>,
): void {
this.emitter.off(eventName, fn)
}
emit<K extends EventKey<EventMap>>(
eventName: K,
...params: EventMap[K] extends undefined ? [undefined?] : [EventMap[K]]
): void {
this.emitter.emit(eventName, ...params)
}
}
export abstract class Connector extends Emitter {
abstract name: string
abstract activate(): Promise<Data>
abstract deactivate(): void
abstract getModel(): Promise<ModelID>
|
abstract getProvider(): Promise<WindowAiProvider>
}
|
src/connectors/types.ts
|
haardikk21-wanda-788b8e1
|
[
{
"filename": "src/connectors/injected.ts",
"retrieved_chunk": "import { ErrorCode, EventType, ModelID } from '../types'\nimport { WindowAiProvider } from '../types/declarations'\nimport { Connector, Data } from './types'\nexport class InjectedConnector extends Connector {\n name = 'injected'\n constructor() {\n super()\n this.handleEvent = this.handleEvent.bind(this)\n }\n async activate(): Promise<Data> {",
"score": 0.9096123576164246
},
{
"filename": "src/connectors/injected.ts",
"retrieved_chunk": " throw Error('model not found')\n }\n }\n async getProvider(): Promise<WindowAiProvider> {\n if (!window.ai) throw Error(`window.ai not found`)\n return window.ai\n }\n private handleEvent(event: EventType, data: unknown) {\n if (event === EventType.ModelChanged) {\n this.emit('change', { model: (<{ model: ModelID }>data).model })",
"score": 0.846357524394989
},
{
"filename": "src/connectors/injected.ts",
"retrieved_chunk": " if (!window.ai) throw Error(`window.ai not found`)\n if (window.ai.addEventListener) {\n window.ai.addEventListener(this.handleEvent)\n }\n try {\n const model = await window.ai.getCurrentModel()\n return { model, provider: window.ai }\n } catch (error) {\n throw Error(`activate failed`)\n }",
"score": 0.8425295948982239
},
{
"filename": "src/types/declarations.d.ts",
"retrieved_chunk": "interface WindowAiProvider {\n getCurrentModel: () => Promise<ModelID>\n getCompletion<T extends Input>(\n input: T,\n options?: CompletionOptions<T>,\n ): Promise<T extends PromptInput ? TextOutput : MessageOutput>\n addEventListener?<T>(\n handler: (event: EventType, data: T | ErrorCode) => void,\n ): string\n}",
"score": 0.8419215679168701
},
{
"filename": "src/connectors/index.ts",
"retrieved_chunk": "export { InjectedConnector } from './injected'\nexport type { Connector, Data } from './types'",
"score": 0.8376557230949402
}
] |
typescript
|
abstract getProvider(): Promise<WindowAiProvider>
}
|
|
import { ErrorCode, EventType, ModelID } from '../types'
import { WindowAiProvider } from '../types/declarations'
import { Connector, Data } from './types'
export class InjectedConnector extends Connector {
name = 'injected'
constructor() {
super()
this.handleEvent = this.handleEvent.bind(this)
}
async activate(): Promise<Data> {
if (!window.ai) throw Error(`window.ai not found`)
if (window.ai.addEventListener) {
window.ai.addEventListener(this.handleEvent)
}
try {
const model = await window.ai.getCurrentModel()
return { model, provider: window.ai }
} catch (error) {
throw Error(`activate failed`)
}
}
deactivate(): void {
// no-op
// Disconnect event listeners here once window.ai upstream has removeEventListener
}
async getModel(): Promise<ModelID> {
if (!window.ai) throw Error(`window.ai not found`)
try {
return await window.ai.getCurrentModel()
} catch {
throw Error('model not found')
}
}
async getProvider(): Promise<WindowAiProvider> {
if (!window.ai) throw Error(`window.ai not found`)
return window.ai
}
private handleEvent(event: EventType, data: unknown) {
if (event === EventType.ModelChanged) {
this.emit('change', { model: (<{ model: ModelID }>data).model })
} else if (event === EventType.Error) {
this.
|
emit('error', Error(data as ErrorCode))
}
|
}
}
|
src/connectors/injected.ts
|
haardikk21-wanda-788b8e1
|
[
{
"filename": "src/connectors/types.ts",
"retrieved_chunk": "import EventEmitter from 'events'\nimport { ModelID } from '../types'\nimport { WindowAiProvider } from '../types/declarations'\nexport type Data = {\n model?: ModelID\n provider?: WindowAiProvider\n}\ntype EventMap = {\n change: Data\n disconnect: undefined",
"score": 0.8689108490943909
},
{
"filename": "src/types/declarations.d.ts",
"retrieved_chunk": "interface WindowAiProvider {\n getCurrentModel: () => Promise<ModelID>\n getCompletion<T extends Input>(\n input: T,\n options?: CompletionOptions<T>,\n ): Promise<T extends PromptInput ? TextOutput : MessageOutput>\n addEventListener?<T>(\n handler: (event: EventType, data: T | ErrorCode) => void,\n ): string\n}",
"score": 0.8547064065933228
},
{
"filename": "src/types/declarations.d.ts",
"retrieved_chunk": "declare global {\n interface Window {\n ai?: WindowAiProvider\n }\n}",
"score": 0.8268637657165527
},
{
"filename": "src/connectors/types.ts",
"retrieved_chunk": " this.emitter.emit(eventName, ...params)\n }\n}\nexport abstract class Connector extends Emitter {\n abstract name: string\n abstract activate(): Promise<Data>\n abstract deactivate(): void\n abstract getModel(): Promise<ModelID>\n abstract getProvider(): Promise<WindowAiProvider>\n}",
"score": 0.8237366080284119
},
{
"filename": "src/connectors/types.ts",
"retrieved_chunk": " error: Error\n}\ntype EventKey<T extends EventMap> = string & keyof T\ntype EventReceiver<T> = (params: T) => void\ninterface IEmitter<T extends EventMap> {\n on<K extends EventKey<T>>(eventName: K, fn: EventReceiver<T[K]>): void\n off<K extends EventKey<T>>(eventName: K, fn: EventReceiver<T[K]>): void\n emit<K extends EventKey<T>>(\n eventName: K,\n ...params: T[K] extends undefined ? [undefined?] : [T[K]]",
"score": 0.7783693075180054
}
] |
typescript
|
emit('error', Error(data as ErrorCode))
}
|
import EventEmitter from 'events'
import { ModelID } from '../types'
import { WindowAiProvider } from '../types/declarations'
export type Data = {
model?: ModelID
provider?: WindowAiProvider
}
type EventMap = {
change: Data
disconnect: undefined
error: Error
}
type EventKey<T extends EventMap> = string & keyof T
type EventReceiver<T> = (params: T) => void
interface IEmitter<T extends EventMap> {
on<K extends EventKey<T>>(eventName: K, fn: EventReceiver<T[K]>): void
off<K extends EventKey<T>>(eventName: K, fn: EventReceiver<T[K]>): void
emit<K extends EventKey<T>>(
eventName: K,
...params: T[K] extends undefined ? [undefined?] : [T[K]]
): void
}
export abstract class Emitter implements IEmitter<EventMap> {
private emitter = new EventEmitter()
on<K extends EventKey<EventMap>>(
eventName: K,
fn: EventReceiver<EventMap[K]>,
): void {
this.emitter.on(eventName, fn)
}
off<K extends EventKey<EventMap>>(
eventName: K,
fn: EventReceiver<EventMap[K]>,
): void {
this.emitter.off(eventName, fn)
}
emit<K extends EventKey<EventMap>>(
eventName: K,
...params: EventMap[K] extends undefined ? [undefined?] : [EventMap[K]]
): void {
this.emitter.emit(eventName, ...params)
}
}
export abstract class Connector extends Emitter {
abstract name: string
abstract activate(): Promise<Data>
abstract deactivate(): void
|
abstract getModel(): Promise<ModelID>
abstract getProvider(): Promise<WindowAiProvider>
}
|
src/connectors/types.ts
|
haardikk21-wanda-788b8e1
|
[
{
"filename": "src/connectors/injected.ts",
"retrieved_chunk": "import { ErrorCode, EventType, ModelID } from '../types'\nimport { WindowAiProvider } from '../types/declarations'\nimport { Connector, Data } from './types'\nexport class InjectedConnector extends Connector {\n name = 'injected'\n constructor() {\n super()\n this.handleEvent = this.handleEvent.bind(this)\n }\n async activate(): Promise<Data> {",
"score": 0.9096123576164246
},
{
"filename": "src/connectors/injected.ts",
"retrieved_chunk": " throw Error('model not found')\n }\n }\n async getProvider(): Promise<WindowAiProvider> {\n if (!window.ai) throw Error(`window.ai not found`)\n return window.ai\n }\n private handleEvent(event: EventType, data: unknown) {\n if (event === EventType.ModelChanged) {\n this.emit('change', { model: (<{ model: ModelID }>data).model })",
"score": 0.846357524394989
},
{
"filename": "src/connectors/injected.ts",
"retrieved_chunk": " if (!window.ai) throw Error(`window.ai not found`)\n if (window.ai.addEventListener) {\n window.ai.addEventListener(this.handleEvent)\n }\n try {\n const model = await window.ai.getCurrentModel()\n return { model, provider: window.ai }\n } catch (error) {\n throw Error(`activate failed`)\n }",
"score": 0.8425295948982239
},
{
"filename": "src/types/declarations.d.ts",
"retrieved_chunk": "interface WindowAiProvider {\n getCurrentModel: () => Promise<ModelID>\n getCompletion<T extends Input>(\n input: T,\n options?: CompletionOptions<T>,\n ): Promise<T extends PromptInput ? TextOutput : MessageOutput>\n addEventListener?<T>(\n handler: (event: EventType, data: T | ErrorCode) => void,\n ): string\n}",
"score": 0.8419215679168701
},
{
"filename": "src/connectors/index.ts",
"retrieved_chunk": "export { InjectedConnector } from './injected'\nexport type { Connector, Data } from './types'",
"score": 0.8376557230949402
}
] |
typescript
|
abstract getModel(): Promise<ModelID>
abstract getProvider(): Promise<WindowAiProvider>
}
|
|
import { ErrorCode, EventType, ModelID } from '../types'
import { WindowAiProvider } from '../types/declarations'
import { Connector, Data } from './types'
export class InjectedConnector extends Connector {
name = 'injected'
constructor() {
super()
this.handleEvent = this.handleEvent.bind(this)
}
async activate(): Promise<Data> {
if (!window.ai) throw Error(`window.ai not found`)
if (window.ai.addEventListener) {
window.ai.addEventListener(this.handleEvent)
}
try {
const model = await window.ai.getCurrentModel()
return { model, provider: window.ai }
} catch (error) {
throw Error(`activate failed`)
}
}
deactivate(): void {
// no-op
// Disconnect event listeners here once window.ai upstream has removeEventListener
}
async getModel(): Promise<ModelID> {
if (!window.ai) throw Error(`window.ai not found`)
try {
return await window.ai.getCurrentModel()
} catch {
throw Error('model not found')
}
}
|
async getProvider(): Promise<WindowAiProvider> {
|
if (!window.ai) throw Error(`window.ai not found`)
return window.ai
}
private handleEvent(event: EventType, data: unknown) {
if (event === EventType.ModelChanged) {
this.emit('change', { model: (<{ model: ModelID }>data).model })
} else if (event === EventType.Error) {
this.emit('error', Error(data as ErrorCode))
}
}
}
|
src/connectors/injected.ts
|
haardikk21-wanda-788b8e1
|
[
{
"filename": "src/types/declarations.d.ts",
"retrieved_chunk": "interface WindowAiProvider {\n getCurrentModel: () => Promise<ModelID>\n getCompletion<T extends Input>(\n input: T,\n options?: CompletionOptions<T>,\n ): Promise<T extends PromptInput ? TextOutput : MessageOutput>\n addEventListener?<T>(\n handler: (event: EventType, data: T | ErrorCode) => void,\n ): string\n}",
"score": 0.8801347613334656
},
{
"filename": "src/types/declarations.d.ts",
"retrieved_chunk": "declare global {\n interface Window {\n ai?: WindowAiProvider\n }\n}",
"score": 0.8536602854728699
},
{
"filename": "src/connectors/types.ts",
"retrieved_chunk": "import EventEmitter from 'events'\nimport { ModelID } from '../types'\nimport { WindowAiProvider } from '../types/declarations'\nexport type Data = {\n model?: ModelID\n provider?: WindowAiProvider\n}\ntype EventMap = {\n change: Data\n disconnect: undefined",
"score": 0.8332129716873169
},
{
"filename": "src/connectors/types.ts",
"retrieved_chunk": " this.emitter.emit(eventName, ...params)\n }\n}\nexport abstract class Connector extends Emitter {\n abstract name: string\n abstract activate(): Promise<Data>\n abstract deactivate(): void\n abstract getModel(): Promise<ModelID>\n abstract getProvider(): Promise<WindowAiProvider>\n}",
"score": 0.8326213359832764
},
{
"filename": "src/hooks/useModel.ts",
"retrieved_chunk": "import { useContext } from './useContext'\nexport const useModel = () => {\n const [state] = useContext()\n return state.data?.model\n}",
"score": 0.7945089936256409
}
] |
typescript
|
async getProvider(): Promise<WindowAiProvider> {
|
import { ErrorCode, EventType, ModelID } from '../types'
import { WindowAiProvider } from '../types/declarations'
import { Connector, Data } from './types'
export class InjectedConnector extends Connector {
name = 'injected'
constructor() {
super()
this.handleEvent = this.handleEvent.bind(this)
}
async activate(): Promise<Data> {
if (!window.ai) throw Error(`window.ai not found`)
if (window.ai.addEventListener) {
window.ai.addEventListener(this.handleEvent)
}
try {
const model = await window.ai.getCurrentModel()
return { model, provider: window.ai }
} catch (error) {
throw Error(`activate failed`)
}
}
deactivate(): void {
// no-op
// Disconnect event listeners here once window.ai upstream has removeEventListener
}
async getModel(): Promise<ModelID> {
if (!window.ai) throw Error(`window.ai not found`)
try {
return await window.ai.getCurrentModel()
} catch {
throw Error('model not found')
}
}
async getProvider(): Promise<WindowAiProvider> {
if (!window.ai) throw Error(`window.ai not found`)
return window.ai
}
private handleEvent(event
|
: EventType, data: unknown) {
|
if (event === EventType.ModelChanged) {
this.emit('change', { model: (<{ model: ModelID }>data).model })
} else if (event === EventType.Error) {
this.emit('error', Error(data as ErrorCode))
}
}
}
|
src/connectors/injected.ts
|
haardikk21-wanda-788b8e1
|
[
{
"filename": "src/types/declarations.d.ts",
"retrieved_chunk": "interface WindowAiProvider {\n getCurrentModel: () => Promise<ModelID>\n getCompletion<T extends Input>(\n input: T,\n options?: CompletionOptions<T>,\n ): Promise<T extends PromptInput ? TextOutput : MessageOutput>\n addEventListener?<T>(\n handler: (event: EventType, data: T | ErrorCode) => void,\n ): string\n}",
"score": 0.8511329889297485
},
{
"filename": "src/connectors/types.ts",
"retrieved_chunk": "import EventEmitter from 'events'\nimport { ModelID } from '../types'\nimport { WindowAiProvider } from '../types/declarations'\nexport type Data = {\n model?: ModelID\n provider?: WindowAiProvider\n}\ntype EventMap = {\n change: Data\n disconnect: undefined",
"score": 0.8480032086372375
},
{
"filename": "src/types/declarations.d.ts",
"retrieved_chunk": "declare global {\n interface Window {\n ai?: WindowAiProvider\n }\n}",
"score": 0.8301464319229126
},
{
"filename": "src/connectors/types.ts",
"retrieved_chunk": " this.emitter.emit(eventName, ...params)\n }\n}\nexport abstract class Connector extends Emitter {\n abstract name: string\n abstract activate(): Promise<Data>\n abstract deactivate(): void\n abstract getModel(): Promise<ModelID>\n abstract getProvider(): Promise<WindowAiProvider>\n}",
"score": 0.8289074301719666
},
{
"filename": "src/hooks/useCompletion.ts",
"retrieved_chunk": " throw Error('No provider found')\n }\n return provider.getCompletion(input, options)\n }\n return { getCompletion }\n}",
"score": 0.7737842202186584
}
] |
typescript
|
: EventType, data: unknown) {
|
import { ErrorCode, EventType, ModelID } from '../types'
import { WindowAiProvider } from '../types/declarations'
import { Connector, Data } from './types'
export class InjectedConnector extends Connector {
name = 'injected'
constructor() {
super()
this.handleEvent = this.handleEvent.bind(this)
}
async activate(): Promise<Data> {
if (!window.ai) throw Error(`window.ai not found`)
if (window.ai.addEventListener) {
window.ai.addEventListener(this.handleEvent)
}
try {
const model = await window.ai.getCurrentModel()
return { model, provider: window.ai }
} catch (error) {
throw Error(`activate failed`)
}
}
deactivate(): void {
// no-op
// Disconnect event listeners here once window.ai upstream has removeEventListener
}
async getModel(): Promise<ModelID> {
if (!window.ai) throw Error(`window.ai not found`)
try {
return await window.ai.getCurrentModel()
} catch {
throw Error('model not found')
}
}
async getProvider(): Promise<WindowAiProvider> {
if (!window.ai) throw Error(`window.ai not found`)
return window.ai
}
private handleEvent(event: EventType, data: unknown) {
if
|
(event === EventType.ModelChanged) {
|
this.emit('change', { model: (<{ model: ModelID }>data).model })
} else if (event === EventType.Error) {
this.emit('error', Error(data as ErrorCode))
}
}
}
|
src/connectors/injected.ts
|
haardikk21-wanda-788b8e1
|
[
{
"filename": "src/connectors/types.ts",
"retrieved_chunk": "import EventEmitter from 'events'\nimport { ModelID } from '../types'\nimport { WindowAiProvider } from '../types/declarations'\nexport type Data = {\n model?: ModelID\n provider?: WindowAiProvider\n}\ntype EventMap = {\n change: Data\n disconnect: undefined",
"score": 0.8572690486907959
},
{
"filename": "src/types/declarations.d.ts",
"retrieved_chunk": "interface WindowAiProvider {\n getCurrentModel: () => Promise<ModelID>\n getCompletion<T extends Input>(\n input: T,\n options?: CompletionOptions<T>,\n ): Promise<T extends PromptInput ? TextOutput : MessageOutput>\n addEventListener?<T>(\n handler: (event: EventType, data: T | ErrorCode) => void,\n ): string\n}",
"score": 0.8570717573165894
},
{
"filename": "src/connectors/types.ts",
"retrieved_chunk": " this.emitter.emit(eventName, ...params)\n }\n}\nexport abstract class Connector extends Emitter {\n abstract name: string\n abstract activate(): Promise<Data>\n abstract deactivate(): void\n abstract getModel(): Promise<ModelID>\n abstract getProvider(): Promise<WindowAiProvider>\n}",
"score": 0.829900860786438
},
{
"filename": "src/types/declarations.d.ts",
"retrieved_chunk": "declare global {\n interface Window {\n ai?: WindowAiProvider\n }\n}",
"score": 0.8282648324966431
},
{
"filename": "src/hooks/useModel.ts",
"retrieved_chunk": "import { useContext } from './useContext'\nexport const useModel = () => {\n const [state] = useContext()\n return state.data?.model\n}",
"score": 0.7789846658706665
}
] |
typescript
|
(event === EventType.ModelChanged) {
|
import React from 'react'
import { Connector, Data, InjectedConnector } from './connectors'
type State = {
connector?: Connector
data?: Data
error?: Error
}
type ContextValue = [
{
connectors: Connector[]
connector?: State['connector']
data?: State['data']
},
React.Dispatch<React.SetStateAction<State>>,
]
export const Context = React.createContext<ContextValue | null>(null)
type Props = {
connectors: Connector[]
}
export const Provider: React.FC<React.PropsWithChildren<Props>> = ({
children,
connectors = [new InjectedConnector()],
}) => {
const [state, setState] = React.useState<State>({})
React.useEffect(() => {
if (!state.connector) return
const handleChange = (data: Data) => {
setState((state) => ({ ...state, data }))
}
state.connector.on('change', handleChange)
return () => {
if (!state.connector) return
|
state.connector.off('change', handleChange)
}
|
}, [state.connector])
// Close connectors when unmounting
React.useEffect(() => {
return () => {
if (!state.connector) return
state.connector.deactivate()
}
}, [state.connector])
const value = [
{
connectors,
connector: state.connector,
data: state.data,
},
setState,
] as ContextValue
return React.createElement(Context.Provider, { value }, children)
}
|
src/context.ts
|
haardikk21-wanda-788b8e1
|
[
{
"filename": "src/hooks/useConnect.ts",
"retrieved_chunk": " const connect = useCallback(\n async (connector: Connector) => {\n try {\n if (connector === globalState.connector) return\n setGlobalState((state) => ({ ...state, connector }))\n setState((state) => ({ ...state, connecting: true, error: undefined }))\n const data = await connector.activate()\n setGlobalState((state) => ({ ...state, data }))\n } catch (error) {\n console.error(error)",
"score": 0.8816795349121094
},
{
"filename": "src/hooks/useConnect.ts",
"retrieved_chunk": "import { useCallback, useState } from 'react'\nimport { useContext } from './useContext'\nimport { Connector } from '../connectors'\ntype UseConnectState = {\n connecting: boolean\n error?: Error\n}\nexport const useConnect = () => {\n const [globalState, setGlobalState] = useContext()\n const [state, setState] = useState<UseConnectState>({ connecting: false })",
"score": 0.8570824265480042
},
{
"filename": "src/hooks/useConnect.ts",
"retrieved_chunk": " setState((state) => ({ ...state, error: error as Error }))\n } finally {\n setState((state) => ({ ...state, connecting: false }))\n }\n },\n [globalState.connector, setGlobalState],\n )\n return [\n {\n connecting: state.connecting,",
"score": 0.8245387077331543
},
{
"filename": "src/hooks/useModel.ts",
"retrieved_chunk": "import { useContext } from './useContext'\nexport const useModel = () => {\n const [state] = useContext()\n return state.data?.model\n}",
"score": 0.8200666904449463
},
{
"filename": "src/hooks/useConnect.ts",
"retrieved_chunk": " connector: globalState.connector,\n connectors: globalState.connectors,\n error: state.error,\n },\n connect,\n ] as const\n}",
"score": 0.8142021894454956
}
] |
typescript
|
state.connector.off('change', handleChange)
}
|
import { persistor } from '../store';
import { filesActions } from '../store/filesSlice';
import { useAppDispatch } from '../store/hooks';
import { vaultActions } from '../store/vaultSlice';
interface UseFilesMutationsHook {
/**
* For performance reasons, the caller should ensure that the new
* name is not already in use in *both* the files and vault stores.
*/
rename: (from: string, to: string) => void;
save: (name: string, content: string) => void;
destroy: (name: string) => void;
draft: (autoSelect?: boolean) => void;
select: (name: string) => void;
update: (content: string) => void;
create: (name: string, content: string) => void;
}
const useFilesMutations = (): UseFilesMutationsHook => {
const dispatch = useAppDispatch();
return {
save: (name: string, content: string) => {
dispatch(filesActions.updateSelected(content));
dispatch(vaultActions.save({ name, content }));
persistor.flush();
},
rename: (from: string, to: string) => {
if (from === to) return;
dispatch(filesActions.rename({ from, to }));
dispatch(vaultActions.rename({ from, to }));
persistor.flush();
},
destroy: (name: string) => {
dispatch(filesActions.destroy(name));
dispatch(vaultActions.destroy(name));
persistor.flush();
},
draft: (autoSelect?: boolean) => {
dispatch(filesActions.draft(autoSelect));
},
select: (name: string) => {
dispatch(filesActions.select(name));
},
update: (content: string) => {
dispatch(filesActions.updateSelected(content));
},
create: (name: string, content: string) => {
|
dispatch(filesActions.create({ name, content }));
|
dispatch(vaultActions.save({ name, content }));
persistor.flush();
},
};
};
export default useFilesMutations;
|
src/hooks/useFilesMutations.ts
|
NUSSOC-glide-3ab6925
|
[
{
"filename": "src/store/filesSlice.ts",
"retrieved_chunk": " if (state.selected === name) state.selected = undefined;\n },\n select: (state, action: PayloadAction<string>) => {\n const name = action.payload;\n if (state.files[name] === undefined) return;\n state.selected = name;\n },\n rename: (state, action: PayloadAction<{ from: string; to: string }>) => {\n const { from: oldName, to: newName } = action.payload;\n const isOldNameExist = state.files[oldName] !== undefined;",
"score": 0.8855258226394653
},
{
"filename": "src/store/filesSlice.ts",
"retrieved_chunk": " state.selected = newName;\n },\n updateSelected: (state, action: PayloadAction<string>) => {\n if (state.selected === undefined) return;\n state.files[state.selected] = action.payload;\n },\n destroy: (state, action: PayloadAction<string>) => {\n const name = action.payload;\n delete state.files[name];\n state.list = state.list.filter((file) => file !== name);",
"score": 0.8784671425819397
},
{
"filename": "src/store/filesSlice.ts",
"retrieved_chunk": "});\nconst selectFiles = (state: RootState) => state.files;\nexport const getSelectedFileName = createSelector(\n selectFiles,\n (files) => files.selected,\n);\nexport const getSelectedFile = createSelector(selectFiles, (files) =>\n files.selected\n ? { name: files.selected, content: files.files[files.selected] }\n : { name: undefined, content: undefined },",
"score": 0.868932843208313
},
{
"filename": "src/store/vaultSlice.ts",
"retrieved_chunk": " const { name, content } = action.payload;\n if (state.files[name] === undefined) state.list.push(name);\n state.files[name] = content;\n },\n destroy: (state, action: PayloadAction<string>) => {\n const name = action.payload;\n delete state.files[name];\n state.list = state.list.filter((file) => file !== name);\n },\n rename: (state, action: PayloadAction<{ from: string; to: string }>) => {",
"score": 0.8682628870010376
},
{
"filename": "src/store/filesSlice.ts",
"retrieved_chunk": " state.list,\n (counter) => `untitled-${counter + 1}.py`,\n );\n state.files[name] = '';\n state.list.push(name);\n const select = action.payload;\n if (select) state.selected = name;\n },\n create: (\n state,",
"score": 0.8674468398094177
}
] |
typescript
|
dispatch(filesActions.create({ name, content }));
|
import { firestore } from 'firebase-admin'
import { createFirestoreDataConverter } from './createFirestoreDataConverter'
import { serverTimestamp } from './serverTimestamp'
/**
* Updates the specified document in the provided Firestore collection with the given data.
*
* @param db - The instance of the Firestore database to use.
* @param collectionPath - The path of the collection containing the document to be updated.
* @param docId - The ID of the document to be updated.
* @param params - The data to update the document with.
*
* @returns A boolean indicating the success of the update operation.
*
* @throws Throws an exception with an error message if an error occurs.
*
* @example
* ```typescript
* import { firestore } from 'firebase-admin'
* import { update } from '@skeet-framework/firestore'
*
* const db = firestore();
* const updatedData: firestore.UpdateData<User> = {
* age: 31
* };
*
* async function run() {
* try {
* const path = 'Users'
* const docId = '123456'; // Assuming this ID exists in the Users collection.
* const success = await update<User>(db, path, docId, updatedData);
* if (success) {
* console.log(`Document with ID ${docId} updated successfully.`);
* }
* } catch (error) {
* console.error(`Error updating document: ${error}`);
* }
* }
*
* run();
* ```
*/
export const updateCollectionItem = async <T extends firestore.DocumentData>(
db: firestore.Firestore,
collectionPath: string,
docId: string,
params: firestore.UpdateData<T>
): Promise<boolean> => {
try {
const docRef = db
.collection(collectionPath)
.doc(docId)
.withConverter(createFirestoreDataConverter<T>())
|
await docRef.update({ ...params, updatedAt: serverTimestamp() })
return true
} catch (error) {
|
throw new Error(`Error updating document with ID ${docId}: ${error}`)
}
}
|
src/lib/updateCollectionItem.ts
|
elsoul-skeet-firestore-8c637de
|
[
{
"filename": "src/lib/addCollectionItem.ts",
"retrieved_chunk": ") => {\n try {\n const collectionRef = createCollectionRef<T>(db, collectionPath)\n if (id) {\n const docRef = collectionRef.doc(id)\n await docRef.set({\n ...params,\n createdAt: serverTimestamp(),\n updatedAt: serverTimestamp(),\n })",
"score": 0.907720685005188
},
{
"filename": "src/lib/updateCollectionItem.d.ts",
"retrieved_chunk": " * }\n * } catch (error) {\n * console.error(`Error updating document: ${error}`);\n * }\n * }\n *\n * run();\n * ```\n */\nexport declare const updateCollectionItem: <T extends firestore.DocumentData>(db: firestore.Firestore, collectionPath: string, docId: string, params: firestore.UpdateData<T>) => Promise<boolean>;",
"score": 0.8944542407989502
},
{
"filename": "src/lib/addCollectionItem.ts",
"retrieved_chunk": " return docRef\n } else {\n const data = await collectionRef.add({\n ...params,\n createdAt: serverTimestamp(),\n updatedAt: serverTimestamp(),\n })\n if (!data) {\n throw new Error('no data')\n }",
"score": 0.8670057058334351
},
{
"filename": "src/lib/deleteCollectionItem.ts",
"retrieved_chunk": "): Promise<boolean> => {\n try {\n const docRef = db.collection(collectionPath).doc(docId)\n await docRef.delete()\n return true\n } catch (error) {\n throw new Error(`Error deleting document with ID ${docId}: ${error}`)\n }\n}",
"score": 0.8591983318328857
},
{
"filename": "src/lib/updateCollectionItem.d.ts",
"retrieved_chunk": "import { firestore } from 'firebase-admin';\n/**\n * Updates the specified document in the provided Firestore collection with the given data.\n *\n * @param db - The instance of the Firestore database to use.\n * @param collectionPath - The path of the collection containing the document to be updated.\n * @param docId - The ID of the document to be updated.\n * @param params - The data to update the document with.\n *\n * @returns A boolean indicating the success of the update operation.",
"score": 0.8388663530349731
}
] |
typescript
|
await docRef.update({ ...params, updatedAt: serverTimestamp() })
return true
} catch (error) {
|
import { createCollectionRef } from './createCollectionRef'
import { firestore } from 'firebase-admin'
import { serverTimestamp } from './serverTimestamp'
/**
* Adds multiple documents to the specified collection in Firestore.
* This function supports batched writes, and if the number of items exceeds the maximum batch size (500),
* it will split the items into multiple batches and write them sequentially.
*
* @param db - The instance of the Firestore database to use.
* @param collectionPath - The path of the collection to which the documents will be added.
* @param items - An array of document data to be added.
*
* @returns An array of WriteResult arrays corresponding to each batch.
*
* @throws Throws an exception with an error message if an error occurs.
*
* @example
* ```typescript
* import { firestore } from 'firebase-admin'
* import { adds } from '@skeet-framework/firestore'
*
* const db = firestore();
* const users: User[] = [
* { name: "John Doe", age: 30 },
* { name: "Jane Smith", age: 25 },
* // ... more users ...
* ];
*
* async function run() {
* try {
* const path = 'Users'
* const results = await adds<User>(db, path, users);
* console.log(`Added ${users.length} users in ${results.length} batches.`);
* } catch (error) {
* console.error(`Error adding documents: ${error}`);
* }
* }
*
* run();
* ```
*/
export const addMultipleCollectionItems = async <
T extends firestore.DocumentData
>(
db: firestore.Firestore,
collectionPath: string,
items: T[]
): Promise<firestore.WriteResult[][]> => {
const MAX_BATCH_SIZE = 500
const chunkedItems =
items.length > 500 ? chunkArray(items, MAX_BATCH_SIZE) : [items]
const batchResults: firestore.WriteResult[][] = []
for (const chunk of chunkedItems) {
try {
const batch = db.batch()
const collectionRef
|
= createCollectionRef<T>(db, collectionPath)
chunk.forEach((item) => {
|
const docRef = collectionRef.doc()
batch.set(docRef, {
...item,
createdAt: serverTimestamp(),
updatedAt: serverTimestamp(),
})
})
const writeResults = await batch.commit()
batchResults.push(writeResults)
} catch (error) {
throw new Error(`Error adding a batch of documents: ${error}`)
}
}
return batchResults
}
/**
* Helper function to divide an array into chunks of a specified size.
*
* @param array - The array to be divided.
* @param size - The size of each chunk.
*
* @returns An array of chunked arrays.
*/
function chunkArray<T>(array: T[], size: number): T[][] {
const chunked = []
let index = 0
while (index < array.length) {
chunked.push(array.slice(index, size + index))
index += size
}
return chunked
}
|
src/lib/addMultipleCollectionItems.ts
|
elsoul-skeet-firestore-8c637de
|
[
{
"filename": "src/lib/addMultipleCollectionItems.d.ts",
"retrieved_chunk": " * console.log(`Added ${users.length} users in ${results.length} batches.`);\n * } catch (error) {\n * console.error(`Error adding documents: ${error}`);\n * }\n * }\n *\n * run();\n * ```\n */\nexport declare const addMultipleCollectionItems: <T extends firestore.DocumentData>(db: firestore.Firestore, collectionPath: string, items: T[]) => Promise<firestore.WriteResult[][]>;",
"score": 0.865720808506012
},
{
"filename": "src/lib/addMultipleCollectionItems.d.ts",
"retrieved_chunk": "import { firestore } from 'firebase-admin';\n/**\n * Adds multiple documents to the specified collection in Firestore.\n * This function supports batched writes, and if the number of items exceeds the maximum batch size (500),\n * it will split the items into multiple batches and write them sequentially.\n *\n * @param db - The instance of the Firestore database to use.\n * @param collectionPath - The path of the collection to which the documents will be added.\n * @param items - An array of document data to be added.\n *",
"score": 0.845239520072937
},
{
"filename": "src/lib/updateCollectionItem.ts",
"retrieved_chunk": " */\nexport const updateCollectionItem = async <T extends firestore.DocumentData>(\n db: firestore.Firestore,\n collectionPath: string,\n docId: string,\n params: firestore.UpdateData<T>\n): Promise<boolean> => {\n try {\n const docRef = db\n .collection(collectionPath)",
"score": 0.8296405076980591
},
{
"filename": "src/lib/queryCollectionItems.ts",
"retrieved_chunk": " */\nexport const queryCollectionItems = async <T extends firestore.DocumentData>(\n db: firestore.Firestore,\n collectionPath: string,\n conditions: QueryCondition[]\n): Promise<T[]> => {\n try {\n let query: firestore.Query = db\n .collection(collectionPath)\n .withConverter(createFirestoreDataConverter<T>())",
"score": 0.8259257078170776
},
{
"filename": "src/lib/addCollectionItem.ts",
"retrieved_chunk": ") => {\n try {\n const collectionRef = createCollectionRef<T>(db, collectionPath)\n if (id) {\n const docRef = collectionRef.doc(id)\n await docRef.set({\n ...params,\n createdAt: serverTimestamp(),\n updatedAt: serverTimestamp(),\n })",
"score": 0.8222647309303284
}
] |
typescript
|
= createCollectionRef<T>(db, collectionPath)
chunk.forEach((item) => {
|
import z from 'zod'
import { RouteOptions, ZodRouteHandler } from '../types'
import { error } from '../response'
/**
* Creates a route handler that validates the request data and parameters using the Zod schema.
* If validation fails, it returns a 400 json error with a detailed message.
*
* @param {z.Schema} schema - A Zod schema used to validate the incoming request data and parameters.
* @param {ZodRouteHandler<Env, Schema>} callback - The main callback that will be executed after validation is successful.
*
* @return {ZodRouteHandler}
*
* @example
* const schema = z.object({
* name: z.string(),
* })
*
* type schemaType = z.infer<typeof schema>
*
* withZod<Env, schemaType>(schema, async (options) => {
* console.log(options.data) //=> { name: 'test' }
* return new Response('ok')
* })
*
*/
export function withZod<Env, Schema>(
schema: z.Schema,
callback: ZodRouteHandler<Env, Schema>
) {
return async (options: RouteOptions<Env>) => {
const { request } = options
const queryParams = request.query
const bodyParams = (await request.body()) ?? {}
const existingParams = options.params ?? {}
const params = {
...queryParams,
...bodyParams,
...existingParams,
}
const result = schema.safeParse(params)
if (!result.success) {
const firstError = result.error?.errors?.[0]
if (firstError) {
|
return error(`${firstError.path} ${firstError.message}`.toLowerCase(), {
|
type: firstError.code,
status: 400,
})
} else {
return error('invalid_request')
}
}
return callback({
...options,
data: result.data,
})
}
}
|
src/middleware/zod-validation.ts
|
team-openpm-cloudflare-basics-5bf8ecd
|
[
{
"filename": "src/middleware/zod-validation.test.ts",
"retrieved_chunk": " body: 'name=test',\n })\n )\n expect(response.status).toBe(200)\n })\n it('should should a validation error', async () => {\n const route = withZod<Env, schemaType>(schema, async (options) => {\n expect(options.data).toEqual({ bar: 'test' })\n return new Response('ok')\n })",
"score": 0.7919383645057678
},
{
"filename": "src/middleware/zod-validation.test.ts",
"retrieved_chunk": " it('should pass through form parms', async () => {\n const route = withZod<Env, schemaType>(schema, async (options) => {\n expect(options.data).toEqual({ name: 'test' })\n return new Response('ok')\n })\n const response = await execRoute(\n route,\n buildRequest('https://example.com?name=test', {\n method: 'POST',\n headers: { 'content-type': 'application/x-www-form-urlencoded' },",
"score": 0.7914944887161255
},
{
"filename": "src/router.ts",
"retrieved_chunk": " (request) => {\n if (!method || request.method === method) {\n const match = urlPattern.exec({\n pathname: request.url.pathname,\n })\n if (match) {\n return { params: match.pathname.groups }\n }\n }\n },",
"score": 0.7842918634414673
},
{
"filename": "src/middleware/zod-validation.test.ts",
"retrieved_chunk": " method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify({ name: 'test' }),\n })\n )\n expect(response.status).toBe(200)\n })\n it('should pass through query', async () => {\n const route = withZod<Env, schemaType>(schema, async (options) => {\n expect(options.data).toEqual({ name: 'test' })",
"score": 0.7816457748413086
},
{
"filename": "src/middleware/zod-validation.test.ts",
"retrieved_chunk": " })\n type schemaType = z.infer<typeof schema>\n it('should pass through json', async () => {\n const route = withZod<Env, schemaType>(schema, async (options) => {\n expect(options.data).toEqual({ name: 'test' })\n return new Response('ok')\n })\n const response = await execRoute(\n route,\n buildRequest('https://example.com', {",
"score": 0.7810057401657104
}
] |
typescript
|
return error(`${firstError.path} ${firstError.message}`.toLowerCase(), {
|
import { firestore } from 'firebase-admin'
import { createFirestoreDataConverter } from './createFirestoreDataConverter'
/**
* Represents a condition for querying Firestore collections.
*/
type QueryCondition = {
field?: string
operator?: firestore.WhereFilterOp
value?: any
orderDirection?: firestore.OrderByDirection // "asc" or "desc"
limit?: number
}
/**
* Queries the specified collection in Firestore based on the provided conditions
* and returns an array of documents that match the conditions.
*
* @param db - The instance of the Firestore database to use.
* @param collectionPath - The path of the collection to be queried.
* @param conditions - An array of conditions to apply to the query.
*
* @returns An array of documents from the collection that match the conditions.
*
* @throws Throws an exception with an error message if an error occurs.
*
* @example
* ```typescript
* import { firestore } from 'firebase-admin'
* import { query } from '@skeet-framework/firestore'
* const db = firestore();
*
* // Simple query to get users over 25 years old
* const simpleConditions: QueryCondition[] = [
* { field: "age", operator: ">", value: 25 }
* ];
*
* // Advanced query to get users over 25 years old, ordered by their names
* const advancedConditions: QueryCondition[] = [
* { field: "age", operator: ">", value: 25 },
* { field: "name", orderDirection: "asc" }
* ];
*
* // Query to get users over 25 years old and limit the results to 5
* const limitedConditions: QueryCondition[] = [
* { field: "age", operator: ">", value: 25 },
* { limit: 5 }
* ];
*
* async function run() {
* try {
* const path = 'Users';
*
* // Using the simple conditions
* const usersByAge = await query<User>(db, path, simpleConditions);
* console.log(`Found ${usersByAge.length} users over 25 years old.`);
*
* // Using the advanced conditions
* const orderedUsers = await query<User>(db, path, advancedConditions);
* console.log(`Found ${orderedUsers.length} users over 25 years old, ordered by name.`);
*
* // Using the limited conditions
* const limitedUsers = await query<User>(db, path, limitedConditions);
* console.log(`Found ${limitedUsers.length} users over 25 years old, limited to 5.`);
*
* } catch (error) {
* console.error(`Error querying collection: ${error}`);
* }
* }
*
* run();
* ```
*/
export const queryCollectionItems = async <T extends firestore.DocumentData>(
db: firestore.Firestore,
collectionPath: string,
conditions: QueryCondition[]
): Promise<T[]> => {
try {
let query: firestore.Query = db
.collection(collectionPath)
.withConverter
|
(createFirestoreDataConverter<T>())
for (const condition of conditions) {
|
if (
condition.field &&
condition.operator &&
condition.value !== undefined
) {
query = query.where(
condition.field,
condition.operator,
condition.value
)
}
if (condition.field && condition.orderDirection) {
query = query.orderBy(condition.field, condition.orderDirection)
}
if (condition.limit !== undefined) {
query = query.limit(condition.limit)
}
}
const snapshot = await query.get()
return snapshot.docs.map((doc) => ({
id: doc.id,
...(doc.data() as T),
}))
} catch (error) {
throw new Error(`Error querying collection: ${error}`)
}
}
|
src/lib/queryCollectionItems.ts
|
elsoul-skeet-firestore-8c637de
|
[
{
"filename": "src/lib/queryCollectionItems.d.ts",
"retrieved_chunk": "export declare const queryCollectionItems: <T extends firestore.DocumentData>(db: firestore.Firestore, collectionPath: string, conditions: QueryCondition[]) => Promise<T[]>;\nexport {};",
"score": 0.8939368724822998
},
{
"filename": "src/lib/createCollectionRef.ts",
"retrieved_chunk": "import { firestore } from 'firebase-admin'\nimport { createFirestoreDataConverter } from './createFirestoreDataConverter'\nimport { DocumentData } from 'firebase/firestore'\nexport const createCollectionRef = <T extends DocumentData>(\n db: firestore.Firestore,\n collectionPath: string\n) => {\n return db\n .collection(collectionPath)\n .withConverter(createFirestoreDataConverter<T>())",
"score": 0.8402062058448792
},
{
"filename": "src/lib/createDataRef.ts",
"retrieved_chunk": "import { firestore } from 'firebase-admin'\nimport { createFirestoreDataConverter } from './createFirestoreDataConverter'\nexport const createDataRef = <T extends firestore.DocumentData>(\n db: firestore.Firestore,\n collectionPath: string\n) => {\n return db.doc(collectionPath).withConverter(createFirestoreDataConverter<T>())\n}",
"score": 0.829746425151825
},
{
"filename": "src/lib/getCollectionItem.ts",
"retrieved_chunk": " * run();\n * ```\n */\nexport const getCollectionItem = async <T>(\n db: firestore.Firestore,\n collectionPath: string,\n docId: string\n): Promise<T> => {\n const dataRef = db\n .collection(collectionPath)",
"score": 0.8247042894363403
},
{
"filename": "src/lib/queryCollectionItems.d.ts",
"retrieved_chunk": "import { firestore } from 'firebase-admin';\n/**\n * Represents a condition for querying Firestore collections.\n */\ntype QueryCondition = {\n field?: string;\n operator?: firestore.WhereFilterOp;\n value?: any;\n orderDirection?: firestore.OrderByDirection;\n limit?: number;",
"score": 0.822187602519989
}
] |
typescript
|
(createFirestoreDataConverter<T>())
for (const condition of conditions) {
|
import { BasicRequest } from './request'
import { RequestMethod, Route, RouteHandler } from './types'
export class Router<Env> {
routes: Route<Env>[] = []
/**
* Handles a request by matching it against the registered routes.
* @param request Request
* @param env Environment
* @param ctx Context (for Workers)
* @returns Response
**/
handle(rawRequest: Request, env: Env, ctx: ExecutionContext) {
const request = new BasicRequest(rawRequest)
for (const route of this.routes) {
const match = route[0](request)
if (match) {
return route[1]({ request, env, ctx, params: match.params })
}
}
const match = this.routes.find(([matcher]) => matcher(request))
if (match) {
return match[1]({ request, env, ctx })
}
}
/**
* Registers a new route.
* @param handler RouteHandler
* @param path Path to match
* @param method HTTP method to match
*
* @example
* const router = new Router<Env>()
*
* router.register(async ({ request }) => {
* return new Response('ok')
* }, '/test')
*/
register(handler: RouteHandler<Env>, path:
|
string, method?: RequestMethod) {
|
const urlPattern = new URLPattern({ pathname: path })
this.routes.push([
(request) => {
if (!method || request.method === method) {
const match = urlPattern.exec({
pathname: request.url.pathname,
})
if (match) {
return { params: match.pathname.groups }
}
}
},
handler,
])
}
options(path: string, handler: RouteHandler<Env>) {
this.register(handler, path, 'options')
}
head(path: string, handler: RouteHandler<Env>) {
this.register(handler, path, 'head')
}
/**
* Register a new GET route.
* @param path
* @param handler
*
* @example
* const router = new Router<Env>()
*
* router.get('/test', async ({ request }) => {
* return new Response('ok')
* })
*/
get(path: string, handler: RouteHandler<Env>) {
this.register(handler, path, 'get')
}
post(path: string, handler: RouteHandler<Env>) {
this.register(handler, path, 'post')
}
put(path: string, handler: RouteHandler<Env>) {
this.register(handler, path, 'put')
}
patch(path: string, handler: RouteHandler<Env>) {
this.register(handler, path, 'patch')
}
delete(path: string, handler: RouteHandler<Env>) {
this.register(handler, path, 'delete')
}
/**
* Registers a new route for all HTTP methods.
* @param path
* @param handler
*/
all(path: string, handler: RouteHandler<Env>) {
this.register(handler, path)
}
}
|
src/router.ts
|
team-openpm-cloudflare-basics-5bf8ecd
|
[
{
"filename": "src/router.test.ts",
"retrieved_chunk": "import { describe, it, expect } from 'vitest'\nimport { Router } from './router'\nimport 'urlpattern-polyfill'\ndescribe('router', () => {\n type Env = {\n foo: string\n }\n it('handles routes', async () => {\n const router = new Router<Env>()\n router.register(async ({ request }) => {",
"score": 0.8388267755508423
},
{
"filename": "src/types.ts",
"retrieved_chunk": "export type RouteHandler<Env> = (\n options: RouteOptions<Env>\n) => Promise<Response>\nexport type ZodRouteHandler<Env, Schema> = (\n options: RouteOptions<Env> & { data: Schema }\n) => Promise<Response>\nexport type Route<Env> = [RouteMatcher, RouteHandler<Env>]\nexport enum RequestMethodEnum {\n options = 'options',\n head = 'head',",
"score": 0.8187916278839111
},
{
"filename": "src/router.test.ts",
"retrieved_chunk": " it('handles post routes', async () => {\n const router = new Router<Env>()\n router.post('/test', async ({ request }) => {\n expect(request.url.href).toBe('https://example.com/test')\n return new Response('ok')\n })\n const response = await router.handle(\n new Request('https://example.com/test', { method: 'POST' }),\n { foo: 'bar' },\n {} as any",
"score": 0.8141682744026184
},
{
"filename": "src/types.ts",
"retrieved_chunk": "import { BasicRequest } from './request'\nexport type RouteMatcher = (\n request: BasicRequest\n) => { params: Record<string, string> } | undefined\nexport type RouteOptions<Env> = {\n request: BasicRequest\n env: Env\n ctx: ExecutionContext\n params?: Record<string, string>\n}",
"score": 0.7959185242652893
},
{
"filename": "src/middleware/zod-validation.ts",
"retrieved_chunk": " * console.log(options.data) //=> { name: 'test' }\n * return new Response('ok')\n * })\n *\n */\nexport function withZod<Env, Schema>(\n schema: z.Schema,\n callback: ZodRouteHandler<Env, Schema>\n) {\n return async (options: RouteOptions<Env>) => {",
"score": 0.7808778285980225
}
] |
typescript
|
string, method?: RequestMethod) {
|
import { BasicRequest } from './request'
import { RequestMethod, Route, RouteHandler } from './types'
export class Router<Env> {
routes: Route<Env>[] = []
/**
* Handles a request by matching it against the registered routes.
* @param request Request
* @param env Environment
* @param ctx Context (for Workers)
* @returns Response
**/
handle(rawRequest: Request, env: Env, ctx: ExecutionContext) {
const request = new BasicRequest(rawRequest)
for (const route of this.routes) {
const match = route[0](request)
if (match) {
return route[1]({ request, env, ctx, params: match.params })
}
}
const match = this.routes.find(([matcher]) => matcher(request))
if (match) {
return match[1]({ request, env, ctx })
}
}
/**
* Registers a new route.
* @param handler RouteHandler
* @param path Path to match
* @param method HTTP method to match
*
* @example
* const router = new Router<Env>()
*
* router.register(async ({ request }) => {
* return new Response('ok')
* }, '/test')
*/
register(handler:
|
RouteHandler<Env>, path: string, method?: RequestMethod) {
|
const urlPattern = new URLPattern({ pathname: path })
this.routes.push([
(request) => {
if (!method || request.method === method) {
const match = urlPattern.exec({
pathname: request.url.pathname,
})
if (match) {
return { params: match.pathname.groups }
}
}
},
handler,
])
}
options(path: string, handler: RouteHandler<Env>) {
this.register(handler, path, 'options')
}
head(path: string, handler: RouteHandler<Env>) {
this.register(handler, path, 'head')
}
/**
* Register a new GET route.
* @param path
* @param handler
*
* @example
* const router = new Router<Env>()
*
* router.get('/test', async ({ request }) => {
* return new Response('ok')
* })
*/
get(path: string, handler: RouteHandler<Env>) {
this.register(handler, path, 'get')
}
post(path: string, handler: RouteHandler<Env>) {
this.register(handler, path, 'post')
}
put(path: string, handler: RouteHandler<Env>) {
this.register(handler, path, 'put')
}
patch(path: string, handler: RouteHandler<Env>) {
this.register(handler, path, 'patch')
}
delete(path: string, handler: RouteHandler<Env>) {
this.register(handler, path, 'delete')
}
/**
* Registers a new route for all HTTP methods.
* @param path
* @param handler
*/
all(path: string, handler: RouteHandler<Env>) {
this.register(handler, path)
}
}
|
src/router.ts
|
team-openpm-cloudflare-basics-5bf8ecd
|
[
{
"filename": "src/router.test.ts",
"retrieved_chunk": "import { describe, it, expect } from 'vitest'\nimport { Router } from './router'\nimport 'urlpattern-polyfill'\ndescribe('router', () => {\n type Env = {\n foo: string\n }\n it('handles routes', async () => {\n const router = new Router<Env>()\n router.register(async ({ request }) => {",
"score": 0.8397554159164429
},
{
"filename": "src/types.ts",
"retrieved_chunk": "export type RouteHandler<Env> = (\n options: RouteOptions<Env>\n) => Promise<Response>\nexport type ZodRouteHandler<Env, Schema> = (\n options: RouteOptions<Env> & { data: Schema }\n) => Promise<Response>\nexport type Route<Env> = [RouteMatcher, RouteHandler<Env>]\nexport enum RequestMethodEnum {\n options = 'options',\n head = 'head',",
"score": 0.82143634557724
},
{
"filename": "src/router.test.ts",
"retrieved_chunk": " it('handles post routes', async () => {\n const router = new Router<Env>()\n router.post('/test', async ({ request }) => {\n expect(request.url.href).toBe('https://example.com/test')\n return new Response('ok')\n })\n const response = await router.handle(\n new Request('https://example.com/test', { method: 'POST' }),\n { foo: 'bar' },\n {} as any",
"score": 0.8129987716674805
},
{
"filename": "src/types.ts",
"retrieved_chunk": "import { BasicRequest } from './request'\nexport type RouteMatcher = (\n request: BasicRequest\n) => { params: Record<string, string> } | undefined\nexport type RouteOptions<Env> = {\n request: BasicRequest\n env: Env\n ctx: ExecutionContext\n params?: Record<string, string>\n}",
"score": 0.7969874143600464
},
{
"filename": "src/middleware/zod-validation.ts",
"retrieved_chunk": " * console.log(options.data) //=> { name: 'test' }\n * return new Response('ok')\n * })\n *\n */\nexport function withZod<Env, Schema>(\n schema: z.Schema,\n callback: ZodRouteHandler<Env, Schema>\n) {\n return async (options: RouteOptions<Env>) => {",
"score": 0.7819280624389648
}
] |
typescript
|
RouteHandler<Env>, path: string, method?: RequestMethod) {
|
import { BasicRequest } from './request'
import { RequestMethod, Route, RouteHandler } from './types'
export class Router<Env> {
routes: Route<Env>[] = []
/**
* Handles a request by matching it against the registered routes.
* @param request Request
* @param env Environment
* @param ctx Context (for Workers)
* @returns Response
**/
handle(rawRequest: Request, env: Env, ctx: ExecutionContext) {
const request = new BasicRequest(rawRequest)
for (const route of this.routes) {
const match = route[0](request)
if (match) {
return route[1]({ request, env, ctx, params: match.params })
}
}
const match = this.routes.find(([matcher]) => matcher(request))
if (match) {
return match[1]({ request, env, ctx })
}
}
/**
* Registers a new route.
* @param handler RouteHandler
* @param path Path to match
* @param method HTTP method to match
*
* @example
* const router = new Router<Env>()
*
* router.register(async ({ request }) => {
* return new Response('ok')
* }, '/test')
*/
register(handler: RouteHandler<Env>, path: string, method?: RequestMethod) {
const urlPattern = new URLPattern({ pathname: path })
this.routes.push([
|
(request) => {
|
if (!method || request.method === method) {
const match = urlPattern.exec({
pathname: request.url.pathname,
})
if (match) {
return { params: match.pathname.groups }
}
}
},
handler,
])
}
options(path: string, handler: RouteHandler<Env>) {
this.register(handler, path, 'options')
}
head(path: string, handler: RouteHandler<Env>) {
this.register(handler, path, 'head')
}
/**
* Register a new GET route.
* @param path
* @param handler
*
* @example
* const router = new Router<Env>()
*
* router.get('/test', async ({ request }) => {
* return new Response('ok')
* })
*/
get(path: string, handler: RouteHandler<Env>) {
this.register(handler, path, 'get')
}
post(path: string, handler: RouteHandler<Env>) {
this.register(handler, path, 'post')
}
put(path: string, handler: RouteHandler<Env>) {
this.register(handler, path, 'put')
}
patch(path: string, handler: RouteHandler<Env>) {
this.register(handler, path, 'patch')
}
delete(path: string, handler: RouteHandler<Env>) {
this.register(handler, path, 'delete')
}
/**
* Registers a new route for all HTTP methods.
* @param path
* @param handler
*/
all(path: string, handler: RouteHandler<Env>) {
this.register(handler, path)
}
}
|
src/router.ts
|
team-openpm-cloudflare-basics-5bf8ecd
|
[
{
"filename": "src/router.test.ts",
"retrieved_chunk": "import { describe, it, expect } from 'vitest'\nimport { Router } from './router'\nimport 'urlpattern-polyfill'\ndescribe('router', () => {\n type Env = {\n foo: string\n }\n it('handles routes', async () => {\n const router = new Router<Env>()\n router.register(async ({ request }) => {",
"score": 0.8699130415916443
},
{
"filename": "src/router.test.ts",
"retrieved_chunk": " it('handles post routes', async () => {\n const router = new Router<Env>()\n router.post('/test', async ({ request }) => {\n expect(request.url.href).toBe('https://example.com/test')\n return new Response('ok')\n })\n const response = await router.handle(\n new Request('https://example.com/test', { method: 'POST' }),\n { foo: 'bar' },\n {} as any",
"score": 0.8393548130989075
},
{
"filename": "src/types.ts",
"retrieved_chunk": "export type RouteHandler<Env> = (\n options: RouteOptions<Env>\n) => Promise<Response>\nexport type ZodRouteHandler<Env, Schema> = (\n options: RouteOptions<Env> & { data: Schema }\n) => Promise<Response>\nexport type Route<Env> = [RouteMatcher, RouteHandler<Env>]\nexport enum RequestMethodEnum {\n options = 'options',\n head = 'head',",
"score": 0.8311111927032471
},
{
"filename": "src/types.ts",
"retrieved_chunk": "import { BasicRequest } from './request'\nexport type RouteMatcher = (\n request: BasicRequest\n) => { params: Record<string, string> } | undefined\nexport type RouteOptions<Env> = {\n request: BasicRequest\n env: Env\n ctx: ExecutionContext\n params?: Record<string, string>\n}",
"score": 0.8110384345054626
},
{
"filename": "src/router.test.ts",
"retrieved_chunk": " expect(request.url.href).toBe('https://example.com/test')\n return new Response('ok')\n }, '/test')\n const response = await router.handle(\n new Request('https://example.com/test'),\n { foo: 'bar' },\n {} as any\n )\n expect(response?.status).toBe(200)\n })",
"score": 0.810005247592926
}
] |
typescript
|
(request) => {
|
import { BasicRequest } from './request'
import { RequestMethod, Route, RouteHandler } from './types'
export class Router<Env> {
routes: Route<Env>[] = []
/**
* Handles a request by matching it against the registered routes.
* @param request Request
* @param env Environment
* @param ctx Context (for Workers)
* @returns Response
**/
handle(rawRequest: Request, env: Env, ctx: ExecutionContext) {
const request = new BasicRequest(rawRequest)
for (const route of this.routes) {
const match = route[0](request)
if (match) {
return route[1]({ request, env, ctx, params: match.params })
}
}
const match = this.routes.find(([matcher]) => matcher(request))
if (match) {
return match[1]({ request, env, ctx })
}
}
/**
* Registers a new route.
* @param handler RouteHandler
* @param path Path to match
* @param method HTTP method to match
*
* @example
* const router = new Router<Env>()
*
* router.register(async ({ request }) => {
* return new Response('ok')
* }, '/test')
*/
register(handler: RouteHandler<Env>, path: string, method?: RequestMethod) {
const urlPattern = new URLPattern({ pathname: path })
this.routes.push([
(
|
request) => {
|
if (!method || request.method === method) {
const match = urlPattern.exec({
pathname: request.url.pathname,
})
if (match) {
return { params: match.pathname.groups }
}
}
},
handler,
])
}
options(path: string, handler: RouteHandler<Env>) {
this.register(handler, path, 'options')
}
head(path: string, handler: RouteHandler<Env>) {
this.register(handler, path, 'head')
}
/**
* Register a new GET route.
* @param path
* @param handler
*
* @example
* const router = new Router<Env>()
*
* router.get('/test', async ({ request }) => {
* return new Response('ok')
* })
*/
get(path: string, handler: RouteHandler<Env>) {
this.register(handler, path, 'get')
}
post(path: string, handler: RouteHandler<Env>) {
this.register(handler, path, 'post')
}
put(path: string, handler: RouteHandler<Env>) {
this.register(handler, path, 'put')
}
patch(path: string, handler: RouteHandler<Env>) {
this.register(handler, path, 'patch')
}
delete(path: string, handler: RouteHandler<Env>) {
this.register(handler, path, 'delete')
}
/**
* Registers a new route for all HTTP methods.
* @param path
* @param handler
*/
all(path: string, handler: RouteHandler<Env>) {
this.register(handler, path)
}
}
|
src/router.ts
|
team-openpm-cloudflare-basics-5bf8ecd
|
[
{
"filename": "src/router.test.ts",
"retrieved_chunk": "import { describe, it, expect } from 'vitest'\nimport { Router } from './router'\nimport 'urlpattern-polyfill'\ndescribe('router', () => {\n type Env = {\n foo: string\n }\n it('handles routes', async () => {\n const router = new Router<Env>()\n router.register(async ({ request }) => {",
"score": 0.8625319004058838
},
{
"filename": "src/router.test.ts",
"retrieved_chunk": " it('handles post routes', async () => {\n const router = new Router<Env>()\n router.post('/test', async ({ request }) => {\n expect(request.url.href).toBe('https://example.com/test')\n return new Response('ok')\n })\n const response = await router.handle(\n new Request('https://example.com/test', { method: 'POST' }),\n { foo: 'bar' },\n {} as any",
"score": 0.8330464363098145
},
{
"filename": "src/router.test.ts",
"retrieved_chunk": " expect(request.url.href).toBe('https://example.com/test')\n return new Response('ok')\n }, '/test')\n const response = await router.handle(\n new Request('https://example.com/test'),\n { foo: 'bar' },\n {} as any\n )\n expect(response?.status).toBe(200)\n })",
"score": 0.8140305280685425
},
{
"filename": "src/types.ts",
"retrieved_chunk": "export type RouteHandler<Env> = (\n options: RouteOptions<Env>\n) => Promise<Response>\nexport type ZodRouteHandler<Env, Schema> = (\n options: RouteOptions<Env> & { data: Schema }\n) => Promise<Response>\nexport type Route<Env> = [RouteMatcher, RouteHandler<Env>]\nexport enum RequestMethodEnum {\n options = 'options',\n head = 'head',",
"score": 0.8080167174339294
},
{
"filename": "src/middleware/zod-validation.test.ts",
"retrieved_chunk": " return new Response('ok')\n })\n const response = await execRoute(\n route,\n buildRequest('https://example.com?name=test', {\n method: 'GET',\n })\n )\n expect(response.status).toBe(200)\n })",
"score": 0.7925816774368286
}
] |
typescript
|
request) => {
|
import { describe, it, expect } from 'vitest'
import { BasicRequest } from './request'
describe('request', () => {
it('parses query params', () => {
const request = new BasicRequest(
new Request('https://example.com/test?foo=bar')
)
expect(request.query).toEqual({ foo: 'bar' })
})
it('parses cookies', () => {
const request = new BasicRequest(
new Request('https://example.com/test', {
headers: {
cookie: 'foo=bar',
},
})
)
expect(request.cookies).toEqual({ foo: 'bar' })
})
it('parses headers', () => {
const request = new BasicRequest(
new Request('https://example.com/test', {
headers: {
'content-type': 'application/json',
},
})
)
expect(request.headers.get('content-type')).toBe('application/json')
})
it('parses origin', () => {
const request = new BasicRequest(
new Request('https://example.com/test', {
headers: {
'content-type': 'application/json',
},
})
)
|
expect(request.origin).toBe('https://example.com')
})
it('parses json', async () => {
|
const request = new BasicRequest(
new Request('https://example.com/test', {
method: 'POST',
headers: {
'content-type': 'application/json',
},
body: JSON.stringify({ foo: 'bar' }),
})
)
expect(await request.body()).toEqual({ foo: 'bar' })
})
it('parses forms', async () => {
const request = new BasicRequest(
new Request('https://example.com/test', {
method: 'POST',
headers: {
'content-type': 'application/x-www-form-urlencoded',
},
body: 'foo=bar',
})
)
expect(await request.body()).toEqual({ foo: 'bar' })
})
})
|
src/request.test.ts
|
team-openpm-cloudflare-basics-5bf8ecd
|
[
{
"filename": "src/router.test.ts",
"retrieved_chunk": " expect(request.url.href).toBe('https://example.com/test')\n return new Response('ok')\n }, '/test')\n const response = await router.handle(\n new Request('https://example.com/test'),\n { foo: 'bar' },\n {} as any\n )\n expect(response?.status).toBe(200)\n })",
"score": 0.8426405191421509
},
{
"filename": "src/middleware/zod-validation.test.ts",
"retrieved_chunk": " })\n type schemaType = z.infer<typeof schema>\n it('should pass through json', async () => {\n const route = withZod<Env, schemaType>(schema, async (options) => {\n expect(options.data).toEqual({ name: 'test' })\n return new Response('ok')\n })\n const response = await execRoute(\n route,\n buildRequest('https://example.com', {",
"score": 0.8389763236045837
},
{
"filename": "src/router.test.ts",
"retrieved_chunk": " it('handles post routes', async () => {\n const router = new Router<Env>()\n router.post('/test', async ({ request }) => {\n expect(request.url.href).toBe('https://example.com/test')\n return new Response('ok')\n })\n const response = await router.handle(\n new Request('https://example.com/test', { method: 'POST' }),\n { foo: 'bar' },\n {} as any",
"score": 0.832252025604248
},
{
"filename": "src/middleware/zod-validation.test.ts",
"retrieved_chunk": " method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify({ name: 'test' }),\n })\n )\n expect(response.status).toBe(200)\n })\n it('should pass through query', async () => {\n const route = withZod<Env, schemaType>(schema, async (options) => {\n expect(options.data).toEqual({ name: 'test' })",
"score": 0.8294281363487244
},
{
"filename": "src/router.test.ts",
"retrieved_chunk": " )\n expect(response?.status).toBe(200)\n })\n})",
"score": 0.8292182683944702
}
] |
typescript
|
expect(request.origin).toBe('https://example.com')
})
it('parses json', async () => {
|
// lifecycle methods like beforeEach, afterEach, teardown
// defined in plugins/lifecycle.ts
import Minipass from 'minipass'
import assert from 'node:assert'
import { hrtime } from 'node:process'
import { Readable } from 'node:stream'
import { format } from 'node:util'
import { CallSiteLike } from 'stack-utils'
import { FinalResults } from 'tap-parser'
import Deferred from 'trivial-deferred'
import { Base, BaseOpts } from './base.js'
import { esc } from './esc.js'
import stack from './stack.js'
import { TestPoint } from './test-point.js'
import { Waiter } from './waiter.js'
const queueEmpty = <T extends TestBase>(t: T) =>
t.queue.length === 0 ||
(t.queue.length === 1 &&
t.queue[0] === 'TAP version 14\n')
export interface ClassOf<T> {
new (): T
}
export type TapPlugin<
B extends Object,
O extends TestBaseOpts | any = any
> = ((t: TestBase, opts: O) => B) | ((t: TestBase) => B)
export interface TestBaseOpts extends BaseOpts {
/**
* The number of jobs to run in parallel. Defaults to 1
*/
jobs?: number
/**
* Test function called when this Test is executed
*/
cb?: (...args: any[]) => any
/**
* Flag to always/never show diagnostics. If unset, then
* diagnostics are shown for failing test points only.
*/
diagnostic?: boolean
}
const normalizeMessageExtra = (
defaultMessage: string,
message?: string | { [k: string]: any },
extra?: { [k: string]: any }
): [string, { [k: string]: any }] => {
if (typeof message === 'string') {
return [message || defaultMessage, extra || {}]
} else {
return [defaultMessage, message || {}]
}
}
/**
* Sigil for implicit end() calls that should not
* trigger an error if the user then calls t.end()
*/
const IMPLICIT = Symbol('implicit end')
/**
* Sigil to put in the queue to signal the end of all things
*/
const EOF = Symbol('EOF')
export type QueueEntry =
| string
| TestPoint
| Base
| typeof EOF
| Waiter
| [method: string, ...args: any[]]
/**
* The TestBaseBase class is the base class for all plugins,
* and eventually thus the Test class.
*
* This implements subtest functionality, TAP stream generation,
* lifecycle events, and only the most basic pass/fail assertions.
*
* All other features are added with plugins.
*/
|
export class TestBase extends Base {
|
// NB: generated pluginified Test class needs to declare over this
declare parent?: TestBase
promise?: Promise<any>
jobs: number
// #beforeEnd: [method: string | Symbol, ...args: any[]][] = []
subtests: Base[] = []
pool: Set<Base> = new Set()
queue: QueueEntry[] = ['TAP version 14\n']
cb?: (...args: any[]) => any
count: number = 0
ended: boolean = false
assertAt: CallSiteLike | null = null
assertStack: string | null = null
diagnostic: null | boolean = null
#planEnd: number = -1
#printedResult: boolean = false
#explicitEnded: boolean = false
#multiEndThrew: boolean = false
#n: number = 0
#noparallel: boolean = false
#occupied: null | Waiter | Base = null
#pushedEnd: boolean = false
#nextChildId: number = 1
#currentAssert: null | ((..._: any) => any) = null
#processing: boolean = false
#doingStdinOnly: boolean = false
/**
* true if the test has printed at least one TestPoint
*/
get printedResult(): boolean {
return this.#printedResult
}
constructor(options: TestBaseOpts) {
super(options)
this.jobs =
(options.jobs && Math.max(options.jobs, 1)) || 1
if (typeof options.diagnostic === 'boolean') {
this.diagnostic = options.diagnostic
}
if (options.cb) {
this.#setCB(options.cb)
}
}
#setCB<T extends TestBase>(this: T, cb: (t: T) => any) {
this.cb = (...args: any[]) =>
this.hook.runInAsyncScope(cb, this, ...args)
}
// TAP output generating methods
/**
* immediately exit this and all parent tests with a TAP
* Bail out! message.
*/
bailout(message?: string) {
if (this.parent && (this.results || this.ended)) {
this.parent.bailout(message)
} else {
this.#process()
message = message
? ' ' + ('' + esc(message)).trim()
: ''
message = message.replace(/[\r\n]/g, ' ')
this.parser.write('Bail out!' + message + '\n')
}
this.#end(IMPLICIT)
this.#process()
}
/**
* output a TAP comment, formatted like console.log()
*/
comment(...args: any[]) {
const body = format(...args)
const message =
('# ' + body.split(/\r?\n/).join('\n# ')).trim() +
'\n'
if (this.results) {
this.write(message)
} else {
this.queue.push(message)
}
this.#process()
}
/**
* Called when the test times out.
* Options are passed as diagnostics to the threw() method
*/
timeout(options: { [k: string]: any }) {
options = options || {}
options.expired = options.expired || this.name
if (this.#occupied && this.#occupied instanceof Base) {
this.#occupied.timeout(options)
} else {
super.timeout(options)
}
this.#end(IMPLICIT)
}
/**
* Set TAP pragma configs to affect the behavior of the parser.
* Only `strict` is supported by the parser.
*/
pragma(set: { [k: string]: boolean }) {
const p = Object.keys(set).reduce(
(acc, i) =>
acc + 'pragma ' + (set[i] ? '+' : '-') + i + '\n',
''
)
this.queue.push(p)
this.#process()
}
/**
* Specify the number of Test Points expected by this test.
* Outputs a TAP plan line.
*/
plan(n: number, comment?: string) {
if (this.bailedOut) {
return
}
if (this.#planEnd !== -1) {
throw new Error('Cannot set plan more than once')
}
if (typeof n !== 'number' || n < 0) {
throw new TypeError('plan must be a number')
}
// Cannot get any tests after a trailing plan, or a plan of 0
const ending = this.count !== 0 || n === 0
if (n === 0 && comment && !this.options.skip) {
this.options.skip = comment
}
this.#planEnd = n
comment = comment ? ' # ' + esc(comment.trim()) : ''
this.queue.push('1..' + n + comment + '\n')
if (ending) {
this.#end(IMPLICIT)
} else {
this.#process()
}
}
/**
* A passing (ok) Test Point
*/
pass(message?: string, extra?: { [k: string]: any }) {
this.currentAssert = TestBase.prototype.pass
this.printResult(
true,
...normalizeMessageExtra(
'(unnamed test)',
message,
extra
)
)
return true
}
/**
* A failing (not ok) Test Point
*/
fail(message?: string, extra?: { [k: string]: any }) {
this.currentAssert = TestBase.prototype.fail
const [m, e] = normalizeMessageExtra(
'(unnamed test)',
message,
extra
)
this.printResult(false, m, e)
return !!(e.todo || e.skip)
}
/**
* The current assertion being processed. May only be set if
* not already set.
*/
get currentAssert() {
return this.#currentAssert
}
/**
* The current assertion being processed. May only be set if
* not already set.
*/
set currentAssert(fn: null | ((...a: any[]) => any)) {
if (!this.#currentAssert && typeof fn === 'function') {
this.#currentAssert = fn
}
}
/**
* Print a Test Point
*/
printResult(
ok: boolean,
message: string,
extra: { [k: string]: any },
front: boolean = false
) {
this.#printedResult = true
const n = this.count + 1
this.currentAssert = TestBase.prototype.printResult
const fn = this.#currentAssert
this.#currentAssert = null
if (this.#planEnd !== -1 && n > this.#planEnd) {
if (!this.passing()) return
const failMessage = this.#explicitEnded
? 'test after end() was called'
: 'test count exceeds plan'
const er = new Error(failMessage, {
cause: {
test: this.name,
plan: this.#planEnd,
},
})
Error.captureStackTrace(er, fn || undefined)
this.threw(er)
return
}
extra = extra || {}
if (extra.expectFail) {
ok = !ok
}
if (this.assertAt) {
extra.at = this.assertAt
this.assertAt = null
}
if (this.assertStack) {
extra.stack = this.assertStack
this.assertStack = null
}
if (typeof extra.stack === 'string' && !extra.at) {
extra.at = stack.parseLine(extra.stack.split('\n')[0])
}
if (
!ok &&
!extra.skip &&
!extra.at &&
typeof fn === 'function'
) {
extra.at = stack.at(fn)
if (!extra.todo) {
extra.stack = stack.captureString(80, fn)
}
}
const diagnostic =
typeof extra.diagnostic === 'boolean'
? extra.diagnostic
: typeof this.diagnostic === 'boolean'
? this.diagnostic
: extra.skip || extra.todo
? false
: !ok
if (diagnostic) {
extra.diagnostic = true
}
this.count = n
message = message + ''
const res = { ok, message, extra }
const tp = new TestPoint(ok, message, extra)
// when we jump the queue, skip an extra line
if (front) {
tp.message = tp.message.trimEnd() + '\n\n'
}
if (
this.#occupied &&
this.#occupied instanceof Waiter &&
this.#occupied.finishing
) {
front = true
}
if (front) {
if (
extra.tapChildBuffer ||
extra.tapChildBuffer === ''
) {
this.writeSubComment(tp)
this.parser.write(extra.tapChildBuffer)
}
this.emit('result', res)
this.parser.write(tp.ok + ++this.#n + tp.message)
if (this.bail && !ok && !extra.skip && !extra.todo) {
this.parser.write('Bail out! ' + message + '\n')
}
} else {
this.queue.push(tp)
if (this.bail && !ok && !extra.skip && !extra.todo) {
this.queue.push('Bail out! ' + message + '\n')
}
}
if (this.#planEnd === this.count) {
this.#end(IMPLICIT)
}
this.#process()
}
end(): this {
this.#end()
return super.end()
}
/**
* The leading `# Subtest` comment that introduces a child test
*/
writeSubComment<T extends TestPoint | Base>(p: T) {
const comment =
'# Subtest' +
(p.name ? ': ' + esc(p.name) : '') +
'\n'
this.parser.write(comment)
}
// end TAP otput generating methods
// flow control methods
/**
* Await the end of a Promise before proceeding.
* The supplied callback is called with the Waiter object.
*/
waitOn(
promise: Promise<any | void>,
cb: (w: Waiter) => any,
expectReject: boolean = false
): Promise<void> {
const w = new Waiter(
promise,
w => {
assert.equal(this.#occupied, w)
cb(w)
this.#occupied = null
this.#process()
},
expectReject
)
this.queue.push(w)
this.#process()
return w.promise
}
#end(implicit?: typeof IMPLICIT) {
if (this.#doingStdinOnly && implicit !== IMPLICIT)
throw new Error(
'cannot explicitly end while in stdinOnly mode'
)
this.debug('END implicit=%j', implicit === IMPLICIT)
if (this.ended && implicit === IMPLICIT) return
// beyond here we have to be actually done with things, or else
// the semantic checks on counts and such will be off.
if (!queueEmpty(this) || this.#occupied) {
if (!this.#pushedEnd) {
this.queue.push(['#end', implicit])
}
this.#pushedEnd = true
return this.#process()
}
this.ended = true
if (implicit !== IMPLICIT && !this.#multiEndThrew) {
if (this.#explicitEnded) {
this.#multiEndThrew = true
const er = new Error(
'test end() method called more than once'
)
Error.captureStackTrace(
er,
this.#currentAssert || this.#end
)
er.cause = {
test: this.name,
}
this.threw(er)
return
}
this.#explicitEnded = true
}
if (this.#planEnd === -1) {
this.debug(
'END(%s) implicit plan',
this.name,
this.count
)
this.plan(this.count)
}
this.queue.push(EOF)
this.#process()
}
#process() {
if (this.#processing) {
return this.debug(' < already processing')
}
this.debug(
'\nPROCESSING(%s)',
this.name,
this.queue.length
)
this.#processing = true
while (!this.#occupied) {
const p = this.queue.shift()
if (!p) {
this.debug('> end of queue')
break
}
if (p instanceof Base) {
this.debug('> subtest in queue', p.name)
this.#processSubtest(p)
} else if (p === EOF) {
this.debug(' > EOF', this.name)
// I AM BECOME EOF, DESTROYER OF STREAMS
this.parser.end()
} else if (p instanceof TestPoint) {
this.debug(' > TESTPOINT')
if (
p.extra.tapChildBuffer ||
p.extra.tapChildBuffer === ''
) {
this.writeSubComment(p)
this.parser.write(p.extra.tapChildBuffer)
}
this.emit('res', p.res)
this.parser.write(p.ok + ++this.#n + p.message)
} else if (typeof p === 'string') {
this.debug(' > STRING')
this.parser.write(p)
} else if (p instanceof Waiter) {
p.ready = true
this.#occupied = p
p.finish()
} else if (Array.isArray(p)) {
this.debug(' > METHOD')
const m = p.shift() as keyof this
if (typeof this[m] !== 'function') {
this.debug(
' > weird method not found in queue??',
m,
typeof this[m]
)
continue
}
const fn = (m === '#end' ? this.#end : this[m]) as (
...a: any[]
) => any
const ret = fn.call(this, ...p)
if (
ret &&
typeof ret === 'object' &&
typeof ret.then === 'function'
) {
// returned promise
ret.then(
() => {
this.#processing = false
this.#process()
},
(er: unknown) => {
this.#processing = false
this.threw(er)
}
)
return
}
/* c8 ignore start */
} else {
throw new Error('weird thing got in the queue')
}
/* c8 ignore stop */
}
while (
!this.#noparallel &&
this.pool.size < this.jobs
) {
const p = this.subtests.shift()
if (!p) {
break
}
if (!p.buffered) {
this.#noparallel = true
break
}
this.debug('start subtest', p)
this.emit('subtestStart', p)
this.pool.add(p)
if (this.bailedOut) {
this.#onBufferedEnd(p)
} else {
p.runMain(() => this.#onBufferedEnd(p))
}
}
this.debug(
'done processing',
this.queue,
this.#occupied
)
this.#processing = false
// just in case any tests ended, and we have sync stuff still
// waiting around in the queue to be processed
if (!this.#occupied && this.queue.length) {
this.#process()
}
}
#onBufferedEnd<T extends Base>(p: T) {
p.ondone = p.constructor.prototype.ondone
p.results =
p.results || new FinalResults(true, p.parser)
p.readyToProcess = true
const to = p.options.timeout
const dur =
to && p.passing() ? hrtime.bigint() - p.start : null
if (dur && to && dur > to) {
p.timeout()
} else {
p.setTimeout(0)
}
this.debug(
'%s.#onBufferedEnd',
this.name,
p.name,
p.results.bailout
)
this.pool.delete(p)
p.options.tapChildBuffer = p.output || ''
p.options.stack = ''
if (p.time) p.options.time = p.time
if (this.#occupied === p) this.#occupied = null
p.deferred?.resolve(p.results)
this.emit('subtestEnd', p)
this.#process()
}
#onIndentedEnd<T extends Base>(p: T) {
this.emit('subtestProcess', p)
p.ondone = p.constructor.prototype.ondone
p.results =
p.results || new FinalResults(true, p.parser)
this.debug('#onIndentedEnd', this.name, p.name)
this.#noparallel = false
const sti = this.subtests.indexOf(p)
if (sti !== -1) this.subtests.splice(sti, 1)
p.readyToProcess = true
p.options.time = p.time
const to = p.options.timeout
const dur =
to && p.passing() ? hrtime.bigint() - p.start : null
if (dur && to && dur > to) {
p.timeout()
} else {
p.setTimeout(0)
}
this.debug('#onIndentedEnd %s(%s)', this.name, p.name)
this.#occupied = null
this.debug(
'OIE(%s) b>shift into queue',
this.name,
this.queue
)
p.options.stack = ''
this.printResult(p.passing(), p.name, p.options, true)
this.debug(
'OIE(%s) shifted into queue',
this.name,
this.queue
)
p.deferred?.resolve(p.results)
this.emit('subtestEnd', p)
this.#process()
}
/**
* @internal
*/
main(cb: () => void) {
if (typeof this.options.timeout === 'number') {
this.setTimeout(this.options.timeout)
}
this.debug('MAIN pre', this)
const end = () => {
this.debug(' > implicit end for promise')
this.#end(IMPLICIT)
done()
}
const done = (er?: Error) => {
if (er) this.threw(er)
if (this.results || this.bailedOut) cb()
else this.ondone = () => cb()
}
// This bit of overly clever line-noise wraps the call to user-code
// in a try-catch. We can't rely on the domain for this yet, because
// the 'end' event can trigger a throw after the domain is unhooked,
// but before this is no longer the official "active test"
const ret = (() => {
if (!this.cb) return
try {
return this.cb(this)
} catch (er: any) {
if (!er || typeof er !== 'object') {
er = { error: er }
}
er.tapCaught = 'testFunctionThrow'
this.threw(er)
}
})()
if (ret && ret.then) {
this.promise = ret
ret.tapAbortPromise = done
ret.then(end, (er: any) => {
if (!er || typeof er !== 'object') {
er = { error: er }
}
er.tapCaught = 'returnedPromiseRejection'
done(er)
})
} else done()
this.debug('MAIN post', this)
}
#processSubtest<T extends Base>(p: T) {
this.debug(' > subtest')
this.#occupied = p
if (!p.buffered) {
this.emit('subtestStart', p)
this.debug(' > subtest indented')
p.stream.pipe(this.parser, { end: false })
this.writeSubComment(p)
this.debug('calling runMain', p.runMain.toString())
p.runMain(() => {
this.debug('in runMain', p.runMain.toString())
this.#onIndentedEnd(p)
})
} else if (p.readyToProcess) {
this.emit('subtestProcess', p)
this.debug(' > subtest buffered, finished')
// finished! do the thing!
this.#occupied = null
if (!p.passing() || !p.silent) {
this.printResult(
p.passing(),
p.name,
p.options,
true
)
}
} else {
this.#occupied = p
this.debug(' > subtest buffered, unfinished', p)
// unfinished buffered test.
// nothing to do yet, just leave it there.
this.queue.unshift(p)
}
}
/**
* Parse stdin as the only tap stream (ie, not as a child test)
* If used, then no other subtests or assertions are allowed.
*/
stdinOnly<T extends BaseOpts>(
extra?: T & { tapStream?: Readable | Minipass }
) {
const stream = ((extra && extra.tapStream) ||
process.stdin) as Minipass
if (!stream) {
throw new Error(
'cannot read stdin without stdin stream'
)
}
if (
this.queue.length !== 1 ||
this.queue[0] !== 'TAP version 14\n' ||
this.#processing ||
this.results ||
this.#occupied ||
this.pool.size ||
this.subtests.length
) {
throw new Error(
'Cannot use stdinOnly on a test in progress'
)
}
this.#doingStdinOnly = true
this.queue.length = 0
this.parser.on('child', p => {
// pretend to be a rooted parser, so it gets counts.
p.root = p
const t = new Base({
name: p.name,
parent: this,
parser: p,
bail: p.bail,
strict: p.strict,
omitVersion: p.omitVersion,
preserveWhitespace: p.preserveWhitespace,
childId: this.#nextChildId++,
})
this.emit('subtestAdd', t)
this.emit('subtestStart', t)
this.emit('subtestProcess', t)
p.on('complete', () => {
t.time = p.time
this.emit('subtestEnd', t)
})
})
stream.pause()
stream.pipe(this.parser)
stream.resume()
}
/**
* Mount a subtest, using this Test object as a harness.
* Exposed mainly so that it can be used by builtin plugins.
*
* @internal
*/
sub<T extends Base, O extends TestBaseOpts>(
Class: { new (options: O): T },
extra: O,
caller: (...a: any[]) => unknown
): Promise<FinalResults | null> {
if (this.bailedOut) return Promise.resolve(null)
if (this.results || this.ended) {
const er = new Error(
'cannot create subtest after parent test ends'
)
Error.captureStackTrace(er, caller)
this.threw(er)
return Promise.resolve(null)
}
extra.childId = this.#nextChildId++
if (this.shouldSkipChild(extra)) {
this.pass(extra.name, extra)
return Promise.resolve(null)
}
extra.indent = ' '
if (extra.buffered !== undefined) {
if (this.jobs > 1) {
extra.buffered = true
} else {
extra.buffered = false
}
}
extra.bail =
extra.bail !== undefined ? extra.bail : this.bail
extra.parent = this
extra.stack = stack.captureString(80, caller)
extra.context = this.context
const t = new Class(extra)
this.queue.push(t)
this.subtests.push(t)
this.emit('subtestAdd', t)
const d = new Deferred<FinalResults>()
t.deferred = d
this.#process()
return d.promise
}
/**
* Return true if the child test represented by the options object
* should be skipped. Extended by the grep/only filtering plugins.
*/
shouldSkipChild(extra: { [k: string]: any }) {
return !!(extra.skip || extra.todo)
}
// end flow control methods
}
|
src/test-base.ts
|
tapjs-core-edd7403
|
[
{
"filename": "src/test.ts",
"retrieved_chunk": "// the Test class is built up from PluginBase + all the plugins\nimport { TestBase } from './test-base.js'\nexport class Test extends TestBase {}",
"score": 0.8899943828582764
},
{
"filename": "src/test-template.ts",
"retrieved_chunk": "//{{HEADER COMMENT START}}\n// This is the template file used to generate the Test client\n// module. Prior to being built, it's effectively just a copy\n// of the TestBase class, without any plugins applied.\n//{{HEADER COMMENT END}}\nimport { FinalResults } from 'tap-parser'\nimport parseTestArgs, {\n TestArgs,\n} from './parse-test-args.js'\nimport { TestBase, TestBaseOpts } from './test-base.js'",
"score": 0.8468457460403442
},
{
"filename": "src/test-template.ts",
"retrieved_chunk": "//{{PLUGINS CODE START}}\ntype Plug = TestBase | { t: Test }\nconst plugins: PI[] = []\ntype PlugKeys = keyof TestBase | 't'\n//{{PLUGINS CODE END}}\n//{{OPTS START}}\ntype TestOpts = TestBaseOpts\n//{{OPTS END}}\n//{{TEST INTERFACE START}}\ntype TTest = TestBase",
"score": 0.836768627166748
},
{
"filename": "src/plugin/spawn.ts",
"retrieved_chunk": " }\n}\nconst plugin: TapPlugin<SpawnPlugin> = (t: TestBase) =>\n new SpawnPlugin(t)\nexport default plugin",
"score": 0.8346049785614014
},
{
"filename": "src/test-template.ts",
"retrieved_chunk": " return t\n}\nexport class Test extends TestBase {\n constructor(opts: TestOpts) {\n super(opts)\n return applyPlugins(this)\n }\n test(\n name: string,\n extra: { [k: string]: any },",
"score": 0.8318653106689453
}
] |
typescript
|
export class TestBase extends Base {
|
import { StdioOptions } from 'child_process'
import { FinalResults } from 'tap-parser'
import { BaseOpts } from '../base.js'
import { Spawn } from '../spawn.js'
import { TapPlugin, TestBase } from '../test-base.js'
export interface SpawnOpts extends BaseOpts {
cwd?: string
command?: string
args?: string[]
stdio?: StdioOptions
env?: { [k: string]: string } | typeof process.env
exitCode?: number | null
signal?: string | null
}
class SpawnPlugin {
#t: TestBase
constructor(t: TestBase) {
this.#t = t
}
spawn(cmd: string): Promise<FinalResults | null>
spawn(
cmd: string,
options: SpawnOpts,
name?: string
): Promise<FinalResults | null>
spawn(
cmd: string,
args: string | string[],
name?: string
): Promise<FinalResults | null>
spawn(
cmd: string,
args: string | string[],
options: SpawnOpts,
name?: string
): Promise<FinalResults | null>
spawn(
cmd: string,
args?: string | string[] | SpawnOpts,
options?: SpawnOpts | string,
name?: string
): Promise<FinalResults | null> {
if (typeof args === 'string') {
args = [args]
}
if (typeof options === 'string') {
name = options
options = {}
}
if (typeof args === 'object' && !Array.isArray(args)) {
options = args
args = []
}
options = options || {}
if (options.name === undefined) {
options.name = name
}
options.command = cmd
options.args = args
|
return this.#t.sub(Spawn, options, this.spawn)
}
|
}
const plugin: TapPlugin<SpawnPlugin> = (t: TestBase) =>
new SpawnPlugin(t)
export default plugin
|
src/plugin/spawn.ts
|
tapjs-core-edd7403
|
[
{
"filename": "src/spawn.ts",
"retrieved_chunk": " }\n options = options || {}\n const cwd =\n typeof options.cwd === 'string'\n ? options.cwd\n : process.cwd()\n const args = options.args || []\n options.name =\n options.name || Spawn.procName(cwd, command, args)\n super(options)",
"score": 0.9080370664596558
},
{
"filename": "src/spawn.ts",
"retrieved_chunk": " public args: string[]\n public stdio: StdioOptions\n public env: { [k: string]: string } | typeof process.env\n public proc: null | ChildProcess\n public cb: null | (() => void)\n constructor(options: SpawnOpts) {\n // figure out the name before calling super()\n const command = options.command\n if (!command) {\n throw new TypeError('no command provided')",
"score": 0.8541330099105835
},
{
"filename": "src/spawn.ts",
"retrieved_chunk": " args?: string[]\n stdio?: StdioOptions\n env?: { [k: string]: string } | typeof process.env\n exitCode?: number | null\n signal?: string | null\n}\nexport class Spawn extends Base {\n public declare options: SpawnOpts\n public cwd: string\n public command: string",
"score": 0.85309237241745
},
{
"filename": "src/spawn.ts",
"retrieved_chunk": " this.cwd = cwd\n this.command = command\n this.args = args\n if (options.stdio) {\n if (typeof options.stdio === 'string')\n this.stdio = [options.stdio, 'pipe', options.stdio]\n else {\n this.stdio = options.stdio.slice(0) as StdioOptions\n }\n } else {",
"score": 0.8342404365539551
},
{
"filename": "src/plugin/stdin.ts",
"retrieved_chunk": " name = undefined\n }\n extra = parseTestArgs<Stdin>(\n name,\n extra,\n false,\n '/dev/stdin'\n )\n return this.#t.sub(Stdin, extra, this.stdin)\n }",
"score": 0.8341341018676758
}
] |
typescript
|
return this.#t.sub(Spawn, options, this.spawn)
}
|
// ok, so, export the root PluginBase, PluginHost, and the Base
// Both have the stream stuff, and basic TAP parser stuff
// PluginHost has all the default assertions, so a Plugin can
// do stuff like `return t.ok()`
// Base is a parent of PluginBase, and used for stuff like Spawn,
// Stdin, and Worker subclasses
//
// tap.Test is extended from the generated source, so it has all plugins
/*
## Class heirarchy
Base - streaming, parsing, test status, config loading
+-- Spawn - run a child proc, consume output as tap stream
+-- Stdin - consume stdin as tap stream
+-- Worker - run a worker thread, consume output as tap stream
+-- TestBase - generate tap stream, built-in set of assertions
+-- (builtin plugins...) - add functions for spawn, assertions, snapshot, mock, etc
+-- (user plugins...) - whatever the config says to load
+-- Test - the test class exposed to user
+-- TAP - the root test runner
*/
import Domain from 'async-hook-domain'
import { AsyncResource } from 'async_hooks'
import Minipass, {
ContiguousData,
Encoding,
} from 'minipass'
import { hrtime } from 'node:process'
import { format } from 'node:util'
import {
FinalResults,
Parser,
Result,
TapError,
} from 'tap-parser'
import Deferred from 'trivial-deferred'
import extraFromError from './extra-from-error'
export class TapWrap extends AsyncResource {
test: Base
constructor(test: Base) {
super(`tap.${test.constructor.name}`)
this.test = test
}
}
export class Counts {
total: number = 0
pass: number = 0
fail: number = 0
skip: number = 0
todo: number = 0
}
export class Lists {
fail: Result[] = []
todo: Result[] = []
skip: Result[] = []
pass: Result[] = []
}
const debug =
(name: string) =>
(...args: any[]) => {
const prefix = `TAP ${process.pid} ${name}: `
const msg = format(...args).trim()
console.error(
prefix + msg.split('\n').join(`\n${prefix}`)
)
}
export interface BaseOpts {
// parser-related options
bail?: boolean
strict?: boolean
omitVersion?: boolean
preserveWhitespace?: boolean
skip?: boolean | string
todo?: boolean | string
timeout?: number
time?: number
tapChildBuffer?: string
stack?: string
// basically only set when running in this project
stackIncludesTap?: boolean
parent?: Base
name?: string
childId?: number
context?: any
indent?: string
debug?: boolean
parser?: Parser
buffered?: boolean
silent?: boolean
}
export class Base {
stream: Minipass<string> = new Minipass<string>({
encoding: 'utf8',
})
readyToProcess: boolean = false
options: BaseOpts
indent: string
hook: TapWrap
// this actually is deterministically set in the ctor, but
// in the hook, so tsc doesn't see it.
hookDomain!: Domain
timer?: NodeJS.Timeout
parser: Parser
debug: (...args: any[]) => void
counts: Counts
lists: Lists
name: string
results?: FinalResults
parent?: Base
bail: boolean
strict: boolean
omitVersion: boolean
preserveWhitespace: boolean
errors: TapError[]
childId: number
context: any
output: string
buffered: boolean
bailedOut: string | boolean
start: bigint
time: number
hrtime: bigint
silent: boolean
deferred?: Deferred<FinalResults>
constructor(options: BaseOpts = {}) {
// all tap streams are sync string minipasses
this.hook = new TapWrap(this)
this.options = options
this.counts = new Counts()
this.lists = new Lists()
this.silent = !!options.silent
// if it's null or an object, inherit from it. otherwise, copy it.
const ctx = options.context
if (ctx !== undefined) {
this.context =
typeof ctx === 'object' ? Object.create(ctx) : ctx
} else {
this.context = null
}
this.bail = !!options.bail
this.strict = !!options.strict
this.omitVersion = !!options.omitVersion
this.preserveWhitespace = !!options.preserveWhitespace
this.buffered = !!options.buffered
this.bailedOut = false
this.errors = []
this.parent = options.parent
this.time = 0
this.hrtime = 0n
this.start = 0n
this.childId = options.childId || 0
// do we need this? couldn't we just call the Minipass
this.output = ''
this.indent = options.indent || ''
this.name = options.name || '(unnamed test)'
this.hook.runInAsyncScope(
() =>
(this.hookDomain = new Domain((er, type) => {
if (!er || typeof er !== 'object')
er = { error: er }
er.tapCaught = type
this.threw(er)
}))
)
this.debug = !!options.debug
? debug(this.name)
: () => {}
this.parser =
options.parser ||
new Parser({
bail: this.bail,
strict: this.strict,
omitVersion: this.omitVersion,
preserveWhitespace: this.preserveWhitespace,
name: this.name,
})
this.setupParser()
// ensure that a skip or todo on a child class reverts
// back to Base's no-op main.
if (options.skip || options.todo) {
this.main = Base.prototype.main
}
}
setupParser() {
this.parser.on('line', l => this.online(l))
this.parser.once('bailout', reason =>
this.onbail(reason)
)
this.parser.on('complete', result =>
this.oncomplete(result)
)
this.parser.on('result', () => this.counts.total++)
this.parser.on('pass', () => this.counts.pass++)
this.parser.on('todo', res => {
this.counts.todo++
this.lists.todo.push(res)
})
this.parser.on('skip', res => {
// it is uselessly noisy to print out lists of tests skipped
// because of a --grep or --only argument.
if (/^filter: (only|\/.*\/)$/.test(res.skip)) return
this.counts.skip++
this.lists.skip.push(res)
})
this.parser.on('fail', res => {
this.counts.fail++
this.lists.fail.push(res)
})
}
setTimeout(n: number) {
if (n <= 0) {
if (this.timer) {
clearTimeout(this.timer)
}
this.timer = undefined
} else {
this.timer = setTimeout(() => this.timeout(), n)
this.timer.unref()
}
}
timeout(options?: { [k: string]: any }) {
this.setTimeout(0)
options = options || {}
options.expired = options.expired || this.name
const threw = this.threw(new Error('timeout!'), options)
if (threw) {
this.emit('timeout', threw)
}
}
runMain(cb: () => void) {
this.debug('BASE runMain')
this.start = hrtime.bigint()
this.hook.runInAsyncScope(this.main, this, cb)
}
main(cb: () => void) {
cb()
}
onbail(reason?: string) {
this.bailedOut = reason || true
this.emit('bailout', reason)
}
online(line: string) {
this.debug('LINE %j', line, [this.name, this.indent])
return this.write(this.indent + line)
}
write(
c: ContiguousData,
e?: Encoding | (() => any),
cb?: () => any
) {
if (this.buffered) {
this.output += c
return true
}
if (typeof e === 'function') {
cb = e
e = undefined
}
return this.stream.write(
c,
e as Encoding | undefined,
cb
)
}
oncomplete(results: FinalResults) {
if (this.start) {
this.hrtime = hrtime.bigint() - this.start
this.time =
results.time || Number(this.hrtime / 1000n)
}
this.debug('ONCOMPLETE %j %j', this.name, results)
if (this.results) {
Object.assign(results, this.results)
}
this.results = results
this.emit('complete', results)
const errors = results.failures
.filter(f => f.tapError)
.map(f => {
delete f.diag
delete f.ok
return f
})
if (errors.length) {
this.errors = errors
}
this.onbeforeend()
// XXX old tap had a check here to ensure that buffer and pipes
// are cleared. But Minipass "should" do this now for us, so
// this ought to be fine, but revisit if it causes problems.
this.stream.end()
}
// extension points for Test, Spawn, etc.
onbeforeend() {}
ondone() {}
once(ev: string, handler: (...a: any[]) => any) {
return this.stream.once(ev, handler)
}
on(ev: string, handler: (...a: any[]) => any) {
return this.stream.on(ev, handler)
}
emit(ev: string, ...data: any[]) {
const ret = this.stream.emit(ev, ...data)
if (ev === 'end') {
this.ondone()
this.hook.emitDestroy()
this.hookDomain.destroy()
}
return ret
}
end() {
this.stream.end()
return this
}
threw(er: any, extra?: any, proxy?: boolean) {
this.hook.emitDestroy()
this.hookDomain.destroy()
if (typeof er === 'string') {
er = { message: er }
} else if (!er || typeof er !== 'object') {
er = { error: er }
}
if (this.name && !proxy) {
er.test = this.name
}
const message = er.message
if (!extra) {
extra
|
= extraFromError(er, extra, this.options)
}
|
// if we ended, we have to report it SOMEWHERE, unless we're
// already in the process of bailing out, in which case it's
// a bit excessive.
if (this.results) {
const alreadyBailing = !this.results.ok && this.bail
this.results.ok = false
if (this.parent) {
this.parent.threw(er, extra, true)
} else if (alreadyBailing) {
// we are already bailing out, and this is the top level,
// just make our way hastily to the nearest exit.
return
} else if (!er.stack) {
console.error(er)
} else {
if (message) {
er.message = message
}
delete extra.stack
delete extra.at
console.error('%s: %s', er.name || 'Error', message)
console.error(
er.stack.split(/\n/).slice(1).join('\n')
)
console.error(extra)
}
} else {
this.parser.ok = false
}
return extra
}
passing() {
return this.parser.ok
}
}
|
src/base.ts
|
tapjs-core-edd7403
|
[
{
"filename": "src/extra-from-error.ts",
"retrieved_chunk": " if (!er || typeof er !== 'object') {\n extra.error = er\n return extra\n }\n // pull out error details\n const message = er.message ? er.message\n : er.stack ? er.stack.split('\\n')[0]\n : ''\n if (er.message) {\n try {",
"score": 0.9170312285423279
},
{
"filename": "src/extra-from-error.ts",
"retrieved_chunk": " if (message) {\n try {\n Object.defineProperty(er, 'message', {\n value: message,\n configurable: true\n })\n } catch {}\n }\n if (er.name && er.name !== 'Error') {\n extra.type = er.name",
"score": 0.9157733917236328
},
{
"filename": "src/extra-from-error.ts",
"retrieved_chunk": " }\n Object.assign(extra, Object.fromEntries(Object.entries(er).filter(([k]) =>\n k !== 'message')))\n return extra\n}",
"score": 0.8818786144256592
},
{
"filename": "src/extra-from-error.ts",
"retrieved_chunk": " if (er._babel && er.loc) {\n const msplit = message.split(': ')\n const f = msplit[0].trim()\n extra.message = msplit.slice(1).join(': ')\n .replace(/ \\([0-9]+:[0-9]+\\)$/, '').trim()\n const file = f.indexOf(process.cwd()) === 0\n ? f.substr(process.cwd().length + 1) : f\n if (file !== 'unknown')\n delete er.codeFrame\n extra.at = {",
"score": 0.8614156246185303
},
{
"filename": "src/extra-from-error.ts",
"retrieved_chunk": " Object.defineProperty(er, 'message', {\n value: '',\n configurable: true\n })\n } catch {}\n }\n const st = er.stack && er.stack.substr(\n er._babel ? (message + er.codeFrame).length : 0)\n if (st) {\n const splitst = st.split('\\n')",
"score": 0.8595815896987915
}
] |
typescript
|
= extraFromError(er, extra, this.options)
}
|
import stack from './stack'
import type {BaseOpts} from './base'
export default (er:any, extra?:{[k: string]:any}, options?:BaseOpts) => {
// the yaml module puts big stuff here, pluck it off
if (er.source && typeof er.source === 'object' && er.source.context)
er.source = { ...er.source, context: null }
// pull out all fields from options, other than anything starting
// with tapChild, or anything already set in the extra object.
extra = Object.fromEntries(Object.entries(options || {}).filter(([k]) =>
!/^tapChild/.test(k) && !(k in (extra || {}))))
if (!er || typeof er !== 'object') {
extra.error = er
return extra
}
// pull out error details
const message = er.message ? er.message
: er.stack ? er.stack.split('\n')[0]
: ''
if (er.message) {
try {
Object.defineProperty(er, 'message', {
value: '',
configurable: true
})
} catch {}
}
const st = er.stack && er.stack.substr(
er._babel ? (message + er.codeFrame).length : 0)
if (st) {
const splitst = st.split('\n')
if (er._babel && er.loc) {
const msplit = message.split(': ')
const f = msplit[0].trim()
extra.message = msplit.slice(1).join(': ')
.replace(/ \([0-9]+:[0-9]+\)$/, '').trim()
const file = f.indexOf(process.cwd()) === 0
? f.substr(process.cwd().length + 1) : f
if (file !== 'unknown')
delete er.codeFrame
extra.at = {
file,
line: er.loc.line,
column: er.loc.column + 1,
}
} else {
// parse out the 'at' bit from the first line.
extra
|
.at = stack.parseLine(splitst[1])
}
|
extra.stack = stack.clean(splitst)
}
if (message) {
try {
Object.defineProperty(er, 'message', {
value: message,
configurable: true
})
} catch {}
}
if (er.name && er.name !== 'Error') {
extra.type = er.name
}
Object.assign(extra, Object.fromEntries(Object.entries(er).filter(([k]) =>
k !== 'message')))
return extra
}
|
src/extra-from-error.ts
|
tapjs-core-edd7403
|
[
{
"filename": "src/test-base.ts",
"retrieved_chunk": " extra.at = stack.parseLine(extra.stack.split('\\n')[0])\n }\n if (\n !ok &&\n !extra.skip &&\n !extra.at &&\n typeof fn === 'function'\n ) {\n extra.at = stack.at(fn)\n if (!extra.todo) {",
"score": 0.8947330117225647
},
{
"filename": "src/test-base.ts",
"retrieved_chunk": " }\n if (this.assertAt) {\n extra.at = this.assertAt\n this.assertAt = null\n }\n if (this.assertStack) {\n extra.stack = this.assertStack\n this.assertStack = null\n }\n if (typeof extra.stack === 'string' && !extra.at) {",
"score": 0.8610048294067383
},
{
"filename": "src/clean-yaml-object.ts",
"retrieved_chunk": " const res = { ...object }\n if (hasOwn(res, 'stack') && !hasOwn(res, 'at')) {\n res.at = stack.parseLine(res.stack.split('\\n')[0])\n }\n const file = res.at && res.at.file && resolve(res.at.file)\n if (\n !options.stackIncludesTap &&\n file &&\n file.includes(tapDir)\n ) {",
"score": 0.8383260369300842
},
{
"filename": "src/clean-yaml-object.ts",
"retrieved_chunk": " // don't print locations in tap itself, that's almost never useful\n delete res.at\n }\n if (\n file &&\n res.at &&\n res.at.file &&\n res.at.line &&\n !res.source\n ) {",
"score": 0.8237882852554321
},
{
"filename": "src/base.ts",
"retrieved_chunk": " er.stack.split(/\\n/).slice(1).join('\\n')\n )\n console.error(extra)\n }\n } else {\n this.parser.ok = false\n }\n return extra\n }\n passing() {",
"score": 0.8229725956916809
}
] |
typescript
|
.at = stack.parseLine(splitst[1])
}
|
import { StdioOptions } from 'child_process'
import { FinalResults } from 'tap-parser'
import { BaseOpts } from '../base.js'
import { Spawn } from '../spawn.js'
import { TapPlugin, TestBase } from '../test-base.js'
export interface SpawnOpts extends BaseOpts {
cwd?: string
command?: string
args?: string[]
stdio?: StdioOptions
env?: { [k: string]: string } | typeof process.env
exitCode?: number | null
signal?: string | null
}
class SpawnPlugin {
#t: TestBase
constructor(t: TestBase) {
this.#t = t
}
spawn(cmd: string): Promise<FinalResults | null>
spawn(
cmd: string,
options: SpawnOpts,
name?: string
): Promise<FinalResults | null>
spawn(
cmd: string,
args: string | string[],
name?: string
): Promise<FinalResults | null>
spawn(
cmd: string,
args: string | string[],
options: SpawnOpts,
name?: string
): Promise<FinalResults | null>
spawn(
cmd: string,
args?: string | string[] | SpawnOpts,
options?: SpawnOpts | string,
name?: string
): Promise<FinalResults | null> {
if (typeof args === 'string') {
args = [args]
}
if (typeof options === 'string') {
name = options
options = {}
}
if (typeof args === 'object' && !Array.isArray(args)) {
options = args
args = []
}
options = options || {}
if (options.name === undefined) {
options.name = name
}
options.command = cmd
options.args = args
return this.#t.sub(Spawn, options, this.spawn)
}
}
|
const plugin: TapPlugin<SpawnPlugin> = (t: TestBase) =>
new SpawnPlugin(t)
export default plugin
|
src/plugin/spawn.ts
|
tapjs-core-edd7403
|
[
{
"filename": "src/plugin/stdin.ts",
"retrieved_chunk": "}\nconst plugin: TapPlugin<StdinPlugin> = (t: TestBase) =>\n new StdinPlugin(t)\nexport default plugin",
"score": 0.8710767030715942
},
{
"filename": "src/spawn.ts",
"retrieved_chunk": " }\n options = options || {}\n const cwd =\n typeof options.cwd === 'string'\n ? options.cwd\n : process.cwd()\n const args = options.args || []\n options.name =\n options.name || Spawn.procName(cwd, command, args)\n super(options)",
"score": 0.8657339215278625
},
{
"filename": "src/spawn.ts",
"retrieved_chunk": " args?: string[]\n stdio?: StdioOptions\n env?: { [k: string]: string } | typeof process.env\n exitCode?: number | null\n signal?: string | null\n}\nexport class Spawn extends Base {\n public declare options: SpawnOpts\n public cwd: string\n public command: string",
"score": 0.8573871850967407
},
{
"filename": "src/test-template.ts",
"retrieved_chunk": " return t\n}\nexport class Test extends TestBase {\n constructor(opts: TestOpts) {\n super(opts)\n return applyPlugins(this)\n }\n test(\n name: string,\n extra: { [k: string]: any },",
"score": 0.8451027274131775
},
{
"filename": "src/spawn.ts",
"retrieved_chunk": "import { Base, BaseOpts } from './base'\nimport ProcessInfo from '@tapjs/processinfo'\nimport {\n ChildProcess,\n StdioOptions,\n} from 'node:child_process'\nimport { basename } from 'node:path'\nexport interface SpawnOpts extends BaseOpts {\n cwd?: string\n command?: string",
"score": 0.8409603238105774
}
] |
typescript
|
const plugin: TapPlugin<SpawnPlugin> = (t: TestBase) =>
new SpawnPlugin(t)
export default plugin
|
|
// lifecycle methods like beforeEach, afterEach, teardown
// defined in plugins/lifecycle.ts
import Minipass from 'minipass'
import assert from 'node:assert'
import { hrtime } from 'node:process'
import { Readable } from 'node:stream'
import { format } from 'node:util'
import { CallSiteLike } from 'stack-utils'
import { FinalResults } from 'tap-parser'
import Deferred from 'trivial-deferred'
import { Base, BaseOpts } from './base.js'
import { esc } from './esc.js'
import stack from './stack.js'
import { TestPoint } from './test-point.js'
import { Waiter } from './waiter.js'
const queueEmpty = <T extends TestBase>(t: T) =>
t.queue.length === 0 ||
(t.queue.length === 1 &&
t.queue[0] === 'TAP version 14\n')
export interface ClassOf<T> {
new (): T
}
export type TapPlugin<
B extends Object,
O extends TestBaseOpts | any = any
> = ((t: TestBase, opts: O) => B) | ((t: TestBase) => B)
export interface TestBaseOpts extends BaseOpts {
/**
* The number of jobs to run in parallel. Defaults to 1
*/
jobs?: number
/**
* Test function called when this Test is executed
*/
cb?: (...args: any[]) => any
/**
* Flag to always/never show diagnostics. If unset, then
* diagnostics are shown for failing test points only.
*/
diagnostic?: boolean
}
const normalizeMessageExtra = (
defaultMessage: string,
message?: string | { [k: string]: any },
extra?: { [k: string]: any }
): [string, { [k: string]: any }] => {
if (typeof message === 'string') {
return [message || defaultMessage, extra || {}]
} else {
return [defaultMessage, message || {}]
}
}
/**
* Sigil for implicit end() calls that should not
* trigger an error if the user then calls t.end()
*/
const IMPLICIT = Symbol('implicit end')
/**
* Sigil to put in the queue to signal the end of all things
*/
const EOF = Symbol('EOF')
export type QueueEntry =
| string
| TestPoint
| Base
| typeof EOF
| Waiter
| [method: string, ...args: any[]]
/**
* The TestBaseBase class is the base class for all plugins,
* and eventually thus the Test class.
*
* This implements subtest functionality, TAP stream generation,
* lifecycle events, and only the most basic pass/fail assertions.
*
* All other features are added with plugins.
*/
export class TestBase extends Base {
// NB: generated pluginified Test class needs to declare over this
declare parent?: TestBase
promise?: Promise<any>
jobs: number
// #beforeEnd: [method: string | Symbol, ...args: any[]][] = []
subtests: Base[] = []
pool: Set<Base> = new Set()
queue: QueueEntry[] = ['TAP version 14\n']
cb?: (...args: any[]) => any
count: number = 0
ended: boolean = false
assertAt: CallSiteLike | null = null
assertStack: string | null = null
diagnostic: null | boolean = null
#planEnd: number = -1
#printedResult: boolean = false
#explicitEnded: boolean = false
#multiEndThrew: boolean = false
#n: number = 0
#noparallel: boolean = false
#occupied: null | Waiter | Base = null
#pushedEnd: boolean = false
#nextChildId: number = 1
#currentAssert: null | ((..._: any) => any) = null
#processing: boolean = false
#doingStdinOnly: boolean = false
/**
* true if the test has printed at least one TestPoint
*/
get printedResult(): boolean {
return this.#printedResult
}
constructor(options: TestBaseOpts) {
super(options)
this.jobs =
(options.jobs && Math.max(options.jobs, 1)) || 1
if (typeof options.diagnostic === 'boolean') {
this.diagnostic = options.diagnostic
}
if (options.cb) {
this.#setCB(options.cb)
}
}
#setCB<T extends TestBase>(this: T, cb: (t: T) => any) {
this.cb = (...args: any[]) =>
this.
|
hook.runInAsyncScope(cb, this, ...args)
}
|
// TAP output generating methods
/**
* immediately exit this and all parent tests with a TAP
* Bail out! message.
*/
bailout(message?: string) {
if (this.parent && (this.results || this.ended)) {
this.parent.bailout(message)
} else {
this.#process()
message = message
? ' ' + ('' + esc(message)).trim()
: ''
message = message.replace(/[\r\n]/g, ' ')
this.parser.write('Bail out!' + message + '\n')
}
this.#end(IMPLICIT)
this.#process()
}
/**
* output a TAP comment, formatted like console.log()
*/
comment(...args: any[]) {
const body = format(...args)
const message =
('# ' + body.split(/\r?\n/).join('\n# ')).trim() +
'\n'
if (this.results) {
this.write(message)
} else {
this.queue.push(message)
}
this.#process()
}
/**
* Called when the test times out.
* Options are passed as diagnostics to the threw() method
*/
timeout(options: { [k: string]: any }) {
options = options || {}
options.expired = options.expired || this.name
if (this.#occupied && this.#occupied instanceof Base) {
this.#occupied.timeout(options)
} else {
super.timeout(options)
}
this.#end(IMPLICIT)
}
/**
* Set TAP pragma configs to affect the behavior of the parser.
* Only `strict` is supported by the parser.
*/
pragma(set: { [k: string]: boolean }) {
const p = Object.keys(set).reduce(
(acc, i) =>
acc + 'pragma ' + (set[i] ? '+' : '-') + i + '\n',
''
)
this.queue.push(p)
this.#process()
}
/**
* Specify the number of Test Points expected by this test.
* Outputs a TAP plan line.
*/
plan(n: number, comment?: string) {
if (this.bailedOut) {
return
}
if (this.#planEnd !== -1) {
throw new Error('Cannot set plan more than once')
}
if (typeof n !== 'number' || n < 0) {
throw new TypeError('plan must be a number')
}
// Cannot get any tests after a trailing plan, or a plan of 0
const ending = this.count !== 0 || n === 0
if (n === 0 && comment && !this.options.skip) {
this.options.skip = comment
}
this.#planEnd = n
comment = comment ? ' # ' + esc(comment.trim()) : ''
this.queue.push('1..' + n + comment + '\n')
if (ending) {
this.#end(IMPLICIT)
} else {
this.#process()
}
}
/**
* A passing (ok) Test Point
*/
pass(message?: string, extra?: { [k: string]: any }) {
this.currentAssert = TestBase.prototype.pass
this.printResult(
true,
...normalizeMessageExtra(
'(unnamed test)',
message,
extra
)
)
return true
}
/**
* A failing (not ok) Test Point
*/
fail(message?: string, extra?: { [k: string]: any }) {
this.currentAssert = TestBase.prototype.fail
const [m, e] = normalizeMessageExtra(
'(unnamed test)',
message,
extra
)
this.printResult(false, m, e)
return !!(e.todo || e.skip)
}
/**
* The current assertion being processed. May only be set if
* not already set.
*/
get currentAssert() {
return this.#currentAssert
}
/**
* The current assertion being processed. May only be set if
* not already set.
*/
set currentAssert(fn: null | ((...a: any[]) => any)) {
if (!this.#currentAssert && typeof fn === 'function') {
this.#currentAssert = fn
}
}
/**
* Print a Test Point
*/
printResult(
ok: boolean,
message: string,
extra: { [k: string]: any },
front: boolean = false
) {
this.#printedResult = true
const n = this.count + 1
this.currentAssert = TestBase.prototype.printResult
const fn = this.#currentAssert
this.#currentAssert = null
if (this.#planEnd !== -1 && n > this.#planEnd) {
if (!this.passing()) return
const failMessage = this.#explicitEnded
? 'test after end() was called'
: 'test count exceeds plan'
const er = new Error(failMessage, {
cause: {
test: this.name,
plan: this.#planEnd,
},
})
Error.captureStackTrace(er, fn || undefined)
this.threw(er)
return
}
extra = extra || {}
if (extra.expectFail) {
ok = !ok
}
if (this.assertAt) {
extra.at = this.assertAt
this.assertAt = null
}
if (this.assertStack) {
extra.stack = this.assertStack
this.assertStack = null
}
if (typeof extra.stack === 'string' && !extra.at) {
extra.at = stack.parseLine(extra.stack.split('\n')[0])
}
if (
!ok &&
!extra.skip &&
!extra.at &&
typeof fn === 'function'
) {
extra.at = stack.at(fn)
if (!extra.todo) {
extra.stack = stack.captureString(80, fn)
}
}
const diagnostic =
typeof extra.diagnostic === 'boolean'
? extra.diagnostic
: typeof this.diagnostic === 'boolean'
? this.diagnostic
: extra.skip || extra.todo
? false
: !ok
if (diagnostic) {
extra.diagnostic = true
}
this.count = n
message = message + ''
const res = { ok, message, extra }
const tp = new TestPoint(ok, message, extra)
// when we jump the queue, skip an extra line
if (front) {
tp.message = tp.message.trimEnd() + '\n\n'
}
if (
this.#occupied &&
this.#occupied instanceof Waiter &&
this.#occupied.finishing
) {
front = true
}
if (front) {
if (
extra.tapChildBuffer ||
extra.tapChildBuffer === ''
) {
this.writeSubComment(tp)
this.parser.write(extra.tapChildBuffer)
}
this.emit('result', res)
this.parser.write(tp.ok + ++this.#n + tp.message)
if (this.bail && !ok && !extra.skip && !extra.todo) {
this.parser.write('Bail out! ' + message + '\n')
}
} else {
this.queue.push(tp)
if (this.bail && !ok && !extra.skip && !extra.todo) {
this.queue.push('Bail out! ' + message + '\n')
}
}
if (this.#planEnd === this.count) {
this.#end(IMPLICIT)
}
this.#process()
}
end(): this {
this.#end()
return super.end()
}
/**
* The leading `# Subtest` comment that introduces a child test
*/
writeSubComment<T extends TestPoint | Base>(p: T) {
const comment =
'# Subtest' +
(p.name ? ': ' + esc(p.name) : '') +
'\n'
this.parser.write(comment)
}
// end TAP otput generating methods
// flow control methods
/**
* Await the end of a Promise before proceeding.
* The supplied callback is called with the Waiter object.
*/
waitOn(
promise: Promise<any | void>,
cb: (w: Waiter) => any,
expectReject: boolean = false
): Promise<void> {
const w = new Waiter(
promise,
w => {
assert.equal(this.#occupied, w)
cb(w)
this.#occupied = null
this.#process()
},
expectReject
)
this.queue.push(w)
this.#process()
return w.promise
}
#end(implicit?: typeof IMPLICIT) {
if (this.#doingStdinOnly && implicit !== IMPLICIT)
throw new Error(
'cannot explicitly end while in stdinOnly mode'
)
this.debug('END implicit=%j', implicit === IMPLICIT)
if (this.ended && implicit === IMPLICIT) return
// beyond here we have to be actually done with things, or else
// the semantic checks on counts and such will be off.
if (!queueEmpty(this) || this.#occupied) {
if (!this.#pushedEnd) {
this.queue.push(['#end', implicit])
}
this.#pushedEnd = true
return this.#process()
}
this.ended = true
if (implicit !== IMPLICIT && !this.#multiEndThrew) {
if (this.#explicitEnded) {
this.#multiEndThrew = true
const er = new Error(
'test end() method called more than once'
)
Error.captureStackTrace(
er,
this.#currentAssert || this.#end
)
er.cause = {
test: this.name,
}
this.threw(er)
return
}
this.#explicitEnded = true
}
if (this.#planEnd === -1) {
this.debug(
'END(%s) implicit plan',
this.name,
this.count
)
this.plan(this.count)
}
this.queue.push(EOF)
this.#process()
}
#process() {
if (this.#processing) {
return this.debug(' < already processing')
}
this.debug(
'\nPROCESSING(%s)',
this.name,
this.queue.length
)
this.#processing = true
while (!this.#occupied) {
const p = this.queue.shift()
if (!p) {
this.debug('> end of queue')
break
}
if (p instanceof Base) {
this.debug('> subtest in queue', p.name)
this.#processSubtest(p)
} else if (p === EOF) {
this.debug(' > EOF', this.name)
// I AM BECOME EOF, DESTROYER OF STREAMS
this.parser.end()
} else if (p instanceof TestPoint) {
this.debug(' > TESTPOINT')
if (
p.extra.tapChildBuffer ||
p.extra.tapChildBuffer === ''
) {
this.writeSubComment(p)
this.parser.write(p.extra.tapChildBuffer)
}
this.emit('res', p.res)
this.parser.write(p.ok + ++this.#n + p.message)
} else if (typeof p === 'string') {
this.debug(' > STRING')
this.parser.write(p)
} else if (p instanceof Waiter) {
p.ready = true
this.#occupied = p
p.finish()
} else if (Array.isArray(p)) {
this.debug(' > METHOD')
const m = p.shift() as keyof this
if (typeof this[m] !== 'function') {
this.debug(
' > weird method not found in queue??',
m,
typeof this[m]
)
continue
}
const fn = (m === '#end' ? this.#end : this[m]) as (
...a: any[]
) => any
const ret = fn.call(this, ...p)
if (
ret &&
typeof ret === 'object' &&
typeof ret.then === 'function'
) {
// returned promise
ret.then(
() => {
this.#processing = false
this.#process()
},
(er: unknown) => {
this.#processing = false
this.threw(er)
}
)
return
}
/* c8 ignore start */
} else {
throw new Error('weird thing got in the queue')
}
/* c8 ignore stop */
}
while (
!this.#noparallel &&
this.pool.size < this.jobs
) {
const p = this.subtests.shift()
if (!p) {
break
}
if (!p.buffered) {
this.#noparallel = true
break
}
this.debug('start subtest', p)
this.emit('subtestStart', p)
this.pool.add(p)
if (this.bailedOut) {
this.#onBufferedEnd(p)
} else {
p.runMain(() => this.#onBufferedEnd(p))
}
}
this.debug(
'done processing',
this.queue,
this.#occupied
)
this.#processing = false
// just in case any tests ended, and we have sync stuff still
// waiting around in the queue to be processed
if (!this.#occupied && this.queue.length) {
this.#process()
}
}
#onBufferedEnd<T extends Base>(p: T) {
p.ondone = p.constructor.prototype.ondone
p.results =
p.results || new FinalResults(true, p.parser)
p.readyToProcess = true
const to = p.options.timeout
const dur =
to && p.passing() ? hrtime.bigint() - p.start : null
if (dur && to && dur > to) {
p.timeout()
} else {
p.setTimeout(0)
}
this.debug(
'%s.#onBufferedEnd',
this.name,
p.name,
p.results.bailout
)
this.pool.delete(p)
p.options.tapChildBuffer = p.output || ''
p.options.stack = ''
if (p.time) p.options.time = p.time
if (this.#occupied === p) this.#occupied = null
p.deferred?.resolve(p.results)
this.emit('subtestEnd', p)
this.#process()
}
#onIndentedEnd<T extends Base>(p: T) {
this.emit('subtestProcess', p)
p.ondone = p.constructor.prototype.ondone
p.results =
p.results || new FinalResults(true, p.parser)
this.debug('#onIndentedEnd', this.name, p.name)
this.#noparallel = false
const sti = this.subtests.indexOf(p)
if (sti !== -1) this.subtests.splice(sti, 1)
p.readyToProcess = true
p.options.time = p.time
const to = p.options.timeout
const dur =
to && p.passing() ? hrtime.bigint() - p.start : null
if (dur && to && dur > to) {
p.timeout()
} else {
p.setTimeout(0)
}
this.debug('#onIndentedEnd %s(%s)', this.name, p.name)
this.#occupied = null
this.debug(
'OIE(%s) b>shift into queue',
this.name,
this.queue
)
p.options.stack = ''
this.printResult(p.passing(), p.name, p.options, true)
this.debug(
'OIE(%s) shifted into queue',
this.name,
this.queue
)
p.deferred?.resolve(p.results)
this.emit('subtestEnd', p)
this.#process()
}
/**
* @internal
*/
main(cb: () => void) {
if (typeof this.options.timeout === 'number') {
this.setTimeout(this.options.timeout)
}
this.debug('MAIN pre', this)
const end = () => {
this.debug(' > implicit end for promise')
this.#end(IMPLICIT)
done()
}
const done = (er?: Error) => {
if (er) this.threw(er)
if (this.results || this.bailedOut) cb()
else this.ondone = () => cb()
}
// This bit of overly clever line-noise wraps the call to user-code
// in a try-catch. We can't rely on the domain for this yet, because
// the 'end' event can trigger a throw after the domain is unhooked,
// but before this is no longer the official "active test"
const ret = (() => {
if (!this.cb) return
try {
return this.cb(this)
} catch (er: any) {
if (!er || typeof er !== 'object') {
er = { error: er }
}
er.tapCaught = 'testFunctionThrow'
this.threw(er)
}
})()
if (ret && ret.then) {
this.promise = ret
ret.tapAbortPromise = done
ret.then(end, (er: any) => {
if (!er || typeof er !== 'object') {
er = { error: er }
}
er.tapCaught = 'returnedPromiseRejection'
done(er)
})
} else done()
this.debug('MAIN post', this)
}
#processSubtest<T extends Base>(p: T) {
this.debug(' > subtest')
this.#occupied = p
if (!p.buffered) {
this.emit('subtestStart', p)
this.debug(' > subtest indented')
p.stream.pipe(this.parser, { end: false })
this.writeSubComment(p)
this.debug('calling runMain', p.runMain.toString())
p.runMain(() => {
this.debug('in runMain', p.runMain.toString())
this.#onIndentedEnd(p)
})
} else if (p.readyToProcess) {
this.emit('subtestProcess', p)
this.debug(' > subtest buffered, finished')
// finished! do the thing!
this.#occupied = null
if (!p.passing() || !p.silent) {
this.printResult(
p.passing(),
p.name,
p.options,
true
)
}
} else {
this.#occupied = p
this.debug(' > subtest buffered, unfinished', p)
// unfinished buffered test.
// nothing to do yet, just leave it there.
this.queue.unshift(p)
}
}
/**
* Parse stdin as the only tap stream (ie, not as a child test)
* If used, then no other subtests or assertions are allowed.
*/
stdinOnly<T extends BaseOpts>(
extra?: T & { tapStream?: Readable | Minipass }
) {
const stream = ((extra && extra.tapStream) ||
process.stdin) as Minipass
if (!stream) {
throw new Error(
'cannot read stdin without stdin stream'
)
}
if (
this.queue.length !== 1 ||
this.queue[0] !== 'TAP version 14\n' ||
this.#processing ||
this.results ||
this.#occupied ||
this.pool.size ||
this.subtests.length
) {
throw new Error(
'Cannot use stdinOnly on a test in progress'
)
}
this.#doingStdinOnly = true
this.queue.length = 0
this.parser.on('child', p => {
// pretend to be a rooted parser, so it gets counts.
p.root = p
const t = new Base({
name: p.name,
parent: this,
parser: p,
bail: p.bail,
strict: p.strict,
omitVersion: p.omitVersion,
preserveWhitespace: p.preserveWhitespace,
childId: this.#nextChildId++,
})
this.emit('subtestAdd', t)
this.emit('subtestStart', t)
this.emit('subtestProcess', t)
p.on('complete', () => {
t.time = p.time
this.emit('subtestEnd', t)
})
})
stream.pause()
stream.pipe(this.parser)
stream.resume()
}
/**
* Mount a subtest, using this Test object as a harness.
* Exposed mainly so that it can be used by builtin plugins.
*
* @internal
*/
sub<T extends Base, O extends TestBaseOpts>(
Class: { new (options: O): T },
extra: O,
caller: (...a: any[]) => unknown
): Promise<FinalResults | null> {
if (this.bailedOut) return Promise.resolve(null)
if (this.results || this.ended) {
const er = new Error(
'cannot create subtest after parent test ends'
)
Error.captureStackTrace(er, caller)
this.threw(er)
return Promise.resolve(null)
}
extra.childId = this.#nextChildId++
if (this.shouldSkipChild(extra)) {
this.pass(extra.name, extra)
return Promise.resolve(null)
}
extra.indent = ' '
if (extra.buffered !== undefined) {
if (this.jobs > 1) {
extra.buffered = true
} else {
extra.buffered = false
}
}
extra.bail =
extra.bail !== undefined ? extra.bail : this.bail
extra.parent = this
extra.stack = stack.captureString(80, caller)
extra.context = this.context
const t = new Class(extra)
this.queue.push(t)
this.subtests.push(t)
this.emit('subtestAdd', t)
const d = new Deferred<FinalResults>()
t.deferred = d
this.#process()
return d.promise
}
/**
* Return true if the child test represented by the options object
* should be skipped. Extended by the grep/only filtering plugins.
*/
shouldSkipChild(extra: { [k: string]: any }) {
return !!(extra.skip || extra.todo)
}
// end flow control methods
}
|
src/test-base.ts
|
tapjs-core-edd7403
|
[
{
"filename": "src/plugin/before-each.ts",
"retrieved_chunk": " const runMain = t.runMain\n t.runMain = (cb: () => void) => {\n this.#runBeforeEach(this.#t, () =>\n runMain.call(t, cb)\n )\n }\n }\n #onBeforeEach: ((t: Test) => void)[] = []\n beforeEach(fn: (t: Test) => void | Promise<void>) {\n this.#onBeforeEach.push(fn)",
"score": 0.8835166692733765
},
{
"filename": "src/plugin/after-each.ts",
"retrieved_chunk": " t.runMain = (cb: () => void) => {\n runMain.call(t, () => this.#runAfterEach(this.#t, cb))\n }\n }\n #onAfterEach: ((t: Test) => void)[] = []\n afterEach(fn: (t: Test) => void | Promise<void>) {\n this.#onAfterEach.push(fn)\n }\n #runAfterEach(who: TestBase, cb: () => void) {\n // run all the afterEach methods from the parent",
"score": 0.8706673383712769
},
{
"filename": "src/base.ts",
"retrieved_chunk": " this.setTimeout(0)\n options = options || {}\n options.expired = options.expired || this.name\n const threw = this.threw(new Error('timeout!'), options)\n if (threw) {\n this.emit('timeout', threw)\n }\n }\n runMain(cb: () => void) {\n this.debug('BASE runMain')",
"score": 0.8702621459960938
},
{
"filename": "src/plugin/after-each.ts",
"retrieved_chunk": " cb()\n }\n }\n if (who !== this.#t) {\n loop(this.#onAfterEach, run, onerr)\n } else {\n run()\n }\n }\n}",
"score": 0.8509039878845215
},
{
"filename": "src/test-built.ts",
"retrieved_chunk": " constructor(opts: TestOpts) {\n super(opts)\n return applyPlugins(this)\n }\n test(\n name: string,\n extra: { [k: string]: any },\n cb?: (t: Test) => any\n ): Promise<FinalResults | null>\n test(",
"score": 0.8450369834899902
}
] |
typescript
|
hook.runInAsyncScope(cb, this, ...args)
}
|
import Bag from './services/bag/bag';
import Dispatcher from './services/dispatcher/dispatcher';
import RequestFactory from './services/request/factory';
import Extensions from './extensions';
import { defaultParameters } from './parameters';
import type Event from './events/event';
import type Request from './services/request/request';
import type { KlientRequestConfig } from './services/request/request';
import type { Callback } from './services/dispatcher/dispatcher';
import type { Parameters } from './parameters';
export default class Klient<P extends Parameters = Parameters> {
readonly extensions: string[] = [];
readonly parameters = new Bag(defaultParameters);
readonly services = new Bag();
constructor(urlOrParams?: P | string) {
let parameters: Parameters = {};
if (typeof urlOrParams === 'string') {
parameters.url = urlOrParams;
} else if (urlOrParams && typeof urlOrParams === 'object') {
parameters = urlOrParams;
}
this.parameters.merge(parameters);
// prettier-ignore
this.services
.set('klient', this)
.set('dispatcher', new Dispatcher(this))
.set('factory', new RequestFactory(this));
this.load(this.parameters.get('extensions') as string[] | undefined);
}
/** === Common parameters === */
get url(): string | undefined {
return this.parameters.get('url');
}
get debug(): boolean {
return Boolean(this.parameters.get('debug'));
}
/** === Common services === */
get factory(): RequestFactory {
return this.services.get('factory') as RequestFactory;
}
get dispatcher(): Dispatcher {
return this.services.get('dispatcher') as Dispatcher;
}
/** === Extensions === */
extends(property: string, value: unknown, writable = false): this {
return Object.defineProperty(this, property, { writable, value });
}
load(names?: string[]): this {
Extensions.load(this, names);
return this;
}
/** === Dispatcher/Events === */
on<T extends Event>(event: string, callback: Callback<T>, priority = 0, once = false): this {
this.dispatcher.on(event, callback, priority, once);
return this;
}
once<T extends Event>(event: string, callback: Callback<T>, priority = 0): this {
this.dispatcher.once(event, callback, priority);
return this;
}
off<T extends Event>(event: string, callback: Callback<T>): this {
this.dispatcher.off(event, callback);
return this;
}
/** === Request === */
request<T = unknown>(urlOrConfig: KlientRequestConfig | string): Request<T> {
return this.factory.request(urlOrConfig);
}
|
get<T = unknown>(url: string, config?: KlientRequestConfig): Request<T> {
|
return this.request<T>({ ...config, method: 'GET', url });
}
post<T = unknown>(url: string, data: unknown, config?: KlientRequestConfig): Request<T> {
return this.request<T>({ ...config, method: 'POST', url, data });
}
put<T = unknown>(url: string, data: unknown, config?: KlientRequestConfig): Request<T> {
return this.request<T>({ ...config, method: 'PUT', url, data });
}
patch<T = unknown>(url: string, data: unknown, config?: KlientRequestConfig): Request<T> {
return this.request<T>({ ...config, method: 'PATCH', url, data });
}
delete<T = unknown>(url: string, config?: KlientRequestConfig): Request<T> {
return this.request<T>({ ...config, method: 'DELETE', url });
}
head<T = unknown>(url: string, config?: KlientRequestConfig): Request<T> {
return this.request<T>({ ...config, method: 'HEAD', url });
}
options<T = unknown>(url: string, config?: KlientRequestConfig): Request<T> {
return this.request<T>({ ...config, method: 'OPTIONS', url });
}
file(urlOrConfig: KlientRequestConfig | string): Promise<Blob> {
return this.factory.file(urlOrConfig);
}
cancelPendingRequests(): this {
this.factory.cancelPendingRequests();
return this;
}
isCancel(e: Error) {
return this.factory.isCancel(e);
}
}
|
src/klient.ts
|
klientjs-core-9a67a61
|
[
{
"filename": "src/klient.d.ts",
"retrieved_chunk": " request<T = unknown>(urlOrConfig: KlientRequestConfig | string): Request<T>;\n get<T = unknown>(url: string, config?: KlientRequestConfig): Request<T>;\n post<T = unknown>(url: string, data: unknown, config?: KlientRequestConfig): Request<T>;\n put<T = unknown>(url: string, data: unknown, config?: KlientRequestConfig): Request<T>;\n patch<T = unknown>(url: string, data: unknown, config?: KlientRequestConfig): Request<T>;\n delete<T = unknown>(url: string, config?: KlientRequestConfig): Request<T>;\n head<T = unknown>(url: string, config?: KlientRequestConfig): Request<T>;\n options<T = unknown>(url: string, config?: KlientRequestConfig): Request<T>;\n file(urlOrConfig: KlientRequestConfig | string): Promise<Blob>;\n cancelPendingRequests(): this;",
"score": 0.9057790040969849
},
{
"filename": "src/services/request/factory.ts",
"retrieved_chunk": " request<T = unknown>(urlOrConfig: KlientRequestConfig | string): Request<T> {\n return this.createRequest<T>(urlOrConfig).execute();\n }\n file(urlOrConfig: KlientRequestConfig | string): Promise<Blob> {\n const config = deepmerge(\n { responseType: 'blob', context: { action: 'file' } },\n typeof urlOrConfig === 'string' ? { url: urlOrConfig } : urlOrConfig\n );\n return this.request<Blob>(config).then(({ data }) => data);\n }",
"score": 0.8928372263908386
},
{
"filename": "src/services/request/factory.ts",
"retrieved_chunk": " cancelPendingRequests(): this {\n for (let i = 0, len = this.requests.length; i < len; i += 1) {\n this.requests[i].cancel();\n }\n return this;\n }\n createRequest<T = unknown>(urlOrConfig: KlientRequestConfig | string): Request<T> {\n const config = typeof urlOrConfig === 'string' ? { url: urlOrConfig } : urlOrConfig;\n const request = this.model.new<T>(this.prepare(config), this.klient);\n // Store request during pending state only",
"score": 0.8826927542686462
},
{
"filename": "src/events/request/request.ts",
"retrieved_chunk": "import Event from '../event';\nimport type Request from '../../services/request/request';\nimport type { KlientRequestConfig } from '../../services/request/request';\nexport default class RequestEvent<T = unknown> extends Event {\n static NAME = 'request';\n constructor(public request: Request<T>) {\n super();\n }\n get config(): KlientRequestConfig {\n return this.request.config;",
"score": 0.8796799182891846
},
{
"filename": "src/services/request/factory.d.ts",
"retrieved_chunk": " constructor(klient: Klient);\n request<T = unknown>(urlOrConfig: KlientRequestConfig | string): Request<T>;\n file(urlOrConfig: KlientRequestConfig | string): Promise<Blob>;\n cancelPendingRequests(): this;\n createRequest<T = unknown>(urlOrConfig: KlientRequestConfig | string): Request<T>;\n isCancel(e: Error): any;\n protected prepare(config: KlientRequestConfig): KlientRequestConfig;\n protected removePendingRequest(request: Request): void;\n}\nexport {};",
"score": 0.8783963918685913
}
] |
typescript
|
get<T = unknown>(url: string, config?: KlientRequestConfig): Request<T> {
|
import Event from '../../events/event';
import DebugEvent from '../../events/debug';
import Listener from './listener';
import type Klient from '../../klient';
export type Callback<T extends Event> = (e: T) => Promise<void> | void;
export type Listeners = { [event: string]: Listener<never>[] };
export default class Dispatcher {
readonly listeners: Listeners = {};
constructor(protected readonly klient: Klient) {}
on<T extends Event>(event: string, callback: Callback<T>, priority = 0, once = false): this {
// Avoid duplication
if (this.findListenerIndex(event, callback) !== undefined) {
return this;
}
// Initialize listeners collection if not exists
this.listeners[event] = this.listeners[event] || [];
// Get reference to array containing listeners
const listeners = this.listeners[event];
// Build listener id (incremental)
const id = listeners.length ? Math.max(...listeners.map((l) => l.id)) + 1 : 0;
// Register the listener
listeners.push(new Listener(callback, priority, once, id));
// Listener are sorted in order they are defined
listeners.sort((a, b) => b.id - a.id);
// Sort by priority listeners binded to same event
// Lower priorities are first because we loop on collection from the end (see dispatch method)
listeners.sort((a, b) => a.priority - b.priority);
return this;
}
once<T extends Event>(event: string, callback: Callback<T>, priority = 0): this {
return this.on(event, callback, priority, true);
}
off<T extends Event>(event: string, callback: Callback<T>): this {
const index = this.findListenerIndex(event, callback);
if (index !== undefined) {
this.listeners[event].splice(index, 1);
}
return this;
}
/**
* Invoke all listeners attached to given event.
*
* @param abortOnFailure - Specify if listener failures must abort dispatch process.
*/
async dispatch(e: Event, abortOnFailure = true): Promise<void> {
const event = (e.constructor as typeof Event).NAME;
const listeners = this.listeners[event] || [];
this.debug('start', e, listeners);
// Use inverse loop because we need to remove listeners callable once
for (let i = listeners.length - 1, listener = null; i >= 0; i -= 1) {
listener = listeners[i];
if (Dispatcher.handleListenerSkipping(e, listener)) {
this.debug('skipped', e, listener);
continue;
}
if (listener.once) {
this.listeners[event].splice(i, 1);
}
try {
this.debug('invoking', e, listener);
// Wait for listener whose return a promise
await listener.invoke(e as never); // eslint-disable-line no-await-in-loop
this.debug('invoked', e, listener);
} catch (err) {
this.debug('failed', e, listener, err as Error);
if (abortOnFailure) {
// Reject promise on "abort on listener failure" strategy
return Promise.reject(err);
}
}
if (!e.dispatch.propagation) {
this.debug('stopped', e, listener);
// Stop listeners invokation
break;
}
}
this.debug('end', e, listeners);
return Promise.resolve();
}
protected findListenerIndex<T extends Event>(event: string, callback: Callback<T>): number | undefined {
const listeners = this.listeners[event] || [];
for (let i = 0, len = listeners.length; i < len; i += 1) {
if (listeners[i].callback === callback) {
return i;
}
}
return undefined;
}
protected static handleListenerSkipping(event: Event, listener: Listener<never>): boolean | void {
const { skipNextListeners, skipUntilListener } = event.dispatch;
if (skipNextListeners > 0) {
event.dispatch.skipNextListeners -= 1;
return true;
}
if (skipUntilListener) {
if (listener.id === skipUntilListener) {
event.dispatch.skipUntilListener = undefined;
return;
}
return true;
}
}
protected debug(
action: string,
relatedEvent: Event,
|
handler: Listener<never> | Listener<never>[],
error: Error | null = null
): void {
|
if (relatedEvent instanceof DebugEvent || !this.klient.debug) {
return;
}
this.dispatch(new DebugEvent(action, relatedEvent, handler, error), false);
}
}
|
src/services/dispatcher/dispatcher.ts
|
klientjs-core-9a67a61
|
[
{
"filename": "src/services/dispatcher/dispatcher.d.ts",
"retrieved_chunk": " protected debug(action: string, relatedEvent: Event, handler: Listener<never> | Listener<never>[], error?: Error | null): void;\n}\nexport {};",
"score": 0.9332485198974609
},
{
"filename": "src/events/debug.ts",
"retrieved_chunk": "import Event from './event';\nimport type Listener from '../services/dispatcher/listener';\nexport default class DebugEvent extends Event {\n static NAME = 'debug';\n constructor(\n public action: string,\n public relatedEvent: Event,\n public handler: Listener<never> | Listener<never>[],\n public error: Error | null\n ) {",
"score": 0.896975040435791
},
{
"filename": "src/events/debug.d.ts",
"retrieved_chunk": "import Event from './event';\nimport type Listener from '../services/dispatcher/listener';\nexport default class DebugEvent extends Event {\n action: string;\n relatedEvent: Event;\n handler: Listener<never> | Listener<never>[];\n error: Error | null;\n static NAME: string;\n constructor(action: string, relatedEvent: Event, handler: Listener<never> | Listener<never>[], error: Error | null);\n}",
"score": 0.8889884948730469
},
{
"filename": "src/__tests__/debug.test.ts",
"retrieved_chunk": " const spyInvokingEvent = jest.fn();\n const spyInvokedEvent = jest.fn();\n const spyDispatchStoppedEvent = jest.fn();\n const spyDispatchFailedEvent = jest.fn();\n const spyDispatchEndEvent = jest.fn();\n klient.on('debug', (e: DebugEvent) => {\n switch (e.action) {\n case 'start':\n spyStartDispatchEvent();\n break;",
"score": 0.8054609298706055
},
{
"filename": "src/klient.ts",
"retrieved_chunk": " }\n /** === Dispatcher/Events === */\n on<T extends Event>(event: string, callback: Callback<T>, priority = 0, once = false): this {\n this.dispatcher.on(event, callback, priority, once);\n return this;\n }\n once<T extends Event>(event: string, callback: Callback<T>, priority = 0): this {\n this.dispatcher.once(event, callback, priority);\n return this;\n }",
"score": 0.7844234704971313
}
] |
typescript
|
handler: Listener<never> | Listener<never>[],
error: Error | null = null
): void {
|
import axios from 'axios';
import type { AxiosResponse, AxiosError, AxiosRequestConfig, AxiosPromise } from 'axios';
import RequestEvent from '../../events/request/request';
import RequestSuccessEvent from '../../events/request/success';
import RequestErrorEvent from '../../events/request/error';
import RequestDoneEvent from '../../events/request/done';
import RequestCancelEvent from '../../events/request/cancel';
import type Klient from '../..';
export type ResolveRequest = (response: AxiosResponse) => void;
export type RejectRequest = (error: AxiosError) => void;
export type RequestCallback = (resolve: ResolveRequest, reject: RejectRequest) => void;
type PromiseCallbacks = { resolve: ResolveRequest; reject: RejectRequest };
type RequestEventTypes = typeof RequestSuccessEvent | typeof RequestErrorEvent | typeof RequestCancelEvent;
type RequestContext = Record<string, any>; // eslint-disable-line @typescript-eslint/no-explicit-any
export interface KlientRequestConfig extends AxiosRequestConfig {
context?: RequestContext;
}
/**
* Request is a Promise object able to dispatch events before/after axios execution.
* Theses events allow to access and make action on request config/result at any step of execution.
* The Request will be resolved/rejected only after all events be dispatched.
*
* The events workflow is describe below :
*
* 1) RequestEvent (dispatched with abortOnFailure strategy)
* 2) Axios execution
* 2.1) Optional : RequestCancelEvent - only if request is cancelled (will reject promise and skip next events)
* 3) RequestSuccessEvent OR RequestErrorEvent
* 4) RequestDoneEvent
*/
export default class Request<T = unknown> extends Promise<AxiosResponse<T>> {
context: RequestContext = { action: 'request' };
config: KlientRequestConfig = {};
result?: AxiosError | AxiosResponse;
// Allow override axios execution
handler: (config: AxiosRequestConfig) => AxiosPromise<T> = axios;
protected klient!: Klient;
protected callbacks!: PromiseCallbacks;
protected readonly primaryEvent
|
= new RequestEvent<T>(this);
|
protected readonly abortController = new AbortController();
protected constructor(callback: RequestCallback) {
super(callback);
}
static new<T>({ context, ...axiosConfig }: KlientRequestConfig, klient: Klient): Request<T> {
const callbacks = {} as PromiseCallbacks;
const request = new this<T>((resolve: ResolveRequest, reject: RejectRequest) => {
callbacks.resolve = resolve;
callbacks.reject = reject;
});
request.klient = klient;
request.config = axiosConfig;
request.callbacks = callbacks;
request.config.signal = request.abortController.signal;
request.context = { ...request.context, ...context };
return request;
}
static isCancel(e: Error) {
return axios.isCancel(e);
}
cancel(): this {
this.abortController.abort();
return this;
}
execute(): this {
this.dispatcher
.dispatch(this.primaryEvent)
.then(() => {
this.doRequest();
})
.catch((e) => {
this.reject(e);
});
return this;
}
protected doRequest(): this {
if (!this.result) {
this.handler(this.config)
.then((r) => {
this.resolve(r);
})
.catch((e) => {
this.reject(e);
});
}
return this;
}
protected resolve(response: AxiosResponse<T>): Promise<void> {
this.result = response;
return this.dispatchResultEvent(RequestSuccessEvent).then(() => {
this.callbacks.resolve(this.result as AxiosResponse<T>);
});
}
protected reject(error: AxiosError): Promise<void> {
this.result = error;
return this.dispatchResultEvent(Request.isCancel(error) ? RequestCancelEvent : RequestErrorEvent).then(() => {
this.callbacks.reject(this.result as AxiosError);
});
}
protected dispatchResultEvent(EventClass: RequestEventTypes): Promise<void> {
const event = new EventClass(this.primaryEvent);
return new Promise((resolve) => {
this.dispatcher.dispatch(event, false).then(() => {
if (event instanceof RequestCancelEvent) {
return resolve();
}
this.dispatcher.dispatch(new RequestDoneEvent(event), false).then(resolve);
});
});
}
protected get dispatcher() {
return this.klient.dispatcher;
}
}
|
src/services/request/request.ts
|
klientjs-core-9a67a61
|
[
{
"filename": "src/services/request/request.d.ts",
"retrieved_chunk": "export interface KlientRequestConfig extends AxiosRequestConfig {\n context?: RequestContext;\n}\nexport default class Request<T = unknown> extends Promise<AxiosResponse<T>> {\n context: RequestContext;\n config: KlientRequestConfig;\n result?: AxiosError | AxiosResponse;\n handler: (config: AxiosRequestConfig) => AxiosPromise<T>;\n protected klient: Klient;\n protected callbacks: PromiseCallbacks;",
"score": 0.9479730129241943
},
{
"filename": "src/services/request/request.d.ts",
"retrieved_chunk": " protected readonly primaryEvent: RequestEvent;\n protected readonly abortController: AbortController;\n protected constructor(callback: RequestCallback);\n static new<T>({ context, ...axiosConfig }: KlientRequestConfig, klient: Klient): Request<T>;\n static isCancel(e: Error): boolean;\n cancel(): this;\n execute(): this;\n protected doRequest(): this;\n protected resolve(response: AxiosResponse<T>): Promise<void>;\n protected reject(error: AxiosError): Promise<void>;",
"score": 0.9298792481422424
},
{
"filename": "src/events/request/request.d.ts",
"retrieved_chunk": "import Event from '../event';\nimport type Request from '../../services/request/request';\nimport type { KlientRequestConfig } from '../../services/request/request';\nexport default class RequestEvent<T = unknown> extends Event {\n request: Request<T>;\n static NAME: string;\n constructor(request: Request<T>);\n get config(): KlientRequestConfig;\n get context(): {\n [x: string]: any;",
"score": 0.8990097045898438
},
{
"filename": "src/services/request/request.d.ts",
"retrieved_chunk": "import type { AxiosResponse, AxiosError, AxiosRequestConfig, AxiosPromise } from 'axios';\ndeclare class RequestEvent {\n}\ndeclare class RequestSuccessEvent {\n}\ndeclare class RequestErrorEvent {\n}\ndeclare class RequestCancelEvent {\n}\ndeclare class Klient {",
"score": 0.8966031074523926
},
{
"filename": "src/events/request/request.ts",
"retrieved_chunk": "import Event from '../event';\nimport type Request from '../../services/request/request';\nimport type { KlientRequestConfig } from '../../services/request/request';\nexport default class RequestEvent<T = unknown> extends Event {\n static NAME = 'request';\n constructor(public request: Request<T>) {\n super();\n }\n get config(): KlientRequestConfig {\n return this.request.config;",
"score": 0.8924347162246704
}
] |
typescript
|
= new RequestEvent<T>(this);
|
import Event from '../../events/event';
import DebugEvent from '../../events/debug';
import Listener from './listener';
import type Klient from '../../klient';
export type Callback<T extends Event> = (e: T) => Promise<void> | void;
export type Listeners = { [event: string]: Listener<never>[] };
export default class Dispatcher {
readonly listeners: Listeners = {};
constructor(protected readonly klient: Klient) {}
on<T extends Event>(event: string, callback: Callback<T>, priority = 0, once = false): this {
// Avoid duplication
if (this.findListenerIndex(event, callback) !== undefined) {
return this;
}
// Initialize listeners collection if not exists
this.listeners[event] = this.listeners[event] || [];
// Get reference to array containing listeners
const listeners = this.listeners[event];
// Build listener id (incremental)
const id = listeners.length ? Math.max(...listeners.map((l) => l.id)) + 1 : 0;
// Register the listener
listeners.push(new Listener(callback, priority, once, id));
// Listener are sorted in order they are defined
listeners.sort((a, b) => b.id - a.id);
// Sort by priority listeners binded to same event
// Lower priorities are first because we loop on collection from the end (see dispatch method)
listeners.sort((a, b) => a.priority - b.priority);
return this;
}
once<T extends Event>(event: string, callback: Callback<T>, priority = 0): this {
return this.on(event, callback, priority, true);
}
off<T extends Event>(event: string, callback: Callback<T>): this {
const index = this.findListenerIndex(event, callback);
if (index !== undefined) {
this.listeners[event].splice(index, 1);
}
return this;
}
/**
* Invoke all listeners attached to given event.
*
* @param abortOnFailure - Specify if listener failures must abort dispatch process.
*/
async dispatch(e: Event, abortOnFailure = true): Promise<void> {
const event = (e.constructor as typeof Event).NAME;
const listeners = this.listeners[event] || [];
this.debug('start', e, listeners);
// Use inverse loop because we need to remove listeners callable once
for (let i = listeners.length - 1, listener = null; i >= 0; i -= 1) {
listener = listeners[i];
if (Dispatcher.handleListenerSkipping(e, listener)) {
this.debug('skipped', e, listener);
continue;
}
if (listener.once) {
this.listeners[event].splice(i, 1);
}
try {
this.debug('invoking', e, listener);
// Wait for listener whose return a promise
await listener.invoke(e as never); // eslint-disable-line no-await-in-loop
this.debug('invoked', e, listener);
} catch (err) {
this.debug('failed', e, listener, err as Error);
if (abortOnFailure) {
// Reject promise on "abort on listener failure" strategy
return Promise.reject(err);
}
}
if (!e.dispatch.propagation) {
this.debug('stopped', e, listener);
// Stop listeners invokation
break;
}
}
this.debug('end', e, listeners);
return Promise.resolve();
}
protected findListenerIndex<T extends Event>(event: string, callback: Callback<T>): number | undefined {
const listeners = this.listeners[event] || [];
for (let i = 0, len = listeners.length; i < len; i += 1) {
if (listeners[i].callback === callback) {
return i;
}
}
return undefined;
}
|
protected static handleListenerSkipping(event: Event, listener: Listener<never>): boolean | void {
|
const { skipNextListeners, skipUntilListener } = event.dispatch;
if (skipNextListeners > 0) {
event.dispatch.skipNextListeners -= 1;
return true;
}
if (skipUntilListener) {
if (listener.id === skipUntilListener) {
event.dispatch.skipUntilListener = undefined;
return;
}
return true;
}
}
protected debug(
action: string,
relatedEvent: Event,
handler: Listener<never> | Listener<never>[],
error: Error | null = null
): void {
if (relatedEvent instanceof DebugEvent || !this.klient.debug) {
return;
}
this.dispatch(new DebugEvent(action, relatedEvent, handler, error), false);
}
}
|
src/services/dispatcher/dispatcher.ts
|
klientjs-core-9a67a61
|
[
{
"filename": "src/services/dispatcher/dispatcher.d.ts",
"retrieved_chunk": "export default class Dispatcher {\n protected readonly klient: Klient;\n readonly listeners: Listeners;\n constructor(klient: Klient);\n on<T extends Event>(event: string, callback: Callback<T>, priority?: number, once?: boolean): this;\n once<T extends Event>(event: string, callback: Callback<T>, priority?: number): this;\n off<T extends Event>(event: string, callback: Callback<T>): this;\n dispatch(e: Event, abortOnFailure?: boolean): Promise<void>;\n protected findListenerIndex<T extends Event>(event: string, callback: Callback<T>): number | undefined;\n protected static handleListenerSkipping(event: Event, listener: Listener<never>): boolean | void;",
"score": 0.8393136262893677
},
{
"filename": "src/services/dispatcher/listener.ts",
"retrieved_chunk": "import type Event from '../../events/event';\nimport type { Callback } from './dispatcher';\nexport default class Listener<T extends Event> {\n constructor(readonly callback: Callback<T>, readonly priority: number, readonly once: boolean, readonly id: number) {}\n invoke(event: T): Promise<void> {\n let result;\n try {\n result = this.callback(event);\n if (!(result instanceof Promise)) {\n result = Promise.resolve();",
"score": 0.8237358331680298
},
{
"filename": "src/services/dispatcher/listener.d.ts",
"retrieved_chunk": "import type Event from '../../events/event';\nimport type { Callback } from './dispatcher';\nexport default class Listener<T extends Event> {\n readonly callback: Callback<T>;\n readonly priority: number;\n readonly once: boolean;\n readonly id: number;\n constructor(callback: Callback<T>, priority: number, once: boolean, id: number);\n invoke(event: T): Promise<void>;\n}",
"score": 0.8108535408973694
},
{
"filename": "src/events/event.d.ts",
"retrieved_chunk": "export default class Event {\n static NAME: string;\n readonly dispatch: {\n propagation: boolean;\n skipNextListeners: number;\n skipUntilListener?: number;\n };\n stopPropagation(): void;\n skipNextListeners(total: number): void;\n skipUntilListener(id: number): void;",
"score": 0.805860161781311
},
{
"filename": "src/events/event.ts",
"retrieved_chunk": "export default class Event {\n static NAME = 'event';\n readonly dispatch: {\n propagation: boolean;\n skipNextListeners: number;\n skipUntilListener?: number;\n } = {\n propagation: true,\n skipNextListeners: 0,\n skipUntilListener: undefined",
"score": 0.8058325052261353
}
] |
typescript
|
protected static handleListenerSkipping(event: Event, listener: Listener<never>): boolean | void {
|
import { StdioOptions } from 'child_process'
import { FinalResults } from 'tap-parser'
import { BaseOpts } from '../base.js'
import { Spawn } from '../spawn.js'
import { TapPlugin, TestBase } from '../test-base.js'
export interface SpawnOpts extends BaseOpts {
cwd?: string
command?: string
args?: string[]
stdio?: StdioOptions
env?: { [k: string]: string } | typeof process.env
exitCode?: number | null
signal?: string | null
}
class SpawnPlugin {
#t: TestBase
constructor(t: TestBase) {
this.#t = t
}
spawn(cmd: string): Promise<FinalResults | null>
spawn(
cmd: string,
options: SpawnOpts,
name?: string
): Promise<FinalResults | null>
spawn(
cmd: string,
args: string | string[],
name?: string
): Promise<FinalResults | null>
spawn(
cmd: string,
args: string | string[],
options: SpawnOpts,
name?: string
): Promise<FinalResults | null>
spawn(
cmd: string,
args?: string | string[] | SpawnOpts,
options?: SpawnOpts | string,
name?: string
): Promise<FinalResults | null> {
if (typeof args === 'string') {
args = [args]
}
if (typeof options === 'string') {
name = options
options = {}
}
if (typeof args === 'object' && !Array.isArray(args)) {
options = args
args = []
}
options = options || {}
if (options.name === undefined) {
options.name = name
}
options.command = cmd
options.args = args
return this.#t.sub(Spawn, options, this.spawn)
}
}
const plugin:
|
TapPlugin<SpawnPlugin> = (t: TestBase) =>
new SpawnPlugin(t)
export default plugin
|
src/plugin/spawn.ts
|
tapjs-core-edd7403
|
[
{
"filename": "src/plugin/stdin.ts",
"retrieved_chunk": "}\nconst plugin: TapPlugin<StdinPlugin> = (t: TestBase) =>\n new StdinPlugin(t)\nexport default plugin",
"score": 0.873397946357727
},
{
"filename": "src/spawn.ts",
"retrieved_chunk": " args?: string[]\n stdio?: StdioOptions\n env?: { [k: string]: string } | typeof process.env\n exitCode?: number | null\n signal?: string | null\n}\nexport class Spawn extends Base {\n public declare options: SpawnOpts\n public cwd: string\n public command: string",
"score": 0.863815188407898
},
{
"filename": "src/spawn.ts",
"retrieved_chunk": " }\n options = options || {}\n const cwd =\n typeof options.cwd === 'string'\n ? options.cwd\n : process.cwd()\n const args = options.args || []\n options.name =\n options.name || Spawn.procName(cwd, command, args)\n super(options)",
"score": 0.8560781478881836
},
{
"filename": "src/spawn.ts",
"retrieved_chunk": "import { Base, BaseOpts } from './base'\nimport ProcessInfo from '@tapjs/processinfo'\nimport {\n ChildProcess,\n StdioOptions,\n} from 'node:child_process'\nimport { basename } from 'node:path'\nexport interface SpawnOpts extends BaseOpts {\n cwd?: string\n command?: string",
"score": 0.8439900875091553
},
{
"filename": "src/plugin/stdin.ts",
"retrieved_chunk": "import { FinalResults } from 'tap-parser'\nimport parseTestArgs from '../parse-test-args.js'\nimport { Stdin, StdinOpts } from '../stdin.js'\nimport { TapPlugin, TestBase } from '../test-base.js'\nclass StdinPlugin {\n #t: TestBase\n constructor(t: TestBase) {\n this.#t = t\n }\n stdin(",
"score": 0.8411556482315063
}
] |
typescript
|
TapPlugin<SpawnPlugin> = (t: TestBase) =>
new SpawnPlugin(t)
export default plugin
|
|
import * as deepmerge from 'deepmerge';
import type { AxiosRequestConfig } from 'axios';
import type Klient from '../../klient';
import Request from './request';
import type { KlientRequestConfig } from './request';
export default class RequestFactory {
model = Request;
// Requests are stocked during their execution only.
readonly requests: Request[] = [];
constructor(protected readonly klient: Klient) {}
request<T = unknown>(urlOrConfig: KlientRequestConfig | string): Request<T> {
return this.createRequest<T>(urlOrConfig).execute();
}
file(urlOrConfig: KlientRequestConfig | string): Promise<Blob> {
const config = deepmerge(
{ responseType: 'blob', context: { action: 'file' } },
typeof urlOrConfig === 'string' ? { url: urlOrConfig } : urlOrConfig
);
return this.request<Blob>(config).then(({ data }) => data);
}
cancelPendingRequests(): this {
for (let i = 0, len = this.requests.length; i < len; i += 1) {
this.requests[i].cancel();
}
return this;
}
createRequest<T = unknown>(urlOrConfig: KlientRequestConfig | string): Request<T> {
const config = typeof urlOrConfig === 'string' ? { url: urlOrConfig } : urlOrConfig;
const request = this.model.new<T>(this.prepare(config), this.klient);
// Store request during pending state only
this.requests.push(request);
// Remove request when promise has been fulfilled
request
.then((r) => {
this.removePendingRequest(request);
return r;
})
.catch((e) => {
this.removePendingRequest(request);
return e;
});
return request;
}
isCancel(e: Error) {
return this.model.isCancel(e);
}
protected
|
prepare(config: KlientRequestConfig): KlientRequestConfig {
|
return deepmerge.all([
{ baseURL: this.klient.url },
(this.klient.parameters.get('request') as AxiosRequestConfig) || {},
config
]);
}
protected removePendingRequest(request: Request) {
const i = this.requests.indexOf(request);
if (this.requests[i] instanceof Request) {
this.requests.splice(i, 1);
}
}
}
|
src/services/request/factory.ts
|
klientjs-core-9a67a61
|
[
{
"filename": "src/services/request/factory.d.ts",
"retrieved_chunk": " constructor(klient: Klient);\n request<T = unknown>(urlOrConfig: KlientRequestConfig | string): Request<T>;\n file(urlOrConfig: KlientRequestConfig | string): Promise<Blob>;\n cancelPendingRequests(): this;\n createRequest<T = unknown>(urlOrConfig: KlientRequestConfig | string): Request<T>;\n isCancel(e: Error): any;\n protected prepare(config: KlientRequestConfig): KlientRequestConfig;\n protected removePendingRequest(request: Request): void;\n}\nexport {};",
"score": 0.8672925233840942
},
{
"filename": "src/services/request/request.ts",
"retrieved_chunk": " request.config = axiosConfig;\n request.callbacks = callbacks;\n request.config.signal = request.abortController.signal;\n request.context = { ...request.context, ...context };\n return request;\n }\n static isCancel(e: Error) {\n return axios.isCancel(e);\n }\n cancel(): this {",
"score": 0.8507510423660278
},
{
"filename": "src/klient.d.ts",
"retrieved_chunk": " request<T = unknown>(urlOrConfig: KlientRequestConfig | string): Request<T>;\n get<T = unknown>(url: string, config?: KlientRequestConfig): Request<T>;\n post<T = unknown>(url: string, data: unknown, config?: KlientRequestConfig): Request<T>;\n put<T = unknown>(url: string, data: unknown, config?: KlientRequestConfig): Request<T>;\n patch<T = unknown>(url: string, data: unknown, config?: KlientRequestConfig): Request<T>;\n delete<T = unknown>(url: string, config?: KlientRequestConfig): Request<T>;\n head<T = unknown>(url: string, config?: KlientRequestConfig): Request<T>;\n options<T = unknown>(url: string, config?: KlientRequestConfig): Request<T>;\n file(urlOrConfig: KlientRequestConfig | string): Promise<Blob>;\n cancelPendingRequests(): this;",
"score": 0.8358026742935181
},
{
"filename": "src/services/request/request.d.ts",
"retrieved_chunk": " protected readonly primaryEvent: RequestEvent;\n protected readonly abortController: AbortController;\n protected constructor(callback: RequestCallback);\n static new<T>({ context, ...axiosConfig }: KlientRequestConfig, klient: Klient): Request<T>;\n static isCancel(e: Error): boolean;\n cancel(): this;\n execute(): this;\n protected doRequest(): this;\n protected resolve(response: AxiosResponse<T>): Promise<void>;\n protected reject(error: AxiosError): Promise<void>;",
"score": 0.835021436214447
},
{
"filename": "src/klient.ts",
"retrieved_chunk": " off<T extends Event>(event: string, callback: Callback<T>): this {\n this.dispatcher.off(event, callback);\n return this;\n }\n /** === Request === */\n request<T = unknown>(urlOrConfig: KlientRequestConfig | string): Request<T> {\n return this.factory.request(urlOrConfig);\n }\n get<T = unknown>(url: string, config?: KlientRequestConfig): Request<T> {\n return this.request<T>({ ...config, method: 'GET', url });",
"score": 0.8344162106513977
}
] |
typescript
|
prepare(config: KlientRequestConfig): KlientRequestConfig {
|
import Event from '../../events/event';
import DebugEvent from '../../events/debug';
import Listener from './listener';
import type Klient from '../../klient';
export type Callback<T extends Event> = (e: T) => Promise<void> | void;
export type Listeners = { [event: string]: Listener<never>[] };
export default class Dispatcher {
readonly listeners: Listeners = {};
constructor(protected readonly klient: Klient) {}
on<T extends Event>(event: string, callback: Callback<T>, priority = 0, once = false): this {
// Avoid duplication
if (this.findListenerIndex(event, callback) !== undefined) {
return this;
}
// Initialize listeners collection if not exists
this.listeners[event] = this.listeners[event] || [];
// Get reference to array containing listeners
const listeners = this.listeners[event];
// Build listener id (incremental)
const id = listeners.length ? Math.max(...listeners.map((l) => l.id)) + 1 : 0;
// Register the listener
listeners.push(new Listener(callback, priority, once, id));
// Listener are sorted in order they are defined
listeners.sort((a, b) => b.id - a.id);
// Sort by priority listeners binded to same event
// Lower priorities are first because we loop on collection from the end (see dispatch method)
listeners.sort((a, b) => a.priority - b.priority);
return this;
}
once<T extends Event>(event: string, callback: Callback<T>, priority = 0): this {
return this.on(event, callback, priority, true);
}
off<T extends Event>(event: string, callback: Callback<T>): this {
const index = this.findListenerIndex(event, callback);
if (index !== undefined) {
this.listeners[event].splice(index, 1);
}
return this;
}
/**
* Invoke all listeners attached to given event.
*
* @param abortOnFailure - Specify if listener failures must abort dispatch process.
*/
async dispatch(e: Event, abortOnFailure = true): Promise<void> {
const event = (e.constructor as typeof Event).NAME;
const listeners = this.listeners[event] || [];
this.debug('start', e, listeners);
// Use inverse loop because we need to remove listeners callable once
for (let i = listeners.length - 1, listener = null; i >= 0; i -= 1) {
listener = listeners[i];
if (Dispatcher.handleListenerSkipping(e, listener)) {
this.debug('skipped', e, listener);
continue;
}
if (listener.once) {
this.listeners[event].splice(i, 1);
}
try {
this.debug('invoking', e, listener);
// Wait for listener whose return a promise
await listener.invoke(e as never); // eslint-disable-line no-await-in-loop
this.debug('invoked', e, listener);
} catch (err) {
this.debug('failed', e, listener, err as Error);
if (abortOnFailure) {
// Reject promise on "abort on listener failure" strategy
return Promise.reject(err);
}
}
if (!e.dispatch.propagation) {
this.debug('stopped', e, listener);
// Stop listeners invokation
break;
}
}
this.debug('end', e, listeners);
return Promise.resolve();
}
protected findListenerIndex<T extends Event>(event: string, callback: Callback<T>): number | undefined {
const listeners = this.listeners[event] || [];
for (let i = 0, len = listeners.length; i < len; i += 1) {
if (listeners[i].callback === callback) {
return i;
}
}
return undefined;
}
protected static handleListenerSkipping(event: Event, listener: Listener<never>): boolean | void {
const { skipNextListeners, skipUntilListener } = event.dispatch;
if (skipNextListeners > 0) {
event.dispatch.skipNextListeners -= 1;
return true;
}
if (skipUntilListener) {
if (listener.id === skipUntilListener) {
event.dispatch.skipUntilListener = undefined;
return;
}
return true;
}
}
protected debug(
action: string,
relatedEvent: Event,
handler: Listener<never> | Listener<never>[],
error: Error | null = null
): void {
if (relatedEvent
|
instanceof DebugEvent || !this.klient.debug) {
|
return;
}
this.dispatch(new DebugEvent(action, relatedEvent, handler, error), false);
}
}
|
src/services/dispatcher/dispatcher.ts
|
klientjs-core-9a67a61
|
[
{
"filename": "src/services/dispatcher/dispatcher.d.ts",
"retrieved_chunk": " protected debug(action: string, relatedEvent: Event, handler: Listener<never> | Listener<never>[], error?: Error | null): void;\n}\nexport {};",
"score": 0.9022576808929443
},
{
"filename": "src/events/debug.ts",
"retrieved_chunk": "import Event from './event';\nimport type Listener from '../services/dispatcher/listener';\nexport default class DebugEvent extends Event {\n static NAME = 'debug';\n constructor(\n public action: string,\n public relatedEvent: Event,\n public handler: Listener<never> | Listener<never>[],\n public error: Error | null\n ) {",
"score": 0.8872907161712646
},
{
"filename": "src/events/debug.d.ts",
"retrieved_chunk": "import Event from './event';\nimport type Listener from '../services/dispatcher/listener';\nexport default class DebugEvent extends Event {\n action: string;\n relatedEvent: Event;\n handler: Listener<never> | Listener<never>[];\n error: Error | null;\n static NAME: string;\n constructor(action: string, relatedEvent: Event, handler: Listener<never> | Listener<never>[], error: Error | null);\n}",
"score": 0.8790251016616821
},
{
"filename": "src/__tests__/debug.test.ts",
"retrieved_chunk": " const spyInvokingEvent = jest.fn();\n const spyInvokedEvent = jest.fn();\n const spyDispatchStoppedEvent = jest.fn();\n const spyDispatchFailedEvent = jest.fn();\n const spyDispatchEndEvent = jest.fn();\n klient.on('debug', (e: DebugEvent) => {\n switch (e.action) {\n case 'start':\n spyStartDispatchEvent();\n break;",
"score": 0.836240291595459
},
{
"filename": "src/__tests__/debug.test.ts",
"retrieved_chunk": "import { mockAxiosWithRestApi } from '@klient/testing';\nimport Klient, { DebugEvent } from '..';\njest.mock('axios');\nmockAxiosWithRestApi();\ntest('debug', async () => {\n const klient = new Klient({ debug: true });\n const spyRequestEvent = jest.fn();\n const spyRequest2Event = jest.fn();\n const spyStartDispatchEvent = jest.fn();\n const spySkippedEvent = jest.fn();",
"score": 0.8143285512924194
}
] |
typescript
|
instanceof DebugEvent || !this.klient.debug) {
|
import { StdioOptions } from 'child_process'
import { FinalResults } from 'tap-parser'
import { BaseOpts } from '../base.js'
import { Spawn } from '../spawn.js'
import { TapPlugin, TestBase } from '../test-base.js'
export interface SpawnOpts extends BaseOpts {
cwd?: string
command?: string
args?: string[]
stdio?: StdioOptions
env?: { [k: string]: string } | typeof process.env
exitCode?: number | null
signal?: string | null
}
class SpawnPlugin {
#t: TestBase
constructor(t: TestBase) {
this.#t = t
}
spawn(cmd: string): Promise<FinalResults | null>
spawn(
cmd: string,
options: SpawnOpts,
name?: string
): Promise<FinalResults | null>
spawn(
cmd: string,
args: string | string[],
name?: string
): Promise<FinalResults | null>
spawn(
cmd: string,
args: string | string[],
options: SpawnOpts,
name?: string
): Promise<FinalResults | null>
spawn(
cmd: string,
args?: string | string[] | SpawnOpts,
options?: SpawnOpts | string,
name?: string
): Promise<FinalResults | null> {
if (typeof args === 'string') {
args = [args]
}
if (typeof options === 'string') {
name = options
options = {}
}
if (typeof args === 'object' && !Array.isArray(args)) {
options = args
args = []
}
options = options || {}
|
if (options.name === undefined) {
|
options.name = name
}
options.command = cmd
options.args = args
return this.#t.sub(Spawn, options, this.spawn)
}
}
const plugin: TapPlugin<SpawnPlugin> = (t: TestBase) =>
new SpawnPlugin(t)
export default plugin
|
src/plugin/spawn.ts
|
tapjs-core-edd7403
|
[
{
"filename": "src/parse-test-args.ts",
"retrieved_chunk": " (typeof arg === 'string' || typeof arg === 'number')\n )\n name = '' + arg\n else if (arg && typeof arg === 'object') {\n extra = arg\n if (name === undefined) name = null\n } else if (typeof arg === 'function') {\n if (extra === undefined) extra = {}\n if (name === undefined) name = null\n cb = arg",
"score": 0.8519371151924133
},
{
"filename": "src/base.ts",
"retrieved_chunk": " // if it's null or an object, inherit from it. otherwise, copy it.\n const ctx = options.context\n if (ctx !== undefined) {\n this.context =\n typeof ctx === 'object' ? Object.create(ctx) : ctx\n } else {\n this.context = null\n }\n this.bail = !!options.bail\n this.strict = !!options.strict",
"score": 0.8455363512039185
},
{
"filename": "src/spawn.ts",
"retrieved_chunk": " }\n options = options || {}\n const cwd =\n typeof options.cwd === 'string'\n ? options.cwd\n : process.cwd()\n const args = options.args || []\n options.name =\n options.name || Spawn.procName(cwd, command, args)\n super(options)",
"score": 0.8423729538917542
},
{
"filename": "src/parse-test-args.ts",
"retrieved_chunk": " let extra: { [k: string]: any } | null | undefined =\n undefined\n let cb: ((t: T) => any) | null | undefined = undefined\n // this only works if it's literally the 4th argument.\n // used internally.\n const defaultName = args[3] || ''\n for (let i = 0; i < 3 && i < args.length; i++) {\n const arg = args[i]\n if (\n name === undefined &&",
"score": 0.8360203504562378
},
{
"filename": "src/spawn.ts",
"retrieved_chunk": " this.cwd = cwd\n this.command = command\n this.args = args\n if (options.stdio) {\n if (typeof options.stdio === 'string')\n this.stdio = [options.stdio, 'pipe', options.stdio]\n else {\n this.stdio = options.stdio.slice(0) as StdioOptions\n }\n } else {",
"score": 0.8333474397659302
}
] |
typescript
|
if (options.name === undefined) {
|
import * as deepmerge from 'deepmerge';
import * as objectPath from 'object-path';
import { isPlainObject, isPlainArray, softClone } from '../../toolbox/object';
import { watch, unwatch, invokeWatchers, getWatchers, Watchable, WatchCallback } from './watch';
type BagItems = Record<string, unknown>;
export default class Bag implements BagItems, Watchable {
[x: string]: unknown;
constructor(items: BagItems = {}) {
Object.keys(items).forEach((key) => {
this[key] = items[key];
});
}
get watchers() {
return getWatchers(this);
}
has(path: string) {
return objectPath.get(this, path) !== undefined;
}
get(path: string) {
return objectPath.get(this.all(), path);
}
all() {
return softClone(this);
}
set(path: string, value: unknown): this {
const prevState = this.all();
objectPath.set(this, path, value);
return invokeWatchers(this, this.all(), prevState);
}
merge(...items: BagItems[]): this {
const prevState = this.all();
const nextState = deepmerge.all<BagItems>([this.all(), ...items], {
arrayMerge: (_destinationArray: unknown[], sourceArray: unknown[]) => sourceArray,
isMergeableObject: (o: object) => isPlainArray(o) || isPlainObject(o)
});
Object.keys(nextState).forEach((key) => {
this[key] = nextState[key];
});
return invokeWatchers(this, nextState, prevState);
}
watch(path:
|
string, onChange: WatchCallback, deep = false): this {
|
return watch(this, path, onChange, deep);
}
unwatch(path: string, onChange: WatchCallback): this {
return unwatch(this, path, onChange);
}
}
|
src/services/bag/bag.ts
|
klientjs-core-9a67a61
|
[
{
"filename": "src/services/bag/watch.d.ts",
"retrieved_chunk": "export type Watchable = object;\nexport type WatchCallback<T = unknown, Z = T> = (next: T, prev: Z) => void;\ntype WatcherItem = {\n callback: WatchCallback;\n deep: boolean;\n};\nexport declare function getWatchers(watchable: Watchable): Record<string, WatcherItem[]>;\nexport declare function watch<T extends Watchable>(watchable: T, path: string, onChange: WatchCallback, deep: boolean): T;\nexport declare function unwatch<T extends Watchable>(watchable: T, path: string, onChange: WatchCallback): T;\nexport declare function invokeWatchers<T extends Watchable>(watchable: T, next: object, prev: object): T;",
"score": 0.8828274607658386
},
{
"filename": "src/services/bag/watch.ts",
"retrieved_chunk": " * Register callback to listen changes made on specific path of given watchable object\n */\nexport function watch<T extends Watchable>(watchable: T, path: string, onChange: WatchCallback, deep: boolean): T {\n const id = getInstanceId(watchable);\n watchers[id] = getWatchers(watchable);\n const collection = watchers[id][path] || [];\n for (let i = 0, len = collection.length; i < len; i += 1) {\n if (collection[i].callback === onChange) {\n return watchable;\n }",
"score": 0.8721964359283447
},
{
"filename": "src/services/bag/watch.ts",
"retrieved_chunk": " return watchable;\n }\n collection.splice(index, 1);\n watchers[id][path] = collection;\n return watchable;\n}\n/**\n * Invoke all watchers attached to given watchable object with prev and next state\n */\nexport function invokeWatchers<T extends Watchable>(watchable: T, next: object, prev: object): T {",
"score": 0.8693751096725464
},
{
"filename": "src/services/bag/watch.ts",
"retrieved_chunk": " watched[targetPath].forEach((watcher) => {\n if ((path === targetPath || watcher.deep) && !invoked.includes(watcher)) {\n watcher.callback(objectPath.get(next, targetPath), objectPath.get(prev, targetPath));\n invoked.push(watcher);\n }\n });\n });\n });\n return watchable;\n}",
"score": 0.8621433973312378
},
{
"filename": "src/services/bag/watch.ts",
"retrieved_chunk": " }\n collection.push({ callback: onChange, deep });\n watchers[id][path] = collection;\n return watchable;\n}\n/**\n * Unregister watcher callback for given path\n */\nexport function unwatch<T extends Watchable>(watchable: T, path: string, onChange: WatchCallback): T {\n const id = getInstanceId(watchable);",
"score": 0.858720600605011
}
] |
typescript
|
string, onChange: WatchCallback, deep = false): this {
|
import * as deepmerge from 'deepmerge';
import * as objectPath from 'object-path';
import { isPlainObject, isPlainArray, softClone } from '../../toolbox/object';
import { watch, unwatch, invokeWatchers, getWatchers, Watchable, WatchCallback } from './watch';
type BagItems = Record<string, unknown>;
export default class Bag implements BagItems, Watchable {
[x: string]: unknown;
constructor(items: BagItems = {}) {
Object.keys(items).forEach((key) => {
this[key] = items[key];
});
}
get watchers() {
return getWatchers(this);
}
has(path: string) {
return objectPath.get(this, path) !== undefined;
}
get(path: string) {
return objectPath.get(this.all(), path);
}
all() {
return softClone(this);
}
set(path: string, value: unknown): this {
const prevState = this.all();
objectPath.set(this, path, value);
return invokeWatchers(this, this.all(), prevState);
}
merge(...items: BagItems[]): this {
const prevState = this.all();
const nextState = deepmerge.all<BagItems>([this.all(), ...items], {
arrayMerge: (_destinationArray: unknown[], sourceArray: unknown[]) => sourceArray,
isMergeableObject: (o: object) => isPlainArray(o) || isPlainObject(o)
});
Object.keys(nextState).forEach((key) => {
this[key] = nextState[key];
});
return invokeWatchers(this, nextState, prevState);
}
watch(path: string, onChange: WatchCallback, deep = false): this {
|
return watch(this, path, onChange, deep);
|
}
unwatch(path: string, onChange: WatchCallback): this {
return unwatch(this, path, onChange);
}
}
|
src/services/bag/bag.ts
|
klientjs-core-9a67a61
|
[
{
"filename": "src/services/bag/watch.d.ts",
"retrieved_chunk": "export type Watchable = object;\nexport type WatchCallback<T = unknown, Z = T> = (next: T, prev: Z) => void;\ntype WatcherItem = {\n callback: WatchCallback;\n deep: boolean;\n};\nexport declare function getWatchers(watchable: Watchable): Record<string, WatcherItem[]>;\nexport declare function watch<T extends Watchable>(watchable: T, path: string, onChange: WatchCallback, deep: boolean): T;\nexport declare function unwatch<T extends Watchable>(watchable: T, path: string, onChange: WatchCallback): T;\nexport declare function invokeWatchers<T extends Watchable>(watchable: T, next: object, prev: object): T;",
"score": 0.8939569592475891
},
{
"filename": "src/services/bag/watch.ts",
"retrieved_chunk": " * Register callback to listen changes made on specific path of given watchable object\n */\nexport function watch<T extends Watchable>(watchable: T, path: string, onChange: WatchCallback, deep: boolean): T {\n const id = getInstanceId(watchable);\n watchers[id] = getWatchers(watchable);\n const collection = watchers[id][path] || [];\n for (let i = 0, len = collection.length; i < len; i += 1) {\n if (collection[i].callback === onChange) {\n return watchable;\n }",
"score": 0.8766419887542725
},
{
"filename": "src/services/bag/watch.ts",
"retrieved_chunk": " return watchable;\n }\n collection.splice(index, 1);\n watchers[id][path] = collection;\n return watchable;\n}\n/**\n * Invoke all watchers attached to given watchable object with prev and next state\n */\nexport function invokeWatchers<T extends Watchable>(watchable: T, next: object, prev: object): T {",
"score": 0.8692128658294678
},
{
"filename": "src/services/bag/watch.ts",
"retrieved_chunk": " watched[targetPath].forEach((watcher) => {\n if ((path === targetPath || watcher.deep) && !invoked.includes(watcher)) {\n watcher.callback(objectPath.get(next, targetPath), objectPath.get(prev, targetPath));\n invoked.push(watcher);\n }\n });\n });\n });\n return watchable;\n}",
"score": 0.8690537214279175
},
{
"filename": "src/services/bag/watch.ts",
"retrieved_chunk": " }\n collection.push({ callback: onChange, deep });\n watchers[id][path] = collection;\n return watchable;\n}\n/**\n * Unregister watcher callback for given path\n */\nexport function unwatch<T extends Watchable>(watchable: T, path: string, onChange: WatchCallback): T {\n const id = getInstanceId(watchable);",
"score": 0.8580096960067749
}
] |
typescript
|
return watch(this, path, onChange, deep);
|
import * as deepmerge from 'deepmerge';
import * as objectPath from 'object-path';
import { isPlainObject, isPlainArray, softClone } from '../../toolbox/object';
import { watch, unwatch, invokeWatchers, getWatchers, Watchable, WatchCallback } from './watch';
type BagItems = Record<string, unknown>;
export default class Bag implements BagItems, Watchable {
[x: string]: unknown;
constructor(items: BagItems = {}) {
Object.keys(items).forEach((key) => {
this[key] = items[key];
});
}
get watchers() {
return getWatchers(this);
}
has(path: string) {
return objectPath.get(this, path) !== undefined;
}
get(path: string) {
return objectPath.get(this.all(), path);
}
all() {
return softClone(this);
}
set(path: string, value: unknown): this {
const prevState = this.all();
objectPath.set(this, path, value);
return invokeWatchers(this, this.all(), prevState);
}
merge(...items: BagItems[]): this {
const prevState = this.all();
const nextState = deepmerge.all<BagItems>([this.all(), ...items], {
arrayMerge: (_destinationArray: unknown[], sourceArray: unknown[]) => sourceArray,
isMergeableObject: (o: object) => isPlainArray(o) || isPlainObject(o)
});
Object.keys(nextState).forEach((key) => {
this[key] = nextState[key];
});
return invokeWatchers(this, nextState, prevState);
}
watch(path: string, onChange
|
: WatchCallback, deep = false): this {
|
return watch(this, path, onChange, deep);
}
unwatch(path: string, onChange: WatchCallback): this {
return unwatch(this, path, onChange);
}
}
|
src/services/bag/bag.ts
|
klientjs-core-9a67a61
|
[
{
"filename": "src/services/bag/watch.d.ts",
"retrieved_chunk": "export type Watchable = object;\nexport type WatchCallback<T = unknown, Z = T> = (next: T, prev: Z) => void;\ntype WatcherItem = {\n callback: WatchCallback;\n deep: boolean;\n};\nexport declare function getWatchers(watchable: Watchable): Record<string, WatcherItem[]>;\nexport declare function watch<T extends Watchable>(watchable: T, path: string, onChange: WatchCallback, deep: boolean): T;\nexport declare function unwatch<T extends Watchable>(watchable: T, path: string, onChange: WatchCallback): T;\nexport declare function invokeWatchers<T extends Watchable>(watchable: T, next: object, prev: object): T;",
"score": 0.8831740617752075
},
{
"filename": "src/services/bag/watch.ts",
"retrieved_chunk": " * Register callback to listen changes made on specific path of given watchable object\n */\nexport function watch<T extends Watchable>(watchable: T, path: string, onChange: WatchCallback, deep: boolean): T {\n const id = getInstanceId(watchable);\n watchers[id] = getWatchers(watchable);\n const collection = watchers[id][path] || [];\n for (let i = 0, len = collection.length; i < len; i += 1) {\n if (collection[i].callback === onChange) {\n return watchable;\n }",
"score": 0.8728122711181641
},
{
"filename": "src/services/bag/watch.ts",
"retrieved_chunk": " return watchable;\n }\n collection.splice(index, 1);\n watchers[id][path] = collection;\n return watchable;\n}\n/**\n * Invoke all watchers attached to given watchable object with prev and next state\n */\nexport function invokeWatchers<T extends Watchable>(watchable: T, next: object, prev: object): T {",
"score": 0.8692330121994019
},
{
"filename": "src/services/bag/watch.ts",
"retrieved_chunk": " watched[targetPath].forEach((watcher) => {\n if ((path === targetPath || watcher.deep) && !invoked.includes(watcher)) {\n watcher.callback(objectPath.get(next, targetPath), objectPath.get(prev, targetPath));\n invoked.push(watcher);\n }\n });\n });\n });\n return watchable;\n}",
"score": 0.8629719018936157
},
{
"filename": "src/services/bag/watch.ts",
"retrieved_chunk": " }\n collection.push({ callback: onChange, deep });\n watchers[id][path] = collection;\n return watchable;\n}\n/**\n * Unregister watcher callback for given path\n */\nexport function unwatch<T extends Watchable>(watchable: T, path: string, onChange: WatchCallback): T {\n const id = getInstanceId(watchable);",
"score": 0.8594142198562622
}
] |
typescript
|
: WatchCallback, deep = false): this {
|
import Bag from './services/bag/bag';
import Dispatcher from './services/dispatcher/dispatcher';
import RequestFactory from './services/request/factory';
import Extensions from './extensions';
import { defaultParameters } from './parameters';
import type Event from './events/event';
import type Request from './services/request/request';
import type { KlientRequestConfig } from './services/request/request';
import type { Callback } from './services/dispatcher/dispatcher';
import type { Parameters } from './parameters';
export default class Klient<P extends Parameters = Parameters> {
readonly extensions: string[] = [];
readonly parameters = new Bag(defaultParameters);
readonly services = new Bag();
constructor(urlOrParams?: P | string) {
let parameters: Parameters = {};
if (typeof urlOrParams === 'string') {
parameters.url = urlOrParams;
} else if (urlOrParams && typeof urlOrParams === 'object') {
parameters = urlOrParams;
}
this.parameters.merge(parameters);
// prettier-ignore
this.services
.set('klient', this)
.set('dispatcher', new Dispatcher(this))
.set('factory', new RequestFactory(this));
this.load(this.parameters.get('extensions') as string[] | undefined);
}
/** === Common parameters === */
get url(): string | undefined {
return this.parameters.get('url');
}
get debug(): boolean {
return Boolean(this.parameters.get('debug'));
}
/** === Common services === */
get factory(): RequestFactory {
return this.services.get('factory') as RequestFactory;
}
|
get dispatcher(): Dispatcher {
|
return this.services.get('dispatcher') as Dispatcher;
}
/** === Extensions === */
extends(property: string, value: unknown, writable = false): this {
return Object.defineProperty(this, property, { writable, value });
}
load(names?: string[]): this {
Extensions.load(this, names);
return this;
}
/** === Dispatcher/Events === */
on<T extends Event>(event: string, callback: Callback<T>, priority = 0, once = false): this {
this.dispatcher.on(event, callback, priority, once);
return this;
}
once<T extends Event>(event: string, callback: Callback<T>, priority = 0): this {
this.dispatcher.once(event, callback, priority);
return this;
}
off<T extends Event>(event: string, callback: Callback<T>): this {
this.dispatcher.off(event, callback);
return this;
}
/** === Request === */
request<T = unknown>(urlOrConfig: KlientRequestConfig | string): Request<T> {
return this.factory.request(urlOrConfig);
}
get<T = unknown>(url: string, config?: KlientRequestConfig): Request<T> {
return this.request<T>({ ...config, method: 'GET', url });
}
post<T = unknown>(url: string, data: unknown, config?: KlientRequestConfig): Request<T> {
return this.request<T>({ ...config, method: 'POST', url, data });
}
put<T = unknown>(url: string, data: unknown, config?: KlientRequestConfig): Request<T> {
return this.request<T>({ ...config, method: 'PUT', url, data });
}
patch<T = unknown>(url: string, data: unknown, config?: KlientRequestConfig): Request<T> {
return this.request<T>({ ...config, method: 'PATCH', url, data });
}
delete<T = unknown>(url: string, config?: KlientRequestConfig): Request<T> {
return this.request<T>({ ...config, method: 'DELETE', url });
}
head<T = unknown>(url: string, config?: KlientRequestConfig): Request<T> {
return this.request<T>({ ...config, method: 'HEAD', url });
}
options<T = unknown>(url: string, config?: KlientRequestConfig): Request<T> {
return this.request<T>({ ...config, method: 'OPTIONS', url });
}
file(urlOrConfig: KlientRequestConfig | string): Promise<Blob> {
return this.factory.file(urlOrConfig);
}
cancelPendingRequests(): this {
this.factory.cancelPendingRequests();
return this;
}
isCancel(e: Error) {
return this.factory.isCancel(e);
}
}
|
src/klient.ts
|
klientjs-core-9a67a61
|
[
{
"filename": "src/klient.d.ts",
"retrieved_chunk": " constructor(urlOrParams?: P | string);\n get url(): string | undefined;\n get debug(): boolean;\n get factory(): RequestFactory;\n get dispatcher(): Dispatcher;\n extends(property: string, value: unknown, writable?: boolean): this;\n load(names?: string[]): this;\n on<T extends Event>(event: string, callback: Callback<T>, priority?: number, once?: boolean): this;\n once<T extends Event>(event: string, callback: Callback<T>, priority?: number): this;\n off<T extends Event>(event: string, callback: Callback<T>): this;",
"score": 0.8433918952941895
},
{
"filename": "src/events/request/request.ts",
"retrieved_chunk": " }\n get context() {\n return this.request.context;\n }\n}",
"score": 0.8421783447265625
},
{
"filename": "src/services/request/request.ts",
"retrieved_chunk": " return this.klient.dispatcher;\n }\n}",
"score": 0.8262984156608582
},
{
"filename": "src/parameters.ts",
"retrieved_chunk": "export const defaultParameters: Parameters = {\n url: undefined,\n extensions: undefined,\n request: undefined,\n debug: false\n};",
"score": 0.8184857964515686
},
{
"filename": "src/events/request/error.ts",
"retrieved_chunk": " get response() {\n return this.error.response;\n }\n get data() {\n return this.response?.data;\n }\n}",
"score": 0.810262143611908
}
] |
typescript
|
get dispatcher(): Dispatcher {
|
import * as deepmerge from 'deepmerge';
import type { AxiosRequestConfig } from 'axios';
import type Klient from '../../klient';
import Request from './request';
import type { KlientRequestConfig } from './request';
export default class RequestFactory {
model = Request;
// Requests are stocked during their execution only.
readonly requests: Request[] = [];
constructor(protected readonly klient: Klient) {}
request<T = unknown>(urlOrConfig: KlientRequestConfig | string): Request<T> {
return this.createRequest<T>(urlOrConfig).execute();
}
file(urlOrConfig: KlientRequestConfig | string): Promise<Blob> {
const config = deepmerge(
{ responseType: 'blob', context: { action: 'file' } },
typeof urlOrConfig === 'string' ? { url: urlOrConfig } : urlOrConfig
);
return this.request<Blob>(config).then(({ data }) => data);
}
cancelPendingRequests(): this {
for (let i = 0, len = this.requests.length; i < len; i += 1) {
this.requests[i].cancel();
}
return this;
}
createRequest<T = unknown>(urlOrConfig: KlientRequestConfig | string): Request<T> {
const config = typeof urlOrConfig === 'string' ? { url: urlOrConfig } : urlOrConfig;
const request = this.model.new<T>(this.prepare(config), this.klient);
// Store request during pending state only
this.requests.push(request);
// Remove request when promise has been fulfilled
request
.then((r) => {
this.removePendingRequest(request);
return r;
})
.catch((e) => {
this.removePendingRequest(request);
return e;
});
return request;
}
isCancel(e: Error) {
return this.model.isCancel(e);
}
protected prepare
|
(config: KlientRequestConfig): KlientRequestConfig {
|
return deepmerge.all([
{ baseURL: this.klient.url },
(this.klient.parameters.get('request') as AxiosRequestConfig) || {},
config
]);
}
protected removePendingRequest(request: Request) {
const i = this.requests.indexOf(request);
if (this.requests[i] instanceof Request) {
this.requests.splice(i, 1);
}
}
}
|
src/services/request/factory.ts
|
klientjs-core-9a67a61
|
[
{
"filename": "src/services/request/factory.d.ts",
"retrieved_chunk": " constructor(klient: Klient);\n request<T = unknown>(urlOrConfig: KlientRequestConfig | string): Request<T>;\n file(urlOrConfig: KlientRequestConfig | string): Promise<Blob>;\n cancelPendingRequests(): this;\n createRequest<T = unknown>(urlOrConfig: KlientRequestConfig | string): Request<T>;\n isCancel(e: Error): any;\n protected prepare(config: KlientRequestConfig): KlientRequestConfig;\n protected removePendingRequest(request: Request): void;\n}\nexport {};",
"score": 0.8696234226226807
},
{
"filename": "src/services/request/request.ts",
"retrieved_chunk": " request.config = axiosConfig;\n request.callbacks = callbacks;\n request.config.signal = request.abortController.signal;\n request.context = { ...request.context, ...context };\n return request;\n }\n static isCancel(e: Error) {\n return axios.isCancel(e);\n }\n cancel(): this {",
"score": 0.8576092720031738
},
{
"filename": "src/services/request/request.d.ts",
"retrieved_chunk": " protected readonly primaryEvent: RequestEvent;\n protected readonly abortController: AbortController;\n protected constructor(callback: RequestCallback);\n static new<T>({ context, ...axiosConfig }: KlientRequestConfig, klient: Klient): Request<T>;\n static isCancel(e: Error): boolean;\n cancel(): this;\n execute(): this;\n protected doRequest(): this;\n protected resolve(response: AxiosResponse<T>): Promise<void>;\n protected reject(error: AxiosError): Promise<void>;",
"score": 0.84220290184021
},
{
"filename": "src/klient.ts",
"retrieved_chunk": " off<T extends Event>(event: string, callback: Callback<T>): this {\n this.dispatcher.off(event, callback);\n return this;\n }\n /** === Request === */\n request<T = unknown>(urlOrConfig: KlientRequestConfig | string): Request<T> {\n return this.factory.request(urlOrConfig);\n }\n get<T = unknown>(url: string, config?: KlientRequestConfig): Request<T> {\n return this.request<T>({ ...config, method: 'GET', url });",
"score": 0.8393568992614746
},
{
"filename": "src/klient.d.ts",
"retrieved_chunk": " request<T = unknown>(urlOrConfig: KlientRequestConfig | string): Request<T>;\n get<T = unknown>(url: string, config?: KlientRequestConfig): Request<T>;\n post<T = unknown>(url: string, data: unknown, config?: KlientRequestConfig): Request<T>;\n put<T = unknown>(url: string, data: unknown, config?: KlientRequestConfig): Request<T>;\n patch<T = unknown>(url: string, data: unknown, config?: KlientRequestConfig): Request<T>;\n delete<T = unknown>(url: string, config?: KlientRequestConfig): Request<T>;\n head<T = unknown>(url: string, config?: KlientRequestConfig): Request<T>;\n options<T = unknown>(url: string, config?: KlientRequestConfig): Request<T>;\n file(urlOrConfig: KlientRequestConfig | string): Promise<Blob>;\n cancelPendingRequests(): this;",
"score": 0.8374359011650085
}
] |
typescript
|
(config: KlientRequestConfig): KlientRequestConfig {
|
import * as deepmerge from 'deepmerge';
import * as objectPath from 'object-path';
import { isPlainObject, isPlainArray, softClone } from '../../toolbox/object';
import { watch, unwatch, invokeWatchers, getWatchers, Watchable, WatchCallback } from './watch';
type BagItems = Record<string, unknown>;
export default class Bag implements BagItems, Watchable {
[x: string]: unknown;
constructor(items: BagItems = {}) {
Object.keys(items).forEach((key) => {
this[key] = items[key];
});
}
get watchers() {
return getWatchers(this);
}
has(path: string) {
return objectPath.get(this, path) !== undefined;
}
get(path: string) {
return objectPath.get(this.all(), path);
}
all() {
return softClone(this);
}
set(path: string, value: unknown): this {
const prevState = this.all();
objectPath.set(this, path, value);
return invokeWatchers(this, this.all(), prevState);
}
merge(...items: BagItems[]): this {
const prevState = this.all();
const nextState = deepmerge.all<BagItems>([this.all(), ...items], {
arrayMerge: (_destinationArray: unknown[], sourceArray: unknown[]) => sourceArray,
isMergeableObject: (o: object) => isPlainArray(o) || isPlainObject(o)
});
Object.keys(nextState).forEach((key) => {
this[key] = nextState[key];
});
return invokeWatchers(this, nextState, prevState);
}
watch(path: string,
|
onChange: WatchCallback, deep = false): this {
|
return watch(this, path, onChange, deep);
}
unwatch(path: string, onChange: WatchCallback): this {
return unwatch(this, path, onChange);
}
}
|
src/services/bag/bag.ts
|
klientjs-core-9a67a61
|
[
{
"filename": "src/services/bag/watch.d.ts",
"retrieved_chunk": "export type Watchable = object;\nexport type WatchCallback<T = unknown, Z = T> = (next: T, prev: Z) => void;\ntype WatcherItem = {\n callback: WatchCallback;\n deep: boolean;\n};\nexport declare function getWatchers(watchable: Watchable): Record<string, WatcherItem[]>;\nexport declare function watch<T extends Watchable>(watchable: T, path: string, onChange: WatchCallback, deep: boolean): T;\nexport declare function unwatch<T extends Watchable>(watchable: T, path: string, onChange: WatchCallback): T;\nexport declare function invokeWatchers<T extends Watchable>(watchable: T, next: object, prev: object): T;",
"score": 0.8803991079330444
},
{
"filename": "src/services/bag/watch.ts",
"retrieved_chunk": " return watchable;\n }\n collection.splice(index, 1);\n watchers[id][path] = collection;\n return watchable;\n}\n/**\n * Invoke all watchers attached to given watchable object with prev and next state\n */\nexport function invokeWatchers<T extends Watchable>(watchable: T, next: object, prev: object): T {",
"score": 0.8711031079292297
},
{
"filename": "src/services/bag/watch.ts",
"retrieved_chunk": " * Register callback to listen changes made on specific path of given watchable object\n */\nexport function watch<T extends Watchable>(watchable: T, path: string, onChange: WatchCallback, deep: boolean): T {\n const id = getInstanceId(watchable);\n watchers[id] = getWatchers(watchable);\n const collection = watchers[id][path] || [];\n for (let i = 0, len = collection.length; i < len; i += 1) {\n if (collection[i].callback === onChange) {\n return watchable;\n }",
"score": 0.8697443604469299
},
{
"filename": "src/services/bag/watch.ts",
"retrieved_chunk": " watched[targetPath].forEach((watcher) => {\n if ((path === targetPath || watcher.deep) && !invoked.includes(watcher)) {\n watcher.callback(objectPath.get(next, targetPath), objectPath.get(prev, targetPath));\n invoked.push(watcher);\n }\n });\n });\n });\n return watchable;\n}",
"score": 0.8630066514015198
},
{
"filename": "src/services/bag/watch.ts",
"retrieved_chunk": " }\n collection.push({ callback: onChange, deep });\n watchers[id][path] = collection;\n return watchable;\n}\n/**\n * Unregister watcher callback for given path\n */\nexport function unwatch<T extends Watchable>(watchable: T, path: string, onChange: WatchCallback): T {\n const id = getInstanceId(watchable);",
"score": 0.8564413785934448
}
] |
typescript
|
onChange: WatchCallback, deep = false): this {
|
import axios from 'axios';
import type { AxiosResponse, AxiosError, AxiosRequestConfig, AxiosPromise } from 'axios';
import RequestEvent from '../../events/request/request';
import RequestSuccessEvent from '../../events/request/success';
import RequestErrorEvent from '../../events/request/error';
import RequestDoneEvent from '../../events/request/done';
import RequestCancelEvent from '../../events/request/cancel';
import type Klient from '../..';
export type ResolveRequest = (response: AxiosResponse) => void;
export type RejectRequest = (error: AxiosError) => void;
export type RequestCallback = (resolve: ResolveRequest, reject: RejectRequest) => void;
type PromiseCallbacks = { resolve: ResolveRequest; reject: RejectRequest };
type RequestEventTypes = typeof RequestSuccessEvent | typeof RequestErrorEvent | typeof RequestCancelEvent;
type RequestContext = Record<string, any>; // eslint-disable-line @typescript-eslint/no-explicit-any
export interface KlientRequestConfig extends AxiosRequestConfig {
context?: RequestContext;
}
/**
* Request is a Promise object able to dispatch events before/after axios execution.
* Theses events allow to access and make action on request config/result at any step of execution.
* The Request will be resolved/rejected only after all events be dispatched.
*
* The events workflow is describe below :
*
* 1) RequestEvent (dispatched with abortOnFailure strategy)
* 2) Axios execution
* 2.1) Optional : RequestCancelEvent - only if request is cancelled (will reject promise and skip next events)
* 3) RequestSuccessEvent OR RequestErrorEvent
* 4) RequestDoneEvent
*/
export default class Request<T = unknown> extends Promise<AxiosResponse<T>> {
context: RequestContext = { action: 'request' };
config: KlientRequestConfig = {};
result?: AxiosError | AxiosResponse;
// Allow override axios execution
handler: (config: AxiosRequestConfig) => AxiosPromise<T> = axios;
protected klient!: Klient;
protected callbacks!: PromiseCallbacks;
protected readonly primaryEvent = new RequestEvent<T>(this);
protected readonly abortController = new AbortController();
protected constructor(callback: RequestCallback) {
super(callback);
}
static new<T>({ context, ...axiosConfig }
|
: KlientRequestConfig, klient: Klient): Request<T> {
|
const callbacks = {} as PromiseCallbacks;
const request = new this<T>((resolve: ResolveRequest, reject: RejectRequest) => {
callbacks.resolve = resolve;
callbacks.reject = reject;
});
request.klient = klient;
request.config = axiosConfig;
request.callbacks = callbacks;
request.config.signal = request.abortController.signal;
request.context = { ...request.context, ...context };
return request;
}
static isCancel(e: Error) {
return axios.isCancel(e);
}
cancel(): this {
this.abortController.abort();
return this;
}
execute(): this {
this.dispatcher
.dispatch(this.primaryEvent)
.then(() => {
this.doRequest();
})
.catch((e) => {
this.reject(e);
});
return this;
}
protected doRequest(): this {
if (!this.result) {
this.handler(this.config)
.then((r) => {
this.resolve(r);
})
.catch((e) => {
this.reject(e);
});
}
return this;
}
protected resolve(response: AxiosResponse<T>): Promise<void> {
this.result = response;
return this.dispatchResultEvent(RequestSuccessEvent).then(() => {
this.callbacks.resolve(this.result as AxiosResponse<T>);
});
}
protected reject(error: AxiosError): Promise<void> {
this.result = error;
return this.dispatchResultEvent(Request.isCancel(error) ? RequestCancelEvent : RequestErrorEvent).then(() => {
this.callbacks.reject(this.result as AxiosError);
});
}
protected dispatchResultEvent(EventClass: RequestEventTypes): Promise<void> {
const event = new EventClass(this.primaryEvent);
return new Promise((resolve) => {
this.dispatcher.dispatch(event, false).then(() => {
if (event instanceof RequestCancelEvent) {
return resolve();
}
this.dispatcher.dispatch(new RequestDoneEvent(event), false).then(resolve);
});
});
}
protected get dispatcher() {
return this.klient.dispatcher;
}
}
|
src/services/request/request.ts
|
klientjs-core-9a67a61
|
[
{
"filename": "src/services/request/request.d.ts",
"retrieved_chunk": " protected readonly primaryEvent: RequestEvent;\n protected readonly abortController: AbortController;\n protected constructor(callback: RequestCallback);\n static new<T>({ context, ...axiosConfig }: KlientRequestConfig, klient: Klient): Request<T>;\n static isCancel(e: Error): boolean;\n cancel(): this;\n execute(): this;\n protected doRequest(): this;\n protected resolve(response: AxiosResponse<T>): Promise<void>;\n protected reject(error: AxiosError): Promise<void>;",
"score": 0.95506751537323
},
{
"filename": "src/services/request/request.d.ts",
"retrieved_chunk": "export interface KlientRequestConfig extends AxiosRequestConfig {\n context?: RequestContext;\n}\nexport default class Request<T = unknown> extends Promise<AxiosResponse<T>> {\n context: RequestContext;\n config: KlientRequestConfig;\n result?: AxiosError | AxiosResponse;\n handler: (config: AxiosRequestConfig) => AxiosPromise<T>;\n protected klient: Klient;\n protected callbacks: PromiseCallbacks;",
"score": 0.9212131500244141
},
{
"filename": "src/services/request/request.d.ts",
"retrieved_chunk": "import type { AxiosResponse, AxiosError, AxiosRequestConfig, AxiosPromise } from 'axios';\ndeclare class RequestEvent {\n}\ndeclare class RequestSuccessEvent {\n}\ndeclare class RequestErrorEvent {\n}\ndeclare class RequestCancelEvent {\n}\ndeclare class Klient {",
"score": 0.89292311668396
},
{
"filename": "src/events/request/request.d.ts",
"retrieved_chunk": "import Event from '../event';\nimport type Request from '../../services/request/request';\nimport type { KlientRequestConfig } from '../../services/request/request';\nexport default class RequestEvent<T = unknown> extends Event {\n request: Request<T>;\n static NAME: string;\n constructor(request: Request<T>);\n get config(): KlientRequestConfig;\n get context(): {\n [x: string]: any;",
"score": 0.8796252012252808
},
{
"filename": "src/events/request/request.ts",
"retrieved_chunk": "import Event from '../event';\nimport type Request from '../../services/request/request';\nimport type { KlientRequestConfig } from '../../services/request/request';\nexport default class RequestEvent<T = unknown> extends Event {\n static NAME = 'request';\n constructor(public request: Request<T>) {\n super();\n }\n get config(): KlientRequestConfig {\n return this.request.config;",
"score": 0.8740214109420776
}
] |
typescript
|
: KlientRequestConfig, klient: Klient): Request<T> {
|
import Bag from './services/bag/bag';
import Dispatcher from './services/dispatcher/dispatcher';
import RequestFactory from './services/request/factory';
import Extensions from './extensions';
import { defaultParameters } from './parameters';
import type Event from './events/event';
import type Request from './services/request/request';
import type { KlientRequestConfig } from './services/request/request';
import type { Callback } from './services/dispatcher/dispatcher';
import type { Parameters } from './parameters';
export default class Klient<P extends Parameters = Parameters> {
readonly extensions: string[] = [];
readonly parameters = new Bag(defaultParameters);
readonly services = new Bag();
constructor(urlOrParams?: P | string) {
let parameters: Parameters = {};
if (typeof urlOrParams === 'string') {
parameters.url = urlOrParams;
} else if (urlOrParams && typeof urlOrParams === 'object') {
parameters = urlOrParams;
}
this.parameters.merge(parameters);
// prettier-ignore
this.services
.set('klient', this)
.set('dispatcher', new Dispatcher(this))
.set('factory', new RequestFactory(this));
this.load(this.parameters.get('extensions') as string[] | undefined);
}
/** === Common parameters === */
get url(): string | undefined {
return this.parameters.get('url');
}
get debug(): boolean {
return Boolean(this.parameters.get('debug'));
}
/** === Common services === */
get factory(): RequestFactory {
return this.services.get('factory') as RequestFactory;
}
get dispatcher(): Dispatcher {
return this.services.get('dispatcher') as Dispatcher;
}
/** === Extensions === */
extends(property: string, value: unknown, writable = false): this {
return Object.defineProperty(this, property, { writable, value });
}
load(names?: string[]): this {
|
Extensions.load(this, names);
|
return this;
}
/** === Dispatcher/Events === */
on<T extends Event>(event: string, callback: Callback<T>, priority = 0, once = false): this {
this.dispatcher.on(event, callback, priority, once);
return this;
}
once<T extends Event>(event: string, callback: Callback<T>, priority = 0): this {
this.dispatcher.once(event, callback, priority);
return this;
}
off<T extends Event>(event: string, callback: Callback<T>): this {
this.dispatcher.off(event, callback);
return this;
}
/** === Request === */
request<T = unknown>(urlOrConfig: KlientRequestConfig | string): Request<T> {
return this.factory.request(urlOrConfig);
}
get<T = unknown>(url: string, config?: KlientRequestConfig): Request<T> {
return this.request<T>({ ...config, method: 'GET', url });
}
post<T = unknown>(url: string, data: unknown, config?: KlientRequestConfig): Request<T> {
return this.request<T>({ ...config, method: 'POST', url, data });
}
put<T = unknown>(url: string, data: unknown, config?: KlientRequestConfig): Request<T> {
return this.request<T>({ ...config, method: 'PUT', url, data });
}
patch<T = unknown>(url: string, data: unknown, config?: KlientRequestConfig): Request<T> {
return this.request<T>({ ...config, method: 'PATCH', url, data });
}
delete<T = unknown>(url: string, config?: KlientRequestConfig): Request<T> {
return this.request<T>({ ...config, method: 'DELETE', url });
}
head<T = unknown>(url: string, config?: KlientRequestConfig): Request<T> {
return this.request<T>({ ...config, method: 'HEAD', url });
}
options<T = unknown>(url: string, config?: KlientRequestConfig): Request<T> {
return this.request<T>({ ...config, method: 'OPTIONS', url });
}
file(urlOrConfig: KlientRequestConfig | string): Promise<Blob> {
return this.factory.file(urlOrConfig);
}
cancelPendingRequests(): this {
this.factory.cancelPendingRequests();
return this;
}
isCancel(e: Error) {
return this.factory.isCancel(e);
}
}
|
src/klient.ts
|
klientjs-core-9a67a61
|
[
{
"filename": "src/klient.d.ts",
"retrieved_chunk": " constructor(urlOrParams?: P | string);\n get url(): string | undefined;\n get debug(): boolean;\n get factory(): RequestFactory;\n get dispatcher(): Dispatcher;\n extends(property: string, value: unknown, writable?: boolean): this;\n load(names?: string[]): this;\n on<T extends Event>(event: string, callback: Callback<T>, priority?: number, once?: boolean): this;\n once<T extends Event>(event: string, callback: Callback<T>, priority?: number): this;\n off<T extends Event>(event: string, callback: Callback<T>): this;",
"score": 0.8564498424530029
},
{
"filename": "src/extensions.ts",
"retrieved_chunk": "import type Klient from '.';\nexport type Extension = {\n name: string;\n initialize: (klient: Klient) => void;\n};\nclass Extensions extends Array<Extension> {\n load(klient: Klient, extensions?: string[]): void {\n for (let i = 0, len = this.length; i < len; i += 1) {\n const { name, initialize } = this[i];\n if (!klient.extensions.includes(name) && (!extensions || extensions.includes(name))) {",
"score": 0.8429815173149109
},
{
"filename": "src/extensions.d.ts",
"retrieved_chunk": "import type Klient from '.';\nexport type Extension = {\n name: string;\n initialize: (klient: Klient) => void;\n};\ndeclare class Extensions extends Array<Extension> {\n load(klient: Klient, extensions?: string[]): void;\n}\ndeclare const _default: Extensions;\nexport default _default;",
"score": 0.8332074880599976
},
{
"filename": "src/__tests__/extension.test.ts",
"retrieved_chunk": " Extensions.push({\n name: '@klient/test',\n initialize: (klient) => {\n klient.services.set('test', {\n run() {\n return true;\n }\n });\n klient.parameters.set('test', true);\n klient.extends('writable', 'something', true);",
"score": 0.8308165669441223
},
{
"filename": "src/extensions.ts",
"retrieved_chunk": " initialize(klient);\n klient.extensions.push(name);\n }\n }\n }\n}\nexport default new Extensions();",
"score": 0.8165663480758667
}
] |
typescript
|
Extensions.load(this, names);
|
// lifecycle methods like beforeEach, afterEach, teardown
// defined in plugins/lifecycle.ts
import Minipass from 'minipass'
import assert from 'node:assert'
import { hrtime } from 'node:process'
import { Readable } from 'node:stream'
import { format } from 'node:util'
import { CallSiteLike } from 'stack-utils'
import { FinalResults } from 'tap-parser'
import Deferred from 'trivial-deferred'
import { Base, BaseOpts } from './base.js'
import { esc } from './esc.js'
import stack from './stack.js'
import { TestPoint } from './test-point.js'
import { Waiter } from './waiter.js'
const queueEmpty = <T extends TestBase>(t: T) =>
t.queue.length === 0 ||
(t.queue.length === 1 &&
t.queue[0] === 'TAP version 14\n')
export interface ClassOf<T> {
new (): T
}
export type TapPlugin<
B extends Object,
O extends TestBaseOpts | any = any
> = ((t: TestBase, opts: O) => B) | ((t: TestBase) => B)
export interface TestBaseOpts extends BaseOpts {
/**
* The number of jobs to run in parallel. Defaults to 1
*/
jobs?: number
/**
* Test function called when this Test is executed
*/
cb?: (...args: any[]) => any
/**
* Flag to always/never show diagnostics. If unset, then
* diagnostics are shown for failing test points only.
*/
diagnostic?: boolean
}
const normalizeMessageExtra = (
defaultMessage: string,
message?: string | { [k: string]: any },
extra?: { [k: string]: any }
): [string, { [k: string]: any }] => {
if (typeof message === 'string') {
return [message || defaultMessage, extra || {}]
} else {
return [defaultMessage, message || {}]
}
}
/**
* Sigil for implicit end() calls that should not
* trigger an error if the user then calls t.end()
*/
const IMPLICIT = Symbol('implicit end')
/**
* Sigil to put in the queue to signal the end of all things
*/
const EOF = Symbol('EOF')
export type QueueEntry =
| string
| TestPoint
| Base
| typeof EOF
| Waiter
| [method: string, ...args: any[]]
/**
* The TestBaseBase class is the base class for all plugins,
* and eventually thus the Test class.
*
* This implements subtest functionality, TAP stream generation,
* lifecycle events, and only the most basic pass/fail assertions.
*
* All other features are added with plugins.
*/
export class TestBase extends Base {
// NB: generated pluginified Test class needs to declare over this
declare parent?: TestBase
promise?: Promise<any>
jobs: number
// #beforeEnd: [method: string | Symbol, ...args: any[]][] = []
subtests: Base[] = []
pool: Set<Base> = new Set()
queue: QueueEntry[] = ['TAP version 14\n']
cb?: (...args: any[]) => any
count: number = 0
ended: boolean = false
assertAt: CallSiteLike | null = null
assertStack: string | null = null
diagnostic: null | boolean = null
#planEnd: number = -1
#printedResult: boolean = false
#explicitEnded: boolean = false
#multiEndThrew: boolean = false
#n: number = 0
#noparallel: boolean = false
#occupied: null | Waiter | Base = null
#pushedEnd: boolean = false
#nextChildId: number = 1
#currentAssert: null | ((..._: any) => any) = null
#processing: boolean = false
#doingStdinOnly: boolean = false
/**
* true if the test has printed at least one TestPoint
*/
get printedResult(): boolean {
return this.#printedResult
}
constructor(options: TestBaseOpts) {
super(options)
this.jobs =
(options.jobs && Math.max(options.jobs, 1)) || 1
if (typeof options.diagnostic === 'boolean') {
this.diagnostic = options.diagnostic
}
if (options.cb) {
this.#setCB(options.cb)
}
}
#setCB<T extends TestBase>(this: T, cb: (t: T) => any) {
this.cb = (...args: any[]) =>
this.hook.runInAsyncScope(cb, this, ...args)
}
// TAP output generating methods
/**
* immediately exit this and all parent tests with a TAP
* Bail out! message.
*/
bailout(message?: string) {
if (this.parent && (this.results || this.ended)) {
this.parent.bailout(message)
} else {
this.#process()
message = message
? ' ' + ('' + esc(message)).trim()
: ''
message = message.replace(/[\r\n]/g, ' ')
this
|
.parser.write('Bail out!' + message + '\n')
}
|
this.#end(IMPLICIT)
this.#process()
}
/**
* output a TAP comment, formatted like console.log()
*/
comment(...args: any[]) {
const body = format(...args)
const message =
('# ' + body.split(/\r?\n/).join('\n# ')).trim() +
'\n'
if (this.results) {
this.write(message)
} else {
this.queue.push(message)
}
this.#process()
}
/**
* Called when the test times out.
* Options are passed as diagnostics to the threw() method
*/
timeout(options: { [k: string]: any }) {
options = options || {}
options.expired = options.expired || this.name
if (this.#occupied && this.#occupied instanceof Base) {
this.#occupied.timeout(options)
} else {
super.timeout(options)
}
this.#end(IMPLICIT)
}
/**
* Set TAP pragma configs to affect the behavior of the parser.
* Only `strict` is supported by the parser.
*/
pragma(set: { [k: string]: boolean }) {
const p = Object.keys(set).reduce(
(acc, i) =>
acc + 'pragma ' + (set[i] ? '+' : '-') + i + '\n',
''
)
this.queue.push(p)
this.#process()
}
/**
* Specify the number of Test Points expected by this test.
* Outputs a TAP plan line.
*/
plan(n: number, comment?: string) {
if (this.bailedOut) {
return
}
if (this.#planEnd !== -1) {
throw new Error('Cannot set plan more than once')
}
if (typeof n !== 'number' || n < 0) {
throw new TypeError('plan must be a number')
}
// Cannot get any tests after a trailing plan, or a plan of 0
const ending = this.count !== 0 || n === 0
if (n === 0 && comment && !this.options.skip) {
this.options.skip = comment
}
this.#planEnd = n
comment = comment ? ' # ' + esc(comment.trim()) : ''
this.queue.push('1..' + n + comment + '\n')
if (ending) {
this.#end(IMPLICIT)
} else {
this.#process()
}
}
/**
* A passing (ok) Test Point
*/
pass(message?: string, extra?: { [k: string]: any }) {
this.currentAssert = TestBase.prototype.pass
this.printResult(
true,
...normalizeMessageExtra(
'(unnamed test)',
message,
extra
)
)
return true
}
/**
* A failing (not ok) Test Point
*/
fail(message?: string, extra?: { [k: string]: any }) {
this.currentAssert = TestBase.prototype.fail
const [m, e] = normalizeMessageExtra(
'(unnamed test)',
message,
extra
)
this.printResult(false, m, e)
return !!(e.todo || e.skip)
}
/**
* The current assertion being processed. May only be set if
* not already set.
*/
get currentAssert() {
return this.#currentAssert
}
/**
* The current assertion being processed. May only be set if
* not already set.
*/
set currentAssert(fn: null | ((...a: any[]) => any)) {
if (!this.#currentAssert && typeof fn === 'function') {
this.#currentAssert = fn
}
}
/**
* Print a Test Point
*/
printResult(
ok: boolean,
message: string,
extra: { [k: string]: any },
front: boolean = false
) {
this.#printedResult = true
const n = this.count + 1
this.currentAssert = TestBase.prototype.printResult
const fn = this.#currentAssert
this.#currentAssert = null
if (this.#planEnd !== -1 && n > this.#planEnd) {
if (!this.passing()) return
const failMessage = this.#explicitEnded
? 'test after end() was called'
: 'test count exceeds plan'
const er = new Error(failMessage, {
cause: {
test: this.name,
plan: this.#planEnd,
},
})
Error.captureStackTrace(er, fn || undefined)
this.threw(er)
return
}
extra = extra || {}
if (extra.expectFail) {
ok = !ok
}
if (this.assertAt) {
extra.at = this.assertAt
this.assertAt = null
}
if (this.assertStack) {
extra.stack = this.assertStack
this.assertStack = null
}
if (typeof extra.stack === 'string' && !extra.at) {
extra.at = stack.parseLine(extra.stack.split('\n')[0])
}
if (
!ok &&
!extra.skip &&
!extra.at &&
typeof fn === 'function'
) {
extra.at = stack.at(fn)
if (!extra.todo) {
extra.stack = stack.captureString(80, fn)
}
}
const diagnostic =
typeof extra.diagnostic === 'boolean'
? extra.diagnostic
: typeof this.diagnostic === 'boolean'
? this.diagnostic
: extra.skip || extra.todo
? false
: !ok
if (diagnostic) {
extra.diagnostic = true
}
this.count = n
message = message + ''
const res = { ok, message, extra }
const tp = new TestPoint(ok, message, extra)
// when we jump the queue, skip an extra line
if (front) {
tp.message = tp.message.trimEnd() + '\n\n'
}
if (
this.#occupied &&
this.#occupied instanceof Waiter &&
this.#occupied.finishing
) {
front = true
}
if (front) {
if (
extra.tapChildBuffer ||
extra.tapChildBuffer === ''
) {
this.writeSubComment(tp)
this.parser.write(extra.tapChildBuffer)
}
this.emit('result', res)
this.parser.write(tp.ok + ++this.#n + tp.message)
if (this.bail && !ok && !extra.skip && !extra.todo) {
this.parser.write('Bail out! ' + message + '\n')
}
} else {
this.queue.push(tp)
if (this.bail && !ok && !extra.skip && !extra.todo) {
this.queue.push('Bail out! ' + message + '\n')
}
}
if (this.#planEnd === this.count) {
this.#end(IMPLICIT)
}
this.#process()
}
end(): this {
this.#end()
return super.end()
}
/**
* The leading `# Subtest` comment that introduces a child test
*/
writeSubComment<T extends TestPoint | Base>(p: T) {
const comment =
'# Subtest' +
(p.name ? ': ' + esc(p.name) : '') +
'\n'
this.parser.write(comment)
}
// end TAP otput generating methods
// flow control methods
/**
* Await the end of a Promise before proceeding.
* The supplied callback is called with the Waiter object.
*/
waitOn(
promise: Promise<any | void>,
cb: (w: Waiter) => any,
expectReject: boolean = false
): Promise<void> {
const w = new Waiter(
promise,
w => {
assert.equal(this.#occupied, w)
cb(w)
this.#occupied = null
this.#process()
},
expectReject
)
this.queue.push(w)
this.#process()
return w.promise
}
#end(implicit?: typeof IMPLICIT) {
if (this.#doingStdinOnly && implicit !== IMPLICIT)
throw new Error(
'cannot explicitly end while in stdinOnly mode'
)
this.debug('END implicit=%j', implicit === IMPLICIT)
if (this.ended && implicit === IMPLICIT) return
// beyond here we have to be actually done with things, or else
// the semantic checks on counts and such will be off.
if (!queueEmpty(this) || this.#occupied) {
if (!this.#pushedEnd) {
this.queue.push(['#end', implicit])
}
this.#pushedEnd = true
return this.#process()
}
this.ended = true
if (implicit !== IMPLICIT && !this.#multiEndThrew) {
if (this.#explicitEnded) {
this.#multiEndThrew = true
const er = new Error(
'test end() method called more than once'
)
Error.captureStackTrace(
er,
this.#currentAssert || this.#end
)
er.cause = {
test: this.name,
}
this.threw(er)
return
}
this.#explicitEnded = true
}
if (this.#planEnd === -1) {
this.debug(
'END(%s) implicit plan',
this.name,
this.count
)
this.plan(this.count)
}
this.queue.push(EOF)
this.#process()
}
#process() {
if (this.#processing) {
return this.debug(' < already processing')
}
this.debug(
'\nPROCESSING(%s)',
this.name,
this.queue.length
)
this.#processing = true
while (!this.#occupied) {
const p = this.queue.shift()
if (!p) {
this.debug('> end of queue')
break
}
if (p instanceof Base) {
this.debug('> subtest in queue', p.name)
this.#processSubtest(p)
} else if (p === EOF) {
this.debug(' > EOF', this.name)
// I AM BECOME EOF, DESTROYER OF STREAMS
this.parser.end()
} else if (p instanceof TestPoint) {
this.debug(' > TESTPOINT')
if (
p.extra.tapChildBuffer ||
p.extra.tapChildBuffer === ''
) {
this.writeSubComment(p)
this.parser.write(p.extra.tapChildBuffer)
}
this.emit('res', p.res)
this.parser.write(p.ok + ++this.#n + p.message)
} else if (typeof p === 'string') {
this.debug(' > STRING')
this.parser.write(p)
} else if (p instanceof Waiter) {
p.ready = true
this.#occupied = p
p.finish()
} else if (Array.isArray(p)) {
this.debug(' > METHOD')
const m = p.shift() as keyof this
if (typeof this[m] !== 'function') {
this.debug(
' > weird method not found in queue??',
m,
typeof this[m]
)
continue
}
const fn = (m === '#end' ? this.#end : this[m]) as (
...a: any[]
) => any
const ret = fn.call(this, ...p)
if (
ret &&
typeof ret === 'object' &&
typeof ret.then === 'function'
) {
// returned promise
ret.then(
() => {
this.#processing = false
this.#process()
},
(er: unknown) => {
this.#processing = false
this.threw(er)
}
)
return
}
/* c8 ignore start */
} else {
throw new Error('weird thing got in the queue')
}
/* c8 ignore stop */
}
while (
!this.#noparallel &&
this.pool.size < this.jobs
) {
const p = this.subtests.shift()
if (!p) {
break
}
if (!p.buffered) {
this.#noparallel = true
break
}
this.debug('start subtest', p)
this.emit('subtestStart', p)
this.pool.add(p)
if (this.bailedOut) {
this.#onBufferedEnd(p)
} else {
p.runMain(() => this.#onBufferedEnd(p))
}
}
this.debug(
'done processing',
this.queue,
this.#occupied
)
this.#processing = false
// just in case any tests ended, and we have sync stuff still
// waiting around in the queue to be processed
if (!this.#occupied && this.queue.length) {
this.#process()
}
}
#onBufferedEnd<T extends Base>(p: T) {
p.ondone = p.constructor.prototype.ondone
p.results =
p.results || new FinalResults(true, p.parser)
p.readyToProcess = true
const to = p.options.timeout
const dur =
to && p.passing() ? hrtime.bigint() - p.start : null
if (dur && to && dur > to) {
p.timeout()
} else {
p.setTimeout(0)
}
this.debug(
'%s.#onBufferedEnd',
this.name,
p.name,
p.results.bailout
)
this.pool.delete(p)
p.options.tapChildBuffer = p.output || ''
p.options.stack = ''
if (p.time) p.options.time = p.time
if (this.#occupied === p) this.#occupied = null
p.deferred?.resolve(p.results)
this.emit('subtestEnd', p)
this.#process()
}
#onIndentedEnd<T extends Base>(p: T) {
this.emit('subtestProcess', p)
p.ondone = p.constructor.prototype.ondone
p.results =
p.results || new FinalResults(true, p.parser)
this.debug('#onIndentedEnd', this.name, p.name)
this.#noparallel = false
const sti = this.subtests.indexOf(p)
if (sti !== -1) this.subtests.splice(sti, 1)
p.readyToProcess = true
p.options.time = p.time
const to = p.options.timeout
const dur =
to && p.passing() ? hrtime.bigint() - p.start : null
if (dur && to && dur > to) {
p.timeout()
} else {
p.setTimeout(0)
}
this.debug('#onIndentedEnd %s(%s)', this.name, p.name)
this.#occupied = null
this.debug(
'OIE(%s) b>shift into queue',
this.name,
this.queue
)
p.options.stack = ''
this.printResult(p.passing(), p.name, p.options, true)
this.debug(
'OIE(%s) shifted into queue',
this.name,
this.queue
)
p.deferred?.resolve(p.results)
this.emit('subtestEnd', p)
this.#process()
}
/**
* @internal
*/
main(cb: () => void) {
if (typeof this.options.timeout === 'number') {
this.setTimeout(this.options.timeout)
}
this.debug('MAIN pre', this)
const end = () => {
this.debug(' > implicit end for promise')
this.#end(IMPLICIT)
done()
}
const done = (er?: Error) => {
if (er) this.threw(er)
if (this.results || this.bailedOut) cb()
else this.ondone = () => cb()
}
// This bit of overly clever line-noise wraps the call to user-code
// in a try-catch. We can't rely on the domain for this yet, because
// the 'end' event can trigger a throw after the domain is unhooked,
// but before this is no longer the official "active test"
const ret = (() => {
if (!this.cb) return
try {
return this.cb(this)
} catch (er: any) {
if (!er || typeof er !== 'object') {
er = { error: er }
}
er.tapCaught = 'testFunctionThrow'
this.threw(er)
}
})()
if (ret && ret.then) {
this.promise = ret
ret.tapAbortPromise = done
ret.then(end, (er: any) => {
if (!er || typeof er !== 'object') {
er = { error: er }
}
er.tapCaught = 'returnedPromiseRejection'
done(er)
})
} else done()
this.debug('MAIN post', this)
}
#processSubtest<T extends Base>(p: T) {
this.debug(' > subtest')
this.#occupied = p
if (!p.buffered) {
this.emit('subtestStart', p)
this.debug(' > subtest indented')
p.stream.pipe(this.parser, { end: false })
this.writeSubComment(p)
this.debug('calling runMain', p.runMain.toString())
p.runMain(() => {
this.debug('in runMain', p.runMain.toString())
this.#onIndentedEnd(p)
})
} else if (p.readyToProcess) {
this.emit('subtestProcess', p)
this.debug(' > subtest buffered, finished')
// finished! do the thing!
this.#occupied = null
if (!p.passing() || !p.silent) {
this.printResult(
p.passing(),
p.name,
p.options,
true
)
}
} else {
this.#occupied = p
this.debug(' > subtest buffered, unfinished', p)
// unfinished buffered test.
// nothing to do yet, just leave it there.
this.queue.unshift(p)
}
}
/**
* Parse stdin as the only tap stream (ie, not as a child test)
* If used, then no other subtests or assertions are allowed.
*/
stdinOnly<T extends BaseOpts>(
extra?: T & { tapStream?: Readable | Minipass }
) {
const stream = ((extra && extra.tapStream) ||
process.stdin) as Minipass
if (!stream) {
throw new Error(
'cannot read stdin without stdin stream'
)
}
if (
this.queue.length !== 1 ||
this.queue[0] !== 'TAP version 14\n' ||
this.#processing ||
this.results ||
this.#occupied ||
this.pool.size ||
this.subtests.length
) {
throw new Error(
'Cannot use stdinOnly on a test in progress'
)
}
this.#doingStdinOnly = true
this.queue.length = 0
this.parser.on('child', p => {
// pretend to be a rooted parser, so it gets counts.
p.root = p
const t = new Base({
name: p.name,
parent: this,
parser: p,
bail: p.bail,
strict: p.strict,
omitVersion: p.omitVersion,
preserveWhitespace: p.preserveWhitespace,
childId: this.#nextChildId++,
})
this.emit('subtestAdd', t)
this.emit('subtestStart', t)
this.emit('subtestProcess', t)
p.on('complete', () => {
t.time = p.time
this.emit('subtestEnd', t)
})
})
stream.pause()
stream.pipe(this.parser)
stream.resume()
}
/**
* Mount a subtest, using this Test object as a harness.
* Exposed mainly so that it can be used by builtin plugins.
*
* @internal
*/
sub<T extends Base, O extends TestBaseOpts>(
Class: { new (options: O): T },
extra: O,
caller: (...a: any[]) => unknown
): Promise<FinalResults | null> {
if (this.bailedOut) return Promise.resolve(null)
if (this.results || this.ended) {
const er = new Error(
'cannot create subtest after parent test ends'
)
Error.captureStackTrace(er, caller)
this.threw(er)
return Promise.resolve(null)
}
extra.childId = this.#nextChildId++
if (this.shouldSkipChild(extra)) {
this.pass(extra.name, extra)
return Promise.resolve(null)
}
extra.indent = ' '
if (extra.buffered !== undefined) {
if (this.jobs > 1) {
extra.buffered = true
} else {
extra.buffered = false
}
}
extra.bail =
extra.bail !== undefined ? extra.bail : this.bail
extra.parent = this
extra.stack = stack.captureString(80, caller)
extra.context = this.context
const t = new Class(extra)
this.queue.push(t)
this.subtests.push(t)
this.emit('subtestAdd', t)
const d = new Deferred<FinalResults>()
t.deferred = d
this.#process()
return d.promise
}
/**
* Return true if the child test represented by the options object
* should be skipped. Extended by the grep/only filtering plugins.
*/
shouldSkipChild(extra: { [k: string]: any }) {
return !!(extra.skip || extra.todo)
}
// end flow control methods
}
|
src/test-base.ts
|
tapjs-core-edd7403
|
[
{
"filename": "src/test-point.ts",
"retrieved_chunk": " extra = extra || {}\n message = message\n .trim()\n .replace(/[\\n\\r]/g, ' ')\n .replace(/\\t/g, ' ')\n this.res = { ok, message, extra }\n this.extra = extra\n this.name = message\n this.message = tpMessage(esc(this.name), extra)\n }",
"score": 0.8445433378219604
},
{
"filename": "src/test-point.ts",
"retrieved_chunk": " message += ' ' + esc(extra.skip)\n }\n } else if (extra.todo) {\n message += ' # TODO'\n if (typeof extra.todo === 'string') {\n message += ' ' + esc(extra.todo)\n }\n } else if (extra.time) {\n message += ' # time=' + extra.time + 'ms'\n }",
"score": 0.8092091679573059
},
{
"filename": "src/base.ts",
"retrieved_chunk": " }\n }\n setupParser() {\n this.parser.on('line', l => this.online(l))\n this.parser.once('bailout', reason =>\n this.onbail(reason)\n )\n this.parser.on('complete', result =>\n this.oncomplete(result)\n )",
"score": 0.8074380159378052
},
{
"filename": "src/stdin.ts",
"retrieved_chunk": " }\n threw(er: any, extra?: any, proxy?: boolean) {\n extra = super.threw(er, extra, proxy)\n Object.assign(this.options, extra)\n this.parser.abort(er.message, extra)\n this.parser.end()\n }\n}",
"score": 0.8000290393829346
},
{
"filename": "src/base.ts",
"retrieved_chunk": " // a bit excessive.\n if (this.results) {\n const alreadyBailing = !this.results.ok && this.bail\n this.results.ok = false\n if (this.parent) {\n this.parent.threw(er, extra, true)\n } else if (alreadyBailing) {\n // we are already bailing out, and this is the top level,\n // just make our way hastily to the nearest exit.\n return",
"score": 0.7956457138061523
}
] |
typescript
|
.parser.write('Bail out!' + message + '\n')
}
|
import Bag from './services/bag/bag';
import Dispatcher from './services/dispatcher/dispatcher';
import RequestFactory from './services/request/factory';
import Extensions from './extensions';
import { defaultParameters } from './parameters';
import type Event from './events/event';
import type Request from './services/request/request';
import type { KlientRequestConfig } from './services/request/request';
import type { Callback } from './services/dispatcher/dispatcher';
import type { Parameters } from './parameters';
export default class Klient<P extends Parameters = Parameters> {
readonly extensions: string[] = [];
readonly parameters = new Bag(defaultParameters);
readonly services = new Bag();
constructor(urlOrParams?: P | string) {
let parameters: Parameters = {};
if (typeof urlOrParams === 'string') {
parameters.url = urlOrParams;
} else if (urlOrParams && typeof urlOrParams === 'object') {
parameters = urlOrParams;
}
this.parameters.merge(parameters);
// prettier-ignore
this.services
.set('klient', this)
.set('dispatcher', new Dispatcher(this))
.set('factory', new RequestFactory(this));
this.load(this.parameters.get('extensions') as string[] | undefined);
}
/** === Common parameters === */
get url(): string | undefined {
return this.parameters.get('url');
}
get debug(): boolean {
return Boolean(this.parameters.get('debug'));
}
/** === Common services === */
get factory(): RequestFactory {
return this.services.get('factory') as RequestFactory;
}
get dispatcher(): Dispatcher {
return this.services.get('dispatcher') as Dispatcher;
}
/** === Extensions === */
extends(property: string, value: unknown, writable = false): this {
return Object.defineProperty(this, property, { writable, value });
}
load(names?: string[]): this {
Extensions.load(this, names);
return this;
}
/** === Dispatcher/Events === */
on<T extends Event>(event: string, callback: Callback<T>, priority = 0, once = false): this {
this.dispatcher.on(event, callback, priority, once);
return this;
}
once<T extends Event>(event: string, callback: Callback<T>, priority = 0): this {
this.dispatcher.once(event, callback, priority);
return this;
}
off<T extends Event>(event: string, callback: Callback<T>): this {
this.dispatcher.off(event, callback);
return this;
}
/** === Request === */
request<T = unknown>(urlOrConfig: KlientRequestConfig | string): Request<T> {
return this.factory.
|
request(urlOrConfig);
|
}
get<T = unknown>(url: string, config?: KlientRequestConfig): Request<T> {
return this.request<T>({ ...config, method: 'GET', url });
}
post<T = unknown>(url: string, data: unknown, config?: KlientRequestConfig): Request<T> {
return this.request<T>({ ...config, method: 'POST', url, data });
}
put<T = unknown>(url: string, data: unknown, config?: KlientRequestConfig): Request<T> {
return this.request<T>({ ...config, method: 'PUT', url, data });
}
patch<T = unknown>(url: string, data: unknown, config?: KlientRequestConfig): Request<T> {
return this.request<T>({ ...config, method: 'PATCH', url, data });
}
delete<T = unknown>(url: string, config?: KlientRequestConfig): Request<T> {
return this.request<T>({ ...config, method: 'DELETE', url });
}
head<T = unknown>(url: string, config?: KlientRequestConfig): Request<T> {
return this.request<T>({ ...config, method: 'HEAD', url });
}
options<T = unknown>(url: string, config?: KlientRequestConfig): Request<T> {
return this.request<T>({ ...config, method: 'OPTIONS', url });
}
file(urlOrConfig: KlientRequestConfig | string): Promise<Blob> {
return this.factory.file(urlOrConfig);
}
cancelPendingRequests(): this {
this.factory.cancelPendingRequests();
return this;
}
isCancel(e: Error) {
return this.factory.isCancel(e);
}
}
|
src/klient.ts
|
klientjs-core-9a67a61
|
[
{
"filename": "src/klient.d.ts",
"retrieved_chunk": " request<T = unknown>(urlOrConfig: KlientRequestConfig | string): Request<T>;\n get<T = unknown>(url: string, config?: KlientRequestConfig): Request<T>;\n post<T = unknown>(url: string, data: unknown, config?: KlientRequestConfig): Request<T>;\n put<T = unknown>(url: string, data: unknown, config?: KlientRequestConfig): Request<T>;\n patch<T = unknown>(url: string, data: unknown, config?: KlientRequestConfig): Request<T>;\n delete<T = unknown>(url: string, config?: KlientRequestConfig): Request<T>;\n head<T = unknown>(url: string, config?: KlientRequestConfig): Request<T>;\n options<T = unknown>(url: string, config?: KlientRequestConfig): Request<T>;\n file(urlOrConfig: KlientRequestConfig | string): Promise<Blob>;\n cancelPendingRequests(): this;",
"score": 0.9011382460594177
},
{
"filename": "src/services/request/factory.ts",
"retrieved_chunk": " request<T = unknown>(urlOrConfig: KlientRequestConfig | string): Request<T> {\n return this.createRequest<T>(urlOrConfig).execute();\n }\n file(urlOrConfig: KlientRequestConfig | string): Promise<Blob> {\n const config = deepmerge(\n { responseType: 'blob', context: { action: 'file' } },\n typeof urlOrConfig === 'string' ? { url: urlOrConfig } : urlOrConfig\n );\n return this.request<Blob>(config).then(({ data }) => data);\n }",
"score": 0.8874261379241943
},
{
"filename": "src/services/request/factory.ts",
"retrieved_chunk": " cancelPendingRequests(): this {\n for (let i = 0, len = this.requests.length; i < len; i += 1) {\n this.requests[i].cancel();\n }\n return this;\n }\n createRequest<T = unknown>(urlOrConfig: KlientRequestConfig | string): Request<T> {\n const config = typeof urlOrConfig === 'string' ? { url: urlOrConfig } : urlOrConfig;\n const request = this.model.new<T>(this.prepare(config), this.klient);\n // Store request during pending state only",
"score": 0.8857603073120117
},
{
"filename": "src/events/request/request.ts",
"retrieved_chunk": "import Event from '../event';\nimport type Request from '../../services/request/request';\nimport type { KlientRequestConfig } from '../../services/request/request';\nexport default class RequestEvent<T = unknown> extends Event {\n static NAME = 'request';\n constructor(public request: Request<T>) {\n super();\n }\n get config(): KlientRequestConfig {\n return this.request.config;",
"score": 0.8823561668395996
},
{
"filename": "src/services/request/factory.d.ts",
"retrieved_chunk": " constructor(klient: Klient);\n request<T = unknown>(urlOrConfig: KlientRequestConfig | string): Request<T>;\n file(urlOrConfig: KlientRequestConfig | string): Promise<Blob>;\n cancelPendingRequests(): this;\n createRequest<T = unknown>(urlOrConfig: KlientRequestConfig | string): Request<T>;\n isCancel(e: Error): any;\n protected prepare(config: KlientRequestConfig): KlientRequestConfig;\n protected removePendingRequest(request: Request): void;\n}\nexport {};",
"score": 0.8796113729476929
}
] |
typescript
|
request(urlOrConfig);
|
import Bag from './services/bag/bag';
import Dispatcher from './services/dispatcher/dispatcher';
import RequestFactory from './services/request/factory';
import Extensions from './extensions';
import { defaultParameters } from './parameters';
import type Event from './events/event';
import type Request from './services/request/request';
import type { KlientRequestConfig } from './services/request/request';
import type { Callback } from './services/dispatcher/dispatcher';
import type { Parameters } from './parameters';
export default class Klient<P extends Parameters = Parameters> {
readonly extensions: string[] = [];
readonly parameters = new Bag(defaultParameters);
readonly services = new Bag();
constructor(urlOrParams?: P | string) {
let parameters: Parameters = {};
if (typeof urlOrParams === 'string') {
parameters.url = urlOrParams;
} else if (urlOrParams && typeof urlOrParams === 'object') {
parameters = urlOrParams;
}
this.parameters.merge(parameters);
// prettier-ignore
this.services
.set('klient', this)
.set('dispatcher', new Dispatcher(this))
.set('factory', new RequestFactory(this));
this.load(this.parameters.get('extensions') as string[] | undefined);
}
/** === Common parameters === */
get url(): string | undefined {
return this.parameters.get('url');
}
get debug(): boolean {
return Boolean(this.parameters.get('debug'));
}
/** === Common services === */
get factory(): RequestFactory {
return this.services.get('factory') as RequestFactory;
}
get dispatcher(): Dispatcher {
return this.services.get('dispatcher') as Dispatcher;
}
/** === Extensions === */
extends(property: string, value: unknown, writable = false): this {
return Object.defineProperty(this, property, { writable, value });
}
load(names?: string[]): this {
Extensions.load(this, names);
return this;
}
/** === Dispatcher/Events === */
on<T extends Event>(event: string, callback: Callback<T>, priority = 0, once = false): this {
this.dispatcher.on(event, callback, priority, once);
return this;
}
once<T extends Event>(event: string, callback: Callback<T>, priority = 0): this {
this.dispatcher.once(event, callback, priority);
return this;
}
off<T extends Event>(event: string, callback: Callback<T>): this {
this.dispatcher.off(event, callback);
return this;
}
/** === Request === */
request<T = unknown>(urlOrConfig: KlientRequestConfig | string): Request<T> {
return this.factory.request(urlOrConfig);
}
get<T = unknown>(url: string, config?: KlientRequestConfig): Request<T> {
return this.request<T>({ ...config, method: 'GET', url });
}
post<T = unknown>(url: string, data: unknown, config?: KlientRequestConfig): Request<T> {
return this.request<T>({ ...config, method: 'POST', url, data });
}
put<T = unknown>(url: string, data: unknown, config?: KlientRequestConfig): Request<T> {
return this.request<T>({ ...config, method: 'PUT', url, data });
}
patch<T = unknown>(url: string, data: unknown, config?: KlientRequestConfig): Request<T> {
return this.request<T>({ ...config, method: 'PATCH', url, data });
}
delete<T = unknown>(url: string, config?: KlientRequestConfig): Request<T> {
return this.request<T>({ ...config, method: 'DELETE', url });
}
head<T = unknown>(url: string, config?: KlientRequestConfig): Request<T> {
return this.request<T>({ ...config, method: 'HEAD', url });
}
options<T = unknown>(url: string, config?: KlientRequestConfig): Request<T> {
return this.request<T>({ ...config, method: 'OPTIONS', url });
}
file(urlOrConfig: KlientRequestConfig | string): Promise<Blob> {
return this.
|
factory.file(urlOrConfig);
|
}
cancelPendingRequests(): this {
this.factory.cancelPendingRequests();
return this;
}
isCancel(e: Error) {
return this.factory.isCancel(e);
}
}
|
src/klient.ts
|
klientjs-core-9a67a61
|
[
{
"filename": "src/services/request/factory.ts",
"retrieved_chunk": " request<T = unknown>(urlOrConfig: KlientRequestConfig | string): Request<T> {\n return this.createRequest<T>(urlOrConfig).execute();\n }\n file(urlOrConfig: KlientRequestConfig | string): Promise<Blob> {\n const config = deepmerge(\n { responseType: 'blob', context: { action: 'file' } },\n typeof urlOrConfig === 'string' ? { url: urlOrConfig } : urlOrConfig\n );\n return this.request<Blob>(config).then(({ data }) => data);\n }",
"score": 0.9569137692451477
},
{
"filename": "src/klient.d.ts",
"retrieved_chunk": " request<T = unknown>(urlOrConfig: KlientRequestConfig | string): Request<T>;\n get<T = unknown>(url: string, config?: KlientRequestConfig): Request<T>;\n post<T = unknown>(url: string, data: unknown, config?: KlientRequestConfig): Request<T>;\n put<T = unknown>(url: string, data: unknown, config?: KlientRequestConfig): Request<T>;\n patch<T = unknown>(url: string, data: unknown, config?: KlientRequestConfig): Request<T>;\n delete<T = unknown>(url: string, config?: KlientRequestConfig): Request<T>;\n head<T = unknown>(url: string, config?: KlientRequestConfig): Request<T>;\n options<T = unknown>(url: string, config?: KlientRequestConfig): Request<T>;\n file(urlOrConfig: KlientRequestConfig | string): Promise<Blob>;\n cancelPendingRequests(): this;",
"score": 0.9462548494338989
},
{
"filename": "src/services/request/factory.d.ts",
"retrieved_chunk": " constructor(klient: Klient);\n request<T = unknown>(urlOrConfig: KlientRequestConfig | string): Request<T>;\n file(urlOrConfig: KlientRequestConfig | string): Promise<Blob>;\n cancelPendingRequests(): this;\n createRequest<T = unknown>(urlOrConfig: KlientRequestConfig | string): Request<T>;\n isCancel(e: Error): any;\n protected prepare(config: KlientRequestConfig): KlientRequestConfig;\n protected removePendingRequest(request: Request): void;\n}\nexport {};",
"score": 0.8960223197937012
},
{
"filename": "src/services/request/factory.ts",
"retrieved_chunk": " cancelPendingRequests(): this {\n for (let i = 0, len = this.requests.length; i < len; i += 1) {\n this.requests[i].cancel();\n }\n return this;\n }\n createRequest<T = unknown>(urlOrConfig: KlientRequestConfig | string): Request<T> {\n const config = typeof urlOrConfig === 'string' ? { url: urlOrConfig } : urlOrConfig;\n const request = this.model.new<T>(this.prepare(config), this.klient);\n // Store request during pending state only",
"score": 0.8491991758346558
},
{
"filename": "src/services/request/request.d.ts",
"retrieved_chunk": "export interface KlientRequestConfig extends AxiosRequestConfig {\n context?: RequestContext;\n}\nexport default class Request<T = unknown> extends Promise<AxiosResponse<T>> {\n context: RequestContext;\n config: KlientRequestConfig;\n result?: AxiosError | AxiosResponse;\n handler: (config: AxiosRequestConfig) => AxiosPromise<T>;\n protected klient: Klient;\n protected callbacks: PromiseCallbacks;",
"score": 0.8404293060302734
}
] |
typescript
|
factory.file(urlOrConfig);
|
import axios from 'axios';
import type { AxiosResponse, AxiosError, AxiosRequestConfig, AxiosPromise } from 'axios';
import RequestEvent from '../../events/request/request';
import RequestSuccessEvent from '../../events/request/success';
import RequestErrorEvent from '../../events/request/error';
import RequestDoneEvent from '../../events/request/done';
import RequestCancelEvent from '../../events/request/cancel';
import type Klient from '../..';
export type ResolveRequest = (response: AxiosResponse) => void;
export type RejectRequest = (error: AxiosError) => void;
export type RequestCallback = (resolve: ResolveRequest, reject: RejectRequest) => void;
type PromiseCallbacks = { resolve: ResolveRequest; reject: RejectRequest };
type RequestEventTypes = typeof RequestSuccessEvent | typeof RequestErrorEvent | typeof RequestCancelEvent;
type RequestContext = Record<string, any>; // eslint-disable-line @typescript-eslint/no-explicit-any
export interface KlientRequestConfig extends AxiosRequestConfig {
context?: RequestContext;
}
/**
* Request is a Promise object able to dispatch events before/after axios execution.
* Theses events allow to access and make action on request config/result at any step of execution.
* The Request will be resolved/rejected only after all events be dispatched.
*
* The events workflow is describe below :
*
* 1) RequestEvent (dispatched with abortOnFailure strategy)
* 2) Axios execution
* 2.1) Optional : RequestCancelEvent - only if request is cancelled (will reject promise and skip next events)
* 3) RequestSuccessEvent OR RequestErrorEvent
* 4) RequestDoneEvent
*/
export default class Request<T = unknown> extends Promise<AxiosResponse<T>> {
context: RequestContext = { action: 'request' };
config: KlientRequestConfig = {};
result?: AxiosError | AxiosResponse;
// Allow override axios execution
handler: (config: AxiosRequestConfig) => AxiosPromise<T> = axios;
protected klient!: Klient;
protected callbacks!: PromiseCallbacks;
protected readonly primaryEvent = new RequestEvent<T>(this);
protected readonly abortController = new AbortController();
protected constructor(callback: RequestCallback) {
super(callback);
}
static new<T>({ context, ...axiosConfig }: KlientRequestConfig, klient: Klient): Request<T> {
const callbacks = {} as PromiseCallbacks;
const request = new this<T>((resolve: ResolveRequest, reject: RejectRequest) => {
callbacks.resolve = resolve;
callbacks.reject = reject;
});
request.klient = klient;
request.config = axiosConfig;
request.callbacks = callbacks;
request.config.signal = request.abortController.signal;
request.context = { ...request.context, ...context };
return request;
}
static isCancel(e: Error) {
return axios.isCancel(e);
}
cancel(): this {
this.abortController.abort();
return this;
}
execute(): this {
this.dispatcher
.dispatch(this.primaryEvent)
.then(() => {
this.doRequest();
})
.catch((e) => {
this.reject(e);
});
return this;
}
protected doRequest(): this {
if (!this.result) {
this.handler(this.config)
.then((r) => {
this.resolve(r);
})
.catch((e) => {
this.reject(e);
});
}
return this;
}
protected resolve(response: AxiosResponse<T>): Promise<void> {
this.result = response;
return this.dispatchResultEvent(RequestSuccessEvent).then(() => {
this.callbacks.resolve(this.result as AxiosResponse<T>);
});
}
protected reject(error: AxiosError): Promise<void> {
this.result = error;
return this.dispatchResultEvent(Request.isCancel(error) ? RequestCancelEvent : RequestErrorEvent).then(() => {
this.callbacks.reject(this.result as AxiosError);
});
}
protected dispatchResultEvent(EventClass: RequestEventTypes): Promise<void> {
const event = new EventClass(this.primaryEvent);
return new Promise((resolve) => {
this.dispatcher.dispatch(event, false).then(() => {
if (event instanceof RequestCancelEvent) {
return resolve();
}
|
this.dispatcher.dispatch(new RequestDoneEvent(event), false).then(resolve);
|
});
});
}
protected get dispatcher() {
return this.klient.dispatcher;
}
}
|
src/services/request/request.ts
|
klientjs-core-9a67a61
|
[
{
"filename": "src/services/request/request.d.ts",
"retrieved_chunk": " protected dispatchResultEvent(EventClass: RequestEventTypes): Promise<void>;\n protected get dispatcher(): any;\n}\nexport {};",
"score": 0.904747724533081
},
{
"filename": "src/services/request/request.d.ts",
"retrieved_chunk": " protected readonly primaryEvent: RequestEvent;\n protected readonly abortController: AbortController;\n protected constructor(callback: RequestCallback);\n static new<T>({ context, ...axiosConfig }: KlientRequestConfig, klient: Klient): Request<T>;\n static isCancel(e: Error): boolean;\n cancel(): this;\n execute(): this;\n protected doRequest(): this;\n protected resolve(response: AxiosResponse<T>): Promise<void>;\n protected reject(error: AxiosError): Promise<void>;",
"score": 0.8394322395324707
},
{
"filename": "src/events/request/done.ts",
"retrieved_chunk": "import RequestEvent from './request';\nimport RequestSuccessEvent from './success';\nimport type RequestErrorEvent from './error';\nexport default class RequestDoneEvent<T = unknown> extends RequestEvent {\n static NAME = 'request:done';\n constructor(public relatedEvent: RequestSuccessEvent<T> | RequestErrorEvent<T>) {\n super(relatedEvent.request);\n }\n get success() {\n return this.relatedEvent instanceof RequestSuccessEvent;",
"score": 0.8255000114440918
},
{
"filename": "src/__tests__/debug.test.ts",
"retrieved_chunk": " .then(() => {\n expect(spyRequestEvent).toBeCalledTimes(1);\n expect(spyStartDispatchEvent).toBeCalledTimes(3);\n expect(spyInvokingEvent).toBeCalledTimes(2);\n expect(spyInvokedEvent).toBeCalledTimes(2);\n expect(spyDispatchEndEvent).toBeCalledTimes(3);\n expect(spyDispatchFailedEvent).toBeCalledTimes(0);\n expect(spyDispatchStoppedEvent).toBeCalledTimes(0);\n })\n .catch((e) => {",
"score": 0.8225572109222412
},
{
"filename": "src/services/dispatcher/dispatcher.d.ts",
"retrieved_chunk": "export default class Dispatcher {\n protected readonly klient: Klient;\n readonly listeners: Listeners;\n constructor(klient: Klient);\n on<T extends Event>(event: string, callback: Callback<T>, priority?: number, once?: boolean): this;\n once<T extends Event>(event: string, callback: Callback<T>, priority?: number): this;\n off<T extends Event>(event: string, callback: Callback<T>): this;\n dispatch(e: Event, abortOnFailure?: boolean): Promise<void>;\n protected findListenerIndex<T extends Event>(event: string, callback: Callback<T>): number | undefined;\n protected static handleListenerSkipping(event: Event, listener: Listener<never>): boolean | void;",
"score": 0.8215448260307312
}
] |
typescript
|
this.dispatcher.dispatch(new RequestDoneEvent(event), false).then(resolve);
|
import * as express from 'express';
import { autoInjectable } from 'tsyringe';
import { celebrate } from 'celebrate';
import IRouteBase from '../../interfaces/IRouteBase.interface';
import ExampleController from './example.controller';
import schemas from './example.schema'
@autoInjectable()
export default class FooRoute implements IRouteBase {
private exampleController: ExampleController;
constructor(exampleController: ExampleController) {
this.exampleController = exampleController;
this.initializeRoutes();
}
public router = express.Router();
initializeRoutes() {
/**
* @swagger
*
* /example:
* get:
* summary: Get a Example
* description: Retrieve a Example
* tags:
* - example
* produces:
* - application/json
* parameters:
* - name: id
* in: query
* required: true
* description: Example ID.
* schema:
* type: integer
* responses:
* 200:
* description: Example value.
* schema:
* type: object
* properties:
* value:
* type: string
*/
|
this.router.get('/example', celebrate(schemas.getFoo), this.exampleController.getExampleValue);
|
}
}
|
src/modules/example/example.route.ts
|
erdemkosk-typescript-express-boilerplate-5b4e494
|
[
{
"filename": "src/modules/example/example.controller.ts",
"retrieved_chunk": " const { id } = req.query;\n const example = await this.exampleService.getExampleValue(id);\n res.status(200).json(example);\n };\n}",
"score": 0.8664126992225647
},
{
"filename": "src/modules/example/example.controller.ts",
"retrieved_chunk": "import { Request, Response } from 'express';\nimport { autoInjectable } from 'tsyringe';\nimport ExampleService from './example.service';\n@autoInjectable()\nexport default class ExampleController {\n exampleService: ExampleService;\n constructor(exampleService: ExampleService) {\n this.exampleService = exampleService;\n }\n public getExampleValue = async (req: Request, res: Response): Promise<void> => {",
"score": 0.8320243954658508
},
{
"filename": "src/modules/example/example.schema.ts",
"retrieved_chunk": "import { Joi, Segments } from 'celebrate';\nconst schemas = {\n getFoo: {\n [Segments.QUERY]: {\n id: Joi.number().required(),\n },\n },\n};\nexport default schemas;",
"score": 0.82052081823349
},
{
"filename": "src/modules/example/example.repository.ts",
"retrieved_chunk": "export default class ExampleRepository {\n public async getExampleValue(id: number) {\n const examples = [{\n id: 1,\n name: 'erdem',\n },\n {\n id: 1,\n name: 'kosk',\n }];",
"score": 0.7824856042861938
},
{
"filename": "src/modules/example/example.service.ts",
"retrieved_chunk": "import { autoInjectable } from 'tsyringe';\nimport ExampleRepository from './example.repository';\nimport { ERROR_CLASSES } from '../../util/error.util';\n@autoInjectable()\nexport default class FooService {\n exampleRepository: ExampleRepository;\n constructor(exampleRepository: ExampleRepository) {\n this.exampleRepository = exampleRepository;\n }\n async getExampleValue(id:number) {",
"score": 0.7820086479187012
}
] |
typescript
|
this.router.get('/example', celebrate(schemas.getFoo), this.exampleController.getExampleValue);
|
/* eslint-disable @typescript-eslint/no-explicit-any */
import * as express from 'express';
import 'express-async-errors';
import { Application } from 'express';
import * as swaggerUi from 'swagger-ui-express';
import { swaggerSpec } from './util/swagger.util';
import Logger from './util/logger.util'
class App {
public app: Application;
public port: number;
constructor(
appInit: { port: number; earlyMiddlewares: any; lateMiddlewares: any; routes: any; },
) {
this.app = express();
this.port = appInit.port;
this.middlewares(appInit.earlyMiddlewares);
this.routes(appInit.routes);
this.middlewares(appInit.lateMiddlewares);
this.assets();
this.template();
}
private middlewares(middlewares: { forEach: (arg0: (middleware: any) => void) => void; }) {
middlewares.forEach((middleware) => {
this.app.use(middleware);
});
}
private routes(routes: { forEach: (arg0: (route: any) => void) => void; }) {
routes.forEach((route) => {
this.app.use('/', route.router);
});
this.app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerSpec));
}
// eslint-disable-next-line @typescript-eslint/no-empty-function
private assets() {
}
// eslint-disable-next-line @typescript-eslint/no-empty-function
private template() {
}
public listen() {
this.app.listen(this.port, () => {
|
Logger.info(`App listening on the http://localhost:${this.port}`);
|
});
}
}
export default App;
|
src/app.ts
|
erdemkosk-typescript-express-boilerplate-5b4e494
|
[
{
"filename": "src/server.ts",
"retrieved_chunk": " lateMiddlewares: [\n errors({ statusCode: 422 }),\n errorMiddleware,\n ],\n});\napp.listen();",
"score": 0.8470629453659058
},
{
"filename": "src/server.ts",
"retrieved_chunk": "const app = new App({\n port: config.port,\n earlyMiddlewares: [\n bodyParser.json(),\n bodyParser.urlencoded({ extended: true }),\n loggerMiddleware,\n cors(),\n helmet(),\n ],\n routes: ContainerLogic.getRouteClasses(),",
"score": 0.8353481888771057
},
{
"filename": "src/server.ts",
"retrieved_chunk": "import * as bodyParser from 'body-parser';\nimport * as cors from 'cors';\nimport helmet from 'helmet';\nimport { errors } from 'celebrate';\nimport config from './config';\nimport App from './app';\nimport loggerMiddleware from './middleware/logger.middleware';\nimport errorMiddleware from './middleware/error.middleware';\nimport { ContainerLogic } from './logic/container.logic';\nimport('express-async-errors');",
"score": 0.801856279373169
},
{
"filename": "src/modules/example/example.route.ts",
"retrieved_chunk": " this.exampleController = exampleController;\n this.initializeRoutes();\n }\n public router = express.Router();\n initializeRoutes() {\n /**\n * @swagger\n *\n * /example:\n * get:",
"score": 0.7934945821762085
},
{
"filename": "src/config/enviroments/base.ts",
"retrieved_chunk": "import IConfig from '../IConfig.interface';\nclass BaseConfig implements IConfig {\n public port = Number(process.env.PORT) || 80;\n}\nexport default BaseConfig;",
"score": 0.7847542762756348
}
] |
typescript
|
Logger.info(`App listening on the http://localhost:${this.port}`);
|
// lifecycle methods like beforeEach, afterEach, teardown
// defined in plugins/lifecycle.ts
import Minipass from 'minipass'
import assert from 'node:assert'
import { hrtime } from 'node:process'
import { Readable } from 'node:stream'
import { format } from 'node:util'
import { CallSiteLike } from 'stack-utils'
import { FinalResults } from 'tap-parser'
import Deferred from 'trivial-deferred'
import { Base, BaseOpts } from './base.js'
import { esc } from './esc.js'
import stack from './stack.js'
import { TestPoint } from './test-point.js'
import { Waiter } from './waiter.js'
const queueEmpty = <T extends TestBase>(t: T) =>
t.queue.length === 0 ||
(t.queue.length === 1 &&
t.queue[0] === 'TAP version 14\n')
export interface ClassOf<T> {
new (): T
}
export type TapPlugin<
B extends Object,
O extends TestBaseOpts | any = any
> = ((t: TestBase, opts: O) => B) | ((t: TestBase) => B)
export interface TestBaseOpts extends BaseOpts {
/**
* The number of jobs to run in parallel. Defaults to 1
*/
jobs?: number
/**
* Test function called when this Test is executed
*/
cb?: (...args: any[]) => any
/**
* Flag to always/never show diagnostics. If unset, then
* diagnostics are shown for failing test points only.
*/
diagnostic?: boolean
}
const normalizeMessageExtra = (
defaultMessage: string,
message?: string | { [k: string]: any },
extra?: { [k: string]: any }
): [string, { [k: string]: any }] => {
if (typeof message === 'string') {
return [message || defaultMessage, extra || {}]
} else {
return [defaultMessage, message || {}]
}
}
/**
* Sigil for implicit end() calls that should not
* trigger an error if the user then calls t.end()
*/
const IMPLICIT = Symbol('implicit end')
/**
* Sigil to put in the queue to signal the end of all things
*/
const EOF = Symbol('EOF')
export type QueueEntry =
| string
| TestPoint
| Base
| typeof EOF
| Waiter
| [method: string, ...args: any[]]
/**
* The TestBaseBase class is the base class for all plugins,
* and eventually thus the Test class.
*
* This implements subtest functionality, TAP stream generation,
* lifecycle events, and only the most basic pass/fail assertions.
*
* All other features are added with plugins.
*/
export class TestBase extends Base {
// NB: generated pluginified Test class needs to declare over this
declare parent?: TestBase
promise?: Promise<any>
jobs: number
// #beforeEnd: [method: string | Symbol, ...args: any[]][] = []
subtests: Base[] = []
pool: Set<Base> = new Set()
queue: QueueEntry[] = ['TAP version 14\n']
cb?: (...args: any[]) => any
count: number = 0
ended: boolean = false
assertAt: CallSiteLike | null = null
assertStack: string | null = null
diagnostic: null | boolean = null
#planEnd: number = -1
#printedResult: boolean = false
#explicitEnded: boolean = false
#multiEndThrew: boolean = false
#n: number = 0
#noparallel: boolean = false
#occupied: null | Waiter | Base = null
#pushedEnd: boolean = false
#nextChildId: number = 1
#currentAssert: null | ((..._: any) => any) = null
#processing: boolean = false
#doingStdinOnly: boolean = false
/**
* true if the test has printed at least one TestPoint
*/
get printedResult(): boolean {
return this.#printedResult
}
constructor(options: TestBaseOpts) {
super(options)
this.jobs =
(options.jobs && Math.max(options.jobs, 1)) || 1
if (typeof options.diagnostic === 'boolean') {
this.diagnostic = options.diagnostic
}
if (options.cb) {
this.#setCB(options.cb)
}
}
#setCB<T extends TestBase>(this: T, cb: (t: T) => any) {
this.cb = (...args: any[]) =>
this.hook.runInAsyncScope(cb, this, ...args)
}
// TAP output generating methods
/**
* immediately exit this and all parent tests with a TAP
* Bail out! message.
*/
bailout(message?: string) {
if (this.parent && (this.results || this.ended)) {
this.parent.bailout(message)
} else {
this.#process()
message = message
? ' ' + ('' + esc(message)).trim()
: ''
message = message.replace(/[\r\n]/g, ' ')
this.parser.write('Bail out!' + message + '\n')
}
this.#end(IMPLICIT)
this.#process()
}
/**
* output a TAP comment, formatted like console.log()
*/
comment(...args: any[]) {
const body = format(...args)
const message =
('# ' + body.split(/\r?\n/).join('\n# ')).trim() +
'\n'
if (this.results) {
this.
|
write(message)
} else {
|
this.queue.push(message)
}
this.#process()
}
/**
* Called when the test times out.
* Options are passed as diagnostics to the threw() method
*/
timeout(options: { [k: string]: any }) {
options = options || {}
options.expired = options.expired || this.name
if (this.#occupied && this.#occupied instanceof Base) {
this.#occupied.timeout(options)
} else {
super.timeout(options)
}
this.#end(IMPLICIT)
}
/**
* Set TAP pragma configs to affect the behavior of the parser.
* Only `strict` is supported by the parser.
*/
pragma(set: { [k: string]: boolean }) {
const p = Object.keys(set).reduce(
(acc, i) =>
acc + 'pragma ' + (set[i] ? '+' : '-') + i + '\n',
''
)
this.queue.push(p)
this.#process()
}
/**
* Specify the number of Test Points expected by this test.
* Outputs a TAP plan line.
*/
plan(n: number, comment?: string) {
if (this.bailedOut) {
return
}
if (this.#planEnd !== -1) {
throw new Error('Cannot set plan more than once')
}
if (typeof n !== 'number' || n < 0) {
throw new TypeError('plan must be a number')
}
// Cannot get any tests after a trailing plan, or a plan of 0
const ending = this.count !== 0 || n === 0
if (n === 0 && comment && !this.options.skip) {
this.options.skip = comment
}
this.#planEnd = n
comment = comment ? ' # ' + esc(comment.trim()) : ''
this.queue.push('1..' + n + comment + '\n')
if (ending) {
this.#end(IMPLICIT)
} else {
this.#process()
}
}
/**
* A passing (ok) Test Point
*/
pass(message?: string, extra?: { [k: string]: any }) {
this.currentAssert = TestBase.prototype.pass
this.printResult(
true,
...normalizeMessageExtra(
'(unnamed test)',
message,
extra
)
)
return true
}
/**
* A failing (not ok) Test Point
*/
fail(message?: string, extra?: { [k: string]: any }) {
this.currentAssert = TestBase.prototype.fail
const [m, e] = normalizeMessageExtra(
'(unnamed test)',
message,
extra
)
this.printResult(false, m, e)
return !!(e.todo || e.skip)
}
/**
* The current assertion being processed. May only be set if
* not already set.
*/
get currentAssert() {
return this.#currentAssert
}
/**
* The current assertion being processed. May only be set if
* not already set.
*/
set currentAssert(fn: null | ((...a: any[]) => any)) {
if (!this.#currentAssert && typeof fn === 'function') {
this.#currentAssert = fn
}
}
/**
* Print a Test Point
*/
printResult(
ok: boolean,
message: string,
extra: { [k: string]: any },
front: boolean = false
) {
this.#printedResult = true
const n = this.count + 1
this.currentAssert = TestBase.prototype.printResult
const fn = this.#currentAssert
this.#currentAssert = null
if (this.#planEnd !== -1 && n > this.#planEnd) {
if (!this.passing()) return
const failMessage = this.#explicitEnded
? 'test after end() was called'
: 'test count exceeds plan'
const er = new Error(failMessage, {
cause: {
test: this.name,
plan: this.#planEnd,
},
})
Error.captureStackTrace(er, fn || undefined)
this.threw(er)
return
}
extra = extra || {}
if (extra.expectFail) {
ok = !ok
}
if (this.assertAt) {
extra.at = this.assertAt
this.assertAt = null
}
if (this.assertStack) {
extra.stack = this.assertStack
this.assertStack = null
}
if (typeof extra.stack === 'string' && !extra.at) {
extra.at = stack.parseLine(extra.stack.split('\n')[0])
}
if (
!ok &&
!extra.skip &&
!extra.at &&
typeof fn === 'function'
) {
extra.at = stack.at(fn)
if (!extra.todo) {
extra.stack = stack.captureString(80, fn)
}
}
const diagnostic =
typeof extra.diagnostic === 'boolean'
? extra.diagnostic
: typeof this.diagnostic === 'boolean'
? this.diagnostic
: extra.skip || extra.todo
? false
: !ok
if (diagnostic) {
extra.diagnostic = true
}
this.count = n
message = message + ''
const res = { ok, message, extra }
const tp = new TestPoint(ok, message, extra)
// when we jump the queue, skip an extra line
if (front) {
tp.message = tp.message.trimEnd() + '\n\n'
}
if (
this.#occupied &&
this.#occupied instanceof Waiter &&
this.#occupied.finishing
) {
front = true
}
if (front) {
if (
extra.tapChildBuffer ||
extra.tapChildBuffer === ''
) {
this.writeSubComment(tp)
this.parser.write(extra.tapChildBuffer)
}
this.emit('result', res)
this.parser.write(tp.ok + ++this.#n + tp.message)
if (this.bail && !ok && !extra.skip && !extra.todo) {
this.parser.write('Bail out! ' + message + '\n')
}
} else {
this.queue.push(tp)
if (this.bail && !ok && !extra.skip && !extra.todo) {
this.queue.push('Bail out! ' + message + '\n')
}
}
if (this.#planEnd === this.count) {
this.#end(IMPLICIT)
}
this.#process()
}
end(): this {
this.#end()
return super.end()
}
/**
* The leading `# Subtest` comment that introduces a child test
*/
writeSubComment<T extends TestPoint | Base>(p: T) {
const comment =
'# Subtest' +
(p.name ? ': ' + esc(p.name) : '') +
'\n'
this.parser.write(comment)
}
// end TAP otput generating methods
// flow control methods
/**
* Await the end of a Promise before proceeding.
* The supplied callback is called with the Waiter object.
*/
waitOn(
promise: Promise<any | void>,
cb: (w: Waiter) => any,
expectReject: boolean = false
): Promise<void> {
const w = new Waiter(
promise,
w => {
assert.equal(this.#occupied, w)
cb(w)
this.#occupied = null
this.#process()
},
expectReject
)
this.queue.push(w)
this.#process()
return w.promise
}
#end(implicit?: typeof IMPLICIT) {
if (this.#doingStdinOnly && implicit !== IMPLICIT)
throw new Error(
'cannot explicitly end while in stdinOnly mode'
)
this.debug('END implicit=%j', implicit === IMPLICIT)
if (this.ended && implicit === IMPLICIT) return
// beyond here we have to be actually done with things, or else
// the semantic checks on counts and such will be off.
if (!queueEmpty(this) || this.#occupied) {
if (!this.#pushedEnd) {
this.queue.push(['#end', implicit])
}
this.#pushedEnd = true
return this.#process()
}
this.ended = true
if (implicit !== IMPLICIT && !this.#multiEndThrew) {
if (this.#explicitEnded) {
this.#multiEndThrew = true
const er = new Error(
'test end() method called more than once'
)
Error.captureStackTrace(
er,
this.#currentAssert || this.#end
)
er.cause = {
test: this.name,
}
this.threw(er)
return
}
this.#explicitEnded = true
}
if (this.#planEnd === -1) {
this.debug(
'END(%s) implicit plan',
this.name,
this.count
)
this.plan(this.count)
}
this.queue.push(EOF)
this.#process()
}
#process() {
if (this.#processing) {
return this.debug(' < already processing')
}
this.debug(
'\nPROCESSING(%s)',
this.name,
this.queue.length
)
this.#processing = true
while (!this.#occupied) {
const p = this.queue.shift()
if (!p) {
this.debug('> end of queue')
break
}
if (p instanceof Base) {
this.debug('> subtest in queue', p.name)
this.#processSubtest(p)
} else if (p === EOF) {
this.debug(' > EOF', this.name)
// I AM BECOME EOF, DESTROYER OF STREAMS
this.parser.end()
} else if (p instanceof TestPoint) {
this.debug(' > TESTPOINT')
if (
p.extra.tapChildBuffer ||
p.extra.tapChildBuffer === ''
) {
this.writeSubComment(p)
this.parser.write(p.extra.tapChildBuffer)
}
this.emit('res', p.res)
this.parser.write(p.ok + ++this.#n + p.message)
} else if (typeof p === 'string') {
this.debug(' > STRING')
this.parser.write(p)
} else if (p instanceof Waiter) {
p.ready = true
this.#occupied = p
p.finish()
} else if (Array.isArray(p)) {
this.debug(' > METHOD')
const m = p.shift() as keyof this
if (typeof this[m] !== 'function') {
this.debug(
' > weird method not found in queue??',
m,
typeof this[m]
)
continue
}
const fn = (m === '#end' ? this.#end : this[m]) as (
...a: any[]
) => any
const ret = fn.call(this, ...p)
if (
ret &&
typeof ret === 'object' &&
typeof ret.then === 'function'
) {
// returned promise
ret.then(
() => {
this.#processing = false
this.#process()
},
(er: unknown) => {
this.#processing = false
this.threw(er)
}
)
return
}
/* c8 ignore start */
} else {
throw new Error('weird thing got in the queue')
}
/* c8 ignore stop */
}
while (
!this.#noparallel &&
this.pool.size < this.jobs
) {
const p = this.subtests.shift()
if (!p) {
break
}
if (!p.buffered) {
this.#noparallel = true
break
}
this.debug('start subtest', p)
this.emit('subtestStart', p)
this.pool.add(p)
if (this.bailedOut) {
this.#onBufferedEnd(p)
} else {
p.runMain(() => this.#onBufferedEnd(p))
}
}
this.debug(
'done processing',
this.queue,
this.#occupied
)
this.#processing = false
// just in case any tests ended, and we have sync stuff still
// waiting around in the queue to be processed
if (!this.#occupied && this.queue.length) {
this.#process()
}
}
#onBufferedEnd<T extends Base>(p: T) {
p.ondone = p.constructor.prototype.ondone
p.results =
p.results || new FinalResults(true, p.parser)
p.readyToProcess = true
const to = p.options.timeout
const dur =
to && p.passing() ? hrtime.bigint() - p.start : null
if (dur && to && dur > to) {
p.timeout()
} else {
p.setTimeout(0)
}
this.debug(
'%s.#onBufferedEnd',
this.name,
p.name,
p.results.bailout
)
this.pool.delete(p)
p.options.tapChildBuffer = p.output || ''
p.options.stack = ''
if (p.time) p.options.time = p.time
if (this.#occupied === p) this.#occupied = null
p.deferred?.resolve(p.results)
this.emit('subtestEnd', p)
this.#process()
}
#onIndentedEnd<T extends Base>(p: T) {
this.emit('subtestProcess', p)
p.ondone = p.constructor.prototype.ondone
p.results =
p.results || new FinalResults(true, p.parser)
this.debug('#onIndentedEnd', this.name, p.name)
this.#noparallel = false
const sti = this.subtests.indexOf(p)
if (sti !== -1) this.subtests.splice(sti, 1)
p.readyToProcess = true
p.options.time = p.time
const to = p.options.timeout
const dur =
to && p.passing() ? hrtime.bigint() - p.start : null
if (dur && to && dur > to) {
p.timeout()
} else {
p.setTimeout(0)
}
this.debug('#onIndentedEnd %s(%s)', this.name, p.name)
this.#occupied = null
this.debug(
'OIE(%s) b>shift into queue',
this.name,
this.queue
)
p.options.stack = ''
this.printResult(p.passing(), p.name, p.options, true)
this.debug(
'OIE(%s) shifted into queue',
this.name,
this.queue
)
p.deferred?.resolve(p.results)
this.emit('subtestEnd', p)
this.#process()
}
/**
* @internal
*/
main(cb: () => void) {
if (typeof this.options.timeout === 'number') {
this.setTimeout(this.options.timeout)
}
this.debug('MAIN pre', this)
const end = () => {
this.debug(' > implicit end for promise')
this.#end(IMPLICIT)
done()
}
const done = (er?: Error) => {
if (er) this.threw(er)
if (this.results || this.bailedOut) cb()
else this.ondone = () => cb()
}
// This bit of overly clever line-noise wraps the call to user-code
// in a try-catch. We can't rely on the domain for this yet, because
// the 'end' event can trigger a throw after the domain is unhooked,
// but before this is no longer the official "active test"
const ret = (() => {
if (!this.cb) return
try {
return this.cb(this)
} catch (er: any) {
if (!er || typeof er !== 'object') {
er = { error: er }
}
er.tapCaught = 'testFunctionThrow'
this.threw(er)
}
})()
if (ret && ret.then) {
this.promise = ret
ret.tapAbortPromise = done
ret.then(end, (er: any) => {
if (!er || typeof er !== 'object') {
er = { error: er }
}
er.tapCaught = 'returnedPromiseRejection'
done(er)
})
} else done()
this.debug('MAIN post', this)
}
#processSubtest<T extends Base>(p: T) {
this.debug(' > subtest')
this.#occupied = p
if (!p.buffered) {
this.emit('subtestStart', p)
this.debug(' > subtest indented')
p.stream.pipe(this.parser, { end: false })
this.writeSubComment(p)
this.debug('calling runMain', p.runMain.toString())
p.runMain(() => {
this.debug('in runMain', p.runMain.toString())
this.#onIndentedEnd(p)
})
} else if (p.readyToProcess) {
this.emit('subtestProcess', p)
this.debug(' > subtest buffered, finished')
// finished! do the thing!
this.#occupied = null
if (!p.passing() || !p.silent) {
this.printResult(
p.passing(),
p.name,
p.options,
true
)
}
} else {
this.#occupied = p
this.debug(' > subtest buffered, unfinished', p)
// unfinished buffered test.
// nothing to do yet, just leave it there.
this.queue.unshift(p)
}
}
/**
* Parse stdin as the only tap stream (ie, not as a child test)
* If used, then no other subtests or assertions are allowed.
*/
stdinOnly<T extends BaseOpts>(
extra?: T & { tapStream?: Readable | Minipass }
) {
const stream = ((extra && extra.tapStream) ||
process.stdin) as Minipass
if (!stream) {
throw new Error(
'cannot read stdin without stdin stream'
)
}
if (
this.queue.length !== 1 ||
this.queue[0] !== 'TAP version 14\n' ||
this.#processing ||
this.results ||
this.#occupied ||
this.pool.size ||
this.subtests.length
) {
throw new Error(
'Cannot use stdinOnly on a test in progress'
)
}
this.#doingStdinOnly = true
this.queue.length = 0
this.parser.on('child', p => {
// pretend to be a rooted parser, so it gets counts.
p.root = p
const t = new Base({
name: p.name,
parent: this,
parser: p,
bail: p.bail,
strict: p.strict,
omitVersion: p.omitVersion,
preserveWhitespace: p.preserveWhitespace,
childId: this.#nextChildId++,
})
this.emit('subtestAdd', t)
this.emit('subtestStart', t)
this.emit('subtestProcess', t)
p.on('complete', () => {
t.time = p.time
this.emit('subtestEnd', t)
})
})
stream.pause()
stream.pipe(this.parser)
stream.resume()
}
/**
* Mount a subtest, using this Test object as a harness.
* Exposed mainly so that it can be used by builtin plugins.
*
* @internal
*/
sub<T extends Base, O extends TestBaseOpts>(
Class: { new (options: O): T },
extra: O,
caller: (...a: any[]) => unknown
): Promise<FinalResults | null> {
if (this.bailedOut) return Promise.resolve(null)
if (this.results || this.ended) {
const er = new Error(
'cannot create subtest after parent test ends'
)
Error.captureStackTrace(er, caller)
this.threw(er)
return Promise.resolve(null)
}
extra.childId = this.#nextChildId++
if (this.shouldSkipChild(extra)) {
this.pass(extra.name, extra)
return Promise.resolve(null)
}
extra.indent = ' '
if (extra.buffered !== undefined) {
if (this.jobs > 1) {
extra.buffered = true
} else {
extra.buffered = false
}
}
extra.bail =
extra.bail !== undefined ? extra.bail : this.bail
extra.parent = this
extra.stack = stack.captureString(80, caller)
extra.context = this.context
const t = new Class(extra)
this.queue.push(t)
this.subtests.push(t)
this.emit('subtestAdd', t)
const d = new Deferred<FinalResults>()
t.deferred = d
this.#process()
return d.promise
}
/**
* Return true if the child test represented by the options object
* should be skipped. Extended by the grep/only filtering plugins.
*/
shouldSkipChild(extra: { [k: string]: any }) {
return !!(extra.skip || extra.todo)
}
// end flow control methods
}
|
src/test-base.ts
|
tapjs-core-edd7403
|
[
{
"filename": "src/spawn.ts",
"retrieved_chunk": " }\n main(cb: () => void) {\n this.cb = cb\n this.setTimeout(this.options.timeout || 0)\n this.parser.on('comment', c => {\n const tomatch = c.match(/# timeout=([0-9]+)\\n$/)\n if (tomatch) {\n this.setTimeout(+tomatch[1])\n }\n })",
"score": 0.8092986345291138
},
{
"filename": "src/base.ts",
"retrieved_chunk": " const msg = format(...args).trim()\n console.error(\n prefix + msg.split('\\n').join(`\\n${prefix}`)\n )\n }\nexport interface BaseOpts {\n // parser-related options\n bail?: boolean\n strict?: boolean\n omitVersion?: boolean",
"score": 0.8069356679916382
},
{
"filename": "src/spawn.ts",
"retrieved_chunk": " : command + ' ' + args.join(' ')\n ).replace(/\\\\/g, '/')\n }\n}",
"score": 0.7938081622123718
},
{
"filename": "src/diags.ts",
"retrieved_chunk": " .map(l => (l.trim() ? ' ' + l : l.trim()))\n .join('\\n') +\n ' ...\\n'\n )\n}",
"score": 0.7923067212104797
},
{
"filename": "src/test-point.ts",
"retrieved_chunk": "}\nconst tpMessage = (\n description: string,\n extra: { [k: string]: any },\n options: TestBaseOpts = {}\n): string => {\n let message = description ? ` - ${description}` : ''\n if (extra.skip) {\n message += ' # SKIP'\n if (typeof extra.skip === 'string') {",
"score": 0.7917848825454712
}
] |
typescript
|
write(message)
} else {
|
// lifecycle methods like beforeEach, afterEach, teardown
// defined in plugins/lifecycle.ts
import Minipass from 'minipass'
import assert from 'node:assert'
import { hrtime } from 'node:process'
import { Readable } from 'node:stream'
import { format } from 'node:util'
import { CallSiteLike } from 'stack-utils'
import { FinalResults } from 'tap-parser'
import Deferred from 'trivial-deferred'
import { Base, BaseOpts } from './base.js'
import { esc } from './esc.js'
import stack from './stack.js'
import { TestPoint } from './test-point.js'
import { Waiter } from './waiter.js'
const queueEmpty = <T extends TestBase>(t: T) =>
t.queue.length === 0 ||
(t.queue.length === 1 &&
t.queue[0] === 'TAP version 14\n')
export interface ClassOf<T> {
new (): T
}
export type TapPlugin<
B extends Object,
O extends TestBaseOpts | any = any
> = ((t: TestBase, opts: O) => B) | ((t: TestBase) => B)
export interface TestBaseOpts extends BaseOpts {
/**
* The number of jobs to run in parallel. Defaults to 1
*/
jobs?: number
/**
* Test function called when this Test is executed
*/
cb?: (...args: any[]) => any
/**
* Flag to always/never show diagnostics. If unset, then
* diagnostics are shown for failing test points only.
*/
diagnostic?: boolean
}
const normalizeMessageExtra = (
defaultMessage: string,
message?: string | { [k: string]: any },
extra?: { [k: string]: any }
): [string, { [k: string]: any }] => {
if (typeof message === 'string') {
return [message || defaultMessage, extra || {}]
} else {
return [defaultMessage, message || {}]
}
}
/**
* Sigil for implicit end() calls that should not
* trigger an error if the user then calls t.end()
*/
const IMPLICIT = Symbol('implicit end')
/**
* Sigil to put in the queue to signal the end of all things
*/
const EOF = Symbol('EOF')
export type QueueEntry =
| string
| TestPoint
| Base
| typeof EOF
| Waiter
| [method: string, ...args: any[]]
/**
* The TestBaseBase class is the base class for all plugins,
* and eventually thus the Test class.
*
* This implements subtest functionality, TAP stream generation,
* lifecycle events, and only the most basic pass/fail assertions.
*
* All other features are added with plugins.
*/
export class TestBase extends Base {
// NB: generated pluginified Test class needs to declare over this
declare parent?: TestBase
promise?: Promise<any>
jobs: number
// #beforeEnd: [method: string | Symbol, ...args: any[]][] = []
subtests: Base[] = []
pool: Set<Base> = new Set()
queue: QueueEntry[] = ['TAP version 14\n']
cb?: (...args: any[]) => any
count: number = 0
ended: boolean = false
assertAt: CallSiteLike | null = null
assertStack: string | null = null
diagnostic: null | boolean = null
#planEnd: number = -1
#printedResult: boolean = false
#explicitEnded: boolean = false
#multiEndThrew: boolean = false
#n: number = 0
#noparallel: boolean = false
#occupied: null | Waiter | Base = null
#pushedEnd: boolean = false
#nextChildId: number = 1
#currentAssert: null | ((..._: any) => any) = null
#processing: boolean = false
#doingStdinOnly: boolean = false
/**
* true if the test has printed at least one TestPoint
*/
get printedResult(): boolean {
return this.#printedResult
}
constructor(options: TestBaseOpts) {
super(options)
this.jobs =
(options.jobs && Math.max(options.jobs, 1)) || 1
if (typeof options.diagnostic === 'boolean') {
this.diagnostic = options.diagnostic
}
if (options.cb) {
this.#setCB(options.cb)
}
}
#setCB<T extends TestBase>(this: T, cb: (t: T) => any) {
this.cb = (...args: any[]) =>
this.hook.runInAsyncScope(cb, this, ...args)
}
// TAP output generating methods
/**
* immediately exit this and all parent tests with a TAP
* Bail out! message.
*/
bailout(message?: string) {
if (this.parent && (this.results || this.ended)) {
this.parent.bailout(message)
} else {
this.#process()
message = message
? ' ' + ('' + esc(message)).trim()
: ''
message = message.replace(/[\r\n]/g, ' ')
this.parser.write('Bail out!' + message + '\n')
}
this.#end(IMPLICIT)
this.#process()
}
/**
* output a TAP comment, formatted like console.log()
*/
comment(...args: any[]) {
const body = format(...args)
const message =
('# ' + body.split(/\r?\n/).join('\n# ')).trim() +
'\n'
if (this.results) {
this.write(message)
} else {
this.queue.push(message)
}
this.#process()
}
/**
* Called when the test times out.
* Options are passed as diagnostics to the threw() method
*/
timeout(options: { [k: string]: any }) {
options = options || {}
options
|
.expired = options.expired || this.name
if (this.#occupied && this.#occupied instanceof Base) {
|
this.#occupied.timeout(options)
} else {
super.timeout(options)
}
this.#end(IMPLICIT)
}
/**
* Set TAP pragma configs to affect the behavior of the parser.
* Only `strict` is supported by the parser.
*/
pragma(set: { [k: string]: boolean }) {
const p = Object.keys(set).reduce(
(acc, i) =>
acc + 'pragma ' + (set[i] ? '+' : '-') + i + '\n',
''
)
this.queue.push(p)
this.#process()
}
/**
* Specify the number of Test Points expected by this test.
* Outputs a TAP plan line.
*/
plan(n: number, comment?: string) {
if (this.bailedOut) {
return
}
if (this.#planEnd !== -1) {
throw new Error('Cannot set plan more than once')
}
if (typeof n !== 'number' || n < 0) {
throw new TypeError('plan must be a number')
}
// Cannot get any tests after a trailing plan, or a plan of 0
const ending = this.count !== 0 || n === 0
if (n === 0 && comment && !this.options.skip) {
this.options.skip = comment
}
this.#planEnd = n
comment = comment ? ' # ' + esc(comment.trim()) : ''
this.queue.push('1..' + n + comment + '\n')
if (ending) {
this.#end(IMPLICIT)
} else {
this.#process()
}
}
/**
* A passing (ok) Test Point
*/
pass(message?: string, extra?: { [k: string]: any }) {
this.currentAssert = TestBase.prototype.pass
this.printResult(
true,
...normalizeMessageExtra(
'(unnamed test)',
message,
extra
)
)
return true
}
/**
* A failing (not ok) Test Point
*/
fail(message?: string, extra?: { [k: string]: any }) {
this.currentAssert = TestBase.prototype.fail
const [m, e] = normalizeMessageExtra(
'(unnamed test)',
message,
extra
)
this.printResult(false, m, e)
return !!(e.todo || e.skip)
}
/**
* The current assertion being processed. May only be set if
* not already set.
*/
get currentAssert() {
return this.#currentAssert
}
/**
* The current assertion being processed. May only be set if
* not already set.
*/
set currentAssert(fn: null | ((...a: any[]) => any)) {
if (!this.#currentAssert && typeof fn === 'function') {
this.#currentAssert = fn
}
}
/**
* Print a Test Point
*/
printResult(
ok: boolean,
message: string,
extra: { [k: string]: any },
front: boolean = false
) {
this.#printedResult = true
const n = this.count + 1
this.currentAssert = TestBase.prototype.printResult
const fn = this.#currentAssert
this.#currentAssert = null
if (this.#planEnd !== -1 && n > this.#planEnd) {
if (!this.passing()) return
const failMessage = this.#explicitEnded
? 'test after end() was called'
: 'test count exceeds plan'
const er = new Error(failMessage, {
cause: {
test: this.name,
plan: this.#planEnd,
},
})
Error.captureStackTrace(er, fn || undefined)
this.threw(er)
return
}
extra = extra || {}
if (extra.expectFail) {
ok = !ok
}
if (this.assertAt) {
extra.at = this.assertAt
this.assertAt = null
}
if (this.assertStack) {
extra.stack = this.assertStack
this.assertStack = null
}
if (typeof extra.stack === 'string' && !extra.at) {
extra.at = stack.parseLine(extra.stack.split('\n')[0])
}
if (
!ok &&
!extra.skip &&
!extra.at &&
typeof fn === 'function'
) {
extra.at = stack.at(fn)
if (!extra.todo) {
extra.stack = stack.captureString(80, fn)
}
}
const diagnostic =
typeof extra.diagnostic === 'boolean'
? extra.diagnostic
: typeof this.diagnostic === 'boolean'
? this.diagnostic
: extra.skip || extra.todo
? false
: !ok
if (diagnostic) {
extra.diagnostic = true
}
this.count = n
message = message + ''
const res = { ok, message, extra }
const tp = new TestPoint(ok, message, extra)
// when we jump the queue, skip an extra line
if (front) {
tp.message = tp.message.trimEnd() + '\n\n'
}
if (
this.#occupied &&
this.#occupied instanceof Waiter &&
this.#occupied.finishing
) {
front = true
}
if (front) {
if (
extra.tapChildBuffer ||
extra.tapChildBuffer === ''
) {
this.writeSubComment(tp)
this.parser.write(extra.tapChildBuffer)
}
this.emit('result', res)
this.parser.write(tp.ok + ++this.#n + tp.message)
if (this.bail && !ok && !extra.skip && !extra.todo) {
this.parser.write('Bail out! ' + message + '\n')
}
} else {
this.queue.push(tp)
if (this.bail && !ok && !extra.skip && !extra.todo) {
this.queue.push('Bail out! ' + message + '\n')
}
}
if (this.#planEnd === this.count) {
this.#end(IMPLICIT)
}
this.#process()
}
end(): this {
this.#end()
return super.end()
}
/**
* The leading `# Subtest` comment that introduces a child test
*/
writeSubComment<T extends TestPoint | Base>(p: T) {
const comment =
'# Subtest' +
(p.name ? ': ' + esc(p.name) : '') +
'\n'
this.parser.write(comment)
}
// end TAP otput generating methods
// flow control methods
/**
* Await the end of a Promise before proceeding.
* The supplied callback is called with the Waiter object.
*/
waitOn(
promise: Promise<any | void>,
cb: (w: Waiter) => any,
expectReject: boolean = false
): Promise<void> {
const w = new Waiter(
promise,
w => {
assert.equal(this.#occupied, w)
cb(w)
this.#occupied = null
this.#process()
},
expectReject
)
this.queue.push(w)
this.#process()
return w.promise
}
#end(implicit?: typeof IMPLICIT) {
if (this.#doingStdinOnly && implicit !== IMPLICIT)
throw new Error(
'cannot explicitly end while in stdinOnly mode'
)
this.debug('END implicit=%j', implicit === IMPLICIT)
if (this.ended && implicit === IMPLICIT) return
// beyond here we have to be actually done with things, or else
// the semantic checks on counts and such will be off.
if (!queueEmpty(this) || this.#occupied) {
if (!this.#pushedEnd) {
this.queue.push(['#end', implicit])
}
this.#pushedEnd = true
return this.#process()
}
this.ended = true
if (implicit !== IMPLICIT && !this.#multiEndThrew) {
if (this.#explicitEnded) {
this.#multiEndThrew = true
const er = new Error(
'test end() method called more than once'
)
Error.captureStackTrace(
er,
this.#currentAssert || this.#end
)
er.cause = {
test: this.name,
}
this.threw(er)
return
}
this.#explicitEnded = true
}
if (this.#planEnd === -1) {
this.debug(
'END(%s) implicit plan',
this.name,
this.count
)
this.plan(this.count)
}
this.queue.push(EOF)
this.#process()
}
#process() {
if (this.#processing) {
return this.debug(' < already processing')
}
this.debug(
'\nPROCESSING(%s)',
this.name,
this.queue.length
)
this.#processing = true
while (!this.#occupied) {
const p = this.queue.shift()
if (!p) {
this.debug('> end of queue')
break
}
if (p instanceof Base) {
this.debug('> subtest in queue', p.name)
this.#processSubtest(p)
} else if (p === EOF) {
this.debug(' > EOF', this.name)
// I AM BECOME EOF, DESTROYER OF STREAMS
this.parser.end()
} else if (p instanceof TestPoint) {
this.debug(' > TESTPOINT')
if (
p.extra.tapChildBuffer ||
p.extra.tapChildBuffer === ''
) {
this.writeSubComment(p)
this.parser.write(p.extra.tapChildBuffer)
}
this.emit('res', p.res)
this.parser.write(p.ok + ++this.#n + p.message)
} else if (typeof p === 'string') {
this.debug(' > STRING')
this.parser.write(p)
} else if (p instanceof Waiter) {
p.ready = true
this.#occupied = p
p.finish()
} else if (Array.isArray(p)) {
this.debug(' > METHOD')
const m = p.shift() as keyof this
if (typeof this[m] !== 'function') {
this.debug(
' > weird method not found in queue??',
m,
typeof this[m]
)
continue
}
const fn = (m === '#end' ? this.#end : this[m]) as (
...a: any[]
) => any
const ret = fn.call(this, ...p)
if (
ret &&
typeof ret === 'object' &&
typeof ret.then === 'function'
) {
// returned promise
ret.then(
() => {
this.#processing = false
this.#process()
},
(er: unknown) => {
this.#processing = false
this.threw(er)
}
)
return
}
/* c8 ignore start */
} else {
throw new Error('weird thing got in the queue')
}
/* c8 ignore stop */
}
while (
!this.#noparallel &&
this.pool.size < this.jobs
) {
const p = this.subtests.shift()
if (!p) {
break
}
if (!p.buffered) {
this.#noparallel = true
break
}
this.debug('start subtest', p)
this.emit('subtestStart', p)
this.pool.add(p)
if (this.bailedOut) {
this.#onBufferedEnd(p)
} else {
p.runMain(() => this.#onBufferedEnd(p))
}
}
this.debug(
'done processing',
this.queue,
this.#occupied
)
this.#processing = false
// just in case any tests ended, and we have sync stuff still
// waiting around in the queue to be processed
if (!this.#occupied && this.queue.length) {
this.#process()
}
}
#onBufferedEnd<T extends Base>(p: T) {
p.ondone = p.constructor.prototype.ondone
p.results =
p.results || new FinalResults(true, p.parser)
p.readyToProcess = true
const to = p.options.timeout
const dur =
to && p.passing() ? hrtime.bigint() - p.start : null
if (dur && to && dur > to) {
p.timeout()
} else {
p.setTimeout(0)
}
this.debug(
'%s.#onBufferedEnd',
this.name,
p.name,
p.results.bailout
)
this.pool.delete(p)
p.options.tapChildBuffer = p.output || ''
p.options.stack = ''
if (p.time) p.options.time = p.time
if (this.#occupied === p) this.#occupied = null
p.deferred?.resolve(p.results)
this.emit('subtestEnd', p)
this.#process()
}
#onIndentedEnd<T extends Base>(p: T) {
this.emit('subtestProcess', p)
p.ondone = p.constructor.prototype.ondone
p.results =
p.results || new FinalResults(true, p.parser)
this.debug('#onIndentedEnd', this.name, p.name)
this.#noparallel = false
const sti = this.subtests.indexOf(p)
if (sti !== -1) this.subtests.splice(sti, 1)
p.readyToProcess = true
p.options.time = p.time
const to = p.options.timeout
const dur =
to && p.passing() ? hrtime.bigint() - p.start : null
if (dur && to && dur > to) {
p.timeout()
} else {
p.setTimeout(0)
}
this.debug('#onIndentedEnd %s(%s)', this.name, p.name)
this.#occupied = null
this.debug(
'OIE(%s) b>shift into queue',
this.name,
this.queue
)
p.options.stack = ''
this.printResult(p.passing(), p.name, p.options, true)
this.debug(
'OIE(%s) shifted into queue',
this.name,
this.queue
)
p.deferred?.resolve(p.results)
this.emit('subtestEnd', p)
this.#process()
}
/**
* @internal
*/
main(cb: () => void) {
if (typeof this.options.timeout === 'number') {
this.setTimeout(this.options.timeout)
}
this.debug('MAIN pre', this)
const end = () => {
this.debug(' > implicit end for promise')
this.#end(IMPLICIT)
done()
}
const done = (er?: Error) => {
if (er) this.threw(er)
if (this.results || this.bailedOut) cb()
else this.ondone = () => cb()
}
// This bit of overly clever line-noise wraps the call to user-code
// in a try-catch. We can't rely on the domain for this yet, because
// the 'end' event can trigger a throw after the domain is unhooked,
// but before this is no longer the official "active test"
const ret = (() => {
if (!this.cb) return
try {
return this.cb(this)
} catch (er: any) {
if (!er || typeof er !== 'object') {
er = { error: er }
}
er.tapCaught = 'testFunctionThrow'
this.threw(er)
}
})()
if (ret && ret.then) {
this.promise = ret
ret.tapAbortPromise = done
ret.then(end, (er: any) => {
if (!er || typeof er !== 'object') {
er = { error: er }
}
er.tapCaught = 'returnedPromiseRejection'
done(er)
})
} else done()
this.debug('MAIN post', this)
}
#processSubtest<T extends Base>(p: T) {
this.debug(' > subtest')
this.#occupied = p
if (!p.buffered) {
this.emit('subtestStart', p)
this.debug(' > subtest indented')
p.stream.pipe(this.parser, { end: false })
this.writeSubComment(p)
this.debug('calling runMain', p.runMain.toString())
p.runMain(() => {
this.debug('in runMain', p.runMain.toString())
this.#onIndentedEnd(p)
})
} else if (p.readyToProcess) {
this.emit('subtestProcess', p)
this.debug(' > subtest buffered, finished')
// finished! do the thing!
this.#occupied = null
if (!p.passing() || !p.silent) {
this.printResult(
p.passing(),
p.name,
p.options,
true
)
}
} else {
this.#occupied = p
this.debug(' > subtest buffered, unfinished', p)
// unfinished buffered test.
// nothing to do yet, just leave it there.
this.queue.unshift(p)
}
}
/**
* Parse stdin as the only tap stream (ie, not as a child test)
* If used, then no other subtests or assertions are allowed.
*/
stdinOnly<T extends BaseOpts>(
extra?: T & { tapStream?: Readable | Minipass }
) {
const stream = ((extra && extra.tapStream) ||
process.stdin) as Minipass
if (!stream) {
throw new Error(
'cannot read stdin without stdin stream'
)
}
if (
this.queue.length !== 1 ||
this.queue[0] !== 'TAP version 14\n' ||
this.#processing ||
this.results ||
this.#occupied ||
this.pool.size ||
this.subtests.length
) {
throw new Error(
'Cannot use stdinOnly on a test in progress'
)
}
this.#doingStdinOnly = true
this.queue.length = 0
this.parser.on('child', p => {
// pretend to be a rooted parser, so it gets counts.
p.root = p
const t = new Base({
name: p.name,
parent: this,
parser: p,
bail: p.bail,
strict: p.strict,
omitVersion: p.omitVersion,
preserveWhitespace: p.preserveWhitespace,
childId: this.#nextChildId++,
})
this.emit('subtestAdd', t)
this.emit('subtestStart', t)
this.emit('subtestProcess', t)
p.on('complete', () => {
t.time = p.time
this.emit('subtestEnd', t)
})
})
stream.pause()
stream.pipe(this.parser)
stream.resume()
}
/**
* Mount a subtest, using this Test object as a harness.
* Exposed mainly so that it can be used by builtin plugins.
*
* @internal
*/
sub<T extends Base, O extends TestBaseOpts>(
Class: { new (options: O): T },
extra: O,
caller: (...a: any[]) => unknown
): Promise<FinalResults | null> {
if (this.bailedOut) return Promise.resolve(null)
if (this.results || this.ended) {
const er = new Error(
'cannot create subtest after parent test ends'
)
Error.captureStackTrace(er, caller)
this.threw(er)
return Promise.resolve(null)
}
extra.childId = this.#nextChildId++
if (this.shouldSkipChild(extra)) {
this.pass(extra.name, extra)
return Promise.resolve(null)
}
extra.indent = ' '
if (extra.buffered !== undefined) {
if (this.jobs > 1) {
extra.buffered = true
} else {
extra.buffered = false
}
}
extra.bail =
extra.bail !== undefined ? extra.bail : this.bail
extra.parent = this
extra.stack = stack.captureString(80, caller)
extra.context = this.context
const t = new Class(extra)
this.queue.push(t)
this.subtests.push(t)
this.emit('subtestAdd', t)
const d = new Deferred<FinalResults>()
t.deferred = d
this.#process()
return d.promise
}
/**
* Return true if the child test represented by the options object
* should be skipped. Extended by the grep/only filtering plugins.
*/
shouldSkipChild(extra: { [k: string]: any }) {
return !!(extra.skip || extra.todo)
}
// end flow control methods
}
|
src/test-base.ts
|
tapjs-core-edd7403
|
[
{
"filename": "src/base.ts",
"retrieved_chunk": " this.setTimeout(0)\n options = options || {}\n options.expired = options.expired || this.name\n const threw = this.threw(new Error('timeout!'), options)\n if (threw) {\n this.emit('timeout', threw)\n }\n }\n runMain(cb: () => void) {\n this.debug('BASE runMain')",
"score": 0.8405863046646118
},
{
"filename": "src/spawn.ts",
"retrieved_chunk": " !this.options.signal &&\n this.options.exitCode === undefined\n ) {\n super.timeout(options)\n this.proc.kill('SIGKILL')\n }\n }, 1000)\n t.unref()\n }\n }",
"score": 0.8113795518875122
},
{
"filename": "src/stdin.ts",
"retrieved_chunk": " }\n threw(er: any, extra?: any, proxy?: boolean) {\n extra = super.threw(er, extra, proxy)\n Object.assign(this.options, extra)\n this.parser.abort(er.message, extra)\n this.parser.end()\n }\n}",
"score": 0.8085556030273438
},
{
"filename": "src/base.ts",
"retrieved_chunk": " if (this.timer) {\n clearTimeout(this.timer)\n }\n this.timer = undefined\n } else {\n this.timer = setTimeout(() => this.timeout(), n)\n this.timer.unref()\n }\n }\n timeout(options?: { [k: string]: any }) {",
"score": 0.8011695146560669
},
{
"filename": "src/spawn.ts",
"retrieved_chunk": " this.parser.ok = false\n }\n return this.callCb()\n }\n timeout(options?: { [k: string]: any }) {\n if (this.proc) {\n this.proc.kill('SIGTERM')\n const t = setTimeout(() => {\n if (\n this.proc &&",
"score": 0.8006569743156433
}
] |
typescript
|
.expired = options.expired || this.name
if (this.#occupied && this.#occupied instanceof Base) {
|
// lifecycle methods like beforeEach, afterEach, teardown
// defined in plugins/lifecycle.ts
import Minipass from 'minipass'
import assert from 'node:assert'
import { hrtime } from 'node:process'
import { Readable } from 'node:stream'
import { format } from 'node:util'
import { CallSiteLike } from 'stack-utils'
import { FinalResults } from 'tap-parser'
import Deferred from 'trivial-deferred'
import { Base, BaseOpts } from './base.js'
import { esc } from './esc.js'
import stack from './stack.js'
import { TestPoint } from './test-point.js'
import { Waiter } from './waiter.js'
const queueEmpty = <T extends TestBase>(t: T) =>
t.queue.length === 0 ||
(t.queue.length === 1 &&
t.queue[0] === 'TAP version 14\n')
export interface ClassOf<T> {
new (): T
}
export type TapPlugin<
B extends Object,
O extends TestBaseOpts | any = any
> = ((t: TestBase, opts: O) => B) | ((t: TestBase) => B)
export interface TestBaseOpts extends BaseOpts {
/**
* The number of jobs to run in parallel. Defaults to 1
*/
jobs?: number
/**
* Test function called when this Test is executed
*/
cb?: (...args: any[]) => any
/**
* Flag to always/never show diagnostics. If unset, then
* diagnostics are shown for failing test points only.
*/
diagnostic?: boolean
}
const normalizeMessageExtra = (
defaultMessage: string,
message?: string | { [k: string]: any },
extra?: { [k: string]: any }
): [string, { [k: string]: any }] => {
if (typeof message === 'string') {
return [message || defaultMessage, extra || {}]
} else {
return [defaultMessage, message || {}]
}
}
/**
* Sigil for implicit end() calls that should not
* trigger an error if the user then calls t.end()
*/
const IMPLICIT = Symbol('implicit end')
/**
* Sigil to put in the queue to signal the end of all things
*/
const EOF = Symbol('EOF')
export type QueueEntry =
| string
| TestPoint
| Base
| typeof EOF
| Waiter
| [method: string, ...args: any[]]
/**
* The TestBaseBase class is the base class for all plugins,
* and eventually thus the Test class.
*
* This implements subtest functionality, TAP stream generation,
* lifecycle events, and only the most basic pass/fail assertions.
*
* All other features are added with plugins.
*/
export class TestBase extends Base {
// NB: generated pluginified Test class needs to declare over this
declare parent?: TestBase
promise?: Promise<any>
jobs: number
// #beforeEnd: [method: string | Symbol, ...args: any[]][] = []
subtests: Base[] = []
pool: Set<Base> = new Set()
queue: QueueEntry[] = ['TAP version 14\n']
cb?: (...args: any[]) => any
count: number = 0
ended: boolean = false
assertAt: CallSiteLike | null = null
assertStack: string | null = null
diagnostic: null | boolean = null
#planEnd: number = -1
#printedResult: boolean = false
#explicitEnded: boolean = false
#multiEndThrew: boolean = false
#n: number = 0
#noparallel: boolean = false
#occupied: null | Waiter | Base = null
#pushedEnd: boolean = false
#nextChildId: number = 1
#currentAssert: null | ((..._: any) => any) = null
#processing: boolean = false
#doingStdinOnly: boolean = false
/**
* true if the test has printed at least one TestPoint
*/
get printedResult(): boolean {
return this.#printedResult
}
constructor(options: TestBaseOpts) {
super(options)
this.jobs =
(options.jobs && Math.max(options.jobs, 1)) || 1
if (typeof options.diagnostic === 'boolean') {
this.diagnostic = options.diagnostic
}
if (options.cb) {
this.#setCB(options.cb)
}
}
#setCB<T extends TestBase>(this: T, cb: (t: T) => any) {
this.cb = (...args: any[]) =>
this.hook.runInAsyncScope(cb, this, ...args)
}
// TAP output generating methods
/**
* immediately exit this and all parent tests with a TAP
* Bail out! message.
*/
bailout(message?: string) {
if (this.parent && (this.results || this.ended)) {
this.parent.bailout(message)
} else {
this.#process()
message = message
? ' ' + ('' + esc(message)).trim()
: ''
message = message.replace(/[\r\n]/g, ' ')
this.parser.write('Bail out!' + message + '\n')
}
this.#end(IMPLICIT)
this.#process()
}
/**
* output a TAP comment, formatted like console.log()
*/
comment(...args: any[]) {
const body = format(...args)
const message =
('# ' + body.split(/\r?\n/).join('\n# ')).trim() +
'\n'
if (this.results) {
this.write(message)
} else {
this.queue.push(message)
}
this.#process()
}
/**
* Called when the test times out.
* Options are passed as diagnostics to the threw() method
*/
timeout(options: { [k: string]: any }) {
options = options || {}
options.expired = options.expired || this.name
if (this.#occupied && this.#occupied instanceof Base) {
this.#occupied.timeout(options)
} else {
super.timeout(options)
}
this.#end(IMPLICIT)
}
/**
* Set TAP pragma configs to affect the behavior of the parser.
* Only `strict` is supported by the parser.
*/
pragma(set: { [k: string]: boolean }) {
const p = Object.keys(set).reduce(
(acc, i) =>
acc + 'pragma ' + (set[i] ? '+' : '-') + i + '\n',
''
)
this.queue.push(p)
this.#process()
}
/**
* Specify the number of Test Points expected by this test.
* Outputs a TAP plan line.
*/
plan(n: number, comment?: string) {
if (this.bailedOut) {
return
}
if (this.#planEnd !== -1) {
throw new Error('Cannot set plan more than once')
}
if (typeof n !== 'number' || n < 0) {
throw new TypeError('plan must be a number')
}
// Cannot get any tests after a trailing plan, or a plan of 0
const ending = this.count !== 0 || n === 0
|
if (n === 0 && comment && !this.options.skip) {
|
this.options.skip = comment
}
this.#planEnd = n
comment = comment ? ' # ' + esc(comment.trim()) : ''
this.queue.push('1..' + n + comment + '\n')
if (ending) {
this.#end(IMPLICIT)
} else {
this.#process()
}
}
/**
* A passing (ok) Test Point
*/
pass(message?: string, extra?: { [k: string]: any }) {
this.currentAssert = TestBase.prototype.pass
this.printResult(
true,
...normalizeMessageExtra(
'(unnamed test)',
message,
extra
)
)
return true
}
/**
* A failing (not ok) Test Point
*/
fail(message?: string, extra?: { [k: string]: any }) {
this.currentAssert = TestBase.prototype.fail
const [m, e] = normalizeMessageExtra(
'(unnamed test)',
message,
extra
)
this.printResult(false, m, e)
return !!(e.todo || e.skip)
}
/**
* The current assertion being processed. May only be set if
* not already set.
*/
get currentAssert() {
return this.#currentAssert
}
/**
* The current assertion being processed. May only be set if
* not already set.
*/
set currentAssert(fn: null | ((...a: any[]) => any)) {
if (!this.#currentAssert && typeof fn === 'function') {
this.#currentAssert = fn
}
}
/**
* Print a Test Point
*/
printResult(
ok: boolean,
message: string,
extra: { [k: string]: any },
front: boolean = false
) {
this.#printedResult = true
const n = this.count + 1
this.currentAssert = TestBase.prototype.printResult
const fn = this.#currentAssert
this.#currentAssert = null
if (this.#planEnd !== -1 && n > this.#planEnd) {
if (!this.passing()) return
const failMessage = this.#explicitEnded
? 'test after end() was called'
: 'test count exceeds plan'
const er = new Error(failMessage, {
cause: {
test: this.name,
plan: this.#planEnd,
},
})
Error.captureStackTrace(er, fn || undefined)
this.threw(er)
return
}
extra = extra || {}
if (extra.expectFail) {
ok = !ok
}
if (this.assertAt) {
extra.at = this.assertAt
this.assertAt = null
}
if (this.assertStack) {
extra.stack = this.assertStack
this.assertStack = null
}
if (typeof extra.stack === 'string' && !extra.at) {
extra.at = stack.parseLine(extra.stack.split('\n')[0])
}
if (
!ok &&
!extra.skip &&
!extra.at &&
typeof fn === 'function'
) {
extra.at = stack.at(fn)
if (!extra.todo) {
extra.stack = stack.captureString(80, fn)
}
}
const diagnostic =
typeof extra.diagnostic === 'boolean'
? extra.diagnostic
: typeof this.diagnostic === 'boolean'
? this.diagnostic
: extra.skip || extra.todo
? false
: !ok
if (diagnostic) {
extra.diagnostic = true
}
this.count = n
message = message + ''
const res = { ok, message, extra }
const tp = new TestPoint(ok, message, extra)
// when we jump the queue, skip an extra line
if (front) {
tp.message = tp.message.trimEnd() + '\n\n'
}
if (
this.#occupied &&
this.#occupied instanceof Waiter &&
this.#occupied.finishing
) {
front = true
}
if (front) {
if (
extra.tapChildBuffer ||
extra.tapChildBuffer === ''
) {
this.writeSubComment(tp)
this.parser.write(extra.tapChildBuffer)
}
this.emit('result', res)
this.parser.write(tp.ok + ++this.#n + tp.message)
if (this.bail && !ok && !extra.skip && !extra.todo) {
this.parser.write('Bail out! ' + message + '\n')
}
} else {
this.queue.push(tp)
if (this.bail && !ok && !extra.skip && !extra.todo) {
this.queue.push('Bail out! ' + message + '\n')
}
}
if (this.#planEnd === this.count) {
this.#end(IMPLICIT)
}
this.#process()
}
end(): this {
this.#end()
return super.end()
}
/**
* The leading `# Subtest` comment that introduces a child test
*/
writeSubComment<T extends TestPoint | Base>(p: T) {
const comment =
'# Subtest' +
(p.name ? ': ' + esc(p.name) : '') +
'\n'
this.parser.write(comment)
}
// end TAP otput generating methods
// flow control methods
/**
* Await the end of a Promise before proceeding.
* The supplied callback is called with the Waiter object.
*/
waitOn(
promise: Promise<any | void>,
cb: (w: Waiter) => any,
expectReject: boolean = false
): Promise<void> {
const w = new Waiter(
promise,
w => {
assert.equal(this.#occupied, w)
cb(w)
this.#occupied = null
this.#process()
},
expectReject
)
this.queue.push(w)
this.#process()
return w.promise
}
#end(implicit?: typeof IMPLICIT) {
if (this.#doingStdinOnly && implicit !== IMPLICIT)
throw new Error(
'cannot explicitly end while in stdinOnly mode'
)
this.debug('END implicit=%j', implicit === IMPLICIT)
if (this.ended && implicit === IMPLICIT) return
// beyond here we have to be actually done with things, or else
// the semantic checks on counts and such will be off.
if (!queueEmpty(this) || this.#occupied) {
if (!this.#pushedEnd) {
this.queue.push(['#end', implicit])
}
this.#pushedEnd = true
return this.#process()
}
this.ended = true
if (implicit !== IMPLICIT && !this.#multiEndThrew) {
if (this.#explicitEnded) {
this.#multiEndThrew = true
const er = new Error(
'test end() method called more than once'
)
Error.captureStackTrace(
er,
this.#currentAssert || this.#end
)
er.cause = {
test: this.name,
}
this.threw(er)
return
}
this.#explicitEnded = true
}
if (this.#planEnd === -1) {
this.debug(
'END(%s) implicit plan',
this.name,
this.count
)
this.plan(this.count)
}
this.queue.push(EOF)
this.#process()
}
#process() {
if (this.#processing) {
return this.debug(' < already processing')
}
this.debug(
'\nPROCESSING(%s)',
this.name,
this.queue.length
)
this.#processing = true
while (!this.#occupied) {
const p = this.queue.shift()
if (!p) {
this.debug('> end of queue')
break
}
if (p instanceof Base) {
this.debug('> subtest in queue', p.name)
this.#processSubtest(p)
} else if (p === EOF) {
this.debug(' > EOF', this.name)
// I AM BECOME EOF, DESTROYER OF STREAMS
this.parser.end()
} else if (p instanceof TestPoint) {
this.debug(' > TESTPOINT')
if (
p.extra.tapChildBuffer ||
p.extra.tapChildBuffer === ''
) {
this.writeSubComment(p)
this.parser.write(p.extra.tapChildBuffer)
}
this.emit('res', p.res)
this.parser.write(p.ok + ++this.#n + p.message)
} else if (typeof p === 'string') {
this.debug(' > STRING')
this.parser.write(p)
} else if (p instanceof Waiter) {
p.ready = true
this.#occupied = p
p.finish()
} else if (Array.isArray(p)) {
this.debug(' > METHOD')
const m = p.shift() as keyof this
if (typeof this[m] !== 'function') {
this.debug(
' > weird method not found in queue??',
m,
typeof this[m]
)
continue
}
const fn = (m === '#end' ? this.#end : this[m]) as (
...a: any[]
) => any
const ret = fn.call(this, ...p)
if (
ret &&
typeof ret === 'object' &&
typeof ret.then === 'function'
) {
// returned promise
ret.then(
() => {
this.#processing = false
this.#process()
},
(er: unknown) => {
this.#processing = false
this.threw(er)
}
)
return
}
/* c8 ignore start */
} else {
throw new Error('weird thing got in the queue')
}
/* c8 ignore stop */
}
while (
!this.#noparallel &&
this.pool.size < this.jobs
) {
const p = this.subtests.shift()
if (!p) {
break
}
if (!p.buffered) {
this.#noparallel = true
break
}
this.debug('start subtest', p)
this.emit('subtestStart', p)
this.pool.add(p)
if (this.bailedOut) {
this.#onBufferedEnd(p)
} else {
p.runMain(() => this.#onBufferedEnd(p))
}
}
this.debug(
'done processing',
this.queue,
this.#occupied
)
this.#processing = false
// just in case any tests ended, and we have sync stuff still
// waiting around in the queue to be processed
if (!this.#occupied && this.queue.length) {
this.#process()
}
}
#onBufferedEnd<T extends Base>(p: T) {
p.ondone = p.constructor.prototype.ondone
p.results =
p.results || new FinalResults(true, p.parser)
p.readyToProcess = true
const to = p.options.timeout
const dur =
to && p.passing() ? hrtime.bigint() - p.start : null
if (dur && to && dur > to) {
p.timeout()
} else {
p.setTimeout(0)
}
this.debug(
'%s.#onBufferedEnd',
this.name,
p.name,
p.results.bailout
)
this.pool.delete(p)
p.options.tapChildBuffer = p.output || ''
p.options.stack = ''
if (p.time) p.options.time = p.time
if (this.#occupied === p) this.#occupied = null
p.deferred?.resolve(p.results)
this.emit('subtestEnd', p)
this.#process()
}
#onIndentedEnd<T extends Base>(p: T) {
this.emit('subtestProcess', p)
p.ondone = p.constructor.prototype.ondone
p.results =
p.results || new FinalResults(true, p.parser)
this.debug('#onIndentedEnd', this.name, p.name)
this.#noparallel = false
const sti = this.subtests.indexOf(p)
if (sti !== -1) this.subtests.splice(sti, 1)
p.readyToProcess = true
p.options.time = p.time
const to = p.options.timeout
const dur =
to && p.passing() ? hrtime.bigint() - p.start : null
if (dur && to && dur > to) {
p.timeout()
} else {
p.setTimeout(0)
}
this.debug('#onIndentedEnd %s(%s)', this.name, p.name)
this.#occupied = null
this.debug(
'OIE(%s) b>shift into queue',
this.name,
this.queue
)
p.options.stack = ''
this.printResult(p.passing(), p.name, p.options, true)
this.debug(
'OIE(%s) shifted into queue',
this.name,
this.queue
)
p.deferred?.resolve(p.results)
this.emit('subtestEnd', p)
this.#process()
}
/**
* @internal
*/
main(cb: () => void) {
if (typeof this.options.timeout === 'number') {
this.setTimeout(this.options.timeout)
}
this.debug('MAIN pre', this)
const end = () => {
this.debug(' > implicit end for promise')
this.#end(IMPLICIT)
done()
}
const done = (er?: Error) => {
if (er) this.threw(er)
if (this.results || this.bailedOut) cb()
else this.ondone = () => cb()
}
// This bit of overly clever line-noise wraps the call to user-code
// in a try-catch. We can't rely on the domain for this yet, because
// the 'end' event can trigger a throw after the domain is unhooked,
// but before this is no longer the official "active test"
const ret = (() => {
if (!this.cb) return
try {
return this.cb(this)
} catch (er: any) {
if (!er || typeof er !== 'object') {
er = { error: er }
}
er.tapCaught = 'testFunctionThrow'
this.threw(er)
}
})()
if (ret && ret.then) {
this.promise = ret
ret.tapAbortPromise = done
ret.then(end, (er: any) => {
if (!er || typeof er !== 'object') {
er = { error: er }
}
er.tapCaught = 'returnedPromiseRejection'
done(er)
})
} else done()
this.debug('MAIN post', this)
}
#processSubtest<T extends Base>(p: T) {
this.debug(' > subtest')
this.#occupied = p
if (!p.buffered) {
this.emit('subtestStart', p)
this.debug(' > subtest indented')
p.stream.pipe(this.parser, { end: false })
this.writeSubComment(p)
this.debug('calling runMain', p.runMain.toString())
p.runMain(() => {
this.debug('in runMain', p.runMain.toString())
this.#onIndentedEnd(p)
})
} else if (p.readyToProcess) {
this.emit('subtestProcess', p)
this.debug(' > subtest buffered, finished')
// finished! do the thing!
this.#occupied = null
if (!p.passing() || !p.silent) {
this.printResult(
p.passing(),
p.name,
p.options,
true
)
}
} else {
this.#occupied = p
this.debug(' > subtest buffered, unfinished', p)
// unfinished buffered test.
// nothing to do yet, just leave it there.
this.queue.unshift(p)
}
}
/**
* Parse stdin as the only tap stream (ie, not as a child test)
* If used, then no other subtests or assertions are allowed.
*/
stdinOnly<T extends BaseOpts>(
extra?: T & { tapStream?: Readable | Minipass }
) {
const stream = ((extra && extra.tapStream) ||
process.stdin) as Minipass
if (!stream) {
throw new Error(
'cannot read stdin without stdin stream'
)
}
if (
this.queue.length !== 1 ||
this.queue[0] !== 'TAP version 14\n' ||
this.#processing ||
this.results ||
this.#occupied ||
this.pool.size ||
this.subtests.length
) {
throw new Error(
'Cannot use stdinOnly on a test in progress'
)
}
this.#doingStdinOnly = true
this.queue.length = 0
this.parser.on('child', p => {
// pretend to be a rooted parser, so it gets counts.
p.root = p
const t = new Base({
name: p.name,
parent: this,
parser: p,
bail: p.bail,
strict: p.strict,
omitVersion: p.omitVersion,
preserveWhitespace: p.preserveWhitespace,
childId: this.#nextChildId++,
})
this.emit('subtestAdd', t)
this.emit('subtestStart', t)
this.emit('subtestProcess', t)
p.on('complete', () => {
t.time = p.time
this.emit('subtestEnd', t)
})
})
stream.pause()
stream.pipe(this.parser)
stream.resume()
}
/**
* Mount a subtest, using this Test object as a harness.
* Exposed mainly so that it can be used by builtin plugins.
*
* @internal
*/
sub<T extends Base, O extends TestBaseOpts>(
Class: { new (options: O): T },
extra: O,
caller: (...a: any[]) => unknown
): Promise<FinalResults | null> {
if (this.bailedOut) return Promise.resolve(null)
if (this.results || this.ended) {
const er = new Error(
'cannot create subtest after parent test ends'
)
Error.captureStackTrace(er, caller)
this.threw(er)
return Promise.resolve(null)
}
extra.childId = this.#nextChildId++
if (this.shouldSkipChild(extra)) {
this.pass(extra.name, extra)
return Promise.resolve(null)
}
extra.indent = ' '
if (extra.buffered !== undefined) {
if (this.jobs > 1) {
extra.buffered = true
} else {
extra.buffered = false
}
}
extra.bail =
extra.bail !== undefined ? extra.bail : this.bail
extra.parent = this
extra.stack = stack.captureString(80, caller)
extra.context = this.context
const t = new Class(extra)
this.queue.push(t)
this.subtests.push(t)
this.emit('subtestAdd', t)
const d = new Deferred<FinalResults>()
t.deferred = d
this.#process()
return d.promise
}
/**
* Return true if the child test represented by the options object
* should be skipped. Extended by the grep/only filtering plugins.
*/
shouldSkipChild(extra: { [k: string]: any }) {
return !!(extra.skip || extra.todo)
}
// end flow control methods
}
|
src/test-base.ts
|
tapjs-core-edd7403
|
[
{
"filename": "src/base.ts",
"retrieved_chunk": " this.counts.skip++\n this.lists.skip.push(res)\n })\n this.parser.on('fail', res => {\n this.counts.fail++\n this.lists.fail.push(res)\n })\n }\n setTimeout(n: number) {\n if (n <= 0) {",
"score": 0.8198918104171753
},
{
"filename": "src/spawn.ts",
"retrieved_chunk": " !code &&\n !signal\n ) {\n this.options.skip =\n this.results.plan.skipReason || true\n }\n if (code || signal) {\n if (this.results) {\n this.results.ok = false\n }",
"score": 0.8064100742340088
},
{
"filename": "src/spawn.ts",
"retrieved_chunk": " }\n main(cb: () => void) {\n this.cb = cb\n this.setTimeout(this.options.timeout || 0)\n this.parser.on('comment', c => {\n const tomatch = c.match(/# timeout=([0-9]+)\\n$/)\n if (tomatch) {\n this.setTimeout(+tomatch[1])\n }\n })",
"score": 0.792188286781311
},
{
"filename": "src/base.ts",
"retrieved_chunk": " // do we need this? couldn't we just call the Minipass\n this.output = ''\n this.indent = options.indent || ''\n this.name = options.name || '(unnamed test)'\n this.hook.runInAsyncScope(\n () =>\n (this.hookDomain = new Domain((er, type) => {\n if (!er || typeof er !== 'object')\n er = { error: er }\n er.tapCaught = type",
"score": 0.7824662327766418
},
{
"filename": "src/base.ts",
"retrieved_chunk": " if (this.timer) {\n clearTimeout(this.timer)\n }\n this.timer = undefined\n } else {\n this.timer = setTimeout(() => this.timeout(), n)\n this.timer.unref()\n }\n }\n timeout(options?: { [k: string]: any }) {",
"score": 0.7820835709571838
}
] |
typescript
|
if (n === 0 && comment && !this.options.skip) {
|
import axios from 'axios';
import type { AxiosResponse, AxiosError, AxiosRequestConfig, AxiosPromise } from 'axios';
import RequestEvent from '../../events/request/request';
import RequestSuccessEvent from '../../events/request/success';
import RequestErrorEvent from '../../events/request/error';
import RequestDoneEvent from '../../events/request/done';
import RequestCancelEvent from '../../events/request/cancel';
import type Klient from '../..';
export type ResolveRequest = (response: AxiosResponse) => void;
export type RejectRequest = (error: AxiosError) => void;
export type RequestCallback = (resolve: ResolveRequest, reject: RejectRequest) => void;
type PromiseCallbacks = { resolve: ResolveRequest; reject: RejectRequest };
type RequestEventTypes = typeof RequestSuccessEvent | typeof RequestErrorEvent | typeof RequestCancelEvent;
type RequestContext = Record<string, any>; // eslint-disable-line @typescript-eslint/no-explicit-any
export interface KlientRequestConfig extends AxiosRequestConfig {
context?: RequestContext;
}
/**
* Request is a Promise object able to dispatch events before/after axios execution.
* Theses events allow to access and make action on request config/result at any step of execution.
* The Request will be resolved/rejected only after all events be dispatched.
*
* The events workflow is describe below :
*
* 1) RequestEvent (dispatched with abortOnFailure strategy)
* 2) Axios execution
* 2.1) Optional : RequestCancelEvent - only if request is cancelled (will reject promise and skip next events)
* 3) RequestSuccessEvent OR RequestErrorEvent
* 4) RequestDoneEvent
*/
export default class Request<T = unknown> extends Promise<AxiosResponse<T>> {
context: RequestContext = { action: 'request' };
config: KlientRequestConfig = {};
result?: AxiosError | AxiosResponse;
// Allow override axios execution
handler: (config: AxiosRequestConfig) => AxiosPromise<T> = axios;
protected klient!: Klient;
protected callbacks!: PromiseCallbacks;
protected readonly primaryEvent = new RequestEvent<T>(this);
protected readonly abortController = new AbortController();
protected constructor(callback: RequestCallback) {
super(callback);
}
static new<T>({ context, ...axiosConfig }: KlientRequestConfig, klient: Klient): Request<T> {
const callbacks = {} as PromiseCallbacks;
const request = new this<T>((resolve: ResolveRequest, reject: RejectRequest) => {
callbacks.resolve = resolve;
callbacks.reject = reject;
});
request.klient = klient;
request.config = axiosConfig;
request.callbacks = callbacks;
request.config.signal = request.abortController.signal;
request.context = { ...request.context, ...context };
return request;
}
static isCancel(e: Error) {
return axios.isCancel(e);
}
cancel(): this {
this.abortController.abort();
return this;
}
execute(): this {
this.dispatcher
.dispatch(this.primaryEvent)
.then(() => {
this.doRequest();
})
.catch((e) => {
this.reject(e);
});
return this;
}
protected doRequest(): this {
if (!this.result) {
this.handler(this.config)
.then((r) => {
this.resolve(r);
})
.catch((e) => {
this.reject(e);
});
}
return this;
}
protected resolve(response: AxiosResponse<T>): Promise<void> {
this.result = response;
return this.dispatchResultEvent(RequestSuccessEvent).then(() => {
this.callbacks.resolve(this.result as AxiosResponse<T>);
});
}
protected reject(error: AxiosError): Promise<void> {
this.result = error;
return this.dispatchResultEvent(Request.isCancel(error) ? RequestCancelEvent : RequestErrorEvent).then(() => {
this.callbacks.reject(this.result as AxiosError);
});
}
protected dispatchResultEvent(EventClass: RequestEventTypes): Promise<void> {
|
const event = new EventClass(this.primaryEvent);
|
return new Promise((resolve) => {
this.dispatcher.dispatch(event, false).then(() => {
if (event instanceof RequestCancelEvent) {
return resolve();
}
this.dispatcher.dispatch(new RequestDoneEvent(event), false).then(resolve);
});
});
}
protected get dispatcher() {
return this.klient.dispatcher;
}
}
|
src/services/request/request.ts
|
klientjs-core-9a67a61
|
[
{
"filename": "src/services/request/request.d.ts",
"retrieved_chunk": " protected readonly primaryEvent: RequestEvent;\n protected readonly abortController: AbortController;\n protected constructor(callback: RequestCallback);\n static new<T>({ context, ...axiosConfig }: KlientRequestConfig, klient: Klient): Request<T>;\n static isCancel(e: Error): boolean;\n cancel(): this;\n execute(): this;\n protected doRequest(): this;\n protected resolve(response: AxiosResponse<T>): Promise<void>;\n protected reject(error: AxiosError): Promise<void>;",
"score": 0.8671144843101501
},
{
"filename": "src/services/request/request.d.ts",
"retrieved_chunk": "}\nexport type ResolveRequest = (response: AxiosResponse) => void;\nexport type RejectRequest = (error: AxiosError) => void;\nexport type RequestCallback = (resolve: ResolveRequest, reject: RejectRequest) => void;\ntype PromiseCallbacks = {\n resolve: ResolveRequest;\n reject: RejectRequest;\n};\ntype RequestEventTypes = typeof RequestSuccessEvent | typeof RequestErrorEvent | typeof RequestCancelEvent;\ntype RequestContext = Record<string, any>;",
"score": 0.8640174865722656
},
{
"filename": "src/events/request/error.ts",
"retrieved_chunk": "import type { AxiosError } from 'axios';\nimport RequestEvent from './request';\nexport default class RequestErrorEvent<T = unknown> extends RequestEvent<T> {\n static NAME = 'request:error';\n constructor(public relatedEvent: RequestEvent<T>) {\n super(relatedEvent.request);\n }\n get error(): AxiosError {\n return this.request.result as AxiosError;\n }",
"score": 0.8558995127677917
},
{
"filename": "src/events/request/error.d.ts",
"retrieved_chunk": "import type { AxiosError } from 'axios';\nimport RequestEvent from './request';\nexport default class RequestErrorEvent<T = unknown> extends RequestEvent<T> {\n relatedEvent: RequestEvent<T>;\n static NAME: string;\n constructor(relatedEvent: RequestEvent<T>);\n get error(): AxiosError;\n get response(): import(\"axios\").AxiosResponse<unknown, any> | undefined;\n get data(): unknown;\n}",
"score": 0.8490502834320068
},
{
"filename": "src/services/request/request.d.ts",
"retrieved_chunk": "import type { AxiosResponse, AxiosError, AxiosRequestConfig, AxiosPromise } from 'axios';\ndeclare class RequestEvent {\n}\ndeclare class RequestSuccessEvent {\n}\ndeclare class RequestErrorEvent {\n}\ndeclare class RequestCancelEvent {\n}\ndeclare class Klient {",
"score": 0.8433228135108948
}
] |
typescript
|
const event = new EventClass(this.primaryEvent);
|
import axios from 'axios';
import type { AxiosResponse, AxiosError, AxiosRequestConfig, AxiosPromise } from 'axios';
import RequestEvent from '../../events/request/request';
import RequestSuccessEvent from '../../events/request/success';
import RequestErrorEvent from '../../events/request/error';
import RequestDoneEvent from '../../events/request/done';
import RequestCancelEvent from '../../events/request/cancel';
import type Klient from '../..';
export type ResolveRequest = (response: AxiosResponse) => void;
export type RejectRequest = (error: AxiosError) => void;
export type RequestCallback = (resolve: ResolveRequest, reject: RejectRequest) => void;
type PromiseCallbacks = { resolve: ResolveRequest; reject: RejectRequest };
type RequestEventTypes = typeof RequestSuccessEvent | typeof RequestErrorEvent | typeof RequestCancelEvent;
type RequestContext = Record<string, any>; // eslint-disable-line @typescript-eslint/no-explicit-any
export interface KlientRequestConfig extends AxiosRequestConfig {
context?: RequestContext;
}
/**
* Request is a Promise object able to dispatch events before/after axios execution.
* Theses events allow to access and make action on request config/result at any step of execution.
* The Request will be resolved/rejected only after all events be dispatched.
*
* The events workflow is describe below :
*
* 1) RequestEvent (dispatched with abortOnFailure strategy)
* 2) Axios execution
* 2.1) Optional : RequestCancelEvent - only if request is cancelled (will reject promise and skip next events)
* 3) RequestSuccessEvent OR RequestErrorEvent
* 4) RequestDoneEvent
*/
export default class Request<T = unknown> extends Promise<AxiosResponse<T>> {
context: RequestContext = { action: 'request' };
config: KlientRequestConfig = {};
result?: AxiosError | AxiosResponse;
// Allow override axios execution
handler: (config: AxiosRequestConfig) => AxiosPromise<T> = axios;
protected klient!: Klient;
protected callbacks!: PromiseCallbacks;
|
protected readonly primaryEvent = new RequestEvent<T>(this);
|
protected readonly abortController = new AbortController();
protected constructor(callback: RequestCallback) {
super(callback);
}
static new<T>({ context, ...axiosConfig }: KlientRequestConfig, klient: Klient): Request<T> {
const callbacks = {} as PromiseCallbacks;
const request = new this<T>((resolve: ResolveRequest, reject: RejectRequest) => {
callbacks.resolve = resolve;
callbacks.reject = reject;
});
request.klient = klient;
request.config = axiosConfig;
request.callbacks = callbacks;
request.config.signal = request.abortController.signal;
request.context = { ...request.context, ...context };
return request;
}
static isCancel(e: Error) {
return axios.isCancel(e);
}
cancel(): this {
this.abortController.abort();
return this;
}
execute(): this {
this.dispatcher
.dispatch(this.primaryEvent)
.then(() => {
this.doRequest();
})
.catch((e) => {
this.reject(e);
});
return this;
}
protected doRequest(): this {
if (!this.result) {
this.handler(this.config)
.then((r) => {
this.resolve(r);
})
.catch((e) => {
this.reject(e);
});
}
return this;
}
protected resolve(response: AxiosResponse<T>): Promise<void> {
this.result = response;
return this.dispatchResultEvent(RequestSuccessEvent).then(() => {
this.callbacks.resolve(this.result as AxiosResponse<T>);
});
}
protected reject(error: AxiosError): Promise<void> {
this.result = error;
return this.dispatchResultEvent(Request.isCancel(error) ? RequestCancelEvent : RequestErrorEvent).then(() => {
this.callbacks.reject(this.result as AxiosError);
});
}
protected dispatchResultEvent(EventClass: RequestEventTypes): Promise<void> {
const event = new EventClass(this.primaryEvent);
return new Promise((resolve) => {
this.dispatcher.dispatch(event, false).then(() => {
if (event instanceof RequestCancelEvent) {
return resolve();
}
this.dispatcher.dispatch(new RequestDoneEvent(event), false).then(resolve);
});
});
}
protected get dispatcher() {
return this.klient.dispatcher;
}
}
|
src/services/request/request.ts
|
klientjs-core-9a67a61
|
[
{
"filename": "src/services/request/request.d.ts",
"retrieved_chunk": "export interface KlientRequestConfig extends AxiosRequestConfig {\n context?: RequestContext;\n}\nexport default class Request<T = unknown> extends Promise<AxiosResponse<T>> {\n context: RequestContext;\n config: KlientRequestConfig;\n result?: AxiosError | AxiosResponse;\n handler: (config: AxiosRequestConfig) => AxiosPromise<T>;\n protected klient: Klient;\n protected callbacks: PromiseCallbacks;",
"score": 0.9493575692176819
},
{
"filename": "src/services/request/request.d.ts",
"retrieved_chunk": " protected readonly primaryEvent: RequestEvent;\n protected readonly abortController: AbortController;\n protected constructor(callback: RequestCallback);\n static new<T>({ context, ...axiosConfig }: KlientRequestConfig, klient: Klient): Request<T>;\n static isCancel(e: Error): boolean;\n cancel(): this;\n execute(): this;\n protected doRequest(): this;\n protected resolve(response: AxiosResponse<T>): Promise<void>;\n protected reject(error: AxiosError): Promise<void>;",
"score": 0.9321973323822021
},
{
"filename": "src/events/request/request.d.ts",
"retrieved_chunk": "import Event from '../event';\nimport type Request from '../../services/request/request';\nimport type { KlientRequestConfig } from '../../services/request/request';\nexport default class RequestEvent<T = unknown> extends Event {\n request: Request<T>;\n static NAME: string;\n constructor(request: Request<T>);\n get config(): KlientRequestConfig;\n get context(): {\n [x: string]: any;",
"score": 0.9010019302368164
},
{
"filename": "src/services/request/request.d.ts",
"retrieved_chunk": "import type { AxiosResponse, AxiosError, AxiosRequestConfig, AxiosPromise } from 'axios';\ndeclare class RequestEvent {\n}\ndeclare class RequestSuccessEvent {\n}\ndeclare class RequestErrorEvent {\n}\ndeclare class RequestCancelEvent {\n}\ndeclare class Klient {",
"score": 0.8992979526519775
},
{
"filename": "src/events/request/request.ts",
"retrieved_chunk": "import Event from '../event';\nimport type Request from '../../services/request/request';\nimport type { KlientRequestConfig } from '../../services/request/request';\nexport default class RequestEvent<T = unknown> extends Event {\n static NAME = 'request';\n constructor(public request: Request<T>) {\n super();\n }\n get config(): KlientRequestConfig {\n return this.request.config;",
"score": 0.895311176776886
}
] |
typescript
|
protected readonly primaryEvent = new RequestEvent<T>(this);
|
import Event from '../../events/event';
import DebugEvent from '../../events/debug';
import Listener from './listener';
import type Klient from '../../klient';
export type Callback<T extends Event> = (e: T) => Promise<void> | void;
export type Listeners = { [event: string]: Listener<never>[] };
export default class Dispatcher {
readonly listeners: Listeners = {};
constructor(protected readonly klient: Klient) {}
on<T extends Event>(event: string, callback: Callback<T>, priority = 0, once = false): this {
// Avoid duplication
if (this.findListenerIndex(event, callback) !== undefined) {
return this;
}
// Initialize listeners collection if not exists
this.listeners[event] = this.listeners[event] || [];
// Get reference to array containing listeners
const listeners = this.listeners[event];
// Build listener id (incremental)
const id = listeners.length ? Math.max(...listeners.map((l) => l.id)) + 1 : 0;
// Register the listener
listeners.push(new Listener(callback, priority, once, id));
// Listener are sorted in order they are defined
listeners.sort((a, b) => b.id - a.id);
// Sort by priority listeners binded to same event
// Lower priorities are first because we loop on collection from the end (see dispatch method)
listeners.sort((a, b) => a.priority - b.priority);
return this;
}
once<T extends Event>(event: string, callback: Callback<T>, priority = 0): this {
return this.on(event, callback, priority, true);
}
off<T extends Event>(event: string, callback: Callback<T>): this {
const index = this.findListenerIndex(event, callback);
if (index !== undefined) {
this.listeners[event].splice(index, 1);
}
return this;
}
/**
* Invoke all listeners attached to given event.
*
* @param abortOnFailure - Specify if listener failures must abort dispatch process.
*/
async dispatch(e: Event, abortOnFailure = true): Promise<void> {
const event = (e.constructor as typeof Event).NAME;
const listeners = this.listeners[event] || [];
this.debug('start', e, listeners);
// Use inverse loop because we need to remove listeners callable once
for (let i = listeners.length - 1, listener = null; i >= 0; i -= 1) {
listener = listeners[i];
if (Dispatcher.handleListenerSkipping(e, listener)) {
this.debug('skipped', e, listener);
continue;
}
if (listener.once) {
this.listeners[event].splice(i, 1);
}
try {
this.debug('invoking', e, listener);
// Wait for listener whose return a promise
await listener.invoke(e as never); // eslint-disable-line no-await-in-loop
this.debug('invoked', e, listener);
} catch (err) {
this.debug('failed', e, listener, err as Error);
if (abortOnFailure) {
// Reject promise on "abort on listener failure" strategy
return Promise.reject(err);
}
}
if (!e.dispatch.propagation) {
this.debug('stopped', e, listener);
// Stop listeners invokation
break;
}
}
this.debug('end', e, listeners);
return Promise.resolve();
}
protected findListenerIndex<T extends Event>(event: string, callback: Callback<T>): number | undefined {
const listeners = this.listeners[event] || [];
for (let i = 0, len = listeners.length; i < len; i += 1) {
if (listeners[i].callback === callback) {
return i;
}
}
return undefined;
}
protected static handleListenerSkipping(event: Event, listener: Listener<never>): boolean | void {
const { skipNextListeners, skipUntilListener } = event.dispatch;
if (skipNextListeners > 0) {
event.dispatch.skipNextListeners -= 1;
return true;
}
if (skipUntilListener) {
if (listener.id === skipUntilListener) {
event.dispatch.skipUntilListener = undefined;
return;
}
return true;
}
}
protected debug(
action: string,
relatedEvent: Event,
handler: Listener<never> | Listener<never>[],
error: Error | null = null
): void {
|
if (relatedEvent instanceof DebugEvent || !this.klient.debug) {
|
return;
}
this.dispatch(new DebugEvent(action, relatedEvent, handler, error), false);
}
}
|
src/services/dispatcher/dispatcher.ts
|
klientjs-core-9a67a61
|
[
{
"filename": "src/services/dispatcher/dispatcher.d.ts",
"retrieved_chunk": " protected debug(action: string, relatedEvent: Event, handler: Listener<never> | Listener<never>[], error?: Error | null): void;\n}\nexport {};",
"score": 0.9076623916625977
},
{
"filename": "src/events/debug.ts",
"retrieved_chunk": "import Event from './event';\nimport type Listener from '../services/dispatcher/listener';\nexport default class DebugEvent extends Event {\n static NAME = 'debug';\n constructor(\n public action: string,\n public relatedEvent: Event,\n public handler: Listener<never> | Listener<never>[],\n public error: Error | null\n ) {",
"score": 0.8955113887786865
},
{
"filename": "src/events/debug.d.ts",
"retrieved_chunk": "import Event from './event';\nimport type Listener from '../services/dispatcher/listener';\nexport default class DebugEvent extends Event {\n action: string;\n relatedEvent: Event;\n handler: Listener<never> | Listener<never>[];\n error: Error | null;\n static NAME: string;\n constructor(action: string, relatedEvent: Event, handler: Listener<never> | Listener<never>[], error: Error | null);\n}",
"score": 0.8870102167129517
},
{
"filename": "src/__tests__/debug.test.ts",
"retrieved_chunk": " const spyInvokingEvent = jest.fn();\n const spyInvokedEvent = jest.fn();\n const spyDispatchStoppedEvent = jest.fn();\n const spyDispatchFailedEvent = jest.fn();\n const spyDispatchEndEvent = jest.fn();\n klient.on('debug', (e: DebugEvent) => {\n switch (e.action) {\n case 'start':\n spyStartDispatchEvent();\n break;",
"score": 0.8366036415100098
},
{
"filename": "src/__tests__/debug.test.ts",
"retrieved_chunk": "import { mockAxiosWithRestApi } from '@klient/testing';\nimport Klient, { DebugEvent } from '..';\njest.mock('axios');\nmockAxiosWithRestApi();\ntest('debug', async () => {\n const klient = new Klient({ debug: true });\n const spyRequestEvent = jest.fn();\n const spyRequest2Event = jest.fn();\n const spyStartDispatchEvent = jest.fn();\n const spySkippedEvent = jest.fn();",
"score": 0.8220027089118958
}
] |
typescript
|
if (relatedEvent instanceof DebugEvent || !this.klient.debug) {
|
import * as deepmerge from 'deepmerge';
import type { AxiosRequestConfig } from 'axios';
import type Klient from '../../klient';
import Request from './request';
import type { KlientRequestConfig } from './request';
export default class RequestFactory {
model = Request;
// Requests are stocked during their execution only.
readonly requests: Request[] = [];
constructor(protected readonly klient: Klient) {}
request<T = unknown>(urlOrConfig: KlientRequestConfig | string): Request<T> {
return this.createRequest<T>(urlOrConfig).execute();
}
file(urlOrConfig: KlientRequestConfig | string): Promise<Blob> {
const config = deepmerge(
{ responseType: 'blob', context: { action: 'file' } },
typeof urlOrConfig === 'string' ? { url: urlOrConfig } : urlOrConfig
);
return this.request<Blob>(config).then(({ data }) => data);
}
cancelPendingRequests(): this {
for (let i = 0, len = this.requests.length; i < len; i += 1) {
this.requests[i].cancel();
}
return this;
}
createRequest<T = unknown>(urlOrConfig: KlientRequestConfig | string): Request<T> {
const config = typeof urlOrConfig === 'string' ? { url: urlOrConfig } : urlOrConfig;
const request = this.model.new<T>(this.prepare(config), this.klient);
// Store request during pending state only
this.requests.push(request);
// Remove request when promise has been fulfilled
request
.then((r) => {
this.removePendingRequest(request);
return r;
})
.catch((e) => {
this.removePendingRequest(request);
return e;
});
return request;
}
isCancel(e: Error) {
return this.model.isCancel(e);
}
protected prepare(config: KlientRequestConfig): KlientRequestConfig {
return deepmerge.all([
{ baseURL: this.klient.url },
|
(this.klient.parameters.get('request') as AxiosRequestConfig) || {},
config
]);
|
}
protected removePendingRequest(request: Request) {
const i = this.requests.indexOf(request);
if (this.requests[i] instanceof Request) {
this.requests.splice(i, 1);
}
}
}
|
src/services/request/factory.ts
|
klientjs-core-9a67a61
|
[
{
"filename": "src/services/request/factory.d.ts",
"retrieved_chunk": " constructor(klient: Klient);\n request<T = unknown>(urlOrConfig: KlientRequestConfig | string): Request<T>;\n file(urlOrConfig: KlientRequestConfig | string): Promise<Blob>;\n cancelPendingRequests(): this;\n createRequest<T = unknown>(urlOrConfig: KlientRequestConfig | string): Request<T>;\n isCancel(e: Error): any;\n protected prepare(config: KlientRequestConfig): KlientRequestConfig;\n protected removePendingRequest(request: Request): void;\n}\nexport {};",
"score": 0.8612582087516785
},
{
"filename": "src/services/request/request.ts",
"retrieved_chunk": " request.config = axiosConfig;\n request.callbacks = callbacks;\n request.config.signal = request.abortController.signal;\n request.context = { ...request.context, ...context };\n return request;\n }\n static isCancel(e: Error) {\n return axios.isCancel(e);\n }\n cancel(): this {",
"score": 0.8566538095474243
},
{
"filename": "src/services/request/request.d.ts",
"retrieved_chunk": "export interface KlientRequestConfig extends AxiosRequestConfig {\n context?: RequestContext;\n}\nexport default class Request<T = unknown> extends Promise<AxiosResponse<T>> {\n context: RequestContext;\n config: KlientRequestConfig;\n result?: AxiosError | AxiosResponse;\n handler: (config: AxiosRequestConfig) => AxiosPromise<T>;\n protected klient: Klient;\n protected callbacks: PromiseCallbacks;",
"score": 0.8544188737869263
},
{
"filename": "src/services/request/request.d.ts",
"retrieved_chunk": " protected readonly primaryEvent: RequestEvent;\n protected readonly abortController: AbortController;\n protected constructor(callback: RequestCallback);\n static new<T>({ context, ...axiosConfig }: KlientRequestConfig, klient: Klient): Request<T>;\n static isCancel(e: Error): boolean;\n cancel(): this;\n execute(): this;\n protected doRequest(): this;\n protected resolve(response: AxiosResponse<T>): Promise<void>;\n protected reject(error: AxiosError): Promise<void>;",
"score": 0.8537566065788269
},
{
"filename": "src/services/request/request.ts",
"retrieved_chunk": "export default class Request<T = unknown> extends Promise<AxiosResponse<T>> {\n context: RequestContext = { action: 'request' };\n config: KlientRequestConfig = {};\n result?: AxiosError | AxiosResponse;\n // Allow override axios execution\n handler: (config: AxiosRequestConfig) => AxiosPromise<T> = axios;\n protected klient!: Klient;\n protected callbacks!: PromiseCallbacks;\n protected readonly primaryEvent = new RequestEvent<T>(this);\n protected readonly abortController = new AbortController();",
"score": 0.8468441963195801
}
] |
typescript
|
(this.klient.parameters.get('request') as AxiosRequestConfig) || {},
config
]);
|
import Event from '../../events/event';
import DebugEvent from '../../events/debug';
import Listener from './listener';
import type Klient from '../../klient';
export type Callback<T extends Event> = (e: T) => Promise<void> | void;
export type Listeners = { [event: string]: Listener<never>[] };
export default class Dispatcher {
readonly listeners: Listeners = {};
constructor(protected readonly klient: Klient) {}
on<T extends Event>(event: string, callback: Callback<T>, priority = 0, once = false): this {
// Avoid duplication
if (this.findListenerIndex(event, callback) !== undefined) {
return this;
}
// Initialize listeners collection if not exists
this.listeners[event] = this.listeners[event] || [];
// Get reference to array containing listeners
const listeners = this.listeners[event];
// Build listener id (incremental)
const id = listeners.length ? Math.max(...listeners.map((l) => l.id)) + 1 : 0;
// Register the listener
listeners.push(new Listener(callback, priority, once, id));
// Listener are sorted in order they are defined
listeners.sort((a, b) => b.id - a.id);
// Sort by priority listeners binded to same event
// Lower priorities are first because we loop on collection from the end (see dispatch method)
listeners.sort((a, b) => a.priority - b.priority);
return this;
}
once<T extends Event>(event: string, callback: Callback<T>, priority = 0): this {
return this.on(event, callback, priority, true);
}
off<T extends Event>(event: string, callback: Callback<T>): this {
const index = this.findListenerIndex(event, callback);
if (index !== undefined) {
this.listeners[event].splice(index, 1);
}
return this;
}
/**
* Invoke all listeners attached to given event.
*
* @param abortOnFailure - Specify if listener failures must abort dispatch process.
*/
async dispatch(e: Event, abortOnFailure = true): Promise<void> {
const event = (e.constructor as typeof Event).NAME;
const listeners = this.listeners[event] || [];
this.debug('start', e, listeners);
// Use inverse loop because we need to remove listeners callable once
for (let i = listeners.length - 1, listener = null; i >= 0; i -= 1) {
listener = listeners[i];
if (Dispatcher.handleListenerSkipping(e, listener)) {
this.debug('skipped', e, listener);
continue;
}
if (listener.once) {
this.listeners[event].splice(i, 1);
}
try {
this.debug('invoking', e, listener);
// Wait for listener whose return a promise
await listener.invoke(e as never); // eslint-disable-line no-await-in-loop
this.debug('invoked', e, listener);
} catch (err) {
this.debug('failed', e, listener, err as Error);
if (abortOnFailure) {
// Reject promise on "abort on listener failure" strategy
return Promise.reject(err);
}
}
|
if (!e.dispatch.propagation) {
|
this.debug('stopped', e, listener);
// Stop listeners invokation
break;
}
}
this.debug('end', e, listeners);
return Promise.resolve();
}
protected findListenerIndex<T extends Event>(event: string, callback: Callback<T>): number | undefined {
const listeners = this.listeners[event] || [];
for (let i = 0, len = listeners.length; i < len; i += 1) {
if (listeners[i].callback === callback) {
return i;
}
}
return undefined;
}
protected static handleListenerSkipping(event: Event, listener: Listener<never>): boolean | void {
const { skipNextListeners, skipUntilListener } = event.dispatch;
if (skipNextListeners > 0) {
event.dispatch.skipNextListeners -= 1;
return true;
}
if (skipUntilListener) {
if (listener.id === skipUntilListener) {
event.dispatch.skipUntilListener = undefined;
return;
}
return true;
}
}
protected debug(
action: string,
relatedEvent: Event,
handler: Listener<never> | Listener<never>[],
error: Error | null = null
): void {
if (relatedEvent instanceof DebugEvent || !this.klient.debug) {
return;
}
this.dispatch(new DebugEvent(action, relatedEvent, handler, error), false);
}
}
|
src/services/dispatcher/dispatcher.ts
|
klientjs-core-9a67a61
|
[
{
"filename": "src/services/dispatcher/listener.ts",
"retrieved_chunk": "import type Event from '../../events/event';\nimport type { Callback } from './dispatcher';\nexport default class Listener<T extends Event> {\n constructor(readonly callback: Callback<T>, readonly priority: number, readonly once: boolean, readonly id: number) {}\n invoke(event: T): Promise<void> {\n let result;\n try {\n result = this.callback(event);\n if (!(result instanceof Promise)) {\n result = Promise.resolve();",
"score": 0.8244011998176575
},
{
"filename": "src/__tests__/listener.test.ts",
"retrieved_chunk": " expect(spyRequestEvent).toHaveBeenCalledBefore(spyRequestEventAfterFirst, false);\n expect(spyRequestEventHigherPriority).toHaveBeenCalledBefore(spyRequestEvent, false);\n});\ntest('listener:skip:stop-propagation', async () => {\n const klient = new Klient();\n const spyRequestEvent = jest.fn();\n const spyRequestEventSkipped = jest.fn();\n const spyAfterRequestEventSkipped = jest.fn();\n const spyLastRequestEvent = jest.fn();\n klient.on('request', (e) => {",
"score": 0.8032702207565308
},
{
"filename": "src/events/event.ts",
"retrieved_chunk": " };\n stopPropagation() {\n this.dispatch.propagation = false;\n }\n skipNextListeners(total: number) {\n this.dispatch.skipNextListeners = total;\n }\n skipUntilListener(id: number) {\n this.dispatch.skipUntilListener = id;\n }",
"score": 0.8017852902412415
},
{
"filename": "src/__tests__/debug.test.ts",
"retrieved_chunk": " console.log(e);\n throw e;\n });\n klient.on('request', (e) => {\n e.stopPropagation();\n });\n await klient\n .request('/posts')\n .then(() => {\n expect(spyDispatchStoppedEvent).toBeCalledTimes(1);",
"score": 0.7995549440383911
},
{
"filename": "src/services/request/request.ts",
"retrieved_chunk": " return new Promise((resolve) => {\n this.dispatcher.dispatch(event, false).then(() => {\n if (event instanceof RequestCancelEvent) {\n return resolve();\n }\n this.dispatcher.dispatch(new RequestDoneEvent(event), false).then(resolve);\n });\n });\n }\n protected get dispatcher() {",
"score": 0.7986671924591064
}
] |
typescript
|
if (!e.dispatch.propagation) {
|
// lifecycle methods like beforeEach, afterEach, teardown
// defined in plugins/lifecycle.ts
import Minipass from 'minipass'
import assert from 'node:assert'
import { hrtime } from 'node:process'
import { Readable } from 'node:stream'
import { format } from 'node:util'
import { CallSiteLike } from 'stack-utils'
import { FinalResults } from 'tap-parser'
import Deferred from 'trivial-deferred'
import { Base, BaseOpts } from './base.js'
import { esc } from './esc.js'
import stack from './stack.js'
import { TestPoint } from './test-point.js'
import { Waiter } from './waiter.js'
const queueEmpty = <T extends TestBase>(t: T) =>
t.queue.length === 0 ||
(t.queue.length === 1 &&
t.queue[0] === 'TAP version 14\n')
export interface ClassOf<T> {
new (): T
}
export type TapPlugin<
B extends Object,
O extends TestBaseOpts | any = any
> = ((t: TestBase, opts: O) => B) | ((t: TestBase) => B)
export interface TestBaseOpts extends BaseOpts {
/**
* The number of jobs to run in parallel. Defaults to 1
*/
jobs?: number
/**
* Test function called when this Test is executed
*/
cb?: (...args: any[]) => any
/**
* Flag to always/never show diagnostics. If unset, then
* diagnostics are shown for failing test points only.
*/
diagnostic?: boolean
}
const normalizeMessageExtra = (
defaultMessage: string,
message?: string | { [k: string]: any },
extra?: { [k: string]: any }
): [string, { [k: string]: any }] => {
if (typeof message === 'string') {
return [message || defaultMessage, extra || {}]
} else {
return [defaultMessage, message || {}]
}
}
/**
* Sigil for implicit end() calls that should not
* trigger an error if the user then calls t.end()
*/
const IMPLICIT = Symbol('implicit end')
/**
* Sigil to put in the queue to signal the end of all things
*/
const EOF = Symbol('EOF')
export type QueueEntry =
| string
| TestPoint
| Base
| typeof EOF
| Waiter
| [method: string, ...args: any[]]
/**
* The TestBaseBase class is the base class for all plugins,
* and eventually thus the Test class.
*
* This implements subtest functionality, TAP stream generation,
* lifecycle events, and only the most basic pass/fail assertions.
*
* All other features are added with plugins.
*/
export class TestBase extends Base {
// NB: generated pluginified Test class needs to declare over this
declare parent?: TestBase
promise?: Promise<any>
jobs: number
// #beforeEnd: [method: string | Symbol, ...args: any[]][] = []
subtests: Base[] = []
pool: Set<Base> = new Set()
queue: QueueEntry[] = ['TAP version 14\n']
cb?: (...args: any[]) => any
count: number = 0
ended: boolean = false
assertAt: CallSiteLike | null = null
assertStack: string | null = null
diagnostic: null | boolean = null
#planEnd: number = -1
#printedResult: boolean = false
#explicitEnded: boolean = false
#multiEndThrew: boolean = false
#n: number = 0
#noparallel: boolean = false
#occupied: null | Waiter | Base = null
#pushedEnd: boolean = false
#nextChildId: number = 1
#currentAssert: null | ((..._: any) => any) = null
#processing: boolean = false
#doingStdinOnly: boolean = false
/**
* true if the test has printed at least one TestPoint
*/
get printedResult(): boolean {
return this.#printedResult
}
constructor(options: TestBaseOpts) {
super(options)
this.jobs =
(options.jobs && Math.max(options.jobs, 1)) || 1
if (typeof options.diagnostic === 'boolean') {
this.diagnostic = options.diagnostic
}
if (options.cb) {
this.#setCB(options.cb)
}
}
#setCB<T extends TestBase>(this: T, cb: (t: T) => any) {
this.cb = (...args: any[]) =>
this.hook.runInAsyncScope(cb, this, ...args)
}
// TAP output generating methods
/**
* immediately exit this and all parent tests with a TAP
* Bail out! message.
*/
bailout(message?: string) {
if (this.parent && (this.results || this.ended)) {
this.parent.bailout(message)
} else {
this.#process()
message = message
? ' ' + ('' + esc(message)).trim()
: ''
message = message.replace(/[\r\n]/g, ' ')
this.parser.write('Bail out!' + message + '\n')
}
this.#end(IMPLICIT)
this.#process()
}
/**
* output a TAP comment, formatted like console.log()
*/
comment(...args: any[]) {
const body = format(...args)
const message =
('# ' + body.split(/\r?\n/).join('\n# ')).trim() +
'\n'
if (this.results) {
this.write(message)
} else {
this.queue.push(message)
}
this.#process()
}
/**
* Called when the test times out.
* Options are passed as diagnostics to the threw() method
*/
timeout(options: { [k: string]: any }) {
options = options || {}
options.expired = options.expired || this.name
if (this.#occupied && this.#occupied instanceof Base) {
this.#occupied.timeout(options)
} else {
super.timeout(options)
}
this.#end(IMPLICIT)
}
/**
* Set TAP pragma configs to affect the behavior of the parser.
* Only `strict` is supported by the parser.
*/
pragma(set: { [k: string]: boolean }) {
const p = Object.keys(set).reduce(
(acc, i) =>
acc + 'pragma ' + (set[i] ? '+' : '-') + i + '\n',
''
)
this.queue.push(p)
this.#process()
}
/**
* Specify the number of Test Points expected by this test.
* Outputs a TAP plan line.
*/
plan(n: number, comment?: string) {
if (this.bailedOut) {
return
}
if (this.#planEnd !== -1) {
throw new Error('Cannot set plan more than once')
}
if (typeof n !== 'number' || n < 0) {
throw new TypeError('plan must be a number')
}
// Cannot get any tests after a trailing plan, or a plan of 0
const ending = this.count !== 0 || n === 0
if (n === 0 && comment && !this.options.skip) {
this.options.skip = comment
}
this.#planEnd = n
comment = comment ? ' # ' + esc(comment.trim()) : ''
this.queue.push('1..' + n + comment + '\n')
if (ending) {
this.#end(IMPLICIT)
} else {
this.#process()
}
}
/**
* A passing (ok) Test Point
*/
pass(message?: string, extra?: { [k: string]: any }) {
this.currentAssert = TestBase.prototype.pass
this.printResult(
true,
...normalizeMessageExtra(
'(unnamed test)',
message,
extra
)
)
return true
}
/**
* A failing (not ok) Test Point
*/
fail(message?: string, extra?: { [k: string]: any }) {
this.currentAssert = TestBase.prototype.fail
const [m, e] = normalizeMessageExtra(
'(unnamed test)',
message,
extra
)
this.printResult(false, m, e)
return !!(e.todo || e.skip)
}
/**
* The current assertion being processed. May only be set if
* not already set.
*/
get currentAssert() {
return this.#currentAssert
}
/**
* The current assertion being processed. May only be set if
* not already set.
*/
set currentAssert(fn: null | ((...a: any[]) => any)) {
if (!this.#currentAssert && typeof fn === 'function') {
this.#currentAssert = fn
}
}
/**
* Print a Test Point
*/
printResult(
ok: boolean,
message: string,
extra: { [k: string]: any },
front: boolean = false
) {
this.#printedResult = true
const n = this.count + 1
this.currentAssert = TestBase.prototype.printResult
const fn = this.#currentAssert
this.#currentAssert = null
if (this.#planEnd !== -1 && n > this.#planEnd) {
if (!this.passing()) return
const failMessage = this.#explicitEnded
? 'test after end() was called'
: 'test count exceeds plan'
const er = new Error(failMessage, {
cause: {
test: this.name,
plan: this.#planEnd,
},
})
Error.captureStackTrace(er, fn || undefined)
this.threw(er)
return
}
extra = extra || {}
if (extra.expectFail) {
ok = !ok
}
if (this.assertAt) {
extra.at = this.assertAt
this.assertAt = null
}
if (this.assertStack) {
extra.stack = this.assertStack
this.assertStack = null
}
if (typeof extra.stack === 'string' && !extra.at) {
|
extra.at = stack.parseLine(extra.stack.split('\n')[0])
}
|
if (
!ok &&
!extra.skip &&
!extra.at &&
typeof fn === 'function'
) {
extra.at = stack.at(fn)
if (!extra.todo) {
extra.stack = stack.captureString(80, fn)
}
}
const diagnostic =
typeof extra.diagnostic === 'boolean'
? extra.diagnostic
: typeof this.diagnostic === 'boolean'
? this.diagnostic
: extra.skip || extra.todo
? false
: !ok
if (diagnostic) {
extra.diagnostic = true
}
this.count = n
message = message + ''
const res = { ok, message, extra }
const tp = new TestPoint(ok, message, extra)
// when we jump the queue, skip an extra line
if (front) {
tp.message = tp.message.trimEnd() + '\n\n'
}
if (
this.#occupied &&
this.#occupied instanceof Waiter &&
this.#occupied.finishing
) {
front = true
}
if (front) {
if (
extra.tapChildBuffer ||
extra.tapChildBuffer === ''
) {
this.writeSubComment(tp)
this.parser.write(extra.tapChildBuffer)
}
this.emit('result', res)
this.parser.write(tp.ok + ++this.#n + tp.message)
if (this.bail && !ok && !extra.skip && !extra.todo) {
this.parser.write('Bail out! ' + message + '\n')
}
} else {
this.queue.push(tp)
if (this.bail && !ok && !extra.skip && !extra.todo) {
this.queue.push('Bail out! ' + message + '\n')
}
}
if (this.#planEnd === this.count) {
this.#end(IMPLICIT)
}
this.#process()
}
end(): this {
this.#end()
return super.end()
}
/**
* The leading `# Subtest` comment that introduces a child test
*/
writeSubComment<T extends TestPoint | Base>(p: T) {
const comment =
'# Subtest' +
(p.name ? ': ' + esc(p.name) : '') +
'\n'
this.parser.write(comment)
}
// end TAP otput generating methods
// flow control methods
/**
* Await the end of a Promise before proceeding.
* The supplied callback is called with the Waiter object.
*/
waitOn(
promise: Promise<any | void>,
cb: (w: Waiter) => any,
expectReject: boolean = false
): Promise<void> {
const w = new Waiter(
promise,
w => {
assert.equal(this.#occupied, w)
cb(w)
this.#occupied = null
this.#process()
},
expectReject
)
this.queue.push(w)
this.#process()
return w.promise
}
#end(implicit?: typeof IMPLICIT) {
if (this.#doingStdinOnly && implicit !== IMPLICIT)
throw new Error(
'cannot explicitly end while in stdinOnly mode'
)
this.debug('END implicit=%j', implicit === IMPLICIT)
if (this.ended && implicit === IMPLICIT) return
// beyond here we have to be actually done with things, or else
// the semantic checks on counts and such will be off.
if (!queueEmpty(this) || this.#occupied) {
if (!this.#pushedEnd) {
this.queue.push(['#end', implicit])
}
this.#pushedEnd = true
return this.#process()
}
this.ended = true
if (implicit !== IMPLICIT && !this.#multiEndThrew) {
if (this.#explicitEnded) {
this.#multiEndThrew = true
const er = new Error(
'test end() method called more than once'
)
Error.captureStackTrace(
er,
this.#currentAssert || this.#end
)
er.cause = {
test: this.name,
}
this.threw(er)
return
}
this.#explicitEnded = true
}
if (this.#planEnd === -1) {
this.debug(
'END(%s) implicit plan',
this.name,
this.count
)
this.plan(this.count)
}
this.queue.push(EOF)
this.#process()
}
#process() {
if (this.#processing) {
return this.debug(' < already processing')
}
this.debug(
'\nPROCESSING(%s)',
this.name,
this.queue.length
)
this.#processing = true
while (!this.#occupied) {
const p = this.queue.shift()
if (!p) {
this.debug('> end of queue')
break
}
if (p instanceof Base) {
this.debug('> subtest in queue', p.name)
this.#processSubtest(p)
} else if (p === EOF) {
this.debug(' > EOF', this.name)
// I AM BECOME EOF, DESTROYER OF STREAMS
this.parser.end()
} else if (p instanceof TestPoint) {
this.debug(' > TESTPOINT')
if (
p.extra.tapChildBuffer ||
p.extra.tapChildBuffer === ''
) {
this.writeSubComment(p)
this.parser.write(p.extra.tapChildBuffer)
}
this.emit('res', p.res)
this.parser.write(p.ok + ++this.#n + p.message)
} else if (typeof p === 'string') {
this.debug(' > STRING')
this.parser.write(p)
} else if (p instanceof Waiter) {
p.ready = true
this.#occupied = p
p.finish()
} else if (Array.isArray(p)) {
this.debug(' > METHOD')
const m = p.shift() as keyof this
if (typeof this[m] !== 'function') {
this.debug(
' > weird method not found in queue??',
m,
typeof this[m]
)
continue
}
const fn = (m === '#end' ? this.#end : this[m]) as (
...a: any[]
) => any
const ret = fn.call(this, ...p)
if (
ret &&
typeof ret === 'object' &&
typeof ret.then === 'function'
) {
// returned promise
ret.then(
() => {
this.#processing = false
this.#process()
},
(er: unknown) => {
this.#processing = false
this.threw(er)
}
)
return
}
/* c8 ignore start */
} else {
throw new Error('weird thing got in the queue')
}
/* c8 ignore stop */
}
while (
!this.#noparallel &&
this.pool.size < this.jobs
) {
const p = this.subtests.shift()
if (!p) {
break
}
if (!p.buffered) {
this.#noparallel = true
break
}
this.debug('start subtest', p)
this.emit('subtestStart', p)
this.pool.add(p)
if (this.bailedOut) {
this.#onBufferedEnd(p)
} else {
p.runMain(() => this.#onBufferedEnd(p))
}
}
this.debug(
'done processing',
this.queue,
this.#occupied
)
this.#processing = false
// just in case any tests ended, and we have sync stuff still
// waiting around in the queue to be processed
if (!this.#occupied && this.queue.length) {
this.#process()
}
}
#onBufferedEnd<T extends Base>(p: T) {
p.ondone = p.constructor.prototype.ondone
p.results =
p.results || new FinalResults(true, p.parser)
p.readyToProcess = true
const to = p.options.timeout
const dur =
to && p.passing() ? hrtime.bigint() - p.start : null
if (dur && to && dur > to) {
p.timeout()
} else {
p.setTimeout(0)
}
this.debug(
'%s.#onBufferedEnd',
this.name,
p.name,
p.results.bailout
)
this.pool.delete(p)
p.options.tapChildBuffer = p.output || ''
p.options.stack = ''
if (p.time) p.options.time = p.time
if (this.#occupied === p) this.#occupied = null
p.deferred?.resolve(p.results)
this.emit('subtestEnd', p)
this.#process()
}
#onIndentedEnd<T extends Base>(p: T) {
this.emit('subtestProcess', p)
p.ondone = p.constructor.prototype.ondone
p.results =
p.results || new FinalResults(true, p.parser)
this.debug('#onIndentedEnd', this.name, p.name)
this.#noparallel = false
const sti = this.subtests.indexOf(p)
if (sti !== -1) this.subtests.splice(sti, 1)
p.readyToProcess = true
p.options.time = p.time
const to = p.options.timeout
const dur =
to && p.passing() ? hrtime.bigint() - p.start : null
if (dur && to && dur > to) {
p.timeout()
} else {
p.setTimeout(0)
}
this.debug('#onIndentedEnd %s(%s)', this.name, p.name)
this.#occupied = null
this.debug(
'OIE(%s) b>shift into queue',
this.name,
this.queue
)
p.options.stack = ''
this.printResult(p.passing(), p.name, p.options, true)
this.debug(
'OIE(%s) shifted into queue',
this.name,
this.queue
)
p.deferred?.resolve(p.results)
this.emit('subtestEnd', p)
this.#process()
}
/**
* @internal
*/
main(cb: () => void) {
if (typeof this.options.timeout === 'number') {
this.setTimeout(this.options.timeout)
}
this.debug('MAIN pre', this)
const end = () => {
this.debug(' > implicit end for promise')
this.#end(IMPLICIT)
done()
}
const done = (er?: Error) => {
if (er) this.threw(er)
if (this.results || this.bailedOut) cb()
else this.ondone = () => cb()
}
// This bit of overly clever line-noise wraps the call to user-code
// in a try-catch. We can't rely on the domain for this yet, because
// the 'end' event can trigger a throw after the domain is unhooked,
// but before this is no longer the official "active test"
const ret = (() => {
if (!this.cb) return
try {
return this.cb(this)
} catch (er: any) {
if (!er || typeof er !== 'object') {
er = { error: er }
}
er.tapCaught = 'testFunctionThrow'
this.threw(er)
}
})()
if (ret && ret.then) {
this.promise = ret
ret.tapAbortPromise = done
ret.then(end, (er: any) => {
if (!er || typeof er !== 'object') {
er = { error: er }
}
er.tapCaught = 'returnedPromiseRejection'
done(er)
})
} else done()
this.debug('MAIN post', this)
}
#processSubtest<T extends Base>(p: T) {
this.debug(' > subtest')
this.#occupied = p
if (!p.buffered) {
this.emit('subtestStart', p)
this.debug(' > subtest indented')
p.stream.pipe(this.parser, { end: false })
this.writeSubComment(p)
this.debug('calling runMain', p.runMain.toString())
p.runMain(() => {
this.debug('in runMain', p.runMain.toString())
this.#onIndentedEnd(p)
})
} else if (p.readyToProcess) {
this.emit('subtestProcess', p)
this.debug(' > subtest buffered, finished')
// finished! do the thing!
this.#occupied = null
if (!p.passing() || !p.silent) {
this.printResult(
p.passing(),
p.name,
p.options,
true
)
}
} else {
this.#occupied = p
this.debug(' > subtest buffered, unfinished', p)
// unfinished buffered test.
// nothing to do yet, just leave it there.
this.queue.unshift(p)
}
}
/**
* Parse stdin as the only tap stream (ie, not as a child test)
* If used, then no other subtests or assertions are allowed.
*/
stdinOnly<T extends BaseOpts>(
extra?: T & { tapStream?: Readable | Minipass }
) {
const stream = ((extra && extra.tapStream) ||
process.stdin) as Minipass
if (!stream) {
throw new Error(
'cannot read stdin without stdin stream'
)
}
if (
this.queue.length !== 1 ||
this.queue[0] !== 'TAP version 14\n' ||
this.#processing ||
this.results ||
this.#occupied ||
this.pool.size ||
this.subtests.length
) {
throw new Error(
'Cannot use stdinOnly on a test in progress'
)
}
this.#doingStdinOnly = true
this.queue.length = 0
this.parser.on('child', p => {
// pretend to be a rooted parser, so it gets counts.
p.root = p
const t = new Base({
name: p.name,
parent: this,
parser: p,
bail: p.bail,
strict: p.strict,
omitVersion: p.omitVersion,
preserveWhitespace: p.preserveWhitespace,
childId: this.#nextChildId++,
})
this.emit('subtestAdd', t)
this.emit('subtestStart', t)
this.emit('subtestProcess', t)
p.on('complete', () => {
t.time = p.time
this.emit('subtestEnd', t)
})
})
stream.pause()
stream.pipe(this.parser)
stream.resume()
}
/**
* Mount a subtest, using this Test object as a harness.
* Exposed mainly so that it can be used by builtin plugins.
*
* @internal
*/
sub<T extends Base, O extends TestBaseOpts>(
Class: { new (options: O): T },
extra: O,
caller: (...a: any[]) => unknown
): Promise<FinalResults | null> {
if (this.bailedOut) return Promise.resolve(null)
if (this.results || this.ended) {
const er = new Error(
'cannot create subtest after parent test ends'
)
Error.captureStackTrace(er, caller)
this.threw(er)
return Promise.resolve(null)
}
extra.childId = this.#nextChildId++
if (this.shouldSkipChild(extra)) {
this.pass(extra.name, extra)
return Promise.resolve(null)
}
extra.indent = ' '
if (extra.buffered !== undefined) {
if (this.jobs > 1) {
extra.buffered = true
} else {
extra.buffered = false
}
}
extra.bail =
extra.bail !== undefined ? extra.bail : this.bail
extra.parent = this
extra.stack = stack.captureString(80, caller)
extra.context = this.context
const t = new Class(extra)
this.queue.push(t)
this.subtests.push(t)
this.emit('subtestAdd', t)
const d = new Deferred<FinalResults>()
t.deferred = d
this.#process()
return d.promise
}
/**
* Return true if the child test represented by the options object
* should be skipped. Extended by the grep/only filtering plugins.
*/
shouldSkipChild(extra: { [k: string]: any }) {
return !!(extra.skip || extra.todo)
}
// end flow control methods
}
|
src/test-base.ts
|
tapjs-core-edd7403
|
[
{
"filename": "src/extra-from-error.ts",
"retrieved_chunk": " file,\n line: er.loc.line,\n column: er.loc.column + 1,\n }\n } else {\n // parse out the 'at' bit from the first line.\n extra.at = stack.parseLine(splitst[1])\n }\n extra.stack = stack.clean(splitst)\n }",
"score": 0.8904968500137329
},
{
"filename": "src/base.ts",
"retrieved_chunk": " er.stack.split(/\\n/).slice(1).join('\\n')\n )\n console.error(extra)\n }\n } else {\n this.parser.ok = false\n }\n return extra\n }\n passing() {",
"score": 0.8481534123420715
},
{
"filename": "src/extra-from-error.ts",
"retrieved_chunk": " if (er._babel && er.loc) {\n const msplit = message.split(': ')\n const f = msplit[0].trim()\n extra.message = msplit.slice(1).join(': ')\n .replace(/ \\([0-9]+:[0-9]+\\)$/, '').trim()\n const file = f.indexOf(process.cwd()) === 0\n ? f.substr(process.cwd().length + 1) : f\n if (file !== 'unknown')\n delete er.codeFrame\n extra.at = {",
"score": 0.8476334810256958
},
{
"filename": "src/clean-yaml-object.ts",
"retrieved_chunk": " const res = { ...object }\n if (hasOwn(res, 'stack') && !hasOwn(res, 'at')) {\n res.at = stack.parseLine(res.stack.split('\\n')[0])\n }\n const file = res.at && res.at.file && resolve(res.at.file)\n if (\n !options.stackIncludesTap &&\n file &&\n file.includes(tapDir)\n ) {",
"score": 0.8461340069770813
},
{
"filename": "src/clean-yaml-object.ts",
"retrieved_chunk": " // don't print locations in tap itself, that's almost never useful\n delete res.at\n }\n if (\n file &&\n res.at &&\n res.at.file &&\n res.at.line &&\n !res.source\n ) {",
"score": 0.8239729404449463
}
] |
typescript
|
extra.at = stack.parseLine(extra.stack.split('\n')[0])
}
|
// This file is automatically generated, please do not edit
import { FinalResults } from 'tap-parser'
import parseTestArgs, {
TestArgs,
} from './parse-test-args.js'
import { TestBase, TestBaseOpts } from './test-base.js'
const copyToString = (v: Function) => ({
toString: Object.assign(() => v.toString(), {
toString: () => 'function toString() { [native code] }',
}),
})
import plugin0 from "./plugin/after-each.js"
import plugin1 from "./plugin/before-each.js"
import plugin2 from "./plugin/spawn.js"
import plugin3 from "./plugin/stdin.js"
type PI<O extends TestBaseOpts | any = any> =
| ((t: Test, opts: O) => Plug)
| ((t: Test) => Plug)
const plugins: PI[] = [
plugin0,
plugin1,
plugin2,
plugin3,
]
type Plug =
| TestBase
| { t: Test }
| ReturnType<typeof plugin0>
| ReturnType<typeof plugin1>
| ReturnType<typeof plugin2>
| ReturnType<typeof plugin3>
type PlugKeys =
| keyof TestBase
| 't'
| keyof ReturnType<typeof plugin0>
| keyof ReturnType<typeof plugin1>
| keyof ReturnType<typeof plugin2>
| keyof ReturnType<typeof plugin3>
type SecondParam<
T extends [any] | [any, any],
Fallback extends unknown = unknown
> = T extends [any, any] ? T[1] : Fallback
type Plugin0Opts = SecondParam<
Parameters<typeof plugin0>,
TestBaseOpts
>
type Plugin1Opts = SecondParam<
Parameters<typeof plugin1>,
TestBaseOpts
>
type Plugin2Opts = SecondParam<
Parameters<typeof plugin2>,
TestBaseOpts
>
type Plugin3Opts = SecondParam<
Parameters<typeof plugin3>,
TestBaseOpts
>
type TestOpts = TestBaseOpts
& Plugin0Opts
& Plugin1Opts
& Plugin2Opts
& Plugin3Opts
type TTest = TestBase
& ReturnType<typeof plugin0>
& ReturnType<typeof plugin1>
& ReturnType<typeof plugin2>
& ReturnType<typeof
|
plugin3>
export interface Test extends TTest {
|
end(): this
t: Test
test(
name: string,
extra: { [k: string]: any },
cb?: (t: Test) => any
): Promise<FinalResults | null>
test(
name: string,
cb?: (t: Test) => any
): Promise<FinalResults | null>
test(
extra: { [k: string]: any },
cb?: (t: Test) => any
): Promise<FinalResults | null>
test(cb?: (t: Test) => any): Promise<FinalResults | null>
test(
...args: TestArgs<Test>
): Promise<FinalResults | null>
todo(
name: string,
extra: { [k: string]: any },
cb?: (t: Test) => any
): Promise<FinalResults | null>
todo(
name: string,
cb?: (t: Test) => any
): Promise<FinalResults | null>
todo(
extra: { [k: string]: any },
cb?: (t: Test) => any
): Promise<FinalResults | null>
todo(cb?: (t: Test) => any): Promise<FinalResults | null>
todo(
...args: TestArgs<Test>
): Promise<FinalResults | null>
skip(
name: string,
extra: { [k: string]: any },
cb?: (t: Test) => any
): Promise<FinalResults | null>
skip(
name: string,
cb?: (t: Test) => any
): Promise<FinalResults | null>
skip(
extra: { [k: string]: any },
cb?: (t: Test) => any
): Promise<FinalResults | null>
skip(cb?: (t: Test) => any): Promise<FinalResults | null>
skip(
...args: TestArgs<Test>
): Promise<FinalResults | null>
}
const applyPlugins = (base: Test): Test => {
const ext: Plug[] = [
...plugins.map(p => p(base, base.options)),
base,
]
const getCache = new Map<any, any>()
const t = new Proxy(base, {
has(_, p) {
for (const t of ext) {
if (Reflect.has(t, p)) return true
}
return false
},
ownKeys() {
const k: PlugKeys[] = []
for (const t of ext) {
const keys = Reflect.ownKeys(t) as PlugKeys[]
k.push(...keys)
}
return [...new Set(k)]
},
getOwnPropertyDescriptor(_, p) {
for (const t of ext) {
const prop = Reflect.getOwnPropertyDescriptor(t, p)
if (prop) return prop
}
return undefined
},
set(_, p, v) {
// check to see if there's any setters, and if so, set it there
// otherwise, just set on the base
for (const t of ext) {
let o: Object | null = t
while (o) {
if (Reflect.getOwnPropertyDescriptor(o, p)?.set) {
//@ts-ignore
t[p] = v
return true
}
o = Reflect.getPrototypeOf(o)
}
}
//@ts-ignore
base[p as keyof TestBase] = v
return true
},
get(_, p) {
// cache get results so t.blah === t.blah
// we only cache functions, so that getters aren't memoized
// Of course, a getter that returns a function will be broken,
// at least when accessed from outside the plugin, but that's
// a pretty narrow caveat, and easily documented.
if (getCache.has(p)) return getCache.get(p)
for (const plug of ext) {
if (p in plug) {
//@ts-ignore
const v = plug[p]
// Functions need special handling so that they report
// the correct toString and are called on the correct object
// Otherwise attempting to access #private props will fail.
if (typeof v === 'function') {
const f: (this: Plug, ...args: any) => any =
function (...args: any[]) {
const thisArg = this === t ? plug : this
return v.apply(thisArg, args)
}
const vv = Object.assign(f, copyToString(v))
const nameProp =
Reflect.getOwnPropertyDescriptor(v, 'name')
if (nameProp) {
Reflect.defineProperty(f, 'name', nameProp)
}
getCache.set(p, vv)
return vv
} else {
getCache.set(p, v)
return v
}
}
}
},
})
Object.assign(base, { t })
ext.unshift({ t })
return t
}
export class Test extends TestBase {
constructor(opts: TestOpts) {
super(opts)
return applyPlugins(this)
}
test(
name: string,
extra: { [k: string]: any },
cb?: (t: Test) => any
): Promise<FinalResults | null>
test(
name: string,
cb?: (t: Test) => any
): Promise<FinalResults | null>
test(
extra: { [k: string]: any },
cb?: (t: Test) => any
): Promise<FinalResults | null>
test(cb?: (t: Test) => any): Promise<FinalResults | null>
test(
...args: TestArgs<Test>
): Promise<FinalResults | null> {
const extra = parseTestArgs(...args)
extra.todo = true
return this.sub(Test, extra, this.test)
}
todo(
name: string,
extra: { [k: string]: any },
cb?: (t: Test) => any
): Promise<FinalResults | null>
todo(
name: string,
cb?: (t: Test) => any
): Promise<FinalResults | null>
todo(
extra: { [k: string]: any },
cb?: (t: Test) => any
): Promise<FinalResults | null>
todo(cb?: (t: Test) => any): Promise<FinalResults | null>
todo(
...args: TestArgs<Test>
): Promise<FinalResults | null> {
const extra = parseTestArgs(...args)
extra.todo = true
return this.sub(Test, extra, this.todo)
}
skip(
name: string,
extra: { [k: string]: any },
cb?: (t: Test) => any
): Promise<FinalResults | null>
skip(
name: string,
cb?: (t: Test) => any
): Promise<FinalResults | null>
skip(
extra: { [k: string]: any },
cb?: (t: Test) => any
): Promise<FinalResults | null>
skip(cb?: (t: Test) => any): Promise<FinalResults | null>
skip(
...args: TestArgs<Test>
): Promise<FinalResults | null> {
const extra = parseTestArgs(...args)
extra.skip = true
return this.sub(Test, extra, this.skip)
}
}
|
src/test-built.ts
|
tapjs-core-edd7403
|
[
{
"filename": "src/test-template.ts",
"retrieved_chunk": "//{{PLUGINS CODE START}}\ntype Plug = TestBase | { t: Test }\nconst plugins: PI[] = []\ntype PlugKeys = keyof TestBase | 't'\n//{{PLUGINS CODE END}}\n//{{OPTS START}}\ntype TestOpts = TestBaseOpts\n//{{OPTS END}}\n//{{TEST INTERFACE START}}\ntype TTest = TestBase",
"score": 0.8875314593315125
},
{
"filename": "src/build.ts",
"retrieved_chunk": " .join('')}\ntype TestOpts = TestBaseOpts${plugins\n .map((_, i) => `\\n & Plugin${i}Opts`)\n .join('')}\n`\nconst testInterface = `type TTest = TestBase\n${plugins\n .map((_, i) => ` & ReturnType<typeof plugin${i}>\\n`)\n .join('')}\n`",
"score": 0.8803664445877075
},
{
"filename": "src/build.ts",
"retrieved_chunk": " T extends [any] | [any, any],\n Fallback extends unknown = unknown\n> = T extends [any, any] ? T[1] : Fallback\n${plugins\n .map(\n (_, i) => `type Plugin${i}Opts = SecondParam<\n Parameters<typeof plugin${i}>,\n TestBaseOpts\n>\\n`\n )",
"score": 0.865297794342041
},
{
"filename": "src/test-template.ts",
"retrieved_chunk": " return t\n}\nexport class Test extends TestBase {\n constructor(opts: TestOpts) {\n super(opts)\n return applyPlugins(this)\n }\n test(\n name: string,\n extra: { [k: string]: any },",
"score": 0.865227460861206
},
{
"filename": "src/build.ts",
"retrieved_chunk": " .join('')}\ntype PlugKeys =\n | keyof TestBase\n | 't'\n${plugins\n .map(\n (_, i) => ` | keyof ReturnType<typeof plugin${i}>\\n`\n )\n .join('')}`\nconst opts = `type SecondParam<",
"score": 0.8547563552856445
}
] |
typescript
|
plugin3>
export interface Test extends TTest {
|
// lifecycle methods like beforeEach, afterEach, teardown
// defined in plugins/lifecycle.ts
import Minipass from 'minipass'
import assert from 'node:assert'
import { hrtime } from 'node:process'
import { Readable } from 'node:stream'
import { format } from 'node:util'
import { CallSiteLike } from 'stack-utils'
import { FinalResults } from 'tap-parser'
import Deferred from 'trivial-deferred'
import { Base, BaseOpts } from './base.js'
import { esc } from './esc.js'
import stack from './stack.js'
import { TestPoint } from './test-point.js'
import { Waiter } from './waiter.js'
const queueEmpty = <T extends TestBase>(t: T) =>
t.queue.length === 0 ||
(t.queue.length === 1 &&
t.queue[0] === 'TAP version 14\n')
export interface ClassOf<T> {
new (): T
}
export type TapPlugin<
B extends Object,
O extends TestBaseOpts | any = any
> = ((t: TestBase, opts: O) => B) | ((t: TestBase) => B)
export interface TestBaseOpts extends BaseOpts {
/**
* The number of jobs to run in parallel. Defaults to 1
*/
jobs?: number
/**
* Test function called when this Test is executed
*/
cb?: (...args: any[]) => any
/**
* Flag to always/never show diagnostics. If unset, then
* diagnostics are shown for failing test points only.
*/
diagnostic?: boolean
}
const normalizeMessageExtra = (
defaultMessage: string,
message?: string | { [k: string]: any },
extra?: { [k: string]: any }
): [string, { [k: string]: any }] => {
if (typeof message === 'string') {
return [message || defaultMessage, extra || {}]
} else {
return [defaultMessage, message || {}]
}
}
/**
* Sigil for implicit end() calls that should not
* trigger an error if the user then calls t.end()
*/
const IMPLICIT = Symbol('implicit end')
/**
* Sigil to put in the queue to signal the end of all things
*/
const EOF = Symbol('EOF')
export type QueueEntry =
| string
| TestPoint
| Base
| typeof EOF
| Waiter
| [method: string, ...args: any[]]
/**
* The TestBaseBase class is the base class for all plugins,
* and eventually thus the Test class.
*
* This implements subtest functionality, TAP stream generation,
* lifecycle events, and only the most basic pass/fail assertions.
*
* All other features are added with plugins.
*/
export class TestBase extends Base {
// NB: generated pluginified Test class needs to declare over this
declare parent?: TestBase
promise?: Promise<any>
jobs: number
// #beforeEnd: [method: string | Symbol, ...args: any[]][] = []
subtests: Base[] = []
pool: Set<Base> = new Set()
queue: QueueEntry[] = ['TAP version 14\n']
cb?: (...args: any[]) => any
count: number = 0
ended: boolean = false
assertAt: CallSiteLike | null = null
assertStack: string | null = null
diagnostic: null | boolean = null
#planEnd: number = -1
#printedResult: boolean = false
#explicitEnded: boolean = false
#multiEndThrew: boolean = false
#n: number = 0
#noparallel: boolean = false
#occupied: null | Waiter | Base = null
#pushedEnd: boolean = false
#nextChildId: number = 1
#currentAssert: null | ((..._: any) => any) = null
#processing: boolean = false
#doingStdinOnly: boolean = false
/**
* true if the test has printed at least one TestPoint
*/
get printedResult(): boolean {
return this.#printedResult
}
constructor(options: TestBaseOpts) {
super(options)
this.jobs =
(options.jobs && Math.max(options.jobs, 1)) || 1
if (typeof options.diagnostic === 'boolean') {
this.diagnostic = options.diagnostic
}
if (options.cb) {
this.#setCB(options.cb)
}
}
#setCB<T extends TestBase>(this: T, cb: (t: T) => any) {
this.cb = (...args: any[]) =>
this.hook.runInAsyncScope(cb, this, ...args)
}
// TAP output generating methods
/**
* immediately exit this and all parent tests with a TAP
* Bail out! message.
*/
bailout(message?: string) {
if (this.parent && (this.results || this.ended)) {
this.parent.bailout(message)
} else {
this.#process()
message = message
? ' ' + ('' + esc(message)).trim()
: ''
message = message.replace(/[\r\n]/g, ' ')
this.parser.write('Bail out!' + message + '\n')
}
this.#end(IMPLICIT)
this.#process()
}
/**
* output a TAP comment, formatted like console.log()
*/
comment(...args: any[]) {
const body = format(...args)
const message =
('# ' + body.split(/\r?\n/).join('\n# ')).trim() +
'\n'
if (this.results) {
this.write(message)
} else {
this.queue.push(message)
}
this.#process()
}
/**
* Called when the test times out.
* Options are passed as diagnostics to the threw() method
*/
timeout(options: { [k: string]: any }) {
options = options || {}
options.expired = options.expired || this.name
if (this.#occupied && this.#occupied instanceof Base) {
this.#occupied.timeout(options)
} else {
super.timeout(options)
}
this.#end(IMPLICIT)
}
/**
* Set TAP pragma configs to affect the behavior of the parser.
* Only `strict` is supported by the parser.
*/
pragma(set: { [k: string]: boolean }) {
const p = Object.keys(set).reduce(
(acc, i) =>
acc + 'pragma ' + (set[i] ? '+' : '-') + i + '\n',
''
)
this.queue.push(p)
this.#process()
}
/**
* Specify the number of Test Points expected by this test.
* Outputs a TAP plan line.
*/
plan(n: number, comment?: string) {
if (this.bailedOut) {
return
}
if (this.#planEnd !== -1) {
throw new Error('Cannot set plan more than once')
}
if (typeof n !== 'number' || n < 0) {
throw new TypeError('plan must be a number')
}
// Cannot get any tests after a trailing plan, or a plan of 0
const ending = this.count !== 0 || n === 0
if (n === 0 && comment && !this.options.skip) {
this.options.skip = comment
}
this.#planEnd = n
comment = comment ? ' # ' + esc(comment.trim()) : ''
this.queue.push('1..' + n + comment + '\n')
if (ending) {
this.#end(IMPLICIT)
} else {
this.#process()
}
}
/**
* A passing (ok) Test Point
*/
pass(message?: string, extra?: { [k: string]: any }) {
this.currentAssert = TestBase.prototype.pass
this.printResult(
true,
...normalizeMessageExtra(
'(unnamed test)',
message,
extra
)
)
return true
}
/**
* A failing (not ok) Test Point
*/
fail(message?: string, extra?: { [k: string]: any }) {
this.currentAssert = TestBase.prototype.fail
const [m, e] = normalizeMessageExtra(
'(unnamed test)',
message,
extra
)
this.printResult(false, m, e)
return !!(e.todo || e.skip)
}
/**
* The current assertion being processed. May only be set if
* not already set.
*/
get currentAssert() {
return this.#currentAssert
}
/**
* The current assertion being processed. May only be set if
* not already set.
*/
set currentAssert(fn: null | ((...a: any[]) => any)) {
if (!this.#currentAssert && typeof fn === 'function') {
this.#currentAssert = fn
}
}
/**
* Print a Test Point
*/
printResult(
ok: boolean,
message: string,
extra: { [k: string]: any },
front: boolean = false
) {
this.#printedResult = true
const n = this.count + 1
this.currentAssert = TestBase.prototype.printResult
const fn = this.#currentAssert
this.#currentAssert = null
if (this.#planEnd !== -1 && n > this.#planEnd) {
if (!this.passing()) return
const failMessage = this.#explicitEnded
? 'test after end() was called'
: 'test count exceeds plan'
const er = new Error(failMessage, {
cause: {
test: this.name,
plan: this.#planEnd,
},
})
Error.captureStackTrace(er, fn || undefined)
this.threw(er)
return
}
extra = extra || {}
if (extra.expectFail) {
ok = !ok
}
if (this.assertAt) {
extra.at = this.assertAt
this.assertAt = null
}
if (this.assertStack) {
extra.stack = this.assertStack
this.assertStack = null
}
if (typeof extra.stack === 'string' && !extra.at) {
extra.at = stack.parseLine(extra.stack.split('\n')[0])
}
if (
!ok &&
!extra.skip &&
!extra.at &&
typeof fn === 'function'
) {
extra.at = stack.at(fn)
if (!extra.todo) {
extra.stack = stack.captureString(80, fn)
}
}
const diagnostic =
typeof extra.diagnostic === 'boolean'
? extra.diagnostic
: typeof this.diagnostic === 'boolean'
? this.diagnostic
: extra.skip || extra.todo
? false
: !ok
if (diagnostic) {
extra.diagnostic = true
}
this.count = n
message = message + ''
const res = { ok, message, extra }
const tp = new TestPoint(ok, message, extra)
// when we jump the queue, skip an extra line
if (front) {
tp.message = tp.message.trimEnd() + '\n\n'
}
if (
this.#occupied &&
this.#occupied instanceof Waiter &&
this.#occupied.finishing
) {
front = true
}
if (front) {
if (
extra.tapChildBuffer ||
extra.tapChildBuffer === ''
) {
this.writeSubComment(tp)
this.parser.write(extra.tapChildBuffer)
}
this.emit('result', res)
this.parser.write(tp.ok + ++this.#n + tp.message)
if (this.bail && !ok && !extra.skip && !extra.todo) {
this.parser.write('Bail out! ' + message + '\n')
}
} else {
this.queue.push(tp)
if (this.bail && !ok && !extra.skip && !extra.todo) {
this.queue.push('Bail out! ' + message + '\n')
}
}
if (this.#planEnd === this.count) {
this.#end(IMPLICIT)
}
this.#process()
}
end(): this {
this.#end()
return super.end()
}
/**
* The leading `# Subtest` comment that introduces a child test
*/
writeSubComment<T extends TestPoint | Base>(p: T) {
const comment =
'# Subtest' +
(p.name ? ': ' + esc(p.name) : '') +
'\n'
this.parser.write(comment)
}
// end TAP otput generating methods
// flow control methods
/**
* Await the end of a Promise before proceeding.
* The supplied callback is called with the Waiter object.
*/
waitOn(
promise: Promise<any | void>,
|
cb: (w: Waiter) => any,
expectReject: boolean = false
): Promise<void> {
|
const w = new Waiter(
promise,
w => {
assert.equal(this.#occupied, w)
cb(w)
this.#occupied = null
this.#process()
},
expectReject
)
this.queue.push(w)
this.#process()
return w.promise
}
#end(implicit?: typeof IMPLICIT) {
if (this.#doingStdinOnly && implicit !== IMPLICIT)
throw new Error(
'cannot explicitly end while in stdinOnly mode'
)
this.debug('END implicit=%j', implicit === IMPLICIT)
if (this.ended && implicit === IMPLICIT) return
// beyond here we have to be actually done with things, or else
// the semantic checks on counts and such will be off.
if (!queueEmpty(this) || this.#occupied) {
if (!this.#pushedEnd) {
this.queue.push(['#end', implicit])
}
this.#pushedEnd = true
return this.#process()
}
this.ended = true
if (implicit !== IMPLICIT && !this.#multiEndThrew) {
if (this.#explicitEnded) {
this.#multiEndThrew = true
const er = new Error(
'test end() method called more than once'
)
Error.captureStackTrace(
er,
this.#currentAssert || this.#end
)
er.cause = {
test: this.name,
}
this.threw(er)
return
}
this.#explicitEnded = true
}
if (this.#planEnd === -1) {
this.debug(
'END(%s) implicit plan',
this.name,
this.count
)
this.plan(this.count)
}
this.queue.push(EOF)
this.#process()
}
#process() {
if (this.#processing) {
return this.debug(' < already processing')
}
this.debug(
'\nPROCESSING(%s)',
this.name,
this.queue.length
)
this.#processing = true
while (!this.#occupied) {
const p = this.queue.shift()
if (!p) {
this.debug('> end of queue')
break
}
if (p instanceof Base) {
this.debug('> subtest in queue', p.name)
this.#processSubtest(p)
} else if (p === EOF) {
this.debug(' > EOF', this.name)
// I AM BECOME EOF, DESTROYER OF STREAMS
this.parser.end()
} else if (p instanceof TestPoint) {
this.debug(' > TESTPOINT')
if (
p.extra.tapChildBuffer ||
p.extra.tapChildBuffer === ''
) {
this.writeSubComment(p)
this.parser.write(p.extra.tapChildBuffer)
}
this.emit('res', p.res)
this.parser.write(p.ok + ++this.#n + p.message)
} else if (typeof p === 'string') {
this.debug(' > STRING')
this.parser.write(p)
} else if (p instanceof Waiter) {
p.ready = true
this.#occupied = p
p.finish()
} else if (Array.isArray(p)) {
this.debug(' > METHOD')
const m = p.shift() as keyof this
if (typeof this[m] !== 'function') {
this.debug(
' > weird method not found in queue??',
m,
typeof this[m]
)
continue
}
const fn = (m === '#end' ? this.#end : this[m]) as (
...a: any[]
) => any
const ret = fn.call(this, ...p)
if (
ret &&
typeof ret === 'object' &&
typeof ret.then === 'function'
) {
// returned promise
ret.then(
() => {
this.#processing = false
this.#process()
},
(er: unknown) => {
this.#processing = false
this.threw(er)
}
)
return
}
/* c8 ignore start */
} else {
throw new Error('weird thing got in the queue')
}
/* c8 ignore stop */
}
while (
!this.#noparallel &&
this.pool.size < this.jobs
) {
const p = this.subtests.shift()
if (!p) {
break
}
if (!p.buffered) {
this.#noparallel = true
break
}
this.debug('start subtest', p)
this.emit('subtestStart', p)
this.pool.add(p)
if (this.bailedOut) {
this.#onBufferedEnd(p)
} else {
p.runMain(() => this.#onBufferedEnd(p))
}
}
this.debug(
'done processing',
this.queue,
this.#occupied
)
this.#processing = false
// just in case any tests ended, and we have sync stuff still
// waiting around in the queue to be processed
if (!this.#occupied && this.queue.length) {
this.#process()
}
}
#onBufferedEnd<T extends Base>(p: T) {
p.ondone = p.constructor.prototype.ondone
p.results =
p.results || new FinalResults(true, p.parser)
p.readyToProcess = true
const to = p.options.timeout
const dur =
to && p.passing() ? hrtime.bigint() - p.start : null
if (dur && to && dur > to) {
p.timeout()
} else {
p.setTimeout(0)
}
this.debug(
'%s.#onBufferedEnd',
this.name,
p.name,
p.results.bailout
)
this.pool.delete(p)
p.options.tapChildBuffer = p.output || ''
p.options.stack = ''
if (p.time) p.options.time = p.time
if (this.#occupied === p) this.#occupied = null
p.deferred?.resolve(p.results)
this.emit('subtestEnd', p)
this.#process()
}
#onIndentedEnd<T extends Base>(p: T) {
this.emit('subtestProcess', p)
p.ondone = p.constructor.prototype.ondone
p.results =
p.results || new FinalResults(true, p.parser)
this.debug('#onIndentedEnd', this.name, p.name)
this.#noparallel = false
const sti = this.subtests.indexOf(p)
if (sti !== -1) this.subtests.splice(sti, 1)
p.readyToProcess = true
p.options.time = p.time
const to = p.options.timeout
const dur =
to && p.passing() ? hrtime.bigint() - p.start : null
if (dur && to && dur > to) {
p.timeout()
} else {
p.setTimeout(0)
}
this.debug('#onIndentedEnd %s(%s)', this.name, p.name)
this.#occupied = null
this.debug(
'OIE(%s) b>shift into queue',
this.name,
this.queue
)
p.options.stack = ''
this.printResult(p.passing(), p.name, p.options, true)
this.debug(
'OIE(%s) shifted into queue',
this.name,
this.queue
)
p.deferred?.resolve(p.results)
this.emit('subtestEnd', p)
this.#process()
}
/**
* @internal
*/
main(cb: () => void) {
if (typeof this.options.timeout === 'number') {
this.setTimeout(this.options.timeout)
}
this.debug('MAIN pre', this)
const end = () => {
this.debug(' > implicit end for promise')
this.#end(IMPLICIT)
done()
}
const done = (er?: Error) => {
if (er) this.threw(er)
if (this.results || this.bailedOut) cb()
else this.ondone = () => cb()
}
// This bit of overly clever line-noise wraps the call to user-code
// in a try-catch. We can't rely on the domain for this yet, because
// the 'end' event can trigger a throw after the domain is unhooked,
// but before this is no longer the official "active test"
const ret = (() => {
if (!this.cb) return
try {
return this.cb(this)
} catch (er: any) {
if (!er || typeof er !== 'object') {
er = { error: er }
}
er.tapCaught = 'testFunctionThrow'
this.threw(er)
}
})()
if (ret && ret.then) {
this.promise = ret
ret.tapAbortPromise = done
ret.then(end, (er: any) => {
if (!er || typeof er !== 'object') {
er = { error: er }
}
er.tapCaught = 'returnedPromiseRejection'
done(er)
})
} else done()
this.debug('MAIN post', this)
}
#processSubtest<T extends Base>(p: T) {
this.debug(' > subtest')
this.#occupied = p
if (!p.buffered) {
this.emit('subtestStart', p)
this.debug(' > subtest indented')
p.stream.pipe(this.parser, { end: false })
this.writeSubComment(p)
this.debug('calling runMain', p.runMain.toString())
p.runMain(() => {
this.debug('in runMain', p.runMain.toString())
this.#onIndentedEnd(p)
})
} else if (p.readyToProcess) {
this.emit('subtestProcess', p)
this.debug(' > subtest buffered, finished')
// finished! do the thing!
this.#occupied = null
if (!p.passing() || !p.silent) {
this.printResult(
p.passing(),
p.name,
p.options,
true
)
}
} else {
this.#occupied = p
this.debug(' > subtest buffered, unfinished', p)
// unfinished buffered test.
// nothing to do yet, just leave it there.
this.queue.unshift(p)
}
}
/**
* Parse stdin as the only tap stream (ie, not as a child test)
* If used, then no other subtests or assertions are allowed.
*/
stdinOnly<T extends BaseOpts>(
extra?: T & { tapStream?: Readable | Minipass }
) {
const stream = ((extra && extra.tapStream) ||
process.stdin) as Minipass
if (!stream) {
throw new Error(
'cannot read stdin without stdin stream'
)
}
if (
this.queue.length !== 1 ||
this.queue[0] !== 'TAP version 14\n' ||
this.#processing ||
this.results ||
this.#occupied ||
this.pool.size ||
this.subtests.length
) {
throw new Error(
'Cannot use stdinOnly on a test in progress'
)
}
this.#doingStdinOnly = true
this.queue.length = 0
this.parser.on('child', p => {
// pretend to be a rooted parser, so it gets counts.
p.root = p
const t = new Base({
name: p.name,
parent: this,
parser: p,
bail: p.bail,
strict: p.strict,
omitVersion: p.omitVersion,
preserveWhitespace: p.preserveWhitespace,
childId: this.#nextChildId++,
})
this.emit('subtestAdd', t)
this.emit('subtestStart', t)
this.emit('subtestProcess', t)
p.on('complete', () => {
t.time = p.time
this.emit('subtestEnd', t)
})
})
stream.pause()
stream.pipe(this.parser)
stream.resume()
}
/**
* Mount a subtest, using this Test object as a harness.
* Exposed mainly so that it can be used by builtin plugins.
*
* @internal
*/
sub<T extends Base, O extends TestBaseOpts>(
Class: { new (options: O): T },
extra: O,
caller: (...a: any[]) => unknown
): Promise<FinalResults | null> {
if (this.bailedOut) return Promise.resolve(null)
if (this.results || this.ended) {
const er = new Error(
'cannot create subtest after parent test ends'
)
Error.captureStackTrace(er, caller)
this.threw(er)
return Promise.resolve(null)
}
extra.childId = this.#nextChildId++
if (this.shouldSkipChild(extra)) {
this.pass(extra.name, extra)
return Promise.resolve(null)
}
extra.indent = ' '
if (extra.buffered !== undefined) {
if (this.jobs > 1) {
extra.buffered = true
} else {
extra.buffered = false
}
}
extra.bail =
extra.bail !== undefined ? extra.bail : this.bail
extra.parent = this
extra.stack = stack.captureString(80, caller)
extra.context = this.context
const t = new Class(extra)
this.queue.push(t)
this.subtests.push(t)
this.emit('subtestAdd', t)
const d = new Deferred<FinalResults>()
t.deferred = d
this.#process()
return d.promise
}
/**
* Return true if the child test represented by the options object
* should be skipped. Extended by the grep/only filtering plugins.
*/
shouldSkipChild(extra: { [k: string]: any }) {
return !!(extra.skip || extra.todo)
}
// end flow control methods
}
|
src/test-base.ts
|
tapjs-core-edd7403
|
[
{
"filename": "src/waiter.ts",
"retrieved_chunk": " resolve: null | ((value?:any)=>void) = null\n constructor (promise: Promise<any|void>, cb:(w:Waiter)=>any, expectReject:boolean = false) {\n this.cb = cb\n this.expectReject = !!expectReject\n this.promise = new Promise<void>(res => this.resolve = res)\n promise.then(value => {\n if (this.done) {\n return\n }\n this.resolved = true",
"score": 0.8824049234390259
},
{
"filename": "src/waiter.ts",
"retrieved_chunk": "export class Waiter {\n cb: null | ((w:Waiter)=>any)\n ready: boolean = false\n value: any = null\n resolved: boolean = false\n rejected: boolean = false\n done: boolean = false\n finishing: boolean = false\n expectReject: boolean\n promise: Promise<void>",
"score": 0.8587749004364014
},
{
"filename": "src/test-built.ts",
"retrieved_chunk": " t: Test\n test(\n name: string,\n extra: { [k: string]: any },\n cb?: (t: Test) => any\n ): Promise<FinalResults | null>\n test(\n name: string,\n cb?: (t: Test) => any\n ): Promise<FinalResults | null>",
"score": 0.7940005660057068
},
{
"filename": "src/test-built.ts",
"retrieved_chunk": " todo(\n name: string,\n cb?: (t: Test) => any\n ): Promise<FinalResults | null>\n todo(\n extra: { [k: string]: any },\n cb?: (t: Test) => any\n ): Promise<FinalResults | null>\n todo(cb?: (t: Test) => any): Promise<FinalResults | null>\n todo(",
"score": 0.7904896140098572
},
{
"filename": "src/plugin/after-each.ts",
"retrieved_chunk": " cb()\n }\n }\n if (who !== this.#t) {\n loop(this.#onAfterEach, run, onerr)\n } else {\n run()\n }\n }\n}",
"score": 0.7903125286102295
}
] |
typescript
|
cb: (w: Waiter) => any,
expectReject: boolean = false
): Promise<void> {
|
// lifecycle methods like beforeEach, afterEach, teardown
// defined in plugins/lifecycle.ts
import Minipass from 'minipass'
import assert from 'node:assert'
import { hrtime } from 'node:process'
import { Readable } from 'node:stream'
import { format } from 'node:util'
import { CallSiteLike } from 'stack-utils'
import { FinalResults } from 'tap-parser'
import Deferred from 'trivial-deferred'
import { Base, BaseOpts } from './base.js'
import { esc } from './esc.js'
import stack from './stack.js'
import { TestPoint } from './test-point.js'
import { Waiter } from './waiter.js'
const queueEmpty = <T extends TestBase>(t: T) =>
t.queue.length === 0 ||
(t.queue.length === 1 &&
t.queue[0] === 'TAP version 14\n')
export interface ClassOf<T> {
new (): T
}
export type TapPlugin<
B extends Object,
O extends TestBaseOpts | any = any
> = ((t: TestBase, opts: O) => B) | ((t: TestBase) => B)
export interface TestBaseOpts extends BaseOpts {
/**
* The number of jobs to run in parallel. Defaults to 1
*/
jobs?: number
/**
* Test function called when this Test is executed
*/
cb?: (...args: any[]) => any
/**
* Flag to always/never show diagnostics. If unset, then
* diagnostics are shown for failing test points only.
*/
diagnostic?: boolean
}
const normalizeMessageExtra = (
defaultMessage: string,
message?: string | { [k: string]: any },
extra?: { [k: string]: any }
): [string, { [k: string]: any }] => {
if (typeof message === 'string') {
return [message || defaultMessage, extra || {}]
} else {
return [defaultMessage, message || {}]
}
}
/**
* Sigil for implicit end() calls that should not
* trigger an error if the user then calls t.end()
*/
const IMPLICIT = Symbol('implicit end')
/**
* Sigil to put in the queue to signal the end of all things
*/
const EOF = Symbol('EOF')
export type QueueEntry =
| string
| TestPoint
| Base
| typeof EOF
| Waiter
| [method: string, ...args: any[]]
/**
* The TestBaseBase class is the base class for all plugins,
* and eventually thus the Test class.
*
* This implements subtest functionality, TAP stream generation,
* lifecycle events, and only the most basic pass/fail assertions.
*
* All other features are added with plugins.
*/
export class TestBase extends Base {
// NB: generated pluginified Test class needs to declare over this
declare parent?: TestBase
promise?: Promise<any>
jobs: number
// #beforeEnd: [method: string | Symbol, ...args: any[]][] = []
subtests: Base[] = []
pool: Set<Base> = new Set()
queue: QueueEntry[] = ['TAP version 14\n']
cb?: (...args: any[]) => any
count: number = 0
ended: boolean = false
assertAt: CallSiteLike | null = null
assertStack: string | null = null
diagnostic: null | boolean = null
#planEnd: number = -1
#printedResult: boolean = false
#explicitEnded: boolean = false
#multiEndThrew: boolean = false
#n: number = 0
#noparallel: boolean = false
#occupied: null | Waiter | Base = null
#pushedEnd: boolean = false
#nextChildId: number = 1
#currentAssert: null | ((..._: any) => any) = null
#processing: boolean = false
#doingStdinOnly: boolean = false
/**
* true if the test has printed at least one TestPoint
*/
get printedResult(): boolean {
return this.#printedResult
}
constructor(options: TestBaseOpts) {
super(options)
this.jobs =
(options.jobs && Math.max(options.jobs, 1)) || 1
if (typeof options.diagnostic === 'boolean') {
this.diagnostic = options.diagnostic
}
if (options.cb) {
this.#setCB(options.cb)
}
}
#setCB<T extends TestBase>(this: T, cb: (t: T) => any) {
this.cb = (...args: any[]) =>
this.hook.runInAsyncScope(cb, this, ...args)
}
// TAP output generating methods
/**
* immediately exit this and all parent tests with a TAP
* Bail out! message.
*/
bailout(message?: string) {
if (this.parent && (this.results || this.ended)) {
this.parent.bailout(message)
} else {
this.#process()
message = message
? ' ' + ('' + esc(message)).trim()
: ''
message = message.replace(/[\r\n]/g, ' ')
this.parser.write('Bail out!' + message + '\n')
}
this.#end(IMPLICIT)
this.#process()
}
/**
* output a TAP comment, formatted like console.log()
*/
comment(...args: any[]) {
const body = format(...args)
const message =
('# ' + body.split(/\r?\n/).join('\n# ')).trim() +
'\n'
if (this.results) {
this.write(message)
} else {
this.queue.push(message)
}
this.#process()
}
/**
* Called when the test times out.
* Options are passed as diagnostics to the threw() method
*/
timeout(options: { [k: string]: any }) {
options = options || {}
options.expired = options.expired || this.name
if (this.#occupied && this.#occupied instanceof Base) {
this.#occupied.timeout(options)
} else {
super.timeout(options)
}
this.#end(IMPLICIT)
}
/**
* Set TAP pragma configs to affect the behavior of the parser.
* Only `strict` is supported by the parser.
*/
pragma(set: { [k: string]: boolean }) {
const p = Object.keys(set).reduce(
(acc, i) =>
acc + 'pragma ' + (set[i] ? '+' : '-') + i + '\n',
''
)
this.queue.push(p)
this.#process()
}
/**
* Specify the number of Test Points expected by this test.
* Outputs a TAP plan line.
*/
plan(n: number, comment?: string) {
if (this.bailedOut) {
return
}
if (this.#planEnd !== -1) {
throw new Error('Cannot set plan more than once')
}
if (typeof n !== 'number' || n < 0) {
throw new TypeError('plan must be a number')
}
// Cannot get any tests after a trailing plan, or a plan of 0
const ending = this.count !== 0 || n === 0
if (n === 0 && comment && !this.options.skip) {
this.options.skip = comment
}
this.#planEnd = n
comment = comment ? ' # ' + esc(comment.trim()) : ''
this.queue.push('1..' + n + comment + '\n')
if (ending) {
this.#end(IMPLICIT)
} else {
this.#process()
}
}
/**
* A passing (ok) Test Point
*/
pass(message?: string, extra?: { [k: string]: any }) {
this.currentAssert = TestBase.prototype.pass
this.printResult(
true,
...normalizeMessageExtra(
'(unnamed test)',
message,
extra
)
)
return true
}
/**
* A failing (not ok) Test Point
*/
fail(message?: string, extra?: { [k: string]: any }) {
this.currentAssert = TestBase.prototype.fail
const [m, e] = normalizeMessageExtra(
'(unnamed test)',
message,
extra
)
this.printResult(false, m, e)
return !!(e.todo || e.skip)
}
/**
* The current assertion being processed. May only be set if
* not already set.
*/
get currentAssert() {
return this.#currentAssert
}
/**
* The current assertion being processed. May only be set if
* not already set.
*/
set currentAssert(fn: null | ((...a: any[]) => any)) {
if (!this.#currentAssert && typeof fn === 'function') {
this.#currentAssert = fn
}
}
/**
* Print a Test Point
*/
printResult(
ok: boolean,
message: string,
extra: { [k: string]: any },
front: boolean = false
) {
this.#printedResult = true
const n = this.count + 1
this.currentAssert = TestBase.prototype.printResult
const fn = this.#currentAssert
this.#currentAssert = null
if (this.#planEnd !== -1 && n > this.#planEnd) {
if (!this.passing()) return
const failMessage = this.#explicitEnded
? 'test after end() was called'
: 'test count exceeds plan'
const er = new Error(failMessage, {
cause: {
test: this.name,
plan: this.#planEnd,
},
})
Error.captureStackTrace(er, fn || undefined)
this
|
.threw(er)
return
}
|
extra = extra || {}
if (extra.expectFail) {
ok = !ok
}
if (this.assertAt) {
extra.at = this.assertAt
this.assertAt = null
}
if (this.assertStack) {
extra.stack = this.assertStack
this.assertStack = null
}
if (typeof extra.stack === 'string' && !extra.at) {
extra.at = stack.parseLine(extra.stack.split('\n')[0])
}
if (
!ok &&
!extra.skip &&
!extra.at &&
typeof fn === 'function'
) {
extra.at = stack.at(fn)
if (!extra.todo) {
extra.stack = stack.captureString(80, fn)
}
}
const diagnostic =
typeof extra.diagnostic === 'boolean'
? extra.diagnostic
: typeof this.diagnostic === 'boolean'
? this.diagnostic
: extra.skip || extra.todo
? false
: !ok
if (diagnostic) {
extra.diagnostic = true
}
this.count = n
message = message + ''
const res = { ok, message, extra }
const tp = new TestPoint(ok, message, extra)
// when we jump the queue, skip an extra line
if (front) {
tp.message = tp.message.trimEnd() + '\n\n'
}
if (
this.#occupied &&
this.#occupied instanceof Waiter &&
this.#occupied.finishing
) {
front = true
}
if (front) {
if (
extra.tapChildBuffer ||
extra.tapChildBuffer === ''
) {
this.writeSubComment(tp)
this.parser.write(extra.tapChildBuffer)
}
this.emit('result', res)
this.parser.write(tp.ok + ++this.#n + tp.message)
if (this.bail && !ok && !extra.skip && !extra.todo) {
this.parser.write('Bail out! ' + message + '\n')
}
} else {
this.queue.push(tp)
if (this.bail && !ok && !extra.skip && !extra.todo) {
this.queue.push('Bail out! ' + message + '\n')
}
}
if (this.#planEnd === this.count) {
this.#end(IMPLICIT)
}
this.#process()
}
end(): this {
this.#end()
return super.end()
}
/**
* The leading `# Subtest` comment that introduces a child test
*/
writeSubComment<T extends TestPoint | Base>(p: T) {
const comment =
'# Subtest' +
(p.name ? ': ' + esc(p.name) : '') +
'\n'
this.parser.write(comment)
}
// end TAP otput generating methods
// flow control methods
/**
* Await the end of a Promise before proceeding.
* The supplied callback is called with the Waiter object.
*/
waitOn(
promise: Promise<any | void>,
cb: (w: Waiter) => any,
expectReject: boolean = false
): Promise<void> {
const w = new Waiter(
promise,
w => {
assert.equal(this.#occupied, w)
cb(w)
this.#occupied = null
this.#process()
},
expectReject
)
this.queue.push(w)
this.#process()
return w.promise
}
#end(implicit?: typeof IMPLICIT) {
if (this.#doingStdinOnly && implicit !== IMPLICIT)
throw new Error(
'cannot explicitly end while in stdinOnly mode'
)
this.debug('END implicit=%j', implicit === IMPLICIT)
if (this.ended && implicit === IMPLICIT) return
// beyond here we have to be actually done with things, or else
// the semantic checks on counts and such will be off.
if (!queueEmpty(this) || this.#occupied) {
if (!this.#pushedEnd) {
this.queue.push(['#end', implicit])
}
this.#pushedEnd = true
return this.#process()
}
this.ended = true
if (implicit !== IMPLICIT && !this.#multiEndThrew) {
if (this.#explicitEnded) {
this.#multiEndThrew = true
const er = new Error(
'test end() method called more than once'
)
Error.captureStackTrace(
er,
this.#currentAssert || this.#end
)
er.cause = {
test: this.name,
}
this.threw(er)
return
}
this.#explicitEnded = true
}
if (this.#planEnd === -1) {
this.debug(
'END(%s) implicit plan',
this.name,
this.count
)
this.plan(this.count)
}
this.queue.push(EOF)
this.#process()
}
#process() {
if (this.#processing) {
return this.debug(' < already processing')
}
this.debug(
'\nPROCESSING(%s)',
this.name,
this.queue.length
)
this.#processing = true
while (!this.#occupied) {
const p = this.queue.shift()
if (!p) {
this.debug('> end of queue')
break
}
if (p instanceof Base) {
this.debug('> subtest in queue', p.name)
this.#processSubtest(p)
} else if (p === EOF) {
this.debug(' > EOF', this.name)
// I AM BECOME EOF, DESTROYER OF STREAMS
this.parser.end()
} else if (p instanceof TestPoint) {
this.debug(' > TESTPOINT')
if (
p.extra.tapChildBuffer ||
p.extra.tapChildBuffer === ''
) {
this.writeSubComment(p)
this.parser.write(p.extra.tapChildBuffer)
}
this.emit('res', p.res)
this.parser.write(p.ok + ++this.#n + p.message)
} else if (typeof p === 'string') {
this.debug(' > STRING')
this.parser.write(p)
} else if (p instanceof Waiter) {
p.ready = true
this.#occupied = p
p.finish()
} else if (Array.isArray(p)) {
this.debug(' > METHOD')
const m = p.shift() as keyof this
if (typeof this[m] !== 'function') {
this.debug(
' > weird method not found in queue??',
m,
typeof this[m]
)
continue
}
const fn = (m === '#end' ? this.#end : this[m]) as (
...a: any[]
) => any
const ret = fn.call(this, ...p)
if (
ret &&
typeof ret === 'object' &&
typeof ret.then === 'function'
) {
// returned promise
ret.then(
() => {
this.#processing = false
this.#process()
},
(er: unknown) => {
this.#processing = false
this.threw(er)
}
)
return
}
/* c8 ignore start */
} else {
throw new Error('weird thing got in the queue')
}
/* c8 ignore stop */
}
while (
!this.#noparallel &&
this.pool.size < this.jobs
) {
const p = this.subtests.shift()
if (!p) {
break
}
if (!p.buffered) {
this.#noparallel = true
break
}
this.debug('start subtest', p)
this.emit('subtestStart', p)
this.pool.add(p)
if (this.bailedOut) {
this.#onBufferedEnd(p)
} else {
p.runMain(() => this.#onBufferedEnd(p))
}
}
this.debug(
'done processing',
this.queue,
this.#occupied
)
this.#processing = false
// just in case any tests ended, and we have sync stuff still
// waiting around in the queue to be processed
if (!this.#occupied && this.queue.length) {
this.#process()
}
}
#onBufferedEnd<T extends Base>(p: T) {
p.ondone = p.constructor.prototype.ondone
p.results =
p.results || new FinalResults(true, p.parser)
p.readyToProcess = true
const to = p.options.timeout
const dur =
to && p.passing() ? hrtime.bigint() - p.start : null
if (dur && to && dur > to) {
p.timeout()
} else {
p.setTimeout(0)
}
this.debug(
'%s.#onBufferedEnd',
this.name,
p.name,
p.results.bailout
)
this.pool.delete(p)
p.options.tapChildBuffer = p.output || ''
p.options.stack = ''
if (p.time) p.options.time = p.time
if (this.#occupied === p) this.#occupied = null
p.deferred?.resolve(p.results)
this.emit('subtestEnd', p)
this.#process()
}
#onIndentedEnd<T extends Base>(p: T) {
this.emit('subtestProcess', p)
p.ondone = p.constructor.prototype.ondone
p.results =
p.results || new FinalResults(true, p.parser)
this.debug('#onIndentedEnd', this.name, p.name)
this.#noparallel = false
const sti = this.subtests.indexOf(p)
if (sti !== -1) this.subtests.splice(sti, 1)
p.readyToProcess = true
p.options.time = p.time
const to = p.options.timeout
const dur =
to && p.passing() ? hrtime.bigint() - p.start : null
if (dur && to && dur > to) {
p.timeout()
} else {
p.setTimeout(0)
}
this.debug('#onIndentedEnd %s(%s)', this.name, p.name)
this.#occupied = null
this.debug(
'OIE(%s) b>shift into queue',
this.name,
this.queue
)
p.options.stack = ''
this.printResult(p.passing(), p.name, p.options, true)
this.debug(
'OIE(%s) shifted into queue',
this.name,
this.queue
)
p.deferred?.resolve(p.results)
this.emit('subtestEnd', p)
this.#process()
}
/**
* @internal
*/
main(cb: () => void) {
if (typeof this.options.timeout === 'number') {
this.setTimeout(this.options.timeout)
}
this.debug('MAIN pre', this)
const end = () => {
this.debug(' > implicit end for promise')
this.#end(IMPLICIT)
done()
}
const done = (er?: Error) => {
if (er) this.threw(er)
if (this.results || this.bailedOut) cb()
else this.ondone = () => cb()
}
// This bit of overly clever line-noise wraps the call to user-code
// in a try-catch. We can't rely on the domain for this yet, because
// the 'end' event can trigger a throw after the domain is unhooked,
// but before this is no longer the official "active test"
const ret = (() => {
if (!this.cb) return
try {
return this.cb(this)
} catch (er: any) {
if (!er || typeof er !== 'object') {
er = { error: er }
}
er.tapCaught = 'testFunctionThrow'
this.threw(er)
}
})()
if (ret && ret.then) {
this.promise = ret
ret.tapAbortPromise = done
ret.then(end, (er: any) => {
if (!er || typeof er !== 'object') {
er = { error: er }
}
er.tapCaught = 'returnedPromiseRejection'
done(er)
})
} else done()
this.debug('MAIN post', this)
}
#processSubtest<T extends Base>(p: T) {
this.debug(' > subtest')
this.#occupied = p
if (!p.buffered) {
this.emit('subtestStart', p)
this.debug(' > subtest indented')
p.stream.pipe(this.parser, { end: false })
this.writeSubComment(p)
this.debug('calling runMain', p.runMain.toString())
p.runMain(() => {
this.debug('in runMain', p.runMain.toString())
this.#onIndentedEnd(p)
})
} else if (p.readyToProcess) {
this.emit('subtestProcess', p)
this.debug(' > subtest buffered, finished')
// finished! do the thing!
this.#occupied = null
if (!p.passing() || !p.silent) {
this.printResult(
p.passing(),
p.name,
p.options,
true
)
}
} else {
this.#occupied = p
this.debug(' > subtest buffered, unfinished', p)
// unfinished buffered test.
// nothing to do yet, just leave it there.
this.queue.unshift(p)
}
}
/**
* Parse stdin as the only tap stream (ie, not as a child test)
* If used, then no other subtests or assertions are allowed.
*/
stdinOnly<T extends BaseOpts>(
extra?: T & { tapStream?: Readable | Minipass }
) {
const stream = ((extra && extra.tapStream) ||
process.stdin) as Minipass
if (!stream) {
throw new Error(
'cannot read stdin without stdin stream'
)
}
if (
this.queue.length !== 1 ||
this.queue[0] !== 'TAP version 14\n' ||
this.#processing ||
this.results ||
this.#occupied ||
this.pool.size ||
this.subtests.length
) {
throw new Error(
'Cannot use stdinOnly on a test in progress'
)
}
this.#doingStdinOnly = true
this.queue.length = 0
this.parser.on('child', p => {
// pretend to be a rooted parser, so it gets counts.
p.root = p
const t = new Base({
name: p.name,
parent: this,
parser: p,
bail: p.bail,
strict: p.strict,
omitVersion: p.omitVersion,
preserveWhitespace: p.preserveWhitespace,
childId: this.#nextChildId++,
})
this.emit('subtestAdd', t)
this.emit('subtestStart', t)
this.emit('subtestProcess', t)
p.on('complete', () => {
t.time = p.time
this.emit('subtestEnd', t)
})
})
stream.pause()
stream.pipe(this.parser)
stream.resume()
}
/**
* Mount a subtest, using this Test object as a harness.
* Exposed mainly so that it can be used by builtin plugins.
*
* @internal
*/
sub<T extends Base, O extends TestBaseOpts>(
Class: { new (options: O): T },
extra: O,
caller: (...a: any[]) => unknown
): Promise<FinalResults | null> {
if (this.bailedOut) return Promise.resolve(null)
if (this.results || this.ended) {
const er = new Error(
'cannot create subtest after parent test ends'
)
Error.captureStackTrace(er, caller)
this.threw(er)
return Promise.resolve(null)
}
extra.childId = this.#nextChildId++
if (this.shouldSkipChild(extra)) {
this.pass(extra.name, extra)
return Promise.resolve(null)
}
extra.indent = ' '
if (extra.buffered !== undefined) {
if (this.jobs > 1) {
extra.buffered = true
} else {
extra.buffered = false
}
}
extra.bail =
extra.bail !== undefined ? extra.bail : this.bail
extra.parent = this
extra.stack = stack.captureString(80, caller)
extra.context = this.context
const t = new Class(extra)
this.queue.push(t)
this.subtests.push(t)
this.emit('subtestAdd', t)
const d = new Deferred<FinalResults>()
t.deferred = d
this.#process()
return d.promise
}
/**
* Return true if the child test represented by the options object
* should be skipped. Extended by the grep/only filtering plugins.
*/
shouldSkipChild(extra: { [k: string]: any }) {
return !!(extra.skip || extra.todo)
}
// end flow control methods
}
|
src/test-base.ts
|
tapjs-core-edd7403
|
[
{
"filename": "src/stdin.ts",
"retrieved_chunk": " }\n threw(er: any, extra?: any, proxy?: boolean) {\n extra = super.threw(er, extra, proxy)\n Object.assign(this.options, extra)\n this.parser.abort(er.message, extra)\n this.parser.end()\n }\n}",
"score": 0.8354650139808655
},
{
"filename": "src/base.ts",
"retrieved_chunk": " this.stream.end()\n return this\n }\n threw(er: any, extra?: any, proxy?: boolean) {\n this.hook.emitDestroy()\n this.hookDomain.destroy()\n if (typeof er === 'string') {\n er = { message: er }\n } else if (!er || typeof er !== 'object') {\n er = { error: er }",
"score": 0.833113431930542
},
{
"filename": "src/plugin/after-each.ts",
"retrieved_chunk": " const onerr = (er: any) => {\n who.threw(er)\n cb()\n }\n const p = this.#t.parent\n const pae = !!p && AfterEach.#refs.get(p)\n const run = () => {\n if (pae) {\n pae.#runAfterEach(who, cb)\n } else {",
"score": 0.8301591277122498
},
{
"filename": "src/base.ts",
"retrieved_chunk": " // a bit excessive.\n if (this.results) {\n const alreadyBailing = !this.results.ok && this.bail\n this.results.ok = false\n if (this.parent) {\n this.parent.threw(er, extra, true)\n } else if (alreadyBailing) {\n // we are already bailing out, and this is the top level,\n // just make our way hastily to the nearest exit.\n return",
"score": 0.8209587931632996
},
{
"filename": "src/base.ts",
"retrieved_chunk": " this.threw(er)\n }))\n )\n this.debug = !!options.debug\n ? debug(this.name)\n : () => {}\n this.parser =\n options.parser ||\n new Parser({\n bail: this.bail,",
"score": 0.8165109157562256
}
] |
typescript
|
.threw(er)
return
}
|
// lifecycle methods like beforeEach, afterEach, teardown
// defined in plugins/lifecycle.ts
import Minipass from 'minipass'
import assert from 'node:assert'
import { hrtime } from 'node:process'
import { Readable } from 'node:stream'
import { format } from 'node:util'
import { CallSiteLike } from 'stack-utils'
import { FinalResults } from 'tap-parser'
import Deferred from 'trivial-deferred'
import { Base, BaseOpts } from './base.js'
import { esc } from './esc.js'
import stack from './stack.js'
import { TestPoint } from './test-point.js'
import { Waiter } from './waiter.js'
const queueEmpty = <T extends TestBase>(t: T) =>
t.queue.length === 0 ||
(t.queue.length === 1 &&
t.queue[0] === 'TAP version 14\n')
export interface ClassOf<T> {
new (): T
}
export type TapPlugin<
B extends Object,
O extends TestBaseOpts | any = any
> = ((t: TestBase, opts: O) => B) | ((t: TestBase) => B)
export interface TestBaseOpts extends BaseOpts {
/**
* The number of jobs to run in parallel. Defaults to 1
*/
jobs?: number
/**
* Test function called when this Test is executed
*/
cb?: (...args: any[]) => any
/**
* Flag to always/never show diagnostics. If unset, then
* diagnostics are shown for failing test points only.
*/
diagnostic?: boolean
}
const normalizeMessageExtra = (
defaultMessage: string,
message?: string | { [k: string]: any },
extra?: { [k: string]: any }
): [string, { [k: string]: any }] => {
if (typeof message === 'string') {
return [message || defaultMessage, extra || {}]
} else {
return [defaultMessage, message || {}]
}
}
/**
* Sigil for implicit end() calls that should not
* trigger an error if the user then calls t.end()
*/
const IMPLICIT = Symbol('implicit end')
/**
* Sigil to put in the queue to signal the end of all things
*/
const EOF = Symbol('EOF')
export type QueueEntry =
| string
| TestPoint
| Base
| typeof EOF
| Waiter
| [method: string, ...args: any[]]
/**
* The TestBaseBase class is the base class for all plugins,
* and eventually thus the Test class.
*
* This implements subtest functionality, TAP stream generation,
* lifecycle events, and only the most basic pass/fail assertions.
*
* All other features are added with plugins.
*/
export class TestBase extends Base {
// NB: generated pluginified Test class needs to declare over this
declare parent?: TestBase
promise?: Promise<any>
jobs: number
// #beforeEnd: [method: string | Symbol, ...args: any[]][] = []
subtests: Base[] = []
pool: Set<Base> = new Set()
queue: QueueEntry[] = ['TAP version 14\n']
cb?: (...args: any[]) => any
count: number = 0
ended: boolean = false
assertAt: CallSiteLike | null = null
assertStack: string | null = null
diagnostic: null | boolean = null
#planEnd: number = -1
#printedResult: boolean = false
#explicitEnded: boolean = false
#multiEndThrew: boolean = false
#n: number = 0
#noparallel: boolean = false
#occupied: null | Waiter | Base = null
#pushedEnd: boolean = false
#nextChildId: number = 1
#currentAssert: null | ((..._: any) => any) = null
#processing: boolean = false
#doingStdinOnly: boolean = false
/**
* true if the test has printed at least one TestPoint
*/
get printedResult(): boolean {
return this.#printedResult
}
constructor(options: TestBaseOpts) {
super(options)
this.jobs =
(options.jobs && Math.max(options.jobs, 1)) || 1
if (typeof options.diagnostic === 'boolean') {
this.diagnostic = options.diagnostic
}
if (options.cb) {
this.#setCB(options.cb)
}
}
#setCB<T extends TestBase>(this: T, cb: (t: T) => any) {
this.cb = (...args: any[]) =>
this.hook.runInAsyncScope(cb, this, ...args)
}
// TAP output generating methods
/**
* immediately exit this and all parent tests with a TAP
* Bail out! message.
*/
bailout(message?: string) {
if (this.parent && (this.results || this.ended)) {
this.parent.bailout(message)
} else {
this.#process()
message = message
? ' ' + ('' + esc(message)).trim()
: ''
message = message.replace(/[\r\n]/g, ' ')
this.parser.write('Bail out!' + message + '\n')
}
this.#end(IMPLICIT)
this.#process()
}
/**
* output a TAP comment, formatted like console.log()
*/
comment(...args: any[]) {
const body = format(...args)
const message =
('# ' + body.split(/\r?\n/).join('\n# ')).trim() +
'\n'
if (this.results) {
this.write(message)
} else {
this.queue.push(message)
}
this.#process()
}
/**
* Called when the test times out.
* Options are passed as diagnostics to the threw() method
*/
timeout(options: { [k: string]: any }) {
options = options || {}
options.expired = options.expired || this.name
if (this.#occupied && this.#occupied instanceof Base) {
this.#occupied.timeout(options)
} else {
super.timeout(options)
}
this.#end(IMPLICIT)
}
/**
* Set TAP pragma configs to affect the behavior of the parser.
* Only `strict` is supported by the parser.
*/
pragma(set: { [k: string]: boolean }) {
const p = Object.keys(set).reduce(
(acc, i) =>
acc + 'pragma ' + (set[i] ? '+' : '-') + i + '\n',
''
)
this.queue.push(p)
this.#process()
}
/**
* Specify the number of Test Points expected by this test.
* Outputs a TAP plan line.
*/
plan(n: number, comment?: string) {
if (this.bailedOut) {
return
}
if (this.#planEnd !== -1) {
throw new Error('Cannot set plan more than once')
}
if (typeof n !== 'number' || n < 0) {
throw new TypeError('plan must be a number')
}
// Cannot get any tests after a trailing plan, or a plan of 0
const ending = this.count !== 0 || n === 0
if (n === 0 && comment && !this.options.skip) {
this.options.skip = comment
}
this.#planEnd = n
comment = comment ? ' # ' + esc(comment.trim()) : ''
this.queue.push('1..' + n + comment + '\n')
if (ending) {
this.#end(IMPLICIT)
} else {
this.#process()
}
}
/**
* A passing (ok) Test Point
*/
pass(message?: string, extra?: { [k: string]: any }) {
this.currentAssert = TestBase.prototype.pass
this.printResult(
true,
...normalizeMessageExtra(
'(unnamed test)',
message,
extra
)
)
return true
}
/**
* A failing (not ok) Test Point
*/
fail(message?: string, extra?: { [k: string]: any }) {
this.currentAssert = TestBase.prototype.fail
const [m, e] = normalizeMessageExtra(
'(unnamed test)',
message,
extra
)
this.printResult(false, m, e)
return !!(e.todo || e.skip)
}
/**
* The current assertion being processed. May only be set if
* not already set.
*/
get currentAssert() {
return this.#currentAssert
}
/**
* The current assertion being processed. May only be set if
* not already set.
*/
set currentAssert(fn: null | ((...a: any[]) => any)) {
if (!this.#currentAssert && typeof fn === 'function') {
this.#currentAssert = fn
}
}
/**
* Print a Test Point
*/
printResult(
ok: boolean,
message: string,
extra: { [k: string]: any },
front: boolean = false
) {
this.#printedResult = true
const n = this.count + 1
this.currentAssert = TestBase.prototype.printResult
const fn = this.#currentAssert
this.#currentAssert = null
if (this.#planEnd !== -1 && n > this.#planEnd) {
if (!this.passing()) return
const failMessage = this.#explicitEnded
? 'test after end() was called'
: 'test count exceeds plan'
const er = new Error(failMessage, {
cause: {
test: this.name,
plan: this.#planEnd,
},
})
Error.captureStackTrace(er, fn || undefined)
this.threw(er)
return
}
extra = extra || {}
if (extra.expectFail) {
ok = !ok
}
if (this.assertAt) {
extra.at = this.assertAt
this.assertAt = null
}
if (this.assertStack) {
extra.stack = this.assertStack
this.assertStack = null
}
if (typeof extra.stack === 'string' && !extra.at) {
extra.at = stack.parseLine(extra.stack.split('\n')[0])
}
if (
!ok &&
!extra.skip &&
!extra.at &&
typeof fn === 'function'
) {
extra.at = stack.at(fn)
if (!extra.todo) {
extra.stack = stack.captureString(80, fn)
}
}
const diagnostic =
typeof extra.diagnostic === 'boolean'
? extra.diagnostic
: typeof this.diagnostic === 'boolean'
? this.diagnostic
: extra.skip || extra.todo
? false
: !ok
if (diagnostic) {
extra.diagnostic = true
}
this.count = n
message = message + ''
const res = { ok, message, extra }
const tp = new TestPoint(ok, message, extra)
// when we jump the queue, skip an extra line
if (front) {
tp.message = tp.message.trimEnd() + '\n\n'
}
if (
this.#occupied &&
this.#occupied instanceof Waiter &&
this.#occupied.finishing
) {
front = true
}
if (front) {
if (
extra.tapChildBuffer ||
extra.tapChildBuffer === ''
) {
this.writeSubComment(tp)
this.parser.write(extra.tapChildBuffer)
}
this.emit('result', res)
this.parser.write(tp.ok + ++this.#n + tp.message)
|
if (this.bail && !ok && !extra.skip && !extra.todo) {
|
this.parser.write('Bail out! ' + message + '\n')
}
} else {
this.queue.push(tp)
if (this.bail && !ok && !extra.skip && !extra.todo) {
this.queue.push('Bail out! ' + message + '\n')
}
}
if (this.#planEnd === this.count) {
this.#end(IMPLICIT)
}
this.#process()
}
end(): this {
this.#end()
return super.end()
}
/**
* The leading `# Subtest` comment that introduces a child test
*/
writeSubComment<T extends TestPoint | Base>(p: T) {
const comment =
'# Subtest' +
(p.name ? ': ' + esc(p.name) : '') +
'\n'
this.parser.write(comment)
}
// end TAP otput generating methods
// flow control methods
/**
* Await the end of a Promise before proceeding.
* The supplied callback is called with the Waiter object.
*/
waitOn(
promise: Promise<any | void>,
cb: (w: Waiter) => any,
expectReject: boolean = false
): Promise<void> {
const w = new Waiter(
promise,
w => {
assert.equal(this.#occupied, w)
cb(w)
this.#occupied = null
this.#process()
},
expectReject
)
this.queue.push(w)
this.#process()
return w.promise
}
#end(implicit?: typeof IMPLICIT) {
if (this.#doingStdinOnly && implicit !== IMPLICIT)
throw new Error(
'cannot explicitly end while in stdinOnly mode'
)
this.debug('END implicit=%j', implicit === IMPLICIT)
if (this.ended && implicit === IMPLICIT) return
// beyond here we have to be actually done with things, or else
// the semantic checks on counts and such will be off.
if (!queueEmpty(this) || this.#occupied) {
if (!this.#pushedEnd) {
this.queue.push(['#end', implicit])
}
this.#pushedEnd = true
return this.#process()
}
this.ended = true
if (implicit !== IMPLICIT && !this.#multiEndThrew) {
if (this.#explicitEnded) {
this.#multiEndThrew = true
const er = new Error(
'test end() method called more than once'
)
Error.captureStackTrace(
er,
this.#currentAssert || this.#end
)
er.cause = {
test: this.name,
}
this.threw(er)
return
}
this.#explicitEnded = true
}
if (this.#planEnd === -1) {
this.debug(
'END(%s) implicit plan',
this.name,
this.count
)
this.plan(this.count)
}
this.queue.push(EOF)
this.#process()
}
#process() {
if (this.#processing) {
return this.debug(' < already processing')
}
this.debug(
'\nPROCESSING(%s)',
this.name,
this.queue.length
)
this.#processing = true
while (!this.#occupied) {
const p = this.queue.shift()
if (!p) {
this.debug('> end of queue')
break
}
if (p instanceof Base) {
this.debug('> subtest in queue', p.name)
this.#processSubtest(p)
} else if (p === EOF) {
this.debug(' > EOF', this.name)
// I AM BECOME EOF, DESTROYER OF STREAMS
this.parser.end()
} else if (p instanceof TestPoint) {
this.debug(' > TESTPOINT')
if (
p.extra.tapChildBuffer ||
p.extra.tapChildBuffer === ''
) {
this.writeSubComment(p)
this.parser.write(p.extra.tapChildBuffer)
}
this.emit('res', p.res)
this.parser.write(p.ok + ++this.#n + p.message)
} else if (typeof p === 'string') {
this.debug(' > STRING')
this.parser.write(p)
} else if (p instanceof Waiter) {
p.ready = true
this.#occupied = p
p.finish()
} else if (Array.isArray(p)) {
this.debug(' > METHOD')
const m = p.shift() as keyof this
if (typeof this[m] !== 'function') {
this.debug(
' > weird method not found in queue??',
m,
typeof this[m]
)
continue
}
const fn = (m === '#end' ? this.#end : this[m]) as (
...a: any[]
) => any
const ret = fn.call(this, ...p)
if (
ret &&
typeof ret === 'object' &&
typeof ret.then === 'function'
) {
// returned promise
ret.then(
() => {
this.#processing = false
this.#process()
},
(er: unknown) => {
this.#processing = false
this.threw(er)
}
)
return
}
/* c8 ignore start */
} else {
throw new Error('weird thing got in the queue')
}
/* c8 ignore stop */
}
while (
!this.#noparallel &&
this.pool.size < this.jobs
) {
const p = this.subtests.shift()
if (!p) {
break
}
if (!p.buffered) {
this.#noparallel = true
break
}
this.debug('start subtest', p)
this.emit('subtestStart', p)
this.pool.add(p)
if (this.bailedOut) {
this.#onBufferedEnd(p)
} else {
p.runMain(() => this.#onBufferedEnd(p))
}
}
this.debug(
'done processing',
this.queue,
this.#occupied
)
this.#processing = false
// just in case any tests ended, and we have sync stuff still
// waiting around in the queue to be processed
if (!this.#occupied && this.queue.length) {
this.#process()
}
}
#onBufferedEnd<T extends Base>(p: T) {
p.ondone = p.constructor.prototype.ondone
p.results =
p.results || new FinalResults(true, p.parser)
p.readyToProcess = true
const to = p.options.timeout
const dur =
to && p.passing() ? hrtime.bigint() - p.start : null
if (dur && to && dur > to) {
p.timeout()
} else {
p.setTimeout(0)
}
this.debug(
'%s.#onBufferedEnd',
this.name,
p.name,
p.results.bailout
)
this.pool.delete(p)
p.options.tapChildBuffer = p.output || ''
p.options.stack = ''
if (p.time) p.options.time = p.time
if (this.#occupied === p) this.#occupied = null
p.deferred?.resolve(p.results)
this.emit('subtestEnd', p)
this.#process()
}
#onIndentedEnd<T extends Base>(p: T) {
this.emit('subtestProcess', p)
p.ondone = p.constructor.prototype.ondone
p.results =
p.results || new FinalResults(true, p.parser)
this.debug('#onIndentedEnd', this.name, p.name)
this.#noparallel = false
const sti = this.subtests.indexOf(p)
if (sti !== -1) this.subtests.splice(sti, 1)
p.readyToProcess = true
p.options.time = p.time
const to = p.options.timeout
const dur =
to && p.passing() ? hrtime.bigint() - p.start : null
if (dur && to && dur > to) {
p.timeout()
} else {
p.setTimeout(0)
}
this.debug('#onIndentedEnd %s(%s)', this.name, p.name)
this.#occupied = null
this.debug(
'OIE(%s) b>shift into queue',
this.name,
this.queue
)
p.options.stack = ''
this.printResult(p.passing(), p.name, p.options, true)
this.debug(
'OIE(%s) shifted into queue',
this.name,
this.queue
)
p.deferred?.resolve(p.results)
this.emit('subtestEnd', p)
this.#process()
}
/**
* @internal
*/
main(cb: () => void) {
if (typeof this.options.timeout === 'number') {
this.setTimeout(this.options.timeout)
}
this.debug('MAIN pre', this)
const end = () => {
this.debug(' > implicit end for promise')
this.#end(IMPLICIT)
done()
}
const done = (er?: Error) => {
if (er) this.threw(er)
if (this.results || this.bailedOut) cb()
else this.ondone = () => cb()
}
// This bit of overly clever line-noise wraps the call to user-code
// in a try-catch. We can't rely on the domain for this yet, because
// the 'end' event can trigger a throw after the domain is unhooked,
// but before this is no longer the official "active test"
const ret = (() => {
if (!this.cb) return
try {
return this.cb(this)
} catch (er: any) {
if (!er || typeof er !== 'object') {
er = { error: er }
}
er.tapCaught = 'testFunctionThrow'
this.threw(er)
}
})()
if (ret && ret.then) {
this.promise = ret
ret.tapAbortPromise = done
ret.then(end, (er: any) => {
if (!er || typeof er !== 'object') {
er = { error: er }
}
er.tapCaught = 'returnedPromiseRejection'
done(er)
})
} else done()
this.debug('MAIN post', this)
}
#processSubtest<T extends Base>(p: T) {
this.debug(' > subtest')
this.#occupied = p
if (!p.buffered) {
this.emit('subtestStart', p)
this.debug(' > subtest indented')
p.stream.pipe(this.parser, { end: false })
this.writeSubComment(p)
this.debug('calling runMain', p.runMain.toString())
p.runMain(() => {
this.debug('in runMain', p.runMain.toString())
this.#onIndentedEnd(p)
})
} else if (p.readyToProcess) {
this.emit('subtestProcess', p)
this.debug(' > subtest buffered, finished')
// finished! do the thing!
this.#occupied = null
if (!p.passing() || !p.silent) {
this.printResult(
p.passing(),
p.name,
p.options,
true
)
}
} else {
this.#occupied = p
this.debug(' > subtest buffered, unfinished', p)
// unfinished buffered test.
// nothing to do yet, just leave it there.
this.queue.unshift(p)
}
}
/**
* Parse stdin as the only tap stream (ie, not as a child test)
* If used, then no other subtests or assertions are allowed.
*/
stdinOnly<T extends BaseOpts>(
extra?: T & { tapStream?: Readable | Minipass }
) {
const stream = ((extra && extra.tapStream) ||
process.stdin) as Minipass
if (!stream) {
throw new Error(
'cannot read stdin without stdin stream'
)
}
if (
this.queue.length !== 1 ||
this.queue[0] !== 'TAP version 14\n' ||
this.#processing ||
this.results ||
this.#occupied ||
this.pool.size ||
this.subtests.length
) {
throw new Error(
'Cannot use stdinOnly on a test in progress'
)
}
this.#doingStdinOnly = true
this.queue.length = 0
this.parser.on('child', p => {
// pretend to be a rooted parser, so it gets counts.
p.root = p
const t = new Base({
name: p.name,
parent: this,
parser: p,
bail: p.bail,
strict: p.strict,
omitVersion: p.omitVersion,
preserveWhitespace: p.preserveWhitespace,
childId: this.#nextChildId++,
})
this.emit('subtestAdd', t)
this.emit('subtestStart', t)
this.emit('subtestProcess', t)
p.on('complete', () => {
t.time = p.time
this.emit('subtestEnd', t)
})
})
stream.pause()
stream.pipe(this.parser)
stream.resume()
}
/**
* Mount a subtest, using this Test object as a harness.
* Exposed mainly so that it can be used by builtin plugins.
*
* @internal
*/
sub<T extends Base, O extends TestBaseOpts>(
Class: { new (options: O): T },
extra: O,
caller: (...a: any[]) => unknown
): Promise<FinalResults | null> {
if (this.bailedOut) return Promise.resolve(null)
if (this.results || this.ended) {
const er = new Error(
'cannot create subtest after parent test ends'
)
Error.captureStackTrace(er, caller)
this.threw(er)
return Promise.resolve(null)
}
extra.childId = this.#nextChildId++
if (this.shouldSkipChild(extra)) {
this.pass(extra.name, extra)
return Promise.resolve(null)
}
extra.indent = ' '
if (extra.buffered !== undefined) {
if (this.jobs > 1) {
extra.buffered = true
} else {
extra.buffered = false
}
}
extra.bail =
extra.bail !== undefined ? extra.bail : this.bail
extra.parent = this
extra.stack = stack.captureString(80, caller)
extra.context = this.context
const t = new Class(extra)
this.queue.push(t)
this.subtests.push(t)
this.emit('subtestAdd', t)
const d = new Deferred<FinalResults>()
t.deferred = d
this.#process()
return d.promise
}
/**
* Return true if the child test represented by the options object
* should be skipped. Extended by the grep/only filtering plugins.
*/
shouldSkipChild(extra: { [k: string]: any }) {
return !!(extra.skip || extra.todo)
}
// end flow control methods
}
|
src/test-base.ts
|
tapjs-core-edd7403
|
[
{
"filename": "src/test-point.ts",
"retrieved_chunk": " extra = extra || {}\n message = message\n .trim()\n .replace(/[\\n\\r]/g, ' ')\n .replace(/\\t/g, ' ')\n this.res = { ok, message, extra }\n this.extra = extra\n this.name = message\n this.message = tpMessage(esc(this.name), extra)\n }",
"score": 0.8424701690673828
},
{
"filename": "src/base.ts",
"retrieved_chunk": " // a bit excessive.\n if (this.results) {\n const alreadyBailing = !this.results.ok && this.bail\n this.results.ok = false\n if (this.parent) {\n this.parent.threw(er, extra, true)\n } else if (alreadyBailing) {\n // we are already bailing out, and this is the top level,\n // just make our way hastily to the nearest exit.\n return",
"score": 0.8279749155044556
},
{
"filename": "src/test-point.ts",
"retrieved_chunk": "}\nconst tpMessage = (\n description: string,\n extra: { [k: string]: any },\n options: TestBaseOpts = {}\n): string => {\n let message = description ? ` - ${description}` : ''\n if (extra.skip) {\n message += ' # SKIP'\n if (typeof extra.skip === 'string') {",
"score": 0.8227095007896423
},
{
"filename": "src/base.ts",
"retrieved_chunk": " er.stack.split(/\\n/).slice(1).join('\\n')\n )\n console.error(extra)\n }\n } else {\n this.parser.ok = false\n }\n return extra\n }\n passing() {",
"score": 0.8206750154495239
},
{
"filename": "src/base.ts",
"retrieved_chunk": " if (this.results) {\n Object.assign(results, this.results)\n }\n this.results = results\n this.emit('complete', results)\n const errors = results.failures\n .filter(f => f.tapError)\n .map(f => {\n delete f.diag\n delete f.ok",
"score": 0.8139390349388123
}
] |
typescript
|
if (this.bail && !ok && !extra.skip && !extra.todo) {
|
// This file is automatically generated, please do not edit
import { FinalResults } from 'tap-parser'
import parseTestArgs, {
TestArgs,
} from './parse-test-args.js'
import { TestBase, TestBaseOpts } from './test-base.js'
const copyToString = (v: Function) => ({
toString: Object.assign(() => v.toString(), {
toString: () => 'function toString() { [native code] }',
}),
})
import plugin0 from "./plugin/after-each.js"
import plugin1 from "./plugin/before-each.js"
import plugin2 from "./plugin/spawn.js"
import plugin3 from "./plugin/stdin.js"
type PI<O extends TestBaseOpts | any = any> =
| ((t: Test, opts: O) => Plug)
| ((t: Test) => Plug)
const plugins: PI[] = [
plugin0,
plugin1,
plugin2,
plugin3,
]
type Plug =
| TestBase
| { t: Test }
| ReturnType<typeof plugin0>
| ReturnType<typeof plugin1>
| ReturnType<typeof plugin2>
| ReturnType<typeof plugin3>
type PlugKeys =
| keyof TestBase
| 't'
| keyof ReturnType<typeof plugin0>
| keyof ReturnType<typeof plugin1>
| keyof ReturnType<typeof plugin2>
| keyof ReturnType<typeof plugin3>
type SecondParam<
T extends [any] | [any, any],
Fallback extends unknown = unknown
> = T extends [any, any] ? T[1] : Fallback
type Plugin0Opts = SecondParam<
Parameters<typeof plugin0>,
TestBaseOpts
>
type Plugin1Opts = SecondParam<
Parameters<typeof plugin1>,
TestBaseOpts
>
type Plugin2Opts = SecondParam<
Parameters<typeof plugin2>,
TestBaseOpts
>
type Plugin3Opts = SecondParam<
Parameters<typeof plugin3>,
TestBaseOpts
>
type TestOpts = TestBaseOpts
& Plugin0Opts
& Plugin1Opts
& Plugin2Opts
& Plugin3Opts
type TTest = TestBase
& ReturnType<typeof plugin0>
& ReturnType<typeof plugin1>
|
& ReturnType<typeof plugin2>
& ReturnType<typeof plugin3>
export interface Test extends TTest {
|
end(): this
t: Test
test(
name: string,
extra: { [k: string]: any },
cb?: (t: Test) => any
): Promise<FinalResults | null>
test(
name: string,
cb?: (t: Test) => any
): Promise<FinalResults | null>
test(
extra: { [k: string]: any },
cb?: (t: Test) => any
): Promise<FinalResults | null>
test(cb?: (t: Test) => any): Promise<FinalResults | null>
test(
...args: TestArgs<Test>
): Promise<FinalResults | null>
todo(
name: string,
extra: { [k: string]: any },
cb?: (t: Test) => any
): Promise<FinalResults | null>
todo(
name: string,
cb?: (t: Test) => any
): Promise<FinalResults | null>
todo(
extra: { [k: string]: any },
cb?: (t: Test) => any
): Promise<FinalResults | null>
todo(cb?: (t: Test) => any): Promise<FinalResults | null>
todo(
...args: TestArgs<Test>
): Promise<FinalResults | null>
skip(
name: string,
extra: { [k: string]: any },
cb?: (t: Test) => any
): Promise<FinalResults | null>
skip(
name: string,
cb?: (t: Test) => any
): Promise<FinalResults | null>
skip(
extra: { [k: string]: any },
cb?: (t: Test) => any
): Promise<FinalResults | null>
skip(cb?: (t: Test) => any): Promise<FinalResults | null>
skip(
...args: TestArgs<Test>
): Promise<FinalResults | null>
}
const applyPlugins = (base: Test): Test => {
const ext: Plug[] = [
...plugins.map(p => p(base, base.options)),
base,
]
const getCache = new Map<any, any>()
const t = new Proxy(base, {
has(_, p) {
for (const t of ext) {
if (Reflect.has(t, p)) return true
}
return false
},
ownKeys() {
const k: PlugKeys[] = []
for (const t of ext) {
const keys = Reflect.ownKeys(t) as PlugKeys[]
k.push(...keys)
}
return [...new Set(k)]
},
getOwnPropertyDescriptor(_, p) {
for (const t of ext) {
const prop = Reflect.getOwnPropertyDescriptor(t, p)
if (prop) return prop
}
return undefined
},
set(_, p, v) {
// check to see if there's any setters, and if so, set it there
// otherwise, just set on the base
for (const t of ext) {
let o: Object | null = t
while (o) {
if (Reflect.getOwnPropertyDescriptor(o, p)?.set) {
//@ts-ignore
t[p] = v
return true
}
o = Reflect.getPrototypeOf(o)
}
}
//@ts-ignore
base[p as keyof TestBase] = v
return true
},
get(_, p) {
// cache get results so t.blah === t.blah
// we only cache functions, so that getters aren't memoized
// Of course, a getter that returns a function will be broken,
// at least when accessed from outside the plugin, but that's
// a pretty narrow caveat, and easily documented.
if (getCache.has(p)) return getCache.get(p)
for (const plug of ext) {
if (p in plug) {
//@ts-ignore
const v = plug[p]
// Functions need special handling so that they report
// the correct toString and are called on the correct object
// Otherwise attempting to access #private props will fail.
if (typeof v === 'function') {
const f: (this: Plug, ...args: any) => any =
function (...args: any[]) {
const thisArg = this === t ? plug : this
return v.apply(thisArg, args)
}
const vv = Object.assign(f, copyToString(v))
const nameProp =
Reflect.getOwnPropertyDescriptor(v, 'name')
if (nameProp) {
Reflect.defineProperty(f, 'name', nameProp)
}
getCache.set(p, vv)
return vv
} else {
getCache.set(p, v)
return v
}
}
}
},
})
Object.assign(base, { t })
ext.unshift({ t })
return t
}
export class Test extends TestBase {
constructor(opts: TestOpts) {
super(opts)
return applyPlugins(this)
}
test(
name: string,
extra: { [k: string]: any },
cb?: (t: Test) => any
): Promise<FinalResults | null>
test(
name: string,
cb?: (t: Test) => any
): Promise<FinalResults | null>
test(
extra: { [k: string]: any },
cb?: (t: Test) => any
): Promise<FinalResults | null>
test(cb?: (t: Test) => any): Promise<FinalResults | null>
test(
...args: TestArgs<Test>
): Promise<FinalResults | null> {
const extra = parseTestArgs(...args)
extra.todo = true
return this.sub(Test, extra, this.test)
}
todo(
name: string,
extra: { [k: string]: any },
cb?: (t: Test) => any
): Promise<FinalResults | null>
todo(
name: string,
cb?: (t: Test) => any
): Promise<FinalResults | null>
todo(
extra: { [k: string]: any },
cb?: (t: Test) => any
): Promise<FinalResults | null>
todo(cb?: (t: Test) => any): Promise<FinalResults | null>
todo(
...args: TestArgs<Test>
): Promise<FinalResults | null> {
const extra = parseTestArgs(...args)
extra.todo = true
return this.sub(Test, extra, this.todo)
}
skip(
name: string,
extra: { [k: string]: any },
cb?: (t: Test) => any
): Promise<FinalResults | null>
skip(
name: string,
cb?: (t: Test) => any
): Promise<FinalResults | null>
skip(
extra: { [k: string]: any },
cb?: (t: Test) => any
): Promise<FinalResults | null>
skip(cb?: (t: Test) => any): Promise<FinalResults | null>
skip(
...args: TestArgs<Test>
): Promise<FinalResults | null> {
const extra = parseTestArgs(...args)
extra.skip = true
return this.sub(Test, extra, this.skip)
}
}
|
src/test-built.ts
|
tapjs-core-edd7403
|
[
{
"filename": "src/test-template.ts",
"retrieved_chunk": "//{{PLUGINS CODE START}}\ntype Plug = TestBase | { t: Test }\nconst plugins: PI[] = []\ntype PlugKeys = keyof TestBase | 't'\n//{{PLUGINS CODE END}}\n//{{OPTS START}}\ntype TestOpts = TestBaseOpts\n//{{OPTS END}}\n//{{TEST INTERFACE START}}\ntype TTest = TestBase",
"score": 0.8881107568740845
},
{
"filename": "src/build.ts",
"retrieved_chunk": " .join('')}\ntype TestOpts = TestBaseOpts${plugins\n .map((_, i) => `\\n & Plugin${i}Opts`)\n .join('')}\n`\nconst testInterface = `type TTest = TestBase\n${plugins\n .map((_, i) => ` & ReturnType<typeof plugin${i}>\\n`)\n .join('')}\n`",
"score": 0.8767628073692322
},
{
"filename": "src/test-template.ts",
"retrieved_chunk": " return t\n}\nexport class Test extends TestBase {\n constructor(opts: TestOpts) {\n super(opts)\n return applyPlugins(this)\n }\n test(\n name: string,\n extra: { [k: string]: any },",
"score": 0.8637353181838989
},
{
"filename": "src/build.ts",
"retrieved_chunk": " T extends [any] | [any, any],\n Fallback extends unknown = unknown\n> = T extends [any, any] ? T[1] : Fallback\n${plugins\n .map(\n (_, i) => `type Plugin${i}Opts = SecondParam<\n Parameters<typeof plugin${i}>,\n TestBaseOpts\n>\\n`\n )",
"score": 0.8614545464515686
},
{
"filename": "src/build.ts",
"retrieved_chunk": " .join('')}\ntype PlugKeys =\n | keyof TestBase\n | 't'\n${plugins\n .map(\n (_, i) => ` | keyof ReturnType<typeof plugin${i}>\\n`\n )\n .join('')}`\nconst opts = `type SecondParam<",
"score": 0.8511101007461548
}
] |
typescript
|
& ReturnType<typeof plugin2>
& ReturnType<typeof plugin3>
export interface Test extends TTest {
|
// lifecycle methods like beforeEach, afterEach, teardown
// defined in plugins/lifecycle.ts
import Minipass from 'minipass'
import assert from 'node:assert'
import { hrtime } from 'node:process'
import { Readable } from 'node:stream'
import { format } from 'node:util'
import { CallSiteLike } from 'stack-utils'
import { FinalResults } from 'tap-parser'
import Deferred from 'trivial-deferred'
import { Base, BaseOpts } from './base.js'
import { esc } from './esc.js'
import stack from './stack.js'
import { TestPoint } from './test-point.js'
import { Waiter } from './waiter.js'
const queueEmpty = <T extends TestBase>(t: T) =>
t.queue.length === 0 ||
(t.queue.length === 1 &&
t.queue[0] === 'TAP version 14\n')
export interface ClassOf<T> {
new (): T
}
export type TapPlugin<
B extends Object,
O extends TestBaseOpts | any = any
> = ((t: TestBase, opts: O) => B) | ((t: TestBase) => B)
export interface TestBaseOpts extends BaseOpts {
/**
* The number of jobs to run in parallel. Defaults to 1
*/
jobs?: number
/**
* Test function called when this Test is executed
*/
cb?: (...args: any[]) => any
/**
* Flag to always/never show diagnostics. If unset, then
* diagnostics are shown for failing test points only.
*/
diagnostic?: boolean
}
const normalizeMessageExtra = (
defaultMessage: string,
message?: string | { [k: string]: any },
extra?: { [k: string]: any }
): [string, { [k: string]: any }] => {
if (typeof message === 'string') {
return [message || defaultMessage, extra || {}]
} else {
return [defaultMessage, message || {}]
}
}
/**
* Sigil for implicit end() calls that should not
* trigger an error if the user then calls t.end()
*/
const IMPLICIT = Symbol('implicit end')
/**
* Sigil to put in the queue to signal the end of all things
*/
const EOF = Symbol('EOF')
export type QueueEntry =
| string
| TestPoint
| Base
| typeof EOF
| Waiter
| [method: string, ...args: any[]]
/**
* The TestBaseBase class is the base class for all plugins,
* and eventually thus the Test class.
*
* This implements subtest functionality, TAP stream generation,
* lifecycle events, and only the most basic pass/fail assertions.
*
* All other features are added with plugins.
*/
export class TestBase extends Base {
// NB: generated pluginified Test class needs to declare over this
declare parent?: TestBase
promise?: Promise<any>
jobs: number
// #beforeEnd: [method: string | Symbol, ...args: any[]][] = []
subtests: Base[] = []
pool: Set<Base> = new Set()
queue: QueueEntry[] = ['TAP version 14\n']
cb?: (...args: any[]) => any
count: number = 0
ended: boolean = false
assertAt: CallSiteLike | null = null
assertStack: string | null = null
diagnostic: null | boolean = null
#planEnd: number = -1
#printedResult: boolean = false
#explicitEnded: boolean = false
#multiEndThrew: boolean = false
#n: number = 0
#noparallel: boolean = false
#occupied: null | Waiter | Base = null
#pushedEnd: boolean = false
#nextChildId: number = 1
#currentAssert: null | ((..._: any) => any) = null
#processing: boolean = false
#doingStdinOnly: boolean = false
/**
* true if the test has printed at least one TestPoint
*/
get printedResult(): boolean {
return this.#printedResult
}
constructor(options: TestBaseOpts) {
super(options)
this.jobs =
(options.jobs && Math.max(options.jobs, 1)) || 1
if (typeof options.diagnostic === 'boolean') {
this.diagnostic = options.diagnostic
}
if (options.cb) {
this.#setCB(options.cb)
}
}
#setCB<T extends TestBase>(this: T, cb: (t: T) => any) {
this.cb = (...args: any[]) =>
this.hook.runInAsyncScope(cb, this, ...args)
}
// TAP output generating methods
/**
* immediately exit this and all parent tests with a TAP
* Bail out! message.
*/
bailout(message?: string) {
if (this.parent && (this.results || this.ended)) {
this.parent.bailout(message)
} else {
this.#process()
message = message
? ' ' + ('' + esc(message)).trim()
: ''
message = message.replace(/[\r\n]/g, ' ')
this.parser.write('Bail out!' + message + '\n')
}
this.#end(IMPLICIT)
this.#process()
}
/**
* output a TAP comment, formatted like console.log()
*/
comment(...args: any[]) {
const body = format(...args)
const message =
('# ' + body.split(/\r?\n/).join('\n# ')).trim() +
'\n'
if (this.results) {
this.write(message)
} else {
this.queue.push(message)
}
this.#process()
}
/**
* Called when the test times out.
* Options are passed as diagnostics to the threw() method
*/
timeout(options: { [k: string]: any }) {
options = options || {}
options.expired = options.expired || this.name
if (this.#occupied && this.#occupied instanceof Base) {
this.#occupied.timeout(options)
} else {
super.timeout(options)
}
this.#end(IMPLICIT)
}
/**
* Set TAP pragma configs to affect the behavior of the parser.
* Only `strict` is supported by the parser.
*/
pragma(set: { [k: string]: boolean }) {
const p = Object.keys(set).reduce(
(acc, i) =>
acc + 'pragma ' + (set[i] ? '+' : '-') + i + '\n',
''
)
this.queue.push(p)
this.#process()
}
/**
* Specify the number of Test Points expected by this test.
* Outputs a TAP plan line.
*/
plan(n: number, comment?: string) {
if (this.bailedOut) {
return
}
if (this.#planEnd !== -1) {
throw new Error('Cannot set plan more than once')
}
if (typeof n !== 'number' || n < 0) {
throw new TypeError('plan must be a number')
}
// Cannot get any tests after a trailing plan, or a plan of 0
const ending = this.count !== 0 || n === 0
if (n === 0 && comment && !this.options.skip) {
this.options.skip = comment
}
this.#planEnd = n
comment = comment ? ' # ' + esc(comment.trim()) : ''
this.queue.push('1..' + n + comment + '\n')
if (ending) {
this.#end(IMPLICIT)
} else {
this.#process()
}
}
/**
* A passing (ok) Test Point
*/
pass(message?: string, extra?: { [k: string]: any }) {
this.currentAssert = TestBase.prototype.pass
this.printResult(
true,
...normalizeMessageExtra(
'(unnamed test)',
message,
extra
)
)
return true
}
/**
* A failing (not ok) Test Point
*/
fail(message?: string, extra?: { [k: string]: any }) {
this.currentAssert = TestBase.prototype.fail
const [m, e] = normalizeMessageExtra(
'(unnamed test)',
message,
extra
)
this.printResult(false, m, e)
return !!(e.todo || e.skip)
}
/**
* The current assertion being processed. May only be set if
* not already set.
*/
get currentAssert() {
return this.#currentAssert
}
/**
* The current assertion being processed. May only be set if
* not already set.
*/
set currentAssert(fn: null | ((...a: any[]) => any)) {
if (!this.#currentAssert && typeof fn === 'function') {
this.#currentAssert = fn
}
}
/**
* Print a Test Point
*/
printResult(
ok: boolean,
message: string,
extra: { [k: string]: any },
front: boolean = false
) {
this.#printedResult = true
const n = this.count + 1
this.currentAssert = TestBase.prototype.printResult
const fn = this.#currentAssert
this.#currentAssert = null
if (this.#planEnd !== -1 && n > this.#planEnd) {
if (!this.passing()) return
const failMessage = this.#explicitEnded
? 'test after end() was called'
: 'test count exceeds plan'
const er = new Error(failMessage, {
cause: {
test: this.name,
plan: this.#planEnd,
},
})
Error.captureStackTrace(er, fn || undefined)
this.threw(er)
return
}
extra = extra || {}
if (extra.expectFail) {
ok = !ok
}
if (this.assertAt) {
extra.at = this.assertAt
this.assertAt = null
}
if (this.assertStack) {
extra.stack = this.assertStack
this.assertStack = null
}
if (typeof extra.stack === 'string' && !extra.at) {
extra.at = stack.parseLine(extra.stack.split('\n')[0])
}
if (
!ok &&
!extra.skip &&
!extra.at &&
typeof fn === 'function'
) {
extra.at = stack.at(fn)
if (!extra.todo) {
extra.stack = stack.captureString(80, fn)
}
}
const diagnostic =
typeof extra.diagnostic === 'boolean'
? extra.diagnostic
: typeof this.diagnostic === 'boolean'
? this.diagnostic
: extra.skip || extra.todo
? false
: !ok
if (diagnostic) {
extra.diagnostic = true
}
this.count = n
message = message + ''
const res = { ok, message, extra }
const tp = new TestPoint(ok, message, extra)
// when we jump the queue, skip an extra line
if (front) {
tp.message = tp.message.trimEnd() + '\n\n'
}
if (
this.#occupied &&
this.#occupied instanceof Waiter &&
this.#occupied.finishing
) {
front = true
}
if (front) {
if (
extra.tapChildBuffer ||
extra.tapChildBuffer === ''
) {
this.writeSubComment(tp)
this.parser.write(extra.tapChildBuffer)
}
this.emit('result', res)
this.parser.write(tp.ok + ++this.#n + tp.message)
if (this.bail && !ok && !extra.skip && !extra.todo) {
this.parser.write('Bail out! ' + message + '\n')
}
} else {
this.queue.push(tp)
if (this.bail && !ok && !extra.skip && !extra.todo) {
this.queue.push('Bail out! ' + message + '\n')
}
}
if (this.#planEnd === this.count) {
this.#end(IMPLICIT)
}
this.#process()
}
end(): this {
this.#end()
return super.end()
}
/**
* The leading `# Subtest` comment that introduces a child test
*/
writeSubComment<T extends TestPoint | Base>(p: T) {
const comment =
'# Subtest' +
(p.
|
name ? ': ' + esc(p.name) : '') +
'\n'
this.parser.write(comment)
}
|
// end TAP otput generating methods
// flow control methods
/**
* Await the end of a Promise before proceeding.
* The supplied callback is called with the Waiter object.
*/
waitOn(
promise: Promise<any | void>,
cb: (w: Waiter) => any,
expectReject: boolean = false
): Promise<void> {
const w = new Waiter(
promise,
w => {
assert.equal(this.#occupied, w)
cb(w)
this.#occupied = null
this.#process()
},
expectReject
)
this.queue.push(w)
this.#process()
return w.promise
}
#end(implicit?: typeof IMPLICIT) {
if (this.#doingStdinOnly && implicit !== IMPLICIT)
throw new Error(
'cannot explicitly end while in stdinOnly mode'
)
this.debug('END implicit=%j', implicit === IMPLICIT)
if (this.ended && implicit === IMPLICIT) return
// beyond here we have to be actually done with things, or else
// the semantic checks on counts and such will be off.
if (!queueEmpty(this) || this.#occupied) {
if (!this.#pushedEnd) {
this.queue.push(['#end', implicit])
}
this.#pushedEnd = true
return this.#process()
}
this.ended = true
if (implicit !== IMPLICIT && !this.#multiEndThrew) {
if (this.#explicitEnded) {
this.#multiEndThrew = true
const er = new Error(
'test end() method called more than once'
)
Error.captureStackTrace(
er,
this.#currentAssert || this.#end
)
er.cause = {
test: this.name,
}
this.threw(er)
return
}
this.#explicitEnded = true
}
if (this.#planEnd === -1) {
this.debug(
'END(%s) implicit plan',
this.name,
this.count
)
this.plan(this.count)
}
this.queue.push(EOF)
this.#process()
}
#process() {
if (this.#processing) {
return this.debug(' < already processing')
}
this.debug(
'\nPROCESSING(%s)',
this.name,
this.queue.length
)
this.#processing = true
while (!this.#occupied) {
const p = this.queue.shift()
if (!p) {
this.debug('> end of queue')
break
}
if (p instanceof Base) {
this.debug('> subtest in queue', p.name)
this.#processSubtest(p)
} else if (p === EOF) {
this.debug(' > EOF', this.name)
// I AM BECOME EOF, DESTROYER OF STREAMS
this.parser.end()
} else if (p instanceof TestPoint) {
this.debug(' > TESTPOINT')
if (
p.extra.tapChildBuffer ||
p.extra.tapChildBuffer === ''
) {
this.writeSubComment(p)
this.parser.write(p.extra.tapChildBuffer)
}
this.emit('res', p.res)
this.parser.write(p.ok + ++this.#n + p.message)
} else if (typeof p === 'string') {
this.debug(' > STRING')
this.parser.write(p)
} else if (p instanceof Waiter) {
p.ready = true
this.#occupied = p
p.finish()
} else if (Array.isArray(p)) {
this.debug(' > METHOD')
const m = p.shift() as keyof this
if (typeof this[m] !== 'function') {
this.debug(
' > weird method not found in queue??',
m,
typeof this[m]
)
continue
}
const fn = (m === '#end' ? this.#end : this[m]) as (
...a: any[]
) => any
const ret = fn.call(this, ...p)
if (
ret &&
typeof ret === 'object' &&
typeof ret.then === 'function'
) {
// returned promise
ret.then(
() => {
this.#processing = false
this.#process()
},
(er: unknown) => {
this.#processing = false
this.threw(er)
}
)
return
}
/* c8 ignore start */
} else {
throw new Error('weird thing got in the queue')
}
/* c8 ignore stop */
}
while (
!this.#noparallel &&
this.pool.size < this.jobs
) {
const p = this.subtests.shift()
if (!p) {
break
}
if (!p.buffered) {
this.#noparallel = true
break
}
this.debug('start subtest', p)
this.emit('subtestStart', p)
this.pool.add(p)
if (this.bailedOut) {
this.#onBufferedEnd(p)
} else {
p.runMain(() => this.#onBufferedEnd(p))
}
}
this.debug(
'done processing',
this.queue,
this.#occupied
)
this.#processing = false
// just in case any tests ended, and we have sync stuff still
// waiting around in the queue to be processed
if (!this.#occupied && this.queue.length) {
this.#process()
}
}
#onBufferedEnd<T extends Base>(p: T) {
p.ondone = p.constructor.prototype.ondone
p.results =
p.results || new FinalResults(true, p.parser)
p.readyToProcess = true
const to = p.options.timeout
const dur =
to && p.passing() ? hrtime.bigint() - p.start : null
if (dur && to && dur > to) {
p.timeout()
} else {
p.setTimeout(0)
}
this.debug(
'%s.#onBufferedEnd',
this.name,
p.name,
p.results.bailout
)
this.pool.delete(p)
p.options.tapChildBuffer = p.output || ''
p.options.stack = ''
if (p.time) p.options.time = p.time
if (this.#occupied === p) this.#occupied = null
p.deferred?.resolve(p.results)
this.emit('subtestEnd', p)
this.#process()
}
#onIndentedEnd<T extends Base>(p: T) {
this.emit('subtestProcess', p)
p.ondone = p.constructor.prototype.ondone
p.results =
p.results || new FinalResults(true, p.parser)
this.debug('#onIndentedEnd', this.name, p.name)
this.#noparallel = false
const sti = this.subtests.indexOf(p)
if (sti !== -1) this.subtests.splice(sti, 1)
p.readyToProcess = true
p.options.time = p.time
const to = p.options.timeout
const dur =
to && p.passing() ? hrtime.bigint() - p.start : null
if (dur && to && dur > to) {
p.timeout()
} else {
p.setTimeout(0)
}
this.debug('#onIndentedEnd %s(%s)', this.name, p.name)
this.#occupied = null
this.debug(
'OIE(%s) b>shift into queue',
this.name,
this.queue
)
p.options.stack = ''
this.printResult(p.passing(), p.name, p.options, true)
this.debug(
'OIE(%s) shifted into queue',
this.name,
this.queue
)
p.deferred?.resolve(p.results)
this.emit('subtestEnd', p)
this.#process()
}
/**
* @internal
*/
main(cb: () => void) {
if (typeof this.options.timeout === 'number') {
this.setTimeout(this.options.timeout)
}
this.debug('MAIN pre', this)
const end = () => {
this.debug(' > implicit end for promise')
this.#end(IMPLICIT)
done()
}
const done = (er?: Error) => {
if (er) this.threw(er)
if (this.results || this.bailedOut) cb()
else this.ondone = () => cb()
}
// This bit of overly clever line-noise wraps the call to user-code
// in a try-catch. We can't rely on the domain for this yet, because
// the 'end' event can trigger a throw after the domain is unhooked,
// but before this is no longer the official "active test"
const ret = (() => {
if (!this.cb) return
try {
return this.cb(this)
} catch (er: any) {
if (!er || typeof er !== 'object') {
er = { error: er }
}
er.tapCaught = 'testFunctionThrow'
this.threw(er)
}
})()
if (ret && ret.then) {
this.promise = ret
ret.tapAbortPromise = done
ret.then(end, (er: any) => {
if (!er || typeof er !== 'object') {
er = { error: er }
}
er.tapCaught = 'returnedPromiseRejection'
done(er)
})
} else done()
this.debug('MAIN post', this)
}
#processSubtest<T extends Base>(p: T) {
this.debug(' > subtest')
this.#occupied = p
if (!p.buffered) {
this.emit('subtestStart', p)
this.debug(' > subtest indented')
p.stream.pipe(this.parser, { end: false })
this.writeSubComment(p)
this.debug('calling runMain', p.runMain.toString())
p.runMain(() => {
this.debug('in runMain', p.runMain.toString())
this.#onIndentedEnd(p)
})
} else if (p.readyToProcess) {
this.emit('subtestProcess', p)
this.debug(' > subtest buffered, finished')
// finished! do the thing!
this.#occupied = null
if (!p.passing() || !p.silent) {
this.printResult(
p.passing(),
p.name,
p.options,
true
)
}
} else {
this.#occupied = p
this.debug(' > subtest buffered, unfinished', p)
// unfinished buffered test.
// nothing to do yet, just leave it there.
this.queue.unshift(p)
}
}
/**
* Parse stdin as the only tap stream (ie, not as a child test)
* If used, then no other subtests or assertions are allowed.
*/
stdinOnly<T extends BaseOpts>(
extra?: T & { tapStream?: Readable | Minipass }
) {
const stream = ((extra && extra.tapStream) ||
process.stdin) as Minipass
if (!stream) {
throw new Error(
'cannot read stdin without stdin stream'
)
}
if (
this.queue.length !== 1 ||
this.queue[0] !== 'TAP version 14\n' ||
this.#processing ||
this.results ||
this.#occupied ||
this.pool.size ||
this.subtests.length
) {
throw new Error(
'Cannot use stdinOnly on a test in progress'
)
}
this.#doingStdinOnly = true
this.queue.length = 0
this.parser.on('child', p => {
// pretend to be a rooted parser, so it gets counts.
p.root = p
const t = new Base({
name: p.name,
parent: this,
parser: p,
bail: p.bail,
strict: p.strict,
omitVersion: p.omitVersion,
preserveWhitespace: p.preserveWhitespace,
childId: this.#nextChildId++,
})
this.emit('subtestAdd', t)
this.emit('subtestStart', t)
this.emit('subtestProcess', t)
p.on('complete', () => {
t.time = p.time
this.emit('subtestEnd', t)
})
})
stream.pause()
stream.pipe(this.parser)
stream.resume()
}
/**
* Mount a subtest, using this Test object as a harness.
* Exposed mainly so that it can be used by builtin plugins.
*
* @internal
*/
sub<T extends Base, O extends TestBaseOpts>(
Class: { new (options: O): T },
extra: O,
caller: (...a: any[]) => unknown
): Promise<FinalResults | null> {
if (this.bailedOut) return Promise.resolve(null)
if (this.results || this.ended) {
const er = new Error(
'cannot create subtest after parent test ends'
)
Error.captureStackTrace(er, caller)
this.threw(er)
return Promise.resolve(null)
}
extra.childId = this.#nextChildId++
if (this.shouldSkipChild(extra)) {
this.pass(extra.name, extra)
return Promise.resolve(null)
}
extra.indent = ' '
if (extra.buffered !== undefined) {
if (this.jobs > 1) {
extra.buffered = true
} else {
extra.buffered = false
}
}
extra.bail =
extra.bail !== undefined ? extra.bail : this.bail
extra.parent = this
extra.stack = stack.captureString(80, caller)
extra.context = this.context
const t = new Class(extra)
this.queue.push(t)
this.subtests.push(t)
this.emit('subtestAdd', t)
const d = new Deferred<FinalResults>()
t.deferred = d
this.#process()
return d.promise
}
/**
* Return true if the child test represented by the options object
* should be skipped. Extended by the grep/only filtering plugins.
*/
shouldSkipChild(extra: { [k: string]: any }) {
return !!(extra.skip || extra.todo)
}
// end flow control methods
}
|
src/test-base.ts
|
tapjs-core-edd7403
|
[
{
"filename": "src/test-template.ts",
"retrieved_chunk": " test(cb?: (t: Test) => any): Promise<FinalResults | null>\n test(\n ...args: TestArgs<Test>\n ): Promise<FinalResults | null> {\n const extra = parseTestArgs(...args)\n extra.todo = true\n return this.sub(Test, extra, this.test)\n }\n todo(\n name: string,",
"score": 0.7821927070617676
},
{
"filename": "src/test-point.ts",
"retrieved_chunk": "}\nconst tpMessage = (\n description: string,\n extra: { [k: string]: any },\n options: TestBaseOpts = {}\n): string => {\n let message = description ? ` - ${description}` : ''\n if (extra.skip) {\n message += ' # SKIP'\n if (typeof extra.skip === 'string') {",
"score": 0.7801895141601562
},
{
"filename": "src/test-built.ts",
"retrieved_chunk": " skip(\n ...args: TestArgs<Test>\n ): Promise<FinalResults | null> {\n const extra = parseTestArgs(...args)\n extra.skip = true\n return this.sub(Test, extra, this.skip)\n }\n}",
"score": 0.7795557379722595
},
{
"filename": "src/test-built.ts",
"retrieved_chunk": " ): Promise<FinalResults | null> {\n const extra = parseTestArgs(...args)\n extra.todo = true\n return this.sub(Test, extra, this.test)\n }\n todo(\n name: string,\n extra: { [k: string]: any },\n cb?: (t: Test) => any\n ): Promise<FinalResults | null>",
"score": 0.7780534625053406
},
{
"filename": "src/test-point.ts",
"retrieved_chunk": "import { diags } from './diags.js'\nimport { esc } from './esc.js'\nimport { TestBaseOpts } from './test-base.js'\nexport interface Result {\n ok: boolean\n message: string\n extra: { [k: string]: any }\n}\nexport class TestPoint {\n ok: 'ok ' | 'not ok '",
"score": 0.7777788639068604
}
] |
typescript
|
name ? ': ' + esc(p.name) : '') +
'\n'
this.parser.write(comment)
}
|
// lifecycle methods like beforeEach, afterEach, teardown
// defined in plugins/lifecycle.ts
import Minipass from 'minipass'
import assert from 'node:assert'
import { hrtime } from 'node:process'
import { Readable } from 'node:stream'
import { format } from 'node:util'
import { CallSiteLike } from 'stack-utils'
import { FinalResults } from 'tap-parser'
import Deferred from 'trivial-deferred'
import { Base, BaseOpts } from './base.js'
import { esc } from './esc.js'
import stack from './stack.js'
import { TestPoint } from './test-point.js'
import { Waiter } from './waiter.js'
const queueEmpty = <T extends TestBase>(t: T) =>
t.queue.length === 0 ||
(t.queue.length === 1 &&
t.queue[0] === 'TAP version 14\n')
export interface ClassOf<T> {
new (): T
}
export type TapPlugin<
B extends Object,
O extends TestBaseOpts | any = any
> = ((t: TestBase, opts: O) => B) | ((t: TestBase) => B)
export interface TestBaseOpts extends BaseOpts {
/**
* The number of jobs to run in parallel. Defaults to 1
*/
jobs?: number
/**
* Test function called when this Test is executed
*/
cb?: (...args: any[]) => any
/**
* Flag to always/never show diagnostics. If unset, then
* diagnostics are shown for failing test points only.
*/
diagnostic?: boolean
}
const normalizeMessageExtra = (
defaultMessage: string,
message?: string | { [k: string]: any },
extra?: { [k: string]: any }
): [string, { [k: string]: any }] => {
if (typeof message === 'string') {
return [message || defaultMessage, extra || {}]
} else {
return [defaultMessage, message || {}]
}
}
/**
* Sigil for implicit end() calls that should not
* trigger an error if the user then calls t.end()
*/
const IMPLICIT = Symbol('implicit end')
/**
* Sigil to put in the queue to signal the end of all things
*/
const EOF = Symbol('EOF')
export type QueueEntry =
| string
| TestPoint
| Base
| typeof EOF
| Waiter
| [method: string, ...args: any[]]
/**
* The TestBaseBase class is the base class for all plugins,
* and eventually thus the Test class.
*
* This implements subtest functionality, TAP stream generation,
* lifecycle events, and only the most basic pass/fail assertions.
*
* All other features are added with plugins.
*/
export class TestBase extends Base {
// NB: generated pluginified Test class needs to declare over this
declare parent?: TestBase
promise?: Promise<any>
jobs: number
// #beforeEnd: [method: string | Symbol, ...args: any[]][] = []
subtests: Base[] = []
pool: Set<Base> = new Set()
queue: QueueEntry[] = ['TAP version 14\n']
cb?: (...args: any[]) => any
count: number = 0
ended: boolean = false
assertAt: CallSiteLike | null = null
assertStack: string | null = null
diagnostic: null | boolean = null
#planEnd: number = -1
#printedResult: boolean = false
#explicitEnded: boolean = false
#multiEndThrew: boolean = false
#n: number = 0
#noparallel: boolean = false
#occupied: null | Waiter | Base = null
#pushedEnd: boolean = false
#nextChildId: number = 1
#currentAssert: null | ((..._: any) => any) = null
#processing: boolean = false
#doingStdinOnly: boolean = false
/**
* true if the test has printed at least one TestPoint
*/
get printedResult(): boolean {
return this.#printedResult
}
constructor(options: TestBaseOpts) {
super(options)
this.jobs =
(options.jobs && Math.max(options.jobs, 1)) || 1
if (typeof options.diagnostic === 'boolean') {
this.diagnostic = options.diagnostic
}
if (options.cb) {
this.#setCB(options.cb)
}
}
#setCB<T extends TestBase>(this: T, cb: (t: T) => any) {
this.cb = (...args: any[]) =>
this.hook.runInAsyncScope(cb, this, ...args)
}
// TAP output generating methods
/**
* immediately exit this and all parent tests with a TAP
* Bail out! message.
*/
bailout(message?: string) {
if (this.parent && (this.results || this.ended)) {
this.parent.bailout(message)
} else {
this.#process()
message = message
? ' ' + ('' + esc(message)).trim()
: ''
message = message.replace(/[\r\n]/g, ' ')
this.parser.write('Bail out!' + message + '\n')
}
this.#end(IMPLICIT)
this.#process()
}
/**
* output a TAP comment, formatted like console.log()
*/
comment(...args: any[]) {
const body = format(...args)
const message =
('# ' + body.split(/\r?\n/).join('\n# ')).trim() +
'\n'
if (this.results) {
this.write(message)
} else {
this.queue.push(message)
}
this.#process()
}
/**
* Called when the test times out.
* Options are passed as diagnostics to the threw() method
*/
timeout(options: { [k: string]: any }) {
options = options || {}
options.expired = options.expired || this.name
if (this.#occupied && this.#occupied instanceof Base) {
this.#occupied.timeout(options)
} else {
super.timeout(options)
}
this.#end(IMPLICIT)
}
/**
* Set TAP pragma configs to affect the behavior of the parser.
* Only `strict` is supported by the parser.
*/
pragma(set: { [k: string]: boolean }) {
const p = Object.keys(set).reduce(
(acc, i) =>
acc + 'pragma ' + (set[i] ? '+' : '-') + i + '\n',
''
)
this.queue.push(p)
this.#process()
}
/**
* Specify the number of Test Points expected by this test.
* Outputs a TAP plan line.
*/
plan(n: number, comment?: string) {
if (this.bailedOut) {
return
}
if (this.#planEnd !== -1) {
throw new Error('Cannot set plan more than once')
}
if (typeof n !== 'number' || n < 0) {
throw new TypeError('plan must be a number')
}
// Cannot get any tests after a trailing plan, or a plan of 0
const ending = this.count !== 0 || n === 0
if (n === 0 && comment && !this.options.skip) {
this.options.skip = comment
}
this.#planEnd = n
comment = comment ? ' # ' + esc(comment.trim()) : ''
this.queue.push('1..' + n + comment + '\n')
if (ending) {
this.#end(IMPLICIT)
} else {
this.#process()
}
}
/**
* A passing (ok) Test Point
*/
pass(message?: string, extra?: { [k: string]: any }) {
this.currentAssert = TestBase.prototype.pass
this.printResult(
true,
...normalizeMessageExtra(
'(unnamed test)',
message,
extra
)
)
return true
}
/**
* A failing (not ok) Test Point
*/
fail(message?: string, extra?: { [k: string]: any }) {
this.currentAssert = TestBase.prototype.fail
const [m, e] = normalizeMessageExtra(
'(unnamed test)',
message,
extra
)
this.printResult(false, m, e)
return !!(e.todo || e.skip)
}
/**
* The current assertion being processed. May only be set if
* not already set.
*/
get currentAssert() {
return this.#currentAssert
}
/**
* The current assertion being processed. May only be set if
* not already set.
*/
set currentAssert(fn: null | ((...a: any[]) => any)) {
if (!this.#currentAssert && typeof fn === 'function') {
this.#currentAssert = fn
}
}
/**
* Print a Test Point
*/
printResult(
ok: boolean,
message: string,
extra: { [k: string]: any },
front: boolean = false
) {
this.#printedResult = true
const n = this.count + 1
this.currentAssert = TestBase.prototype.printResult
const fn = this.#currentAssert
this.#currentAssert = null
if (this.#planEnd !== -1 && n > this.#planEnd) {
if (!this.passing()) return
const failMessage = this.#explicitEnded
? 'test after end() was called'
: 'test count exceeds plan'
const er = new Error(failMessage, {
cause: {
test: this.name,
plan: this.#planEnd,
},
})
Error.captureStackTrace(er, fn || undefined)
this.threw(er)
return
}
extra = extra || {}
if (extra.expectFail) {
ok = !ok
}
if (this.assertAt) {
extra.at = this.assertAt
this.assertAt = null
}
if (this.assertStack) {
extra.stack = this.assertStack
this.assertStack = null
}
if (typeof extra.stack === 'string' && !extra.at) {
extra.at = stack.parseLine(extra.stack.split('\n')[0])
}
if (
!ok &&
!extra.skip &&
!extra.at &&
typeof fn === 'function'
) {
extra.at = stack.at(fn)
if (!extra.todo) {
extra.stack = stack.captureString(80, fn)
}
}
const diagnostic =
typeof extra.diagnostic === 'boolean'
? extra.diagnostic
: typeof this.diagnostic === 'boolean'
? this.diagnostic
: extra.skip || extra.todo
? false
: !ok
if (diagnostic) {
extra.diagnostic = true
}
this.count = n
message = message + ''
const res = { ok, message, extra }
const tp = new TestPoint(ok, message, extra)
// when we jump the queue, skip an extra line
if (front) {
tp.message = tp.message.trimEnd() + '\n\n'
}
if (
this.#occupied &&
this.#occupied instanceof Waiter &&
this.#occupied.finishing
) {
front = true
}
if (front) {
if (
extra.tapChildBuffer ||
extra.tapChildBuffer === ''
) {
this.writeSubComment(tp)
this.parser.write(extra.tapChildBuffer)
}
this.emit('result', res)
this.parser.write(tp.ok + ++this.#n + tp.message)
if (this.bail && !ok && !extra.skip && !extra.todo) {
this.parser.write('Bail out! ' + message + '\n')
}
} else {
this.queue.push(tp)
if (this.bail && !ok && !extra.skip && !extra.todo) {
this.queue.push('Bail out! ' + message + '\n')
}
}
if (this.#planEnd === this.count) {
this.#end(IMPLICIT)
}
this.#process()
}
end(): this {
this.#end()
return super.end()
}
/**
* The leading `# Subtest` comment that introduces a child test
*/
|
writeSubComment<T extends TestPoint | Base>(p: T) {
|
const comment =
'# Subtest' +
(p.name ? ': ' + esc(p.name) : '') +
'\n'
this.parser.write(comment)
}
// end TAP otput generating methods
// flow control methods
/**
* Await the end of a Promise before proceeding.
* The supplied callback is called with the Waiter object.
*/
waitOn(
promise: Promise<any | void>,
cb: (w: Waiter) => any,
expectReject: boolean = false
): Promise<void> {
const w = new Waiter(
promise,
w => {
assert.equal(this.#occupied, w)
cb(w)
this.#occupied = null
this.#process()
},
expectReject
)
this.queue.push(w)
this.#process()
return w.promise
}
#end(implicit?: typeof IMPLICIT) {
if (this.#doingStdinOnly && implicit !== IMPLICIT)
throw new Error(
'cannot explicitly end while in stdinOnly mode'
)
this.debug('END implicit=%j', implicit === IMPLICIT)
if (this.ended && implicit === IMPLICIT) return
// beyond here we have to be actually done with things, or else
// the semantic checks on counts and such will be off.
if (!queueEmpty(this) || this.#occupied) {
if (!this.#pushedEnd) {
this.queue.push(['#end', implicit])
}
this.#pushedEnd = true
return this.#process()
}
this.ended = true
if (implicit !== IMPLICIT && !this.#multiEndThrew) {
if (this.#explicitEnded) {
this.#multiEndThrew = true
const er = new Error(
'test end() method called more than once'
)
Error.captureStackTrace(
er,
this.#currentAssert || this.#end
)
er.cause = {
test: this.name,
}
this.threw(er)
return
}
this.#explicitEnded = true
}
if (this.#planEnd === -1) {
this.debug(
'END(%s) implicit plan',
this.name,
this.count
)
this.plan(this.count)
}
this.queue.push(EOF)
this.#process()
}
#process() {
if (this.#processing) {
return this.debug(' < already processing')
}
this.debug(
'\nPROCESSING(%s)',
this.name,
this.queue.length
)
this.#processing = true
while (!this.#occupied) {
const p = this.queue.shift()
if (!p) {
this.debug('> end of queue')
break
}
if (p instanceof Base) {
this.debug('> subtest in queue', p.name)
this.#processSubtest(p)
} else if (p === EOF) {
this.debug(' > EOF', this.name)
// I AM BECOME EOF, DESTROYER OF STREAMS
this.parser.end()
} else if (p instanceof TestPoint) {
this.debug(' > TESTPOINT')
if (
p.extra.tapChildBuffer ||
p.extra.tapChildBuffer === ''
) {
this.writeSubComment(p)
this.parser.write(p.extra.tapChildBuffer)
}
this.emit('res', p.res)
this.parser.write(p.ok + ++this.#n + p.message)
} else if (typeof p === 'string') {
this.debug(' > STRING')
this.parser.write(p)
} else if (p instanceof Waiter) {
p.ready = true
this.#occupied = p
p.finish()
} else if (Array.isArray(p)) {
this.debug(' > METHOD')
const m = p.shift() as keyof this
if (typeof this[m] !== 'function') {
this.debug(
' > weird method not found in queue??',
m,
typeof this[m]
)
continue
}
const fn = (m === '#end' ? this.#end : this[m]) as (
...a: any[]
) => any
const ret = fn.call(this, ...p)
if (
ret &&
typeof ret === 'object' &&
typeof ret.then === 'function'
) {
// returned promise
ret.then(
() => {
this.#processing = false
this.#process()
},
(er: unknown) => {
this.#processing = false
this.threw(er)
}
)
return
}
/* c8 ignore start */
} else {
throw new Error('weird thing got in the queue')
}
/* c8 ignore stop */
}
while (
!this.#noparallel &&
this.pool.size < this.jobs
) {
const p = this.subtests.shift()
if (!p) {
break
}
if (!p.buffered) {
this.#noparallel = true
break
}
this.debug('start subtest', p)
this.emit('subtestStart', p)
this.pool.add(p)
if (this.bailedOut) {
this.#onBufferedEnd(p)
} else {
p.runMain(() => this.#onBufferedEnd(p))
}
}
this.debug(
'done processing',
this.queue,
this.#occupied
)
this.#processing = false
// just in case any tests ended, and we have sync stuff still
// waiting around in the queue to be processed
if (!this.#occupied && this.queue.length) {
this.#process()
}
}
#onBufferedEnd<T extends Base>(p: T) {
p.ondone = p.constructor.prototype.ondone
p.results =
p.results || new FinalResults(true, p.parser)
p.readyToProcess = true
const to = p.options.timeout
const dur =
to && p.passing() ? hrtime.bigint() - p.start : null
if (dur && to && dur > to) {
p.timeout()
} else {
p.setTimeout(0)
}
this.debug(
'%s.#onBufferedEnd',
this.name,
p.name,
p.results.bailout
)
this.pool.delete(p)
p.options.tapChildBuffer = p.output || ''
p.options.stack = ''
if (p.time) p.options.time = p.time
if (this.#occupied === p) this.#occupied = null
p.deferred?.resolve(p.results)
this.emit('subtestEnd', p)
this.#process()
}
#onIndentedEnd<T extends Base>(p: T) {
this.emit('subtestProcess', p)
p.ondone = p.constructor.prototype.ondone
p.results =
p.results || new FinalResults(true, p.parser)
this.debug('#onIndentedEnd', this.name, p.name)
this.#noparallel = false
const sti = this.subtests.indexOf(p)
if (sti !== -1) this.subtests.splice(sti, 1)
p.readyToProcess = true
p.options.time = p.time
const to = p.options.timeout
const dur =
to && p.passing() ? hrtime.bigint() - p.start : null
if (dur && to && dur > to) {
p.timeout()
} else {
p.setTimeout(0)
}
this.debug('#onIndentedEnd %s(%s)', this.name, p.name)
this.#occupied = null
this.debug(
'OIE(%s) b>shift into queue',
this.name,
this.queue
)
p.options.stack = ''
this.printResult(p.passing(), p.name, p.options, true)
this.debug(
'OIE(%s) shifted into queue',
this.name,
this.queue
)
p.deferred?.resolve(p.results)
this.emit('subtestEnd', p)
this.#process()
}
/**
* @internal
*/
main(cb: () => void) {
if (typeof this.options.timeout === 'number') {
this.setTimeout(this.options.timeout)
}
this.debug('MAIN pre', this)
const end = () => {
this.debug(' > implicit end for promise')
this.#end(IMPLICIT)
done()
}
const done = (er?: Error) => {
if (er) this.threw(er)
if (this.results || this.bailedOut) cb()
else this.ondone = () => cb()
}
// This bit of overly clever line-noise wraps the call to user-code
// in a try-catch. We can't rely on the domain for this yet, because
// the 'end' event can trigger a throw after the domain is unhooked,
// but before this is no longer the official "active test"
const ret = (() => {
if (!this.cb) return
try {
return this.cb(this)
} catch (er: any) {
if (!er || typeof er !== 'object') {
er = { error: er }
}
er.tapCaught = 'testFunctionThrow'
this.threw(er)
}
})()
if (ret && ret.then) {
this.promise = ret
ret.tapAbortPromise = done
ret.then(end, (er: any) => {
if (!er || typeof er !== 'object') {
er = { error: er }
}
er.tapCaught = 'returnedPromiseRejection'
done(er)
})
} else done()
this.debug('MAIN post', this)
}
#processSubtest<T extends Base>(p: T) {
this.debug(' > subtest')
this.#occupied = p
if (!p.buffered) {
this.emit('subtestStart', p)
this.debug(' > subtest indented')
p.stream.pipe(this.parser, { end: false })
this.writeSubComment(p)
this.debug('calling runMain', p.runMain.toString())
p.runMain(() => {
this.debug('in runMain', p.runMain.toString())
this.#onIndentedEnd(p)
})
} else if (p.readyToProcess) {
this.emit('subtestProcess', p)
this.debug(' > subtest buffered, finished')
// finished! do the thing!
this.#occupied = null
if (!p.passing() || !p.silent) {
this.printResult(
p.passing(),
p.name,
p.options,
true
)
}
} else {
this.#occupied = p
this.debug(' > subtest buffered, unfinished', p)
// unfinished buffered test.
// nothing to do yet, just leave it there.
this.queue.unshift(p)
}
}
/**
* Parse stdin as the only tap stream (ie, not as a child test)
* If used, then no other subtests or assertions are allowed.
*/
stdinOnly<T extends BaseOpts>(
extra?: T & { tapStream?: Readable | Minipass }
) {
const stream = ((extra && extra.tapStream) ||
process.stdin) as Minipass
if (!stream) {
throw new Error(
'cannot read stdin without stdin stream'
)
}
if (
this.queue.length !== 1 ||
this.queue[0] !== 'TAP version 14\n' ||
this.#processing ||
this.results ||
this.#occupied ||
this.pool.size ||
this.subtests.length
) {
throw new Error(
'Cannot use stdinOnly on a test in progress'
)
}
this.#doingStdinOnly = true
this.queue.length = 0
this.parser.on('child', p => {
// pretend to be a rooted parser, so it gets counts.
p.root = p
const t = new Base({
name: p.name,
parent: this,
parser: p,
bail: p.bail,
strict: p.strict,
omitVersion: p.omitVersion,
preserveWhitespace: p.preserveWhitespace,
childId: this.#nextChildId++,
})
this.emit('subtestAdd', t)
this.emit('subtestStart', t)
this.emit('subtestProcess', t)
p.on('complete', () => {
t.time = p.time
this.emit('subtestEnd', t)
})
})
stream.pause()
stream.pipe(this.parser)
stream.resume()
}
/**
* Mount a subtest, using this Test object as a harness.
* Exposed mainly so that it can be used by builtin plugins.
*
* @internal
*/
sub<T extends Base, O extends TestBaseOpts>(
Class: { new (options: O): T },
extra: O,
caller: (...a: any[]) => unknown
): Promise<FinalResults | null> {
if (this.bailedOut) return Promise.resolve(null)
if (this.results || this.ended) {
const er = new Error(
'cannot create subtest after parent test ends'
)
Error.captureStackTrace(er, caller)
this.threw(er)
return Promise.resolve(null)
}
extra.childId = this.#nextChildId++
if (this.shouldSkipChild(extra)) {
this.pass(extra.name, extra)
return Promise.resolve(null)
}
extra.indent = ' '
if (extra.buffered !== undefined) {
if (this.jobs > 1) {
extra.buffered = true
} else {
extra.buffered = false
}
}
extra.bail =
extra.bail !== undefined ? extra.bail : this.bail
extra.parent = this
extra.stack = stack.captureString(80, caller)
extra.context = this.context
const t = new Class(extra)
this.queue.push(t)
this.subtests.push(t)
this.emit('subtestAdd', t)
const d = new Deferred<FinalResults>()
t.deferred = d
this.#process()
return d.promise
}
/**
* Return true if the child test represented by the options object
* should be skipped. Extended by the grep/only filtering plugins.
*/
shouldSkipChild(extra: { [k: string]: any }) {
return !!(extra.skip || extra.todo)
}
// end flow control methods
}
|
src/test-base.ts
|
tapjs-core-edd7403
|
[
{
"filename": "src/test-template.ts",
"retrieved_chunk": "//{{TEST INTERFACE END}}\nexport interface Test extends TTest {\n end(): this\n t: Test\n test(\n name: string,\n extra: { [k: string]: any },\n cb?: (t: Test) => any\n ): Promise<FinalResults | null>\n test(",
"score": 0.8059313297271729
},
{
"filename": "src/test-template.ts",
"retrieved_chunk": " test(cb?: (t: Test) => any): Promise<FinalResults | null>\n test(\n ...args: TestArgs<Test>\n ): Promise<FinalResults | null> {\n const extra = parseTestArgs(...args)\n extra.todo = true\n return this.sub(Test, extra, this.test)\n }\n todo(\n name: string,",
"score": 0.7913113832473755
},
{
"filename": "src/test-built.ts",
"retrieved_chunk": " }\n }\n }\n },\n })\n Object.assign(base, { t })\n ext.unshift({ t })\n return t\n}\nexport class Test extends TestBase {",
"score": 0.7887832522392273
},
{
"filename": "src/test-built.ts",
"retrieved_chunk": " ): Promise<FinalResults | null> {\n const extra = parseTestArgs(...args)\n extra.todo = true\n return this.sub(Test, extra, this.test)\n }\n todo(\n name: string,\n extra: { [k: string]: any },\n cb?: (t: Test) => any\n ): Promise<FinalResults | null>",
"score": 0.788723349571228
},
{
"filename": "src/test-template.ts",
"retrieved_chunk": " ): Promise<FinalResults | null>\n todo(cb?: (t: Test) => any): Promise<FinalResults | null>\n todo(\n ...args: TestArgs<Test>\n ): Promise<FinalResults | null> {\n const extra = parseTestArgs(...args)\n extra.todo = true\n return this.sub(Test, extra, this.todo)\n }\n skip(",
"score": 0.7873712778091431
}
] |
typescript
|
writeSubComment<T extends TestPoint | Base>(p: T) {
|
// lifecycle methods like beforeEach, afterEach, teardown
// defined in plugins/lifecycle.ts
import Minipass from 'minipass'
import assert from 'node:assert'
import { hrtime } from 'node:process'
import { Readable } from 'node:stream'
import { format } from 'node:util'
import { CallSiteLike } from 'stack-utils'
import { FinalResults } from 'tap-parser'
import Deferred from 'trivial-deferred'
import { Base, BaseOpts } from './base.js'
import { esc } from './esc.js'
import stack from './stack.js'
import { TestPoint } from './test-point.js'
import { Waiter } from './waiter.js'
const queueEmpty = <T extends TestBase>(t: T) =>
t.queue.length === 0 ||
(t.queue.length === 1 &&
t.queue[0] === 'TAP version 14\n')
export interface ClassOf<T> {
new (): T
}
export type TapPlugin<
B extends Object,
O extends TestBaseOpts | any = any
> = ((t: TestBase, opts: O) => B) | ((t: TestBase) => B)
export interface TestBaseOpts extends BaseOpts {
/**
* The number of jobs to run in parallel. Defaults to 1
*/
jobs?: number
/**
* Test function called when this Test is executed
*/
cb?: (...args: any[]) => any
/**
* Flag to always/never show diagnostics. If unset, then
* diagnostics are shown for failing test points only.
*/
diagnostic?: boolean
}
const normalizeMessageExtra = (
defaultMessage: string,
message?: string | { [k: string]: any },
extra?: { [k: string]: any }
): [string, { [k: string]: any }] => {
if (typeof message === 'string') {
return [message || defaultMessage, extra || {}]
} else {
return [defaultMessage, message || {}]
}
}
/**
* Sigil for implicit end() calls that should not
* trigger an error if the user then calls t.end()
*/
const IMPLICIT = Symbol('implicit end')
/**
* Sigil to put in the queue to signal the end of all things
*/
const EOF = Symbol('EOF')
export type QueueEntry =
| string
| TestPoint
| Base
| typeof EOF
| Waiter
| [method: string, ...args: any[]]
/**
* The TestBaseBase class is the base class for all plugins,
* and eventually thus the Test class.
*
* This implements subtest functionality, TAP stream generation,
* lifecycle events, and only the most basic pass/fail assertions.
*
* All other features are added with plugins.
*/
export class TestBase extends Base {
// NB: generated pluginified Test class needs to declare over this
declare parent?: TestBase
promise?: Promise<any>
jobs: number
// #beforeEnd: [method: string | Symbol, ...args: any[]][] = []
subtests: Base[] = []
pool: Set<Base> = new Set()
queue: QueueEntry[] = ['TAP version 14\n']
cb?: (...args: any[]) => any
count: number = 0
ended: boolean = false
assertAt: CallSiteLike | null = null
assertStack: string | null = null
diagnostic: null | boolean = null
#planEnd: number = -1
#printedResult: boolean = false
#explicitEnded: boolean = false
#multiEndThrew: boolean = false
#n: number = 0
#noparallel: boolean = false
#occupied: null | Waiter | Base = null
#pushedEnd: boolean = false
#nextChildId: number = 1
#currentAssert: null | ((..._: any) => any) = null
#processing: boolean = false
#doingStdinOnly: boolean = false
/**
* true if the test has printed at least one TestPoint
*/
get printedResult(): boolean {
return this.#printedResult
}
constructor(options: TestBaseOpts) {
super(options)
this.jobs =
(options.jobs && Math.max(options.jobs, 1)) || 1
if (typeof options.diagnostic === 'boolean') {
this.diagnostic = options.diagnostic
}
if (options.cb) {
this.#setCB(options.cb)
}
}
#setCB<T extends TestBase>(this: T, cb: (t: T) => any) {
this.cb = (...args: any[]) =>
|
this.hook.runInAsyncScope(cb, this, ...args)
}
|
// TAP output generating methods
/**
* immediately exit this and all parent tests with a TAP
* Bail out! message.
*/
bailout(message?: string) {
if (this.parent && (this.results || this.ended)) {
this.parent.bailout(message)
} else {
this.#process()
message = message
? ' ' + ('' + esc(message)).trim()
: ''
message = message.replace(/[\r\n]/g, ' ')
this.parser.write('Bail out!' + message + '\n')
}
this.#end(IMPLICIT)
this.#process()
}
/**
* output a TAP comment, formatted like console.log()
*/
comment(...args: any[]) {
const body = format(...args)
const message =
('# ' + body.split(/\r?\n/).join('\n# ')).trim() +
'\n'
if (this.results) {
this.write(message)
} else {
this.queue.push(message)
}
this.#process()
}
/**
* Called when the test times out.
* Options are passed as diagnostics to the threw() method
*/
timeout(options: { [k: string]: any }) {
options = options || {}
options.expired = options.expired || this.name
if (this.#occupied && this.#occupied instanceof Base) {
this.#occupied.timeout(options)
} else {
super.timeout(options)
}
this.#end(IMPLICIT)
}
/**
* Set TAP pragma configs to affect the behavior of the parser.
* Only `strict` is supported by the parser.
*/
pragma(set: { [k: string]: boolean }) {
const p = Object.keys(set).reduce(
(acc, i) =>
acc + 'pragma ' + (set[i] ? '+' : '-') + i + '\n',
''
)
this.queue.push(p)
this.#process()
}
/**
* Specify the number of Test Points expected by this test.
* Outputs a TAP plan line.
*/
plan(n: number, comment?: string) {
if (this.bailedOut) {
return
}
if (this.#planEnd !== -1) {
throw new Error('Cannot set plan more than once')
}
if (typeof n !== 'number' || n < 0) {
throw new TypeError('plan must be a number')
}
// Cannot get any tests after a trailing plan, or a plan of 0
const ending = this.count !== 0 || n === 0
if (n === 0 && comment && !this.options.skip) {
this.options.skip = comment
}
this.#planEnd = n
comment = comment ? ' # ' + esc(comment.trim()) : ''
this.queue.push('1..' + n + comment + '\n')
if (ending) {
this.#end(IMPLICIT)
} else {
this.#process()
}
}
/**
* A passing (ok) Test Point
*/
pass(message?: string, extra?: { [k: string]: any }) {
this.currentAssert = TestBase.prototype.pass
this.printResult(
true,
...normalizeMessageExtra(
'(unnamed test)',
message,
extra
)
)
return true
}
/**
* A failing (not ok) Test Point
*/
fail(message?: string, extra?: { [k: string]: any }) {
this.currentAssert = TestBase.prototype.fail
const [m, e] = normalizeMessageExtra(
'(unnamed test)',
message,
extra
)
this.printResult(false, m, e)
return !!(e.todo || e.skip)
}
/**
* The current assertion being processed. May only be set if
* not already set.
*/
get currentAssert() {
return this.#currentAssert
}
/**
* The current assertion being processed. May only be set if
* not already set.
*/
set currentAssert(fn: null | ((...a: any[]) => any)) {
if (!this.#currentAssert && typeof fn === 'function') {
this.#currentAssert = fn
}
}
/**
* Print a Test Point
*/
printResult(
ok: boolean,
message: string,
extra: { [k: string]: any },
front: boolean = false
) {
this.#printedResult = true
const n = this.count + 1
this.currentAssert = TestBase.prototype.printResult
const fn = this.#currentAssert
this.#currentAssert = null
if (this.#planEnd !== -1 && n > this.#planEnd) {
if (!this.passing()) return
const failMessage = this.#explicitEnded
? 'test after end() was called'
: 'test count exceeds plan'
const er = new Error(failMessage, {
cause: {
test: this.name,
plan: this.#planEnd,
},
})
Error.captureStackTrace(er, fn || undefined)
this.threw(er)
return
}
extra = extra || {}
if (extra.expectFail) {
ok = !ok
}
if (this.assertAt) {
extra.at = this.assertAt
this.assertAt = null
}
if (this.assertStack) {
extra.stack = this.assertStack
this.assertStack = null
}
if (typeof extra.stack === 'string' && !extra.at) {
extra.at = stack.parseLine(extra.stack.split('\n')[0])
}
if (
!ok &&
!extra.skip &&
!extra.at &&
typeof fn === 'function'
) {
extra.at = stack.at(fn)
if (!extra.todo) {
extra.stack = stack.captureString(80, fn)
}
}
const diagnostic =
typeof extra.diagnostic === 'boolean'
? extra.diagnostic
: typeof this.diagnostic === 'boolean'
? this.diagnostic
: extra.skip || extra.todo
? false
: !ok
if (diagnostic) {
extra.diagnostic = true
}
this.count = n
message = message + ''
const res = { ok, message, extra }
const tp = new TestPoint(ok, message, extra)
// when we jump the queue, skip an extra line
if (front) {
tp.message = tp.message.trimEnd() + '\n\n'
}
if (
this.#occupied &&
this.#occupied instanceof Waiter &&
this.#occupied.finishing
) {
front = true
}
if (front) {
if (
extra.tapChildBuffer ||
extra.tapChildBuffer === ''
) {
this.writeSubComment(tp)
this.parser.write(extra.tapChildBuffer)
}
this.emit('result', res)
this.parser.write(tp.ok + ++this.#n + tp.message)
if (this.bail && !ok && !extra.skip && !extra.todo) {
this.parser.write('Bail out! ' + message + '\n')
}
} else {
this.queue.push(tp)
if (this.bail && !ok && !extra.skip && !extra.todo) {
this.queue.push('Bail out! ' + message + '\n')
}
}
if (this.#planEnd === this.count) {
this.#end(IMPLICIT)
}
this.#process()
}
end(): this {
this.#end()
return super.end()
}
/**
* The leading `# Subtest` comment that introduces a child test
*/
writeSubComment<T extends TestPoint | Base>(p: T) {
const comment =
'# Subtest' +
(p.name ? ': ' + esc(p.name) : '') +
'\n'
this.parser.write(comment)
}
// end TAP otput generating methods
// flow control methods
/**
* Await the end of a Promise before proceeding.
* The supplied callback is called with the Waiter object.
*/
waitOn(
promise: Promise<any | void>,
cb: (w: Waiter) => any,
expectReject: boolean = false
): Promise<void> {
const w = new Waiter(
promise,
w => {
assert.equal(this.#occupied, w)
cb(w)
this.#occupied = null
this.#process()
},
expectReject
)
this.queue.push(w)
this.#process()
return w.promise
}
#end(implicit?: typeof IMPLICIT) {
if (this.#doingStdinOnly && implicit !== IMPLICIT)
throw new Error(
'cannot explicitly end while in stdinOnly mode'
)
this.debug('END implicit=%j', implicit === IMPLICIT)
if (this.ended && implicit === IMPLICIT) return
// beyond here we have to be actually done with things, or else
// the semantic checks on counts and such will be off.
if (!queueEmpty(this) || this.#occupied) {
if (!this.#pushedEnd) {
this.queue.push(['#end', implicit])
}
this.#pushedEnd = true
return this.#process()
}
this.ended = true
if (implicit !== IMPLICIT && !this.#multiEndThrew) {
if (this.#explicitEnded) {
this.#multiEndThrew = true
const er = new Error(
'test end() method called more than once'
)
Error.captureStackTrace(
er,
this.#currentAssert || this.#end
)
er.cause = {
test: this.name,
}
this.threw(er)
return
}
this.#explicitEnded = true
}
if (this.#planEnd === -1) {
this.debug(
'END(%s) implicit plan',
this.name,
this.count
)
this.plan(this.count)
}
this.queue.push(EOF)
this.#process()
}
#process() {
if (this.#processing) {
return this.debug(' < already processing')
}
this.debug(
'\nPROCESSING(%s)',
this.name,
this.queue.length
)
this.#processing = true
while (!this.#occupied) {
const p = this.queue.shift()
if (!p) {
this.debug('> end of queue')
break
}
if (p instanceof Base) {
this.debug('> subtest in queue', p.name)
this.#processSubtest(p)
} else if (p === EOF) {
this.debug(' > EOF', this.name)
// I AM BECOME EOF, DESTROYER OF STREAMS
this.parser.end()
} else if (p instanceof TestPoint) {
this.debug(' > TESTPOINT')
if (
p.extra.tapChildBuffer ||
p.extra.tapChildBuffer === ''
) {
this.writeSubComment(p)
this.parser.write(p.extra.tapChildBuffer)
}
this.emit('res', p.res)
this.parser.write(p.ok + ++this.#n + p.message)
} else if (typeof p === 'string') {
this.debug(' > STRING')
this.parser.write(p)
} else if (p instanceof Waiter) {
p.ready = true
this.#occupied = p
p.finish()
} else if (Array.isArray(p)) {
this.debug(' > METHOD')
const m = p.shift() as keyof this
if (typeof this[m] !== 'function') {
this.debug(
' > weird method not found in queue??',
m,
typeof this[m]
)
continue
}
const fn = (m === '#end' ? this.#end : this[m]) as (
...a: any[]
) => any
const ret = fn.call(this, ...p)
if (
ret &&
typeof ret === 'object' &&
typeof ret.then === 'function'
) {
// returned promise
ret.then(
() => {
this.#processing = false
this.#process()
},
(er: unknown) => {
this.#processing = false
this.threw(er)
}
)
return
}
/* c8 ignore start */
} else {
throw new Error('weird thing got in the queue')
}
/* c8 ignore stop */
}
while (
!this.#noparallel &&
this.pool.size < this.jobs
) {
const p = this.subtests.shift()
if (!p) {
break
}
if (!p.buffered) {
this.#noparallel = true
break
}
this.debug('start subtest', p)
this.emit('subtestStart', p)
this.pool.add(p)
if (this.bailedOut) {
this.#onBufferedEnd(p)
} else {
p.runMain(() => this.#onBufferedEnd(p))
}
}
this.debug(
'done processing',
this.queue,
this.#occupied
)
this.#processing = false
// just in case any tests ended, and we have sync stuff still
// waiting around in the queue to be processed
if (!this.#occupied && this.queue.length) {
this.#process()
}
}
#onBufferedEnd<T extends Base>(p: T) {
p.ondone = p.constructor.prototype.ondone
p.results =
p.results || new FinalResults(true, p.parser)
p.readyToProcess = true
const to = p.options.timeout
const dur =
to && p.passing() ? hrtime.bigint() - p.start : null
if (dur && to && dur > to) {
p.timeout()
} else {
p.setTimeout(0)
}
this.debug(
'%s.#onBufferedEnd',
this.name,
p.name,
p.results.bailout
)
this.pool.delete(p)
p.options.tapChildBuffer = p.output || ''
p.options.stack = ''
if (p.time) p.options.time = p.time
if (this.#occupied === p) this.#occupied = null
p.deferred?.resolve(p.results)
this.emit('subtestEnd', p)
this.#process()
}
#onIndentedEnd<T extends Base>(p: T) {
this.emit('subtestProcess', p)
p.ondone = p.constructor.prototype.ondone
p.results =
p.results || new FinalResults(true, p.parser)
this.debug('#onIndentedEnd', this.name, p.name)
this.#noparallel = false
const sti = this.subtests.indexOf(p)
if (sti !== -1) this.subtests.splice(sti, 1)
p.readyToProcess = true
p.options.time = p.time
const to = p.options.timeout
const dur =
to && p.passing() ? hrtime.bigint() - p.start : null
if (dur && to && dur > to) {
p.timeout()
} else {
p.setTimeout(0)
}
this.debug('#onIndentedEnd %s(%s)', this.name, p.name)
this.#occupied = null
this.debug(
'OIE(%s) b>shift into queue',
this.name,
this.queue
)
p.options.stack = ''
this.printResult(p.passing(), p.name, p.options, true)
this.debug(
'OIE(%s) shifted into queue',
this.name,
this.queue
)
p.deferred?.resolve(p.results)
this.emit('subtestEnd', p)
this.#process()
}
/**
* @internal
*/
main(cb: () => void) {
if (typeof this.options.timeout === 'number') {
this.setTimeout(this.options.timeout)
}
this.debug('MAIN pre', this)
const end = () => {
this.debug(' > implicit end for promise')
this.#end(IMPLICIT)
done()
}
const done = (er?: Error) => {
if (er) this.threw(er)
if (this.results || this.bailedOut) cb()
else this.ondone = () => cb()
}
// This bit of overly clever line-noise wraps the call to user-code
// in a try-catch. We can't rely on the domain for this yet, because
// the 'end' event can trigger a throw after the domain is unhooked,
// but before this is no longer the official "active test"
const ret = (() => {
if (!this.cb) return
try {
return this.cb(this)
} catch (er: any) {
if (!er || typeof er !== 'object') {
er = { error: er }
}
er.tapCaught = 'testFunctionThrow'
this.threw(er)
}
})()
if (ret && ret.then) {
this.promise = ret
ret.tapAbortPromise = done
ret.then(end, (er: any) => {
if (!er || typeof er !== 'object') {
er = { error: er }
}
er.tapCaught = 'returnedPromiseRejection'
done(er)
})
} else done()
this.debug('MAIN post', this)
}
#processSubtest<T extends Base>(p: T) {
this.debug(' > subtest')
this.#occupied = p
if (!p.buffered) {
this.emit('subtestStart', p)
this.debug(' > subtest indented')
p.stream.pipe(this.parser, { end: false })
this.writeSubComment(p)
this.debug('calling runMain', p.runMain.toString())
p.runMain(() => {
this.debug('in runMain', p.runMain.toString())
this.#onIndentedEnd(p)
})
} else if (p.readyToProcess) {
this.emit('subtestProcess', p)
this.debug(' > subtest buffered, finished')
// finished! do the thing!
this.#occupied = null
if (!p.passing() || !p.silent) {
this.printResult(
p.passing(),
p.name,
p.options,
true
)
}
} else {
this.#occupied = p
this.debug(' > subtest buffered, unfinished', p)
// unfinished buffered test.
// nothing to do yet, just leave it there.
this.queue.unshift(p)
}
}
/**
* Parse stdin as the only tap stream (ie, not as a child test)
* If used, then no other subtests or assertions are allowed.
*/
stdinOnly<T extends BaseOpts>(
extra?: T & { tapStream?: Readable | Minipass }
) {
const stream = ((extra && extra.tapStream) ||
process.stdin) as Minipass
if (!stream) {
throw new Error(
'cannot read stdin without stdin stream'
)
}
if (
this.queue.length !== 1 ||
this.queue[0] !== 'TAP version 14\n' ||
this.#processing ||
this.results ||
this.#occupied ||
this.pool.size ||
this.subtests.length
) {
throw new Error(
'Cannot use stdinOnly on a test in progress'
)
}
this.#doingStdinOnly = true
this.queue.length = 0
this.parser.on('child', p => {
// pretend to be a rooted parser, so it gets counts.
p.root = p
const t = new Base({
name: p.name,
parent: this,
parser: p,
bail: p.bail,
strict: p.strict,
omitVersion: p.omitVersion,
preserveWhitespace: p.preserveWhitespace,
childId: this.#nextChildId++,
})
this.emit('subtestAdd', t)
this.emit('subtestStart', t)
this.emit('subtestProcess', t)
p.on('complete', () => {
t.time = p.time
this.emit('subtestEnd', t)
})
})
stream.pause()
stream.pipe(this.parser)
stream.resume()
}
/**
* Mount a subtest, using this Test object as a harness.
* Exposed mainly so that it can be used by builtin plugins.
*
* @internal
*/
sub<T extends Base, O extends TestBaseOpts>(
Class: { new (options: O): T },
extra: O,
caller: (...a: any[]) => unknown
): Promise<FinalResults | null> {
if (this.bailedOut) return Promise.resolve(null)
if (this.results || this.ended) {
const er = new Error(
'cannot create subtest after parent test ends'
)
Error.captureStackTrace(er, caller)
this.threw(er)
return Promise.resolve(null)
}
extra.childId = this.#nextChildId++
if (this.shouldSkipChild(extra)) {
this.pass(extra.name, extra)
return Promise.resolve(null)
}
extra.indent = ' '
if (extra.buffered !== undefined) {
if (this.jobs > 1) {
extra.buffered = true
} else {
extra.buffered = false
}
}
extra.bail =
extra.bail !== undefined ? extra.bail : this.bail
extra.parent = this
extra.stack = stack.captureString(80, caller)
extra.context = this.context
const t = new Class(extra)
this.queue.push(t)
this.subtests.push(t)
this.emit('subtestAdd', t)
const d = new Deferred<FinalResults>()
t.deferred = d
this.#process()
return d.promise
}
/**
* Return true if the child test represented by the options object
* should be skipped. Extended by the grep/only filtering plugins.
*/
shouldSkipChild(extra: { [k: string]: any }) {
return !!(extra.skip || extra.todo)
}
// end flow control methods
}
|
src/test-base.ts
|
tapjs-core-edd7403
|
[
{
"filename": "src/plugin/before-each.ts",
"retrieved_chunk": " const runMain = t.runMain\n t.runMain = (cb: () => void) => {\n this.#runBeforeEach(this.#t, () =>\n runMain.call(t, cb)\n )\n }\n }\n #onBeforeEach: ((t: Test) => void)[] = []\n beforeEach(fn: (t: Test) => void | Promise<void>) {\n this.#onBeforeEach.push(fn)",
"score": 0.8570007085800171
},
{
"filename": "src/base.ts",
"retrieved_chunk": " this.setTimeout(0)\n options = options || {}\n options.expired = options.expired || this.name\n const threw = this.threw(new Error('timeout!'), options)\n if (threw) {\n this.emit('timeout', threw)\n }\n }\n runMain(cb: () => void) {\n this.debug('BASE runMain')",
"score": 0.8549596667289734
},
{
"filename": "src/spawn.ts",
"retrieved_chunk": " }\n main(cb: () => void) {\n this.cb = cb\n this.setTimeout(this.options.timeout || 0)\n this.parser.on('comment', c => {\n const tomatch = c.match(/# timeout=([0-9]+)\\n$/)\n if (tomatch) {\n this.setTimeout(+tomatch[1])\n }\n })",
"score": 0.8397820591926575
},
{
"filename": "src/test-built.ts",
"retrieved_chunk": " constructor(opts: TestOpts) {\n super(opts)\n return applyPlugins(this)\n }\n test(\n name: string,\n extra: { [k: string]: any },\n cb?: (t: Test) => any\n ): Promise<FinalResults | null>\n test(",
"score": 0.835476279258728
},
{
"filename": "src/plugin/after-each.ts",
"retrieved_chunk": " t.runMain = (cb: () => void) => {\n runMain.call(t, () => this.#runAfterEach(this.#t, cb))\n }\n }\n #onAfterEach: ((t: Test) => void)[] = []\n afterEach(fn: (t: Test) => void | Promise<void>) {\n this.#onAfterEach.push(fn)\n }\n #runAfterEach(who: TestBase, cb: () => void) {\n // run all the afterEach methods from the parent",
"score": 0.8354108333587646
}
] |
typescript
|
this.hook.runInAsyncScope(cb, this, ...args)
}
|
// lifecycle methods like beforeEach, afterEach, teardown
// defined in plugins/lifecycle.ts
import Minipass from 'minipass'
import assert from 'node:assert'
import { hrtime } from 'node:process'
import { Readable } from 'node:stream'
import { format } from 'node:util'
import { CallSiteLike } from 'stack-utils'
import { FinalResults } from 'tap-parser'
import Deferred from 'trivial-deferred'
import { Base, BaseOpts } from './base.js'
import { esc } from './esc.js'
import stack from './stack.js'
import { TestPoint } from './test-point.js'
import { Waiter } from './waiter.js'
const queueEmpty = <T extends TestBase>(t: T) =>
t.queue.length === 0 ||
(t.queue.length === 1 &&
t.queue[0] === 'TAP version 14\n')
export interface ClassOf<T> {
new (): T
}
export type TapPlugin<
B extends Object,
O extends TestBaseOpts | any = any
> = ((t: TestBase, opts: O) => B) | ((t: TestBase) => B)
export interface TestBaseOpts extends BaseOpts {
/**
* The number of jobs to run in parallel. Defaults to 1
*/
jobs?: number
/**
* Test function called when this Test is executed
*/
cb?: (...args: any[]) => any
/**
* Flag to always/never show diagnostics. If unset, then
* diagnostics are shown for failing test points only.
*/
diagnostic?: boolean
}
const normalizeMessageExtra = (
defaultMessage: string,
message?: string | { [k: string]: any },
extra?: { [k: string]: any }
): [string, { [k: string]: any }] => {
if (typeof message === 'string') {
return [message || defaultMessage, extra || {}]
} else {
return [defaultMessage, message || {}]
}
}
/**
* Sigil for implicit end() calls that should not
* trigger an error if the user then calls t.end()
*/
const IMPLICIT = Symbol('implicit end')
/**
* Sigil to put in the queue to signal the end of all things
*/
const EOF = Symbol('EOF')
export type QueueEntry =
| string
| TestPoint
| Base
| typeof EOF
| Waiter
| [method: string, ...args: any[]]
/**
* The TestBaseBase class is the base class for all plugins,
* and eventually thus the Test class.
*
* This implements subtest functionality, TAP stream generation,
* lifecycle events, and only the most basic pass/fail assertions.
*
* All other features are added with plugins.
*/
export class TestBase extends Base {
// NB: generated pluginified Test class needs to declare over this
declare parent?: TestBase
promise?: Promise<any>
jobs: number
// #beforeEnd: [method: string | Symbol, ...args: any[]][] = []
subtests: Base[] = []
pool: Set<Base> = new Set()
queue: QueueEntry[] = ['TAP version 14\n']
cb?: (...args: any[]) => any
count: number = 0
ended: boolean = false
assertAt: CallSiteLike | null = null
assertStack: string | null = null
diagnostic: null | boolean = null
#planEnd: number = -1
#printedResult: boolean = false
#explicitEnded: boolean = false
#multiEndThrew: boolean = false
#n: number = 0
#noparallel: boolean = false
#occupied: null | Waiter | Base = null
#pushedEnd: boolean = false
#nextChildId: number = 1
#currentAssert: null | ((..._: any) => any) = null
#processing: boolean = false
#doingStdinOnly: boolean = false
/**
* true if the test has printed at least one TestPoint
*/
get printedResult(): boolean {
return this.#printedResult
}
constructor(options: TestBaseOpts) {
super(options)
this.jobs =
(options.jobs && Math.max(options.jobs, 1)) || 1
if (typeof options.diagnostic === 'boolean') {
this.diagnostic = options.diagnostic
}
if (options.cb) {
this.#setCB(options.cb)
}
}
#setCB<T extends TestBase>(this: T, cb: (t: T) => any) {
this.cb = (...args: any[]) =>
this.hook.runInAsyncScope(cb, this, ...args)
}
// TAP output generating methods
/**
* immediately exit this and all parent tests with a TAP
* Bail out! message.
*/
bailout(message?: string) {
if (this.parent && (this.results || this.ended)) {
this.parent.bailout(message)
} else {
this.#process()
message = message
? ' ' + ('' + esc(message)).trim()
: ''
message = message.replace(/[\r\n]/g, ' ')
this.parser.write('Bail out!' + message + '\n')
}
this.#end(IMPLICIT)
this.#process()
}
/**
* output a TAP comment, formatted like console.log()
*/
comment(...args: any[]) {
const body = format(...args)
const message =
('# ' + body.split(/\r?\n/).join('\n# ')).trim() +
'\n'
if (this.results) {
this.write(message)
} else {
this.queue.push(message)
}
this.#process()
}
/**
* Called when the test times out.
* Options are passed as diagnostics to the threw() method
*/
timeout(options: { [k: string]: any }) {
options = options || {}
options.expired = options.expired || this.name
if (this.#occupied && this.#occupied instanceof Base) {
this.#occupied.timeout(options)
} else {
super.timeout(options)
}
this.#end(IMPLICIT)
}
/**
* Set TAP pragma configs to affect the behavior of the parser.
* Only `strict` is supported by the parser.
*/
pragma(set: { [k: string]: boolean }) {
const p = Object.keys(set).reduce(
(acc, i) =>
acc + 'pragma ' + (set[i] ? '+' : '-') + i + '\n',
''
)
this.queue.push(p)
this.#process()
}
/**
* Specify the number of Test Points expected by this test.
* Outputs a TAP plan line.
*/
plan(n: number, comment?: string) {
if (this.bailedOut) {
return
}
if (this.#planEnd !== -1) {
throw new Error('Cannot set plan more than once')
}
if (typeof n !== 'number' || n < 0) {
throw new TypeError('plan must be a number')
}
// Cannot get any tests after a trailing plan, or a plan of 0
const ending = this.count !== 0 || n === 0
if (n === 0 && comment && !this.options.skip) {
this.options.skip = comment
}
this.#planEnd = n
comment = comment ? ' # ' + esc(comment.trim()) : ''
this.queue.push('1..' + n + comment + '\n')
if (ending) {
this.#end(IMPLICIT)
} else {
this.#process()
}
}
/**
* A passing (ok) Test Point
*/
pass(message?: string, extra?: { [k: string]: any }) {
this.currentAssert = TestBase.prototype.pass
this.printResult(
true,
...normalizeMessageExtra(
'(unnamed test)',
message,
extra
)
)
return true
}
/**
* A failing (not ok) Test Point
*/
fail(message?: string, extra?: { [k: string]: any }) {
this.currentAssert = TestBase.prototype.fail
const [m, e] = normalizeMessageExtra(
'(unnamed test)',
message,
extra
)
this.printResult(false, m, e)
return !!(e.todo || e.skip)
}
/**
* The current assertion being processed. May only be set if
* not already set.
*/
get currentAssert() {
return this.#currentAssert
}
/**
* The current assertion being processed. May only be set if
* not already set.
*/
set currentAssert(fn: null | ((...a: any[]) => any)) {
if (!this.#currentAssert && typeof fn === 'function') {
this.#currentAssert = fn
}
}
/**
* Print a Test Point
*/
printResult(
ok: boolean,
message: string,
extra: { [k: string]: any },
front: boolean = false
) {
this.#printedResult = true
const n = this.count + 1
this.currentAssert = TestBase.prototype.printResult
const fn = this.#currentAssert
this.#currentAssert = null
if (this.#planEnd !== -1 && n > this.#planEnd) {
if (!this.passing()) return
const failMessage = this.#explicitEnded
? 'test after end() was called'
: 'test count exceeds plan'
const er = new Error(failMessage, {
cause: {
test: this.name,
plan: this.#planEnd,
},
})
Error.captureStackTrace(er, fn || undefined)
this.threw(er)
return
}
extra = extra || {}
if (extra.expectFail) {
ok = !ok
}
if (this.assertAt) {
extra.at = this.assertAt
this.assertAt = null
}
if (this.assertStack) {
extra.stack = this.assertStack
this.assertStack = null
}
if (typeof extra.stack === 'string' && !extra.at) {
extra.at = stack.parseLine(extra.stack.split('\n')[0])
}
if (
!ok &&
!extra.skip &&
!extra.at &&
typeof fn === 'function'
) {
extra.at = stack.at(fn)
if (!extra.todo) {
extra.stack = stack.captureString(80, fn)
}
}
const diagnostic =
typeof extra.diagnostic === 'boolean'
? extra.diagnostic
: typeof this.diagnostic === 'boolean'
? this.diagnostic
: extra.skip || extra.todo
? false
: !ok
if (diagnostic) {
extra.diagnostic = true
}
this.count = n
message = message + ''
const res = { ok, message, extra }
const tp = new TestPoint(ok, message, extra)
// when we jump the queue, skip an extra line
if (front) {
tp.message = tp.message.trimEnd() + '\n\n'
}
if (
this.#occupied &&
this.#occupied instanceof Waiter &&
this.#occupied.finishing
) {
front = true
}
if (front) {
if (
extra.tapChildBuffer ||
extra.tapChildBuffer === ''
) {
this.writeSubComment(tp)
this.parser.write(extra.tapChildBuffer)
}
this.emit('result', res)
this.parser.write(tp.ok + ++this.#n + tp.message)
if (this.bail && !ok && !extra.skip && !extra.todo) {
this.parser.write('Bail out! ' + message + '\n')
}
} else {
this.queue.push(tp)
if (this.bail && !ok && !extra.skip && !extra.todo) {
this.queue.push('Bail out! ' + message + '\n')
}
}
if (this.#planEnd === this.count) {
this.#end(IMPLICIT)
}
this.#process()
}
end(): this {
this.#end()
return super.end()
}
/**
* The leading `# Subtest` comment that introduces a child test
*/
writeSubComment<T extends
|
TestPoint | Base>(p: T) {
|
const comment =
'# Subtest' +
(p.name ? ': ' + esc(p.name) : '') +
'\n'
this.parser.write(comment)
}
// end TAP otput generating methods
// flow control methods
/**
* Await the end of a Promise before proceeding.
* The supplied callback is called with the Waiter object.
*/
waitOn(
promise: Promise<any | void>,
cb: (w: Waiter) => any,
expectReject: boolean = false
): Promise<void> {
const w = new Waiter(
promise,
w => {
assert.equal(this.#occupied, w)
cb(w)
this.#occupied = null
this.#process()
},
expectReject
)
this.queue.push(w)
this.#process()
return w.promise
}
#end(implicit?: typeof IMPLICIT) {
if (this.#doingStdinOnly && implicit !== IMPLICIT)
throw new Error(
'cannot explicitly end while in stdinOnly mode'
)
this.debug('END implicit=%j', implicit === IMPLICIT)
if (this.ended && implicit === IMPLICIT) return
// beyond here we have to be actually done with things, or else
// the semantic checks on counts and such will be off.
if (!queueEmpty(this) || this.#occupied) {
if (!this.#pushedEnd) {
this.queue.push(['#end', implicit])
}
this.#pushedEnd = true
return this.#process()
}
this.ended = true
if (implicit !== IMPLICIT && !this.#multiEndThrew) {
if (this.#explicitEnded) {
this.#multiEndThrew = true
const er = new Error(
'test end() method called more than once'
)
Error.captureStackTrace(
er,
this.#currentAssert || this.#end
)
er.cause = {
test: this.name,
}
this.threw(er)
return
}
this.#explicitEnded = true
}
if (this.#planEnd === -1) {
this.debug(
'END(%s) implicit plan',
this.name,
this.count
)
this.plan(this.count)
}
this.queue.push(EOF)
this.#process()
}
#process() {
if (this.#processing) {
return this.debug(' < already processing')
}
this.debug(
'\nPROCESSING(%s)',
this.name,
this.queue.length
)
this.#processing = true
while (!this.#occupied) {
const p = this.queue.shift()
if (!p) {
this.debug('> end of queue')
break
}
if (p instanceof Base) {
this.debug('> subtest in queue', p.name)
this.#processSubtest(p)
} else if (p === EOF) {
this.debug(' > EOF', this.name)
// I AM BECOME EOF, DESTROYER OF STREAMS
this.parser.end()
} else if (p instanceof TestPoint) {
this.debug(' > TESTPOINT')
if (
p.extra.tapChildBuffer ||
p.extra.tapChildBuffer === ''
) {
this.writeSubComment(p)
this.parser.write(p.extra.tapChildBuffer)
}
this.emit('res', p.res)
this.parser.write(p.ok + ++this.#n + p.message)
} else if (typeof p === 'string') {
this.debug(' > STRING')
this.parser.write(p)
} else if (p instanceof Waiter) {
p.ready = true
this.#occupied = p
p.finish()
} else if (Array.isArray(p)) {
this.debug(' > METHOD')
const m = p.shift() as keyof this
if (typeof this[m] !== 'function') {
this.debug(
' > weird method not found in queue??',
m,
typeof this[m]
)
continue
}
const fn = (m === '#end' ? this.#end : this[m]) as (
...a: any[]
) => any
const ret = fn.call(this, ...p)
if (
ret &&
typeof ret === 'object' &&
typeof ret.then === 'function'
) {
// returned promise
ret.then(
() => {
this.#processing = false
this.#process()
},
(er: unknown) => {
this.#processing = false
this.threw(er)
}
)
return
}
/* c8 ignore start */
} else {
throw new Error('weird thing got in the queue')
}
/* c8 ignore stop */
}
while (
!this.#noparallel &&
this.pool.size < this.jobs
) {
const p = this.subtests.shift()
if (!p) {
break
}
if (!p.buffered) {
this.#noparallel = true
break
}
this.debug('start subtest', p)
this.emit('subtestStart', p)
this.pool.add(p)
if (this.bailedOut) {
this.#onBufferedEnd(p)
} else {
p.runMain(() => this.#onBufferedEnd(p))
}
}
this.debug(
'done processing',
this.queue,
this.#occupied
)
this.#processing = false
// just in case any tests ended, and we have sync stuff still
// waiting around in the queue to be processed
if (!this.#occupied && this.queue.length) {
this.#process()
}
}
#onBufferedEnd<T extends Base>(p: T) {
p.ondone = p.constructor.prototype.ondone
p.results =
p.results || new FinalResults(true, p.parser)
p.readyToProcess = true
const to = p.options.timeout
const dur =
to && p.passing() ? hrtime.bigint() - p.start : null
if (dur && to && dur > to) {
p.timeout()
} else {
p.setTimeout(0)
}
this.debug(
'%s.#onBufferedEnd',
this.name,
p.name,
p.results.bailout
)
this.pool.delete(p)
p.options.tapChildBuffer = p.output || ''
p.options.stack = ''
if (p.time) p.options.time = p.time
if (this.#occupied === p) this.#occupied = null
p.deferred?.resolve(p.results)
this.emit('subtestEnd', p)
this.#process()
}
#onIndentedEnd<T extends Base>(p: T) {
this.emit('subtestProcess', p)
p.ondone = p.constructor.prototype.ondone
p.results =
p.results || new FinalResults(true, p.parser)
this.debug('#onIndentedEnd', this.name, p.name)
this.#noparallel = false
const sti = this.subtests.indexOf(p)
if (sti !== -1) this.subtests.splice(sti, 1)
p.readyToProcess = true
p.options.time = p.time
const to = p.options.timeout
const dur =
to && p.passing() ? hrtime.bigint() - p.start : null
if (dur && to && dur > to) {
p.timeout()
} else {
p.setTimeout(0)
}
this.debug('#onIndentedEnd %s(%s)', this.name, p.name)
this.#occupied = null
this.debug(
'OIE(%s) b>shift into queue',
this.name,
this.queue
)
p.options.stack = ''
this.printResult(p.passing(), p.name, p.options, true)
this.debug(
'OIE(%s) shifted into queue',
this.name,
this.queue
)
p.deferred?.resolve(p.results)
this.emit('subtestEnd', p)
this.#process()
}
/**
* @internal
*/
main(cb: () => void) {
if (typeof this.options.timeout === 'number') {
this.setTimeout(this.options.timeout)
}
this.debug('MAIN pre', this)
const end = () => {
this.debug(' > implicit end for promise')
this.#end(IMPLICIT)
done()
}
const done = (er?: Error) => {
if (er) this.threw(er)
if (this.results || this.bailedOut) cb()
else this.ondone = () => cb()
}
// This bit of overly clever line-noise wraps the call to user-code
// in a try-catch. We can't rely on the domain for this yet, because
// the 'end' event can trigger a throw after the domain is unhooked,
// but before this is no longer the official "active test"
const ret = (() => {
if (!this.cb) return
try {
return this.cb(this)
} catch (er: any) {
if (!er || typeof er !== 'object') {
er = { error: er }
}
er.tapCaught = 'testFunctionThrow'
this.threw(er)
}
})()
if (ret && ret.then) {
this.promise = ret
ret.tapAbortPromise = done
ret.then(end, (er: any) => {
if (!er || typeof er !== 'object') {
er = { error: er }
}
er.tapCaught = 'returnedPromiseRejection'
done(er)
})
} else done()
this.debug('MAIN post', this)
}
#processSubtest<T extends Base>(p: T) {
this.debug(' > subtest')
this.#occupied = p
if (!p.buffered) {
this.emit('subtestStart', p)
this.debug(' > subtest indented')
p.stream.pipe(this.parser, { end: false })
this.writeSubComment(p)
this.debug('calling runMain', p.runMain.toString())
p.runMain(() => {
this.debug('in runMain', p.runMain.toString())
this.#onIndentedEnd(p)
})
} else if (p.readyToProcess) {
this.emit('subtestProcess', p)
this.debug(' > subtest buffered, finished')
// finished! do the thing!
this.#occupied = null
if (!p.passing() || !p.silent) {
this.printResult(
p.passing(),
p.name,
p.options,
true
)
}
} else {
this.#occupied = p
this.debug(' > subtest buffered, unfinished', p)
// unfinished buffered test.
// nothing to do yet, just leave it there.
this.queue.unshift(p)
}
}
/**
* Parse stdin as the only tap stream (ie, not as a child test)
* If used, then no other subtests or assertions are allowed.
*/
stdinOnly<T extends BaseOpts>(
extra?: T & { tapStream?: Readable | Minipass }
) {
const stream = ((extra && extra.tapStream) ||
process.stdin) as Minipass
if (!stream) {
throw new Error(
'cannot read stdin without stdin stream'
)
}
if (
this.queue.length !== 1 ||
this.queue[0] !== 'TAP version 14\n' ||
this.#processing ||
this.results ||
this.#occupied ||
this.pool.size ||
this.subtests.length
) {
throw new Error(
'Cannot use stdinOnly on a test in progress'
)
}
this.#doingStdinOnly = true
this.queue.length = 0
this.parser.on('child', p => {
// pretend to be a rooted parser, so it gets counts.
p.root = p
const t = new Base({
name: p.name,
parent: this,
parser: p,
bail: p.bail,
strict: p.strict,
omitVersion: p.omitVersion,
preserveWhitespace: p.preserveWhitespace,
childId: this.#nextChildId++,
})
this.emit('subtestAdd', t)
this.emit('subtestStart', t)
this.emit('subtestProcess', t)
p.on('complete', () => {
t.time = p.time
this.emit('subtestEnd', t)
})
})
stream.pause()
stream.pipe(this.parser)
stream.resume()
}
/**
* Mount a subtest, using this Test object as a harness.
* Exposed mainly so that it can be used by builtin plugins.
*
* @internal
*/
sub<T extends Base, O extends TestBaseOpts>(
Class: { new (options: O): T },
extra: O,
caller: (...a: any[]) => unknown
): Promise<FinalResults | null> {
if (this.bailedOut) return Promise.resolve(null)
if (this.results || this.ended) {
const er = new Error(
'cannot create subtest after parent test ends'
)
Error.captureStackTrace(er, caller)
this.threw(er)
return Promise.resolve(null)
}
extra.childId = this.#nextChildId++
if (this.shouldSkipChild(extra)) {
this.pass(extra.name, extra)
return Promise.resolve(null)
}
extra.indent = ' '
if (extra.buffered !== undefined) {
if (this.jobs > 1) {
extra.buffered = true
} else {
extra.buffered = false
}
}
extra.bail =
extra.bail !== undefined ? extra.bail : this.bail
extra.parent = this
extra.stack = stack.captureString(80, caller)
extra.context = this.context
const t = new Class(extra)
this.queue.push(t)
this.subtests.push(t)
this.emit('subtestAdd', t)
const d = new Deferred<FinalResults>()
t.deferred = d
this.#process()
return d.promise
}
/**
* Return true if the child test represented by the options object
* should be skipped. Extended by the grep/only filtering plugins.
*/
shouldSkipChild(extra: { [k: string]: any }) {
return !!(extra.skip || extra.todo)
}
// end flow control methods
}
|
src/test-base.ts
|
tapjs-core-edd7403
|
[
{
"filename": "src/test-template.ts",
"retrieved_chunk": "//{{TEST INTERFACE END}}\nexport interface Test extends TTest {\n end(): this\n t: Test\n test(\n name: string,\n extra: { [k: string]: any },\n cb?: (t: Test) => any\n ): Promise<FinalResults | null>\n test(",
"score": 0.8066867589950562
},
{
"filename": "src/test-template.ts",
"retrieved_chunk": " test(cb?: (t: Test) => any): Promise<FinalResults | null>\n test(\n ...args: TestArgs<Test>\n ): Promise<FinalResults | null> {\n const extra = parseTestArgs(...args)\n extra.todo = true\n return this.sub(Test, extra, this.test)\n }\n todo(\n name: string,",
"score": 0.7888329029083252
},
{
"filename": "src/test-built.ts",
"retrieved_chunk": " }\n }\n }\n },\n })\n Object.assign(base, { t })\n ext.unshift({ t })\n return t\n}\nexport class Test extends TestBase {",
"score": 0.7852647304534912
},
{
"filename": "src/test-built.ts",
"retrieved_chunk": " ): Promise<FinalResults | null> {\n const extra = parseTestArgs(...args)\n extra.todo = true\n return this.sub(Test, extra, this.test)\n }\n todo(\n name: string,\n extra: { [k: string]: any },\n cb?: (t: Test) => any\n ): Promise<FinalResults | null>",
"score": 0.7841464281082153
},
{
"filename": "src/test-template.ts",
"retrieved_chunk": " ): Promise<FinalResults | null>\n todo(cb?: (t: Test) => any): Promise<FinalResults | null>\n todo(\n ...args: TestArgs<Test>\n ): Promise<FinalResults | null> {\n const extra = parseTestArgs(...args)\n extra.todo = true\n return this.sub(Test, extra, this.todo)\n }\n skip(",
"score": 0.7839552164077759
}
] |
typescript
|
TestPoint | Base>(p: T) {
|
import stack from './stack'
import type {BaseOpts} from './base'
export default (er:any, extra?:{[k: string]:any}, options?:BaseOpts) => {
// the yaml module puts big stuff here, pluck it off
if (er.source && typeof er.source === 'object' && er.source.context)
er.source = { ...er.source, context: null }
// pull out all fields from options, other than anything starting
// with tapChild, or anything already set in the extra object.
extra = Object.fromEntries(Object.entries(options || {}).filter(([k]) =>
!/^tapChild/.test(k) && !(k in (extra || {}))))
if (!er || typeof er !== 'object') {
extra.error = er
return extra
}
// pull out error details
const message = er.message ? er.message
: er.stack ? er.stack.split('\n')[0]
: ''
if (er.message) {
try {
Object.defineProperty(er, 'message', {
value: '',
configurable: true
})
} catch {}
}
const st = er.stack && er.stack.substr(
er._babel ? (message + er.codeFrame).length : 0)
if (st) {
const splitst = st.split('\n')
if (er._babel && er.loc) {
const msplit = message.split(': ')
const f = msplit[0].trim()
extra.message = msplit.slice(1).join(': ')
.replace(/ \([0-9]+:[0-9]+\)$/, '').trim()
const file = f.indexOf(process.cwd()) === 0
? f.substr(process.cwd().length + 1) : f
if (file !== 'unknown')
delete er.codeFrame
extra.at = {
file,
line: er.loc.line,
column: er.loc.column + 1,
}
} else {
// parse out the 'at' bit from the first line.
|
extra.at = stack.parseLine(splitst[1])
}
|
extra.stack = stack.clean(splitst)
}
if (message) {
try {
Object.defineProperty(er, 'message', {
value: message,
configurable: true
})
} catch {}
}
if (er.name && er.name !== 'Error') {
extra.type = er.name
}
Object.assign(extra, Object.fromEntries(Object.entries(er).filter(([k]) =>
k !== 'message')))
return extra
}
|
src/extra-from-error.ts
|
tapjs-core-edd7403
|
[
{
"filename": "src/test-base.ts",
"retrieved_chunk": " extra.at = stack.parseLine(extra.stack.split('\\n')[0])\n }\n if (\n !ok &&\n !extra.skip &&\n !extra.at &&\n typeof fn === 'function'\n ) {\n extra.at = stack.at(fn)\n if (!extra.todo) {",
"score": 0.8911399841308594
},
{
"filename": "src/test-base.ts",
"retrieved_chunk": " }\n if (this.assertAt) {\n extra.at = this.assertAt\n this.assertAt = null\n }\n if (this.assertStack) {\n extra.stack = this.assertStack\n this.assertStack = null\n }\n if (typeof extra.stack === 'string' && !extra.at) {",
"score": 0.868033766746521
},
{
"filename": "src/clean-yaml-object.ts",
"retrieved_chunk": " // don't print locations in tap itself, that's almost never useful\n delete res.at\n }\n if (\n file &&\n res.at &&\n res.at.file &&\n res.at.line &&\n !res.source\n ) {",
"score": 0.8457555770874023
},
{
"filename": "src/clean-yaml-object.ts",
"retrieved_chunk": " const res = { ...object }\n if (hasOwn(res, 'stack') && !hasOwn(res, 'at')) {\n res.at = stack.parseLine(res.stack.split('\\n')[0])\n }\n const file = res.at && res.at.file && resolve(res.at.file)\n if (\n !options.stackIncludesTap &&\n file &&\n file.includes(tapDir)\n ) {",
"score": 0.8372365832328796
},
{
"filename": "src/base.ts",
"retrieved_chunk": " er.stack.split(/\\n/).slice(1).join('\\n')\n )\n console.error(extra)\n }\n } else {\n this.parser.ok = false\n }\n return extra\n }\n passing() {",
"score": 0.8309770226478577
}
] |
typescript
|
extra.at = stack.parseLine(splitst[1])
}
|
// lifecycle methods like beforeEach, afterEach, teardown
// defined in plugins/lifecycle.ts
import Minipass from 'minipass'
import assert from 'node:assert'
import { hrtime } from 'node:process'
import { Readable } from 'node:stream'
import { format } from 'node:util'
import { CallSiteLike } from 'stack-utils'
import { FinalResults } from 'tap-parser'
import Deferred from 'trivial-deferred'
import { Base, BaseOpts } from './base.js'
import { esc } from './esc.js'
import stack from './stack.js'
import { TestPoint } from './test-point.js'
import { Waiter } from './waiter.js'
const queueEmpty = <T extends TestBase>(t: T) =>
t.queue.length === 0 ||
(t.queue.length === 1 &&
t.queue[0] === 'TAP version 14\n')
export interface ClassOf<T> {
new (): T
}
export type TapPlugin<
B extends Object,
O extends TestBaseOpts | any = any
> = ((t: TestBase, opts: O) => B) | ((t: TestBase) => B)
export interface TestBaseOpts extends BaseOpts {
/**
* The number of jobs to run in parallel. Defaults to 1
*/
jobs?: number
/**
* Test function called when this Test is executed
*/
cb?: (...args: any[]) => any
/**
* Flag to always/never show diagnostics. If unset, then
* diagnostics are shown for failing test points only.
*/
diagnostic?: boolean
}
const normalizeMessageExtra = (
defaultMessage: string,
message?: string | { [k: string]: any },
extra?: { [k: string]: any }
): [string, { [k: string]: any }] => {
if (typeof message === 'string') {
return [message || defaultMessage, extra || {}]
} else {
return [defaultMessage, message || {}]
}
}
/**
* Sigil for implicit end() calls that should not
* trigger an error if the user then calls t.end()
*/
const IMPLICIT = Symbol('implicit end')
/**
* Sigil to put in the queue to signal the end of all things
*/
const EOF = Symbol('EOF')
export type QueueEntry =
| string
| TestPoint
| Base
| typeof EOF
| Waiter
| [method: string, ...args: any[]]
/**
* The TestBaseBase class is the base class for all plugins,
* and eventually thus the Test class.
*
* This implements subtest functionality, TAP stream generation,
* lifecycle events, and only the most basic pass/fail assertions.
*
* All other features are added with plugins.
*/
export class TestBase extends Base {
// NB: generated pluginified Test class needs to declare over this
declare parent?: TestBase
promise?: Promise<any>
jobs: number
// #beforeEnd: [method: string | Symbol, ...args: any[]][] = []
subtests: Base[] = []
pool: Set<Base> = new Set()
queue: QueueEntry[] = ['TAP version 14\n']
cb?: (...args: any[]) => any
count: number = 0
ended: boolean = false
assertAt: CallSiteLike | null = null
assertStack: string | null = null
diagnostic: null | boolean = null
#planEnd: number = -1
#printedResult: boolean = false
#explicitEnded: boolean = false
#multiEndThrew: boolean = false
#n: number = 0
#noparallel: boolean = false
#occupied: null | Waiter | Base = null
#pushedEnd: boolean = false
#nextChildId: number = 1
#currentAssert: null | ((..._: any) => any) = null
#processing: boolean = false
#doingStdinOnly: boolean = false
/**
* true if the test has printed at least one TestPoint
*/
get printedResult(): boolean {
return this.#printedResult
}
constructor(options: TestBaseOpts) {
super(options)
this.jobs =
(options.jobs && Math.max(options.jobs, 1)) || 1
if (typeof options.diagnostic === 'boolean') {
this.diagnostic = options.diagnostic
}
if (options.cb) {
this.#setCB(options.cb)
}
}
#setCB<T extends TestBase>(this: T, cb: (t: T) => any) {
this.cb = (...args: any[]) =>
this.hook.runInAsyncScope(cb, this, ...args)
}
// TAP output generating methods
/**
* immediately exit this and all parent tests with a TAP
* Bail out! message.
*/
bailout(message?: string) {
if (this.parent && (this.results || this.ended)) {
this.parent.bailout(message)
} else {
this.#process()
message = message
? ' ' + ('' + esc(message)).trim()
: ''
message = message.replace(/[\r\n]/g, ' ')
this.parser.write('Bail out!' + message + '\n')
}
this.#end(IMPLICIT)
this.#process()
}
/**
* output a TAP comment, formatted like console.log()
*/
comment(...args: any[]) {
const body = format(...args)
const message =
('# ' + body.split(/\r?\n/).join('\n# ')).trim() +
'\n'
if (this.results) {
this.write(message)
} else {
this.queue.push(message)
}
this.#process()
}
/**
* Called when the test times out.
* Options are passed as diagnostics to the threw() method
*/
timeout(options: { [k: string]: any }) {
options = options || {}
options.expired = options.expired || this.name
if (this.#occupied && this.#occupied instanceof Base) {
this.#occupied.timeout(options)
} else {
super.timeout(options)
}
this.#end(IMPLICIT)
}
/**
* Set TAP pragma configs to affect the behavior of the parser.
* Only `strict` is supported by the parser.
*/
pragma(set: { [k: string]: boolean }) {
const p = Object.keys(set).reduce(
(acc, i) =>
acc + 'pragma ' + (set[i] ? '+' : '-') + i + '\n',
''
)
this.queue.push(p)
this.#process()
}
/**
* Specify the number of Test Points expected by this test.
* Outputs a TAP plan line.
*/
plan(n: number, comment?: string) {
if (this.bailedOut) {
return
}
if (this.#planEnd !== -1) {
throw new Error('Cannot set plan more than once')
}
if (typeof n !== 'number' || n < 0) {
throw new TypeError('plan must be a number')
}
// Cannot get any tests after a trailing plan, or a plan of 0
const ending = this.count !== 0 || n === 0
if (n === 0 && comment && !this.options.skip) {
this.options.skip = comment
}
this.#planEnd = n
comment = comment ? ' # ' + esc(comment.trim()) : ''
this.queue.push('1..' + n + comment + '\n')
if (ending) {
this.#end(IMPLICIT)
} else {
this.#process()
}
}
/**
* A passing (ok) Test Point
*/
pass(message?: string, extra?: { [k: string]: any }) {
this.currentAssert = TestBase.prototype.pass
this.printResult(
true,
...normalizeMessageExtra(
'(unnamed test)',
message,
extra
)
)
return true
}
/**
* A failing (not ok) Test Point
*/
fail(message?: string, extra?: { [k: string]: any }) {
this.currentAssert = TestBase.prototype.fail
const [m, e] = normalizeMessageExtra(
'(unnamed test)',
message,
extra
)
this.printResult(false, m, e)
return !!(e.todo || e.skip)
}
/**
* The current assertion being processed. May only be set if
* not already set.
*/
get currentAssert() {
return this.#currentAssert
}
/**
* The current assertion being processed. May only be set if
* not already set.
*/
set currentAssert(fn: null | ((...a: any[]) => any)) {
if (!this.#currentAssert && typeof fn === 'function') {
this.#currentAssert = fn
}
}
/**
* Print a Test Point
*/
printResult(
ok: boolean,
message: string,
extra: { [k: string]: any },
front: boolean = false
) {
this.#printedResult = true
const n = this.count + 1
this.currentAssert = TestBase.prototype.printResult
const fn = this.#currentAssert
this.#currentAssert = null
if (this.#planEnd !== -1 && n > this.#planEnd) {
if (!this.passing()) return
const failMessage = this.#explicitEnded
? 'test after end() was called'
: 'test count exceeds plan'
const er = new Error(failMessage, {
cause: {
test: this.name,
plan: this.#planEnd,
},
})
Error.captureStackTrace(er, fn || undefined)
this.threw(er)
return
}
extra = extra || {}
if (extra.expectFail) {
ok = !ok
}
if (this.assertAt) {
extra.at = this.assertAt
this.assertAt = null
}
if (this.assertStack) {
extra.stack = this.assertStack
this.assertStack = null
}
if (typeof extra.stack === 'string' && !extra.at) {
extra.at = stack.parseLine(extra.stack.split('\n')[0])
}
if (
!ok &&
!extra.skip &&
!extra.at &&
typeof fn === 'function'
) {
extra.at = stack.at(fn)
if (!extra.todo) {
extra.stack = stack.captureString(80, fn)
}
}
const diagnostic =
typeof extra.diagnostic === 'boolean'
? extra.diagnostic
: typeof this.diagnostic === 'boolean'
? this.diagnostic
: extra.skip || extra.todo
? false
: !ok
if (diagnostic) {
extra.diagnostic = true
}
this.count = n
message = message + ''
const res = { ok, message, extra }
const tp
|
= new TestPoint(ok, message, extra)
// when we jump the queue, skip an extra line
if (front) {
|
tp.message = tp.message.trimEnd() + '\n\n'
}
if (
this.#occupied &&
this.#occupied instanceof Waiter &&
this.#occupied.finishing
) {
front = true
}
if (front) {
if (
extra.tapChildBuffer ||
extra.tapChildBuffer === ''
) {
this.writeSubComment(tp)
this.parser.write(extra.tapChildBuffer)
}
this.emit('result', res)
this.parser.write(tp.ok + ++this.#n + tp.message)
if (this.bail && !ok && !extra.skip && !extra.todo) {
this.parser.write('Bail out! ' + message + '\n')
}
} else {
this.queue.push(tp)
if (this.bail && !ok && !extra.skip && !extra.todo) {
this.queue.push('Bail out! ' + message + '\n')
}
}
if (this.#planEnd === this.count) {
this.#end(IMPLICIT)
}
this.#process()
}
end(): this {
this.#end()
return super.end()
}
/**
* The leading `# Subtest` comment that introduces a child test
*/
writeSubComment<T extends TestPoint | Base>(p: T) {
const comment =
'# Subtest' +
(p.name ? ': ' + esc(p.name) : '') +
'\n'
this.parser.write(comment)
}
// end TAP otput generating methods
// flow control methods
/**
* Await the end of a Promise before proceeding.
* The supplied callback is called with the Waiter object.
*/
waitOn(
promise: Promise<any | void>,
cb: (w: Waiter) => any,
expectReject: boolean = false
): Promise<void> {
const w = new Waiter(
promise,
w => {
assert.equal(this.#occupied, w)
cb(w)
this.#occupied = null
this.#process()
},
expectReject
)
this.queue.push(w)
this.#process()
return w.promise
}
#end(implicit?: typeof IMPLICIT) {
if (this.#doingStdinOnly && implicit !== IMPLICIT)
throw new Error(
'cannot explicitly end while in stdinOnly mode'
)
this.debug('END implicit=%j', implicit === IMPLICIT)
if (this.ended && implicit === IMPLICIT) return
// beyond here we have to be actually done with things, or else
// the semantic checks on counts and such will be off.
if (!queueEmpty(this) || this.#occupied) {
if (!this.#pushedEnd) {
this.queue.push(['#end', implicit])
}
this.#pushedEnd = true
return this.#process()
}
this.ended = true
if (implicit !== IMPLICIT && !this.#multiEndThrew) {
if (this.#explicitEnded) {
this.#multiEndThrew = true
const er = new Error(
'test end() method called more than once'
)
Error.captureStackTrace(
er,
this.#currentAssert || this.#end
)
er.cause = {
test: this.name,
}
this.threw(er)
return
}
this.#explicitEnded = true
}
if (this.#planEnd === -1) {
this.debug(
'END(%s) implicit plan',
this.name,
this.count
)
this.plan(this.count)
}
this.queue.push(EOF)
this.#process()
}
#process() {
if (this.#processing) {
return this.debug(' < already processing')
}
this.debug(
'\nPROCESSING(%s)',
this.name,
this.queue.length
)
this.#processing = true
while (!this.#occupied) {
const p = this.queue.shift()
if (!p) {
this.debug('> end of queue')
break
}
if (p instanceof Base) {
this.debug('> subtest in queue', p.name)
this.#processSubtest(p)
} else if (p === EOF) {
this.debug(' > EOF', this.name)
// I AM BECOME EOF, DESTROYER OF STREAMS
this.parser.end()
} else if (p instanceof TestPoint) {
this.debug(' > TESTPOINT')
if (
p.extra.tapChildBuffer ||
p.extra.tapChildBuffer === ''
) {
this.writeSubComment(p)
this.parser.write(p.extra.tapChildBuffer)
}
this.emit('res', p.res)
this.parser.write(p.ok + ++this.#n + p.message)
} else if (typeof p === 'string') {
this.debug(' > STRING')
this.parser.write(p)
} else if (p instanceof Waiter) {
p.ready = true
this.#occupied = p
p.finish()
} else if (Array.isArray(p)) {
this.debug(' > METHOD')
const m = p.shift() as keyof this
if (typeof this[m] !== 'function') {
this.debug(
' > weird method not found in queue??',
m,
typeof this[m]
)
continue
}
const fn = (m === '#end' ? this.#end : this[m]) as (
...a: any[]
) => any
const ret = fn.call(this, ...p)
if (
ret &&
typeof ret === 'object' &&
typeof ret.then === 'function'
) {
// returned promise
ret.then(
() => {
this.#processing = false
this.#process()
},
(er: unknown) => {
this.#processing = false
this.threw(er)
}
)
return
}
/* c8 ignore start */
} else {
throw new Error('weird thing got in the queue')
}
/* c8 ignore stop */
}
while (
!this.#noparallel &&
this.pool.size < this.jobs
) {
const p = this.subtests.shift()
if (!p) {
break
}
if (!p.buffered) {
this.#noparallel = true
break
}
this.debug('start subtest', p)
this.emit('subtestStart', p)
this.pool.add(p)
if (this.bailedOut) {
this.#onBufferedEnd(p)
} else {
p.runMain(() => this.#onBufferedEnd(p))
}
}
this.debug(
'done processing',
this.queue,
this.#occupied
)
this.#processing = false
// just in case any tests ended, and we have sync stuff still
// waiting around in the queue to be processed
if (!this.#occupied && this.queue.length) {
this.#process()
}
}
#onBufferedEnd<T extends Base>(p: T) {
p.ondone = p.constructor.prototype.ondone
p.results =
p.results || new FinalResults(true, p.parser)
p.readyToProcess = true
const to = p.options.timeout
const dur =
to && p.passing() ? hrtime.bigint() - p.start : null
if (dur && to && dur > to) {
p.timeout()
} else {
p.setTimeout(0)
}
this.debug(
'%s.#onBufferedEnd',
this.name,
p.name,
p.results.bailout
)
this.pool.delete(p)
p.options.tapChildBuffer = p.output || ''
p.options.stack = ''
if (p.time) p.options.time = p.time
if (this.#occupied === p) this.#occupied = null
p.deferred?.resolve(p.results)
this.emit('subtestEnd', p)
this.#process()
}
#onIndentedEnd<T extends Base>(p: T) {
this.emit('subtestProcess', p)
p.ondone = p.constructor.prototype.ondone
p.results =
p.results || new FinalResults(true, p.parser)
this.debug('#onIndentedEnd', this.name, p.name)
this.#noparallel = false
const sti = this.subtests.indexOf(p)
if (sti !== -1) this.subtests.splice(sti, 1)
p.readyToProcess = true
p.options.time = p.time
const to = p.options.timeout
const dur =
to && p.passing() ? hrtime.bigint() - p.start : null
if (dur && to && dur > to) {
p.timeout()
} else {
p.setTimeout(0)
}
this.debug('#onIndentedEnd %s(%s)', this.name, p.name)
this.#occupied = null
this.debug(
'OIE(%s) b>shift into queue',
this.name,
this.queue
)
p.options.stack = ''
this.printResult(p.passing(), p.name, p.options, true)
this.debug(
'OIE(%s) shifted into queue',
this.name,
this.queue
)
p.deferred?.resolve(p.results)
this.emit('subtestEnd', p)
this.#process()
}
/**
* @internal
*/
main(cb: () => void) {
if (typeof this.options.timeout === 'number') {
this.setTimeout(this.options.timeout)
}
this.debug('MAIN pre', this)
const end = () => {
this.debug(' > implicit end for promise')
this.#end(IMPLICIT)
done()
}
const done = (er?: Error) => {
if (er) this.threw(er)
if (this.results || this.bailedOut) cb()
else this.ondone = () => cb()
}
// This bit of overly clever line-noise wraps the call to user-code
// in a try-catch. We can't rely on the domain for this yet, because
// the 'end' event can trigger a throw after the domain is unhooked,
// but before this is no longer the official "active test"
const ret = (() => {
if (!this.cb) return
try {
return this.cb(this)
} catch (er: any) {
if (!er || typeof er !== 'object') {
er = { error: er }
}
er.tapCaught = 'testFunctionThrow'
this.threw(er)
}
})()
if (ret && ret.then) {
this.promise = ret
ret.tapAbortPromise = done
ret.then(end, (er: any) => {
if (!er || typeof er !== 'object') {
er = { error: er }
}
er.tapCaught = 'returnedPromiseRejection'
done(er)
})
} else done()
this.debug('MAIN post', this)
}
#processSubtest<T extends Base>(p: T) {
this.debug(' > subtest')
this.#occupied = p
if (!p.buffered) {
this.emit('subtestStart', p)
this.debug(' > subtest indented')
p.stream.pipe(this.parser, { end: false })
this.writeSubComment(p)
this.debug('calling runMain', p.runMain.toString())
p.runMain(() => {
this.debug('in runMain', p.runMain.toString())
this.#onIndentedEnd(p)
})
} else if (p.readyToProcess) {
this.emit('subtestProcess', p)
this.debug(' > subtest buffered, finished')
// finished! do the thing!
this.#occupied = null
if (!p.passing() || !p.silent) {
this.printResult(
p.passing(),
p.name,
p.options,
true
)
}
} else {
this.#occupied = p
this.debug(' > subtest buffered, unfinished', p)
// unfinished buffered test.
// nothing to do yet, just leave it there.
this.queue.unshift(p)
}
}
/**
* Parse stdin as the only tap stream (ie, not as a child test)
* If used, then no other subtests or assertions are allowed.
*/
stdinOnly<T extends BaseOpts>(
extra?: T & { tapStream?: Readable | Minipass }
) {
const stream = ((extra && extra.tapStream) ||
process.stdin) as Minipass
if (!stream) {
throw new Error(
'cannot read stdin without stdin stream'
)
}
if (
this.queue.length !== 1 ||
this.queue[0] !== 'TAP version 14\n' ||
this.#processing ||
this.results ||
this.#occupied ||
this.pool.size ||
this.subtests.length
) {
throw new Error(
'Cannot use stdinOnly on a test in progress'
)
}
this.#doingStdinOnly = true
this.queue.length = 0
this.parser.on('child', p => {
// pretend to be a rooted parser, so it gets counts.
p.root = p
const t = new Base({
name: p.name,
parent: this,
parser: p,
bail: p.bail,
strict: p.strict,
omitVersion: p.omitVersion,
preserveWhitespace: p.preserveWhitespace,
childId: this.#nextChildId++,
})
this.emit('subtestAdd', t)
this.emit('subtestStart', t)
this.emit('subtestProcess', t)
p.on('complete', () => {
t.time = p.time
this.emit('subtestEnd', t)
})
})
stream.pause()
stream.pipe(this.parser)
stream.resume()
}
/**
* Mount a subtest, using this Test object as a harness.
* Exposed mainly so that it can be used by builtin plugins.
*
* @internal
*/
sub<T extends Base, O extends TestBaseOpts>(
Class: { new (options: O): T },
extra: O,
caller: (...a: any[]) => unknown
): Promise<FinalResults | null> {
if (this.bailedOut) return Promise.resolve(null)
if (this.results || this.ended) {
const er = new Error(
'cannot create subtest after parent test ends'
)
Error.captureStackTrace(er, caller)
this.threw(er)
return Promise.resolve(null)
}
extra.childId = this.#nextChildId++
if (this.shouldSkipChild(extra)) {
this.pass(extra.name, extra)
return Promise.resolve(null)
}
extra.indent = ' '
if (extra.buffered !== undefined) {
if (this.jobs > 1) {
extra.buffered = true
} else {
extra.buffered = false
}
}
extra.bail =
extra.bail !== undefined ? extra.bail : this.bail
extra.parent = this
extra.stack = stack.captureString(80, caller)
extra.context = this.context
const t = new Class(extra)
this.queue.push(t)
this.subtests.push(t)
this.emit('subtestAdd', t)
const d = new Deferred<FinalResults>()
t.deferred = d
this.#process()
return d.promise
}
/**
* Return true if the child test represented by the options object
* should be skipped. Extended by the grep/only filtering plugins.
*/
shouldSkipChild(extra: { [k: string]: any }) {
return !!(extra.skip || extra.todo)
}
// end flow control methods
}
|
src/test-base.ts
|
tapjs-core-edd7403
|
[
{
"filename": "src/test-point.ts",
"retrieved_chunk": "import { diags } from './diags.js'\nimport { esc } from './esc.js'\nimport { TestBaseOpts } from './test-base.js'\nexport interface Result {\n ok: boolean\n message: string\n extra: { [k: string]: any }\n}\nexport class TestPoint {\n ok: 'ok ' | 'not ok '",
"score": 0.8590181469917297
},
{
"filename": "src/test-point.ts",
"retrieved_chunk": " extra = extra || {}\n message = message\n .trim()\n .replace(/[\\n\\r]/g, ' ')\n .replace(/\\t/g, ' ')\n this.res = { ok, message, extra }\n this.extra = extra\n this.name = message\n this.message = tpMessage(esc(this.name), extra)\n }",
"score": 0.8394833207130432
},
{
"filename": "src/test-point.ts",
"retrieved_chunk": " const diagYaml = extra.diagnostic\n ? diags(extra, options)\n : ''\n message += diagYaml + '\\n'\n return message\n}",
"score": 0.8343169093132019
},
{
"filename": "src/test-point.ts",
"retrieved_chunk": "}\nconst tpMessage = (\n description: string,\n extra: { [k: string]: any },\n options: TestBaseOpts = {}\n): string => {\n let message = description ? ` - ${description}` : ''\n if (extra.skip) {\n message += ' # SKIP'\n if (typeof extra.skip === 'string') {",
"score": 0.8303013443946838
},
{
"filename": "src/test-point.ts",
"retrieved_chunk": " name: string\n message: string\n extra: { [key: string]: any }\n res: Result\n constructor(\n ok: boolean,\n message: string,\n extra?: { [key: string]: any }\n ) {\n this.ok = ok ? 'ok ' : 'not ok '",
"score": 0.824434220790863
}
] |
typescript
|
= new TestPoint(ok, message, extra)
// when we jump the queue, skip an extra line
if (front) {
|
// lifecycle methods like beforeEach, afterEach, teardown
// defined in plugins/lifecycle.ts
import Minipass from 'minipass'
import assert from 'node:assert'
import { hrtime } from 'node:process'
import { Readable } from 'node:stream'
import { format } from 'node:util'
import { CallSiteLike } from 'stack-utils'
import { FinalResults } from 'tap-parser'
import Deferred from 'trivial-deferred'
import { Base, BaseOpts } from './base.js'
import { esc } from './esc.js'
import stack from './stack.js'
import { TestPoint } from './test-point.js'
import { Waiter } from './waiter.js'
const queueEmpty = <T extends TestBase>(t: T) =>
t.queue.length === 0 ||
(t.queue.length === 1 &&
t.queue[0] === 'TAP version 14\n')
export interface ClassOf<T> {
new (): T
}
export type TapPlugin<
B extends Object,
O extends TestBaseOpts | any = any
> = ((t: TestBase, opts: O) => B) | ((t: TestBase) => B)
export interface TestBaseOpts extends BaseOpts {
/**
* The number of jobs to run in parallel. Defaults to 1
*/
jobs?: number
/**
* Test function called when this Test is executed
*/
cb?: (...args: any[]) => any
/**
* Flag to always/never show diagnostics. If unset, then
* diagnostics are shown for failing test points only.
*/
diagnostic?: boolean
}
const normalizeMessageExtra = (
defaultMessage: string,
message?: string | { [k: string]: any },
extra?: { [k: string]: any }
): [string, { [k: string]: any }] => {
if (typeof message === 'string') {
return [message || defaultMessage, extra || {}]
} else {
return [defaultMessage, message || {}]
}
}
/**
* Sigil for implicit end() calls that should not
* trigger an error if the user then calls t.end()
*/
const IMPLICIT = Symbol('implicit end')
/**
* Sigil to put in the queue to signal the end of all things
*/
const EOF = Symbol('EOF')
export type QueueEntry =
| string
| TestPoint
| Base
| typeof EOF
| Waiter
| [method: string, ...args: any[]]
/**
* The TestBaseBase class is the base class for all plugins,
* and eventually thus the Test class.
*
* This implements subtest functionality, TAP stream generation,
* lifecycle events, and only the most basic pass/fail assertions.
*
* All other features are added with plugins.
*/
export class TestBase extends Base {
// NB: generated pluginified Test class needs to declare over this
declare parent?: TestBase
promise?: Promise<any>
jobs: number
// #beforeEnd: [method: string | Symbol, ...args: any[]][] = []
subtests: Base[] = []
pool: Set<Base> = new Set()
queue: QueueEntry[] = ['TAP version 14\n']
cb?: (...args: any[]) => any
count: number = 0
ended: boolean = false
assertAt: CallSiteLike | null = null
assertStack: string | null = null
diagnostic: null | boolean = null
#planEnd: number = -1
#printedResult: boolean = false
#explicitEnded: boolean = false
#multiEndThrew: boolean = false
#n: number = 0
#noparallel: boolean = false
#occupied: null | Waiter | Base = null
#pushedEnd: boolean = false
#nextChildId: number = 1
#currentAssert: null | ((..._: any) => any) = null
#processing: boolean = false
#doingStdinOnly: boolean = false
/**
* true if the test has printed at least one TestPoint
*/
get printedResult(): boolean {
return this.#printedResult
}
constructor(options: TestBaseOpts) {
super(options)
this.jobs =
(options.jobs && Math.max(options.jobs, 1)) || 1
if (typeof options.diagnostic === 'boolean') {
this.diagnostic = options.diagnostic
}
if (options.cb) {
this.#setCB(options.cb)
}
}
#setCB<T extends TestBase>(this: T, cb: (t: T) => any) {
this.cb = (...args: any[]) =>
this.hook.runInAsyncScope(cb, this, ...args)
}
// TAP output generating methods
/**
* immediately exit this and all parent tests with a TAP
* Bail out! message.
*/
bailout(message?: string) {
if (this.parent && (this.results || this.ended)) {
this.parent.bailout(message)
} else {
this.#process()
message = message
? ' ' + ('' + esc(message)).trim()
: ''
message = message.replace(/[\r\n]/g, ' ')
this.parser.write('Bail out!' + message + '\n')
}
this.#end(IMPLICIT)
this.#process()
}
/**
* output a TAP comment, formatted like console.log()
*/
comment(...args: any[]) {
const body = format(...args)
const message =
('# ' + body.split(/\r?\n/).join('\n# ')).trim() +
'\n'
if (this.results) {
this.write(message)
} else {
this.queue.push(message)
}
this.#process()
}
/**
* Called when the test times out.
* Options are passed as diagnostics to the threw() method
*/
timeout(options: { [k: string]: any }) {
options = options || {}
options.expired = options.expired || this
|
.name
if (this.#occupied && this.#occupied instanceof Base) {
|
this.#occupied.timeout(options)
} else {
super.timeout(options)
}
this.#end(IMPLICIT)
}
/**
* Set TAP pragma configs to affect the behavior of the parser.
* Only `strict` is supported by the parser.
*/
pragma(set: { [k: string]: boolean }) {
const p = Object.keys(set).reduce(
(acc, i) =>
acc + 'pragma ' + (set[i] ? '+' : '-') + i + '\n',
''
)
this.queue.push(p)
this.#process()
}
/**
* Specify the number of Test Points expected by this test.
* Outputs a TAP plan line.
*/
plan(n: number, comment?: string) {
if (this.bailedOut) {
return
}
if (this.#planEnd !== -1) {
throw new Error('Cannot set plan more than once')
}
if (typeof n !== 'number' || n < 0) {
throw new TypeError('plan must be a number')
}
// Cannot get any tests after a trailing plan, or a plan of 0
const ending = this.count !== 0 || n === 0
if (n === 0 && comment && !this.options.skip) {
this.options.skip = comment
}
this.#planEnd = n
comment = comment ? ' # ' + esc(comment.trim()) : ''
this.queue.push('1..' + n + comment + '\n')
if (ending) {
this.#end(IMPLICIT)
} else {
this.#process()
}
}
/**
* A passing (ok) Test Point
*/
pass(message?: string, extra?: { [k: string]: any }) {
this.currentAssert = TestBase.prototype.pass
this.printResult(
true,
...normalizeMessageExtra(
'(unnamed test)',
message,
extra
)
)
return true
}
/**
* A failing (not ok) Test Point
*/
fail(message?: string, extra?: { [k: string]: any }) {
this.currentAssert = TestBase.prototype.fail
const [m, e] = normalizeMessageExtra(
'(unnamed test)',
message,
extra
)
this.printResult(false, m, e)
return !!(e.todo || e.skip)
}
/**
* The current assertion being processed. May only be set if
* not already set.
*/
get currentAssert() {
return this.#currentAssert
}
/**
* The current assertion being processed. May only be set if
* not already set.
*/
set currentAssert(fn: null | ((...a: any[]) => any)) {
if (!this.#currentAssert && typeof fn === 'function') {
this.#currentAssert = fn
}
}
/**
* Print a Test Point
*/
printResult(
ok: boolean,
message: string,
extra: { [k: string]: any },
front: boolean = false
) {
this.#printedResult = true
const n = this.count + 1
this.currentAssert = TestBase.prototype.printResult
const fn = this.#currentAssert
this.#currentAssert = null
if (this.#planEnd !== -1 && n > this.#planEnd) {
if (!this.passing()) return
const failMessage = this.#explicitEnded
? 'test after end() was called'
: 'test count exceeds plan'
const er = new Error(failMessage, {
cause: {
test: this.name,
plan: this.#planEnd,
},
})
Error.captureStackTrace(er, fn || undefined)
this.threw(er)
return
}
extra = extra || {}
if (extra.expectFail) {
ok = !ok
}
if (this.assertAt) {
extra.at = this.assertAt
this.assertAt = null
}
if (this.assertStack) {
extra.stack = this.assertStack
this.assertStack = null
}
if (typeof extra.stack === 'string' && !extra.at) {
extra.at = stack.parseLine(extra.stack.split('\n')[0])
}
if (
!ok &&
!extra.skip &&
!extra.at &&
typeof fn === 'function'
) {
extra.at = stack.at(fn)
if (!extra.todo) {
extra.stack = stack.captureString(80, fn)
}
}
const diagnostic =
typeof extra.diagnostic === 'boolean'
? extra.diagnostic
: typeof this.diagnostic === 'boolean'
? this.diagnostic
: extra.skip || extra.todo
? false
: !ok
if (diagnostic) {
extra.diagnostic = true
}
this.count = n
message = message + ''
const res = { ok, message, extra }
const tp = new TestPoint(ok, message, extra)
// when we jump the queue, skip an extra line
if (front) {
tp.message = tp.message.trimEnd() + '\n\n'
}
if (
this.#occupied &&
this.#occupied instanceof Waiter &&
this.#occupied.finishing
) {
front = true
}
if (front) {
if (
extra.tapChildBuffer ||
extra.tapChildBuffer === ''
) {
this.writeSubComment(tp)
this.parser.write(extra.tapChildBuffer)
}
this.emit('result', res)
this.parser.write(tp.ok + ++this.#n + tp.message)
if (this.bail && !ok && !extra.skip && !extra.todo) {
this.parser.write('Bail out! ' + message + '\n')
}
} else {
this.queue.push(tp)
if (this.bail && !ok && !extra.skip && !extra.todo) {
this.queue.push('Bail out! ' + message + '\n')
}
}
if (this.#planEnd === this.count) {
this.#end(IMPLICIT)
}
this.#process()
}
end(): this {
this.#end()
return super.end()
}
/**
* The leading `# Subtest` comment that introduces a child test
*/
writeSubComment<T extends TestPoint | Base>(p: T) {
const comment =
'# Subtest' +
(p.name ? ': ' + esc(p.name) : '') +
'\n'
this.parser.write(comment)
}
// end TAP otput generating methods
// flow control methods
/**
* Await the end of a Promise before proceeding.
* The supplied callback is called with the Waiter object.
*/
waitOn(
promise: Promise<any | void>,
cb: (w: Waiter) => any,
expectReject: boolean = false
): Promise<void> {
const w = new Waiter(
promise,
w => {
assert.equal(this.#occupied, w)
cb(w)
this.#occupied = null
this.#process()
},
expectReject
)
this.queue.push(w)
this.#process()
return w.promise
}
#end(implicit?: typeof IMPLICIT) {
if (this.#doingStdinOnly && implicit !== IMPLICIT)
throw new Error(
'cannot explicitly end while in stdinOnly mode'
)
this.debug('END implicit=%j', implicit === IMPLICIT)
if (this.ended && implicit === IMPLICIT) return
// beyond here we have to be actually done with things, or else
// the semantic checks on counts and such will be off.
if (!queueEmpty(this) || this.#occupied) {
if (!this.#pushedEnd) {
this.queue.push(['#end', implicit])
}
this.#pushedEnd = true
return this.#process()
}
this.ended = true
if (implicit !== IMPLICIT && !this.#multiEndThrew) {
if (this.#explicitEnded) {
this.#multiEndThrew = true
const er = new Error(
'test end() method called more than once'
)
Error.captureStackTrace(
er,
this.#currentAssert || this.#end
)
er.cause = {
test: this.name,
}
this.threw(er)
return
}
this.#explicitEnded = true
}
if (this.#planEnd === -1) {
this.debug(
'END(%s) implicit plan',
this.name,
this.count
)
this.plan(this.count)
}
this.queue.push(EOF)
this.#process()
}
#process() {
if (this.#processing) {
return this.debug(' < already processing')
}
this.debug(
'\nPROCESSING(%s)',
this.name,
this.queue.length
)
this.#processing = true
while (!this.#occupied) {
const p = this.queue.shift()
if (!p) {
this.debug('> end of queue')
break
}
if (p instanceof Base) {
this.debug('> subtest in queue', p.name)
this.#processSubtest(p)
} else if (p === EOF) {
this.debug(' > EOF', this.name)
// I AM BECOME EOF, DESTROYER OF STREAMS
this.parser.end()
} else if (p instanceof TestPoint) {
this.debug(' > TESTPOINT')
if (
p.extra.tapChildBuffer ||
p.extra.tapChildBuffer === ''
) {
this.writeSubComment(p)
this.parser.write(p.extra.tapChildBuffer)
}
this.emit('res', p.res)
this.parser.write(p.ok + ++this.#n + p.message)
} else if (typeof p === 'string') {
this.debug(' > STRING')
this.parser.write(p)
} else if (p instanceof Waiter) {
p.ready = true
this.#occupied = p
p.finish()
} else if (Array.isArray(p)) {
this.debug(' > METHOD')
const m = p.shift() as keyof this
if (typeof this[m] !== 'function') {
this.debug(
' > weird method not found in queue??',
m,
typeof this[m]
)
continue
}
const fn = (m === '#end' ? this.#end : this[m]) as (
...a: any[]
) => any
const ret = fn.call(this, ...p)
if (
ret &&
typeof ret === 'object' &&
typeof ret.then === 'function'
) {
// returned promise
ret.then(
() => {
this.#processing = false
this.#process()
},
(er: unknown) => {
this.#processing = false
this.threw(er)
}
)
return
}
/* c8 ignore start */
} else {
throw new Error('weird thing got in the queue')
}
/* c8 ignore stop */
}
while (
!this.#noparallel &&
this.pool.size < this.jobs
) {
const p = this.subtests.shift()
if (!p) {
break
}
if (!p.buffered) {
this.#noparallel = true
break
}
this.debug('start subtest', p)
this.emit('subtestStart', p)
this.pool.add(p)
if (this.bailedOut) {
this.#onBufferedEnd(p)
} else {
p.runMain(() => this.#onBufferedEnd(p))
}
}
this.debug(
'done processing',
this.queue,
this.#occupied
)
this.#processing = false
// just in case any tests ended, and we have sync stuff still
// waiting around in the queue to be processed
if (!this.#occupied && this.queue.length) {
this.#process()
}
}
#onBufferedEnd<T extends Base>(p: T) {
p.ondone = p.constructor.prototype.ondone
p.results =
p.results || new FinalResults(true, p.parser)
p.readyToProcess = true
const to = p.options.timeout
const dur =
to && p.passing() ? hrtime.bigint() - p.start : null
if (dur && to && dur > to) {
p.timeout()
} else {
p.setTimeout(0)
}
this.debug(
'%s.#onBufferedEnd',
this.name,
p.name,
p.results.bailout
)
this.pool.delete(p)
p.options.tapChildBuffer = p.output || ''
p.options.stack = ''
if (p.time) p.options.time = p.time
if (this.#occupied === p) this.#occupied = null
p.deferred?.resolve(p.results)
this.emit('subtestEnd', p)
this.#process()
}
#onIndentedEnd<T extends Base>(p: T) {
this.emit('subtestProcess', p)
p.ondone = p.constructor.prototype.ondone
p.results =
p.results || new FinalResults(true, p.parser)
this.debug('#onIndentedEnd', this.name, p.name)
this.#noparallel = false
const sti = this.subtests.indexOf(p)
if (sti !== -1) this.subtests.splice(sti, 1)
p.readyToProcess = true
p.options.time = p.time
const to = p.options.timeout
const dur =
to && p.passing() ? hrtime.bigint() - p.start : null
if (dur && to && dur > to) {
p.timeout()
} else {
p.setTimeout(0)
}
this.debug('#onIndentedEnd %s(%s)', this.name, p.name)
this.#occupied = null
this.debug(
'OIE(%s) b>shift into queue',
this.name,
this.queue
)
p.options.stack = ''
this.printResult(p.passing(), p.name, p.options, true)
this.debug(
'OIE(%s) shifted into queue',
this.name,
this.queue
)
p.deferred?.resolve(p.results)
this.emit('subtestEnd', p)
this.#process()
}
/**
* @internal
*/
main(cb: () => void) {
if (typeof this.options.timeout === 'number') {
this.setTimeout(this.options.timeout)
}
this.debug('MAIN pre', this)
const end = () => {
this.debug(' > implicit end for promise')
this.#end(IMPLICIT)
done()
}
const done = (er?: Error) => {
if (er) this.threw(er)
if (this.results || this.bailedOut) cb()
else this.ondone = () => cb()
}
// This bit of overly clever line-noise wraps the call to user-code
// in a try-catch. We can't rely on the domain for this yet, because
// the 'end' event can trigger a throw after the domain is unhooked,
// but before this is no longer the official "active test"
const ret = (() => {
if (!this.cb) return
try {
return this.cb(this)
} catch (er: any) {
if (!er || typeof er !== 'object') {
er = { error: er }
}
er.tapCaught = 'testFunctionThrow'
this.threw(er)
}
})()
if (ret && ret.then) {
this.promise = ret
ret.tapAbortPromise = done
ret.then(end, (er: any) => {
if (!er || typeof er !== 'object') {
er = { error: er }
}
er.tapCaught = 'returnedPromiseRejection'
done(er)
})
} else done()
this.debug('MAIN post', this)
}
#processSubtest<T extends Base>(p: T) {
this.debug(' > subtest')
this.#occupied = p
if (!p.buffered) {
this.emit('subtestStart', p)
this.debug(' > subtest indented')
p.stream.pipe(this.parser, { end: false })
this.writeSubComment(p)
this.debug('calling runMain', p.runMain.toString())
p.runMain(() => {
this.debug('in runMain', p.runMain.toString())
this.#onIndentedEnd(p)
})
} else if (p.readyToProcess) {
this.emit('subtestProcess', p)
this.debug(' > subtest buffered, finished')
// finished! do the thing!
this.#occupied = null
if (!p.passing() || !p.silent) {
this.printResult(
p.passing(),
p.name,
p.options,
true
)
}
} else {
this.#occupied = p
this.debug(' > subtest buffered, unfinished', p)
// unfinished buffered test.
// nothing to do yet, just leave it there.
this.queue.unshift(p)
}
}
/**
* Parse stdin as the only tap stream (ie, not as a child test)
* If used, then no other subtests or assertions are allowed.
*/
stdinOnly<T extends BaseOpts>(
extra?: T & { tapStream?: Readable | Minipass }
) {
const stream = ((extra && extra.tapStream) ||
process.stdin) as Minipass
if (!stream) {
throw new Error(
'cannot read stdin without stdin stream'
)
}
if (
this.queue.length !== 1 ||
this.queue[0] !== 'TAP version 14\n' ||
this.#processing ||
this.results ||
this.#occupied ||
this.pool.size ||
this.subtests.length
) {
throw new Error(
'Cannot use stdinOnly on a test in progress'
)
}
this.#doingStdinOnly = true
this.queue.length = 0
this.parser.on('child', p => {
// pretend to be a rooted parser, so it gets counts.
p.root = p
const t = new Base({
name: p.name,
parent: this,
parser: p,
bail: p.bail,
strict: p.strict,
omitVersion: p.omitVersion,
preserveWhitespace: p.preserveWhitespace,
childId: this.#nextChildId++,
})
this.emit('subtestAdd', t)
this.emit('subtestStart', t)
this.emit('subtestProcess', t)
p.on('complete', () => {
t.time = p.time
this.emit('subtestEnd', t)
})
})
stream.pause()
stream.pipe(this.parser)
stream.resume()
}
/**
* Mount a subtest, using this Test object as a harness.
* Exposed mainly so that it can be used by builtin plugins.
*
* @internal
*/
sub<T extends Base, O extends TestBaseOpts>(
Class: { new (options: O): T },
extra: O,
caller: (...a: any[]) => unknown
): Promise<FinalResults | null> {
if (this.bailedOut) return Promise.resolve(null)
if (this.results || this.ended) {
const er = new Error(
'cannot create subtest after parent test ends'
)
Error.captureStackTrace(er, caller)
this.threw(er)
return Promise.resolve(null)
}
extra.childId = this.#nextChildId++
if (this.shouldSkipChild(extra)) {
this.pass(extra.name, extra)
return Promise.resolve(null)
}
extra.indent = ' '
if (extra.buffered !== undefined) {
if (this.jobs > 1) {
extra.buffered = true
} else {
extra.buffered = false
}
}
extra.bail =
extra.bail !== undefined ? extra.bail : this.bail
extra.parent = this
extra.stack = stack.captureString(80, caller)
extra.context = this.context
const t = new Class(extra)
this.queue.push(t)
this.subtests.push(t)
this.emit('subtestAdd', t)
const d = new Deferred<FinalResults>()
t.deferred = d
this.#process()
return d.promise
}
/**
* Return true if the child test represented by the options object
* should be skipped. Extended by the grep/only filtering plugins.
*/
shouldSkipChild(extra: { [k: string]: any }) {
return !!(extra.skip || extra.todo)
}
// end flow control methods
}
|
src/test-base.ts
|
tapjs-core-edd7403
|
[
{
"filename": "src/base.ts",
"retrieved_chunk": " this.setTimeout(0)\n options = options || {}\n options.expired = options.expired || this.name\n const threw = this.threw(new Error('timeout!'), options)\n if (threw) {\n this.emit('timeout', threw)\n }\n }\n runMain(cb: () => void) {\n this.debug('BASE runMain')",
"score": 0.837813138961792
},
{
"filename": "src/spawn.ts",
"retrieved_chunk": " !this.options.signal &&\n this.options.exitCode === undefined\n ) {\n super.timeout(options)\n this.proc.kill('SIGKILL')\n }\n }, 1000)\n t.unref()\n }\n }",
"score": 0.8092379570007324
},
{
"filename": "src/stdin.ts",
"retrieved_chunk": " }\n threw(er: any, extra?: any, proxy?: boolean) {\n extra = super.threw(er, extra, proxy)\n Object.assign(this.options, extra)\n this.parser.abort(er.message, extra)\n this.parser.end()\n }\n}",
"score": 0.8062855005264282
},
{
"filename": "src/base.ts",
"retrieved_chunk": " if (this.timer) {\n clearTimeout(this.timer)\n }\n this.timer = undefined\n } else {\n this.timer = setTimeout(() => this.timeout(), n)\n this.timer.unref()\n }\n }\n timeout(options?: { [k: string]: any }) {",
"score": 0.8006554841995239
},
{
"filename": "src/spawn.ts",
"retrieved_chunk": " this.parser.ok = false\n }\n return this.callCb()\n }\n timeout(options?: { [k: string]: any }) {\n if (this.proc) {\n this.proc.kill('SIGTERM')\n const t = setTimeout(() => {\n if (\n this.proc &&",
"score": 0.7968398332595825
}
] |
typescript
|
.name
if (this.#occupied && this.#occupied instanceof Base) {
|
// lifecycle methods like beforeEach, afterEach, teardown
// defined in plugins/lifecycle.ts
import Minipass from 'minipass'
import assert from 'node:assert'
import { hrtime } from 'node:process'
import { Readable } from 'node:stream'
import { format } from 'node:util'
import { CallSiteLike } from 'stack-utils'
import { FinalResults } from 'tap-parser'
import Deferred from 'trivial-deferred'
import { Base, BaseOpts } from './base.js'
import { esc } from './esc.js'
import stack from './stack.js'
import { TestPoint } from './test-point.js'
import { Waiter } from './waiter.js'
const queueEmpty = <T extends TestBase>(t: T) =>
t.queue.length === 0 ||
(t.queue.length === 1 &&
t.queue[0] === 'TAP version 14\n')
export interface ClassOf<T> {
new (): T
}
export type TapPlugin<
B extends Object,
O extends TestBaseOpts | any = any
> = ((t: TestBase, opts: O) => B) | ((t: TestBase) => B)
export interface TestBaseOpts extends BaseOpts {
/**
* The number of jobs to run in parallel. Defaults to 1
*/
jobs?: number
/**
* Test function called when this Test is executed
*/
cb?: (...args: any[]) => any
/**
* Flag to always/never show diagnostics. If unset, then
* diagnostics are shown for failing test points only.
*/
diagnostic?: boolean
}
const normalizeMessageExtra = (
defaultMessage: string,
message?: string | { [k: string]: any },
extra?: { [k: string]: any }
): [string, { [k: string]: any }] => {
if (typeof message === 'string') {
return [message || defaultMessage, extra || {}]
} else {
return [defaultMessage, message || {}]
}
}
/**
* Sigil for implicit end() calls that should not
* trigger an error if the user then calls t.end()
*/
const IMPLICIT = Symbol('implicit end')
/**
* Sigil to put in the queue to signal the end of all things
*/
const EOF = Symbol('EOF')
export type QueueEntry =
| string
| TestPoint
| Base
| typeof EOF
| Waiter
| [method: string, ...args: any[]]
/**
* The TestBaseBase class is the base class for all plugins,
* and eventually thus the Test class.
*
* This implements subtest functionality, TAP stream generation,
* lifecycle events, and only the most basic pass/fail assertions.
*
* All other features are added with plugins.
*/
export class TestBase extends Base {
// NB: generated pluginified Test class needs to declare over this
declare parent?: TestBase
promise?: Promise<any>
jobs: number
// #beforeEnd: [method: string | Symbol, ...args: any[]][] = []
subtests: Base[] = []
pool: Set<Base> = new Set()
queue: QueueEntry[] = ['TAP version 14\n']
cb?: (...args: any[]) => any
count: number = 0
ended: boolean = false
assertAt: CallSiteLike | null = null
assertStack: string | null = null
diagnostic: null | boolean = null
#planEnd: number = -1
#printedResult: boolean = false
#explicitEnded: boolean = false
#multiEndThrew: boolean = false
#n: number = 0
#noparallel: boolean = false
#occupied: null | Waiter | Base = null
#pushedEnd: boolean = false
#nextChildId: number = 1
#currentAssert: null | ((..._: any) => any) = null
#processing: boolean = false
#doingStdinOnly: boolean = false
/**
* true if the test has printed at least one TestPoint
*/
get printedResult(): boolean {
return this.#printedResult
}
constructor(options: TestBaseOpts) {
super(options)
this.jobs =
(options.jobs && Math.max(options.jobs, 1)) || 1
if (typeof options.diagnostic === 'boolean') {
this.diagnostic = options.diagnostic
}
if (options.cb) {
this.#setCB(options.cb)
}
}
#setCB<T extends TestBase>(this: T, cb: (t: T) => any) {
this.cb = (...args: any[]) =>
this.hook.runInAsyncScope(cb, this, ...args)
}
// TAP output generating methods
/**
* immediately exit this and all parent tests with a TAP
* Bail out! message.
*/
bailout(message?: string) {
if (this.parent && (this.results || this.ended)) {
this.parent.bailout(message)
} else {
this.#process()
message = message
? ' ' + ('' + esc(message)).trim()
: ''
message = message.replace(/[\r\n]/g, ' ')
this.parser.write('Bail out!' + message + '\n')
}
this.#end(IMPLICIT)
this.#process()
}
/**
* output a TAP comment, formatted like console.log()
*/
comment(...args: any[]) {
const body = format(...args)
const message =
('# ' + body.split(/\r?\n/).join('\n# ')).trim() +
'\n'
if (this.results) {
this
|
.write(message)
} else {
|
this.queue.push(message)
}
this.#process()
}
/**
* Called when the test times out.
* Options are passed as diagnostics to the threw() method
*/
timeout(options: { [k: string]: any }) {
options = options || {}
options.expired = options.expired || this.name
if (this.#occupied && this.#occupied instanceof Base) {
this.#occupied.timeout(options)
} else {
super.timeout(options)
}
this.#end(IMPLICIT)
}
/**
* Set TAP pragma configs to affect the behavior of the parser.
* Only `strict` is supported by the parser.
*/
pragma(set: { [k: string]: boolean }) {
const p = Object.keys(set).reduce(
(acc, i) =>
acc + 'pragma ' + (set[i] ? '+' : '-') + i + '\n',
''
)
this.queue.push(p)
this.#process()
}
/**
* Specify the number of Test Points expected by this test.
* Outputs a TAP plan line.
*/
plan(n: number, comment?: string) {
if (this.bailedOut) {
return
}
if (this.#planEnd !== -1) {
throw new Error('Cannot set plan more than once')
}
if (typeof n !== 'number' || n < 0) {
throw new TypeError('plan must be a number')
}
// Cannot get any tests after a trailing plan, or a plan of 0
const ending = this.count !== 0 || n === 0
if (n === 0 && comment && !this.options.skip) {
this.options.skip = comment
}
this.#planEnd = n
comment = comment ? ' # ' + esc(comment.trim()) : ''
this.queue.push('1..' + n + comment + '\n')
if (ending) {
this.#end(IMPLICIT)
} else {
this.#process()
}
}
/**
* A passing (ok) Test Point
*/
pass(message?: string, extra?: { [k: string]: any }) {
this.currentAssert = TestBase.prototype.pass
this.printResult(
true,
...normalizeMessageExtra(
'(unnamed test)',
message,
extra
)
)
return true
}
/**
* A failing (not ok) Test Point
*/
fail(message?: string, extra?: { [k: string]: any }) {
this.currentAssert = TestBase.prototype.fail
const [m, e] = normalizeMessageExtra(
'(unnamed test)',
message,
extra
)
this.printResult(false, m, e)
return !!(e.todo || e.skip)
}
/**
* The current assertion being processed. May only be set if
* not already set.
*/
get currentAssert() {
return this.#currentAssert
}
/**
* The current assertion being processed. May only be set if
* not already set.
*/
set currentAssert(fn: null | ((...a: any[]) => any)) {
if (!this.#currentAssert && typeof fn === 'function') {
this.#currentAssert = fn
}
}
/**
* Print a Test Point
*/
printResult(
ok: boolean,
message: string,
extra: { [k: string]: any },
front: boolean = false
) {
this.#printedResult = true
const n = this.count + 1
this.currentAssert = TestBase.prototype.printResult
const fn = this.#currentAssert
this.#currentAssert = null
if (this.#planEnd !== -1 && n > this.#planEnd) {
if (!this.passing()) return
const failMessage = this.#explicitEnded
? 'test after end() was called'
: 'test count exceeds plan'
const er = new Error(failMessage, {
cause: {
test: this.name,
plan: this.#planEnd,
},
})
Error.captureStackTrace(er, fn || undefined)
this.threw(er)
return
}
extra = extra || {}
if (extra.expectFail) {
ok = !ok
}
if (this.assertAt) {
extra.at = this.assertAt
this.assertAt = null
}
if (this.assertStack) {
extra.stack = this.assertStack
this.assertStack = null
}
if (typeof extra.stack === 'string' && !extra.at) {
extra.at = stack.parseLine(extra.stack.split('\n')[0])
}
if (
!ok &&
!extra.skip &&
!extra.at &&
typeof fn === 'function'
) {
extra.at = stack.at(fn)
if (!extra.todo) {
extra.stack = stack.captureString(80, fn)
}
}
const diagnostic =
typeof extra.diagnostic === 'boolean'
? extra.diagnostic
: typeof this.diagnostic === 'boolean'
? this.diagnostic
: extra.skip || extra.todo
? false
: !ok
if (diagnostic) {
extra.diagnostic = true
}
this.count = n
message = message + ''
const res = { ok, message, extra }
const tp = new TestPoint(ok, message, extra)
// when we jump the queue, skip an extra line
if (front) {
tp.message = tp.message.trimEnd() + '\n\n'
}
if (
this.#occupied &&
this.#occupied instanceof Waiter &&
this.#occupied.finishing
) {
front = true
}
if (front) {
if (
extra.tapChildBuffer ||
extra.tapChildBuffer === ''
) {
this.writeSubComment(tp)
this.parser.write(extra.tapChildBuffer)
}
this.emit('result', res)
this.parser.write(tp.ok + ++this.#n + tp.message)
if (this.bail && !ok && !extra.skip && !extra.todo) {
this.parser.write('Bail out! ' + message + '\n')
}
} else {
this.queue.push(tp)
if (this.bail && !ok && !extra.skip && !extra.todo) {
this.queue.push('Bail out! ' + message + '\n')
}
}
if (this.#planEnd === this.count) {
this.#end(IMPLICIT)
}
this.#process()
}
end(): this {
this.#end()
return super.end()
}
/**
* The leading `# Subtest` comment that introduces a child test
*/
writeSubComment<T extends TestPoint | Base>(p: T) {
const comment =
'# Subtest' +
(p.name ? ': ' + esc(p.name) : '') +
'\n'
this.parser.write(comment)
}
// end TAP otput generating methods
// flow control methods
/**
* Await the end of a Promise before proceeding.
* The supplied callback is called with the Waiter object.
*/
waitOn(
promise: Promise<any | void>,
cb: (w: Waiter) => any,
expectReject: boolean = false
): Promise<void> {
const w = new Waiter(
promise,
w => {
assert.equal(this.#occupied, w)
cb(w)
this.#occupied = null
this.#process()
},
expectReject
)
this.queue.push(w)
this.#process()
return w.promise
}
#end(implicit?: typeof IMPLICIT) {
if (this.#doingStdinOnly && implicit !== IMPLICIT)
throw new Error(
'cannot explicitly end while in stdinOnly mode'
)
this.debug('END implicit=%j', implicit === IMPLICIT)
if (this.ended && implicit === IMPLICIT) return
// beyond here we have to be actually done with things, or else
// the semantic checks on counts and such will be off.
if (!queueEmpty(this) || this.#occupied) {
if (!this.#pushedEnd) {
this.queue.push(['#end', implicit])
}
this.#pushedEnd = true
return this.#process()
}
this.ended = true
if (implicit !== IMPLICIT && !this.#multiEndThrew) {
if (this.#explicitEnded) {
this.#multiEndThrew = true
const er = new Error(
'test end() method called more than once'
)
Error.captureStackTrace(
er,
this.#currentAssert || this.#end
)
er.cause = {
test: this.name,
}
this.threw(er)
return
}
this.#explicitEnded = true
}
if (this.#planEnd === -1) {
this.debug(
'END(%s) implicit plan',
this.name,
this.count
)
this.plan(this.count)
}
this.queue.push(EOF)
this.#process()
}
#process() {
if (this.#processing) {
return this.debug(' < already processing')
}
this.debug(
'\nPROCESSING(%s)',
this.name,
this.queue.length
)
this.#processing = true
while (!this.#occupied) {
const p = this.queue.shift()
if (!p) {
this.debug('> end of queue')
break
}
if (p instanceof Base) {
this.debug('> subtest in queue', p.name)
this.#processSubtest(p)
} else if (p === EOF) {
this.debug(' > EOF', this.name)
// I AM BECOME EOF, DESTROYER OF STREAMS
this.parser.end()
} else if (p instanceof TestPoint) {
this.debug(' > TESTPOINT')
if (
p.extra.tapChildBuffer ||
p.extra.tapChildBuffer === ''
) {
this.writeSubComment(p)
this.parser.write(p.extra.tapChildBuffer)
}
this.emit('res', p.res)
this.parser.write(p.ok + ++this.#n + p.message)
} else if (typeof p === 'string') {
this.debug(' > STRING')
this.parser.write(p)
} else if (p instanceof Waiter) {
p.ready = true
this.#occupied = p
p.finish()
} else if (Array.isArray(p)) {
this.debug(' > METHOD')
const m = p.shift() as keyof this
if (typeof this[m] !== 'function') {
this.debug(
' > weird method not found in queue??',
m,
typeof this[m]
)
continue
}
const fn = (m === '#end' ? this.#end : this[m]) as (
...a: any[]
) => any
const ret = fn.call(this, ...p)
if (
ret &&
typeof ret === 'object' &&
typeof ret.then === 'function'
) {
// returned promise
ret.then(
() => {
this.#processing = false
this.#process()
},
(er: unknown) => {
this.#processing = false
this.threw(er)
}
)
return
}
/* c8 ignore start */
} else {
throw new Error('weird thing got in the queue')
}
/* c8 ignore stop */
}
while (
!this.#noparallel &&
this.pool.size < this.jobs
) {
const p = this.subtests.shift()
if (!p) {
break
}
if (!p.buffered) {
this.#noparallel = true
break
}
this.debug('start subtest', p)
this.emit('subtestStart', p)
this.pool.add(p)
if (this.bailedOut) {
this.#onBufferedEnd(p)
} else {
p.runMain(() => this.#onBufferedEnd(p))
}
}
this.debug(
'done processing',
this.queue,
this.#occupied
)
this.#processing = false
// just in case any tests ended, and we have sync stuff still
// waiting around in the queue to be processed
if (!this.#occupied && this.queue.length) {
this.#process()
}
}
#onBufferedEnd<T extends Base>(p: T) {
p.ondone = p.constructor.prototype.ondone
p.results =
p.results || new FinalResults(true, p.parser)
p.readyToProcess = true
const to = p.options.timeout
const dur =
to && p.passing() ? hrtime.bigint() - p.start : null
if (dur && to && dur > to) {
p.timeout()
} else {
p.setTimeout(0)
}
this.debug(
'%s.#onBufferedEnd',
this.name,
p.name,
p.results.bailout
)
this.pool.delete(p)
p.options.tapChildBuffer = p.output || ''
p.options.stack = ''
if (p.time) p.options.time = p.time
if (this.#occupied === p) this.#occupied = null
p.deferred?.resolve(p.results)
this.emit('subtestEnd', p)
this.#process()
}
#onIndentedEnd<T extends Base>(p: T) {
this.emit('subtestProcess', p)
p.ondone = p.constructor.prototype.ondone
p.results =
p.results || new FinalResults(true, p.parser)
this.debug('#onIndentedEnd', this.name, p.name)
this.#noparallel = false
const sti = this.subtests.indexOf(p)
if (sti !== -1) this.subtests.splice(sti, 1)
p.readyToProcess = true
p.options.time = p.time
const to = p.options.timeout
const dur =
to && p.passing() ? hrtime.bigint() - p.start : null
if (dur && to && dur > to) {
p.timeout()
} else {
p.setTimeout(0)
}
this.debug('#onIndentedEnd %s(%s)', this.name, p.name)
this.#occupied = null
this.debug(
'OIE(%s) b>shift into queue',
this.name,
this.queue
)
p.options.stack = ''
this.printResult(p.passing(), p.name, p.options, true)
this.debug(
'OIE(%s) shifted into queue',
this.name,
this.queue
)
p.deferred?.resolve(p.results)
this.emit('subtestEnd', p)
this.#process()
}
/**
* @internal
*/
main(cb: () => void) {
if (typeof this.options.timeout === 'number') {
this.setTimeout(this.options.timeout)
}
this.debug('MAIN pre', this)
const end = () => {
this.debug(' > implicit end for promise')
this.#end(IMPLICIT)
done()
}
const done = (er?: Error) => {
if (er) this.threw(er)
if (this.results || this.bailedOut) cb()
else this.ondone = () => cb()
}
// This bit of overly clever line-noise wraps the call to user-code
// in a try-catch. We can't rely on the domain for this yet, because
// the 'end' event can trigger a throw after the domain is unhooked,
// but before this is no longer the official "active test"
const ret = (() => {
if (!this.cb) return
try {
return this.cb(this)
} catch (er: any) {
if (!er || typeof er !== 'object') {
er = { error: er }
}
er.tapCaught = 'testFunctionThrow'
this.threw(er)
}
})()
if (ret && ret.then) {
this.promise = ret
ret.tapAbortPromise = done
ret.then(end, (er: any) => {
if (!er || typeof er !== 'object') {
er = { error: er }
}
er.tapCaught = 'returnedPromiseRejection'
done(er)
})
} else done()
this.debug('MAIN post', this)
}
#processSubtest<T extends Base>(p: T) {
this.debug(' > subtest')
this.#occupied = p
if (!p.buffered) {
this.emit('subtestStart', p)
this.debug(' > subtest indented')
p.stream.pipe(this.parser, { end: false })
this.writeSubComment(p)
this.debug('calling runMain', p.runMain.toString())
p.runMain(() => {
this.debug('in runMain', p.runMain.toString())
this.#onIndentedEnd(p)
})
} else if (p.readyToProcess) {
this.emit('subtestProcess', p)
this.debug(' > subtest buffered, finished')
// finished! do the thing!
this.#occupied = null
if (!p.passing() || !p.silent) {
this.printResult(
p.passing(),
p.name,
p.options,
true
)
}
} else {
this.#occupied = p
this.debug(' > subtest buffered, unfinished', p)
// unfinished buffered test.
// nothing to do yet, just leave it there.
this.queue.unshift(p)
}
}
/**
* Parse stdin as the only tap stream (ie, not as a child test)
* If used, then no other subtests or assertions are allowed.
*/
stdinOnly<T extends BaseOpts>(
extra?: T & { tapStream?: Readable | Minipass }
) {
const stream = ((extra && extra.tapStream) ||
process.stdin) as Minipass
if (!stream) {
throw new Error(
'cannot read stdin without stdin stream'
)
}
if (
this.queue.length !== 1 ||
this.queue[0] !== 'TAP version 14\n' ||
this.#processing ||
this.results ||
this.#occupied ||
this.pool.size ||
this.subtests.length
) {
throw new Error(
'Cannot use stdinOnly on a test in progress'
)
}
this.#doingStdinOnly = true
this.queue.length = 0
this.parser.on('child', p => {
// pretend to be a rooted parser, so it gets counts.
p.root = p
const t = new Base({
name: p.name,
parent: this,
parser: p,
bail: p.bail,
strict: p.strict,
omitVersion: p.omitVersion,
preserveWhitespace: p.preserveWhitespace,
childId: this.#nextChildId++,
})
this.emit('subtestAdd', t)
this.emit('subtestStart', t)
this.emit('subtestProcess', t)
p.on('complete', () => {
t.time = p.time
this.emit('subtestEnd', t)
})
})
stream.pause()
stream.pipe(this.parser)
stream.resume()
}
/**
* Mount a subtest, using this Test object as a harness.
* Exposed mainly so that it can be used by builtin plugins.
*
* @internal
*/
sub<T extends Base, O extends TestBaseOpts>(
Class: { new (options: O): T },
extra: O,
caller: (...a: any[]) => unknown
): Promise<FinalResults | null> {
if (this.bailedOut) return Promise.resolve(null)
if (this.results || this.ended) {
const er = new Error(
'cannot create subtest after parent test ends'
)
Error.captureStackTrace(er, caller)
this.threw(er)
return Promise.resolve(null)
}
extra.childId = this.#nextChildId++
if (this.shouldSkipChild(extra)) {
this.pass(extra.name, extra)
return Promise.resolve(null)
}
extra.indent = ' '
if (extra.buffered !== undefined) {
if (this.jobs > 1) {
extra.buffered = true
} else {
extra.buffered = false
}
}
extra.bail =
extra.bail !== undefined ? extra.bail : this.bail
extra.parent = this
extra.stack = stack.captureString(80, caller)
extra.context = this.context
const t = new Class(extra)
this.queue.push(t)
this.subtests.push(t)
this.emit('subtestAdd', t)
const d = new Deferred<FinalResults>()
t.deferred = d
this.#process()
return d.promise
}
/**
* Return true if the child test represented by the options object
* should be skipped. Extended by the grep/only filtering plugins.
*/
shouldSkipChild(extra: { [k: string]: any }) {
return !!(extra.skip || extra.todo)
}
// end flow control methods
}
|
src/test-base.ts
|
tapjs-core-edd7403
|
[
{
"filename": "src/spawn.ts",
"retrieved_chunk": " }\n main(cb: () => void) {\n this.cb = cb\n this.setTimeout(this.options.timeout || 0)\n this.parser.on('comment', c => {\n const tomatch = c.match(/# timeout=([0-9]+)\\n$/)\n if (tomatch) {\n this.setTimeout(+tomatch[1])\n }\n })",
"score": 0.8083937764167786
},
{
"filename": "src/base.ts",
"retrieved_chunk": " const msg = format(...args).trim()\n console.error(\n prefix + msg.split('\\n').join(`\\n${prefix}`)\n )\n }\nexport interface BaseOpts {\n // parser-related options\n bail?: boolean\n strict?: boolean\n omitVersion?: boolean",
"score": 0.8060407042503357
},
{
"filename": "src/spawn.ts",
"retrieved_chunk": " : command + ' ' + args.join(' ')\n ).replace(/\\\\/g, '/')\n }\n}",
"score": 0.7928299903869629
},
{
"filename": "src/test-point.ts",
"retrieved_chunk": "}\nconst tpMessage = (\n description: string,\n extra: { [k: string]: any },\n options: TestBaseOpts = {}\n): string => {\n let message = description ? ` - ${description}` : ''\n if (extra.skip) {\n message += ' # SKIP'\n if (typeof extra.skip === 'string') {",
"score": 0.7919251918792725
},
{
"filename": "src/test-point.ts",
"retrieved_chunk": " extra = extra || {}\n message = message\n .trim()\n .replace(/[\\n\\r]/g, ' ')\n .replace(/\\t/g, ' ')\n this.res = { ok, message, extra }\n this.extra = extra\n this.name = message\n this.message = tpMessage(esc(this.name), extra)\n }",
"score": 0.7914915084838867
}
] |
typescript
|
.write(message)
} else {
|
// lifecycle methods like beforeEach, afterEach, teardown
// defined in plugins/lifecycle.ts
import Minipass from 'minipass'
import assert from 'node:assert'
import { hrtime } from 'node:process'
import { Readable } from 'node:stream'
import { format } from 'node:util'
import { CallSiteLike } from 'stack-utils'
import { FinalResults } from 'tap-parser'
import Deferred from 'trivial-deferred'
import { Base, BaseOpts } from './base.js'
import { esc } from './esc.js'
import stack from './stack.js'
import { TestPoint } from './test-point.js'
import { Waiter } from './waiter.js'
const queueEmpty = <T extends TestBase>(t: T) =>
t.queue.length === 0 ||
(t.queue.length === 1 &&
t.queue[0] === 'TAP version 14\n')
export interface ClassOf<T> {
new (): T
}
export type TapPlugin<
B extends Object,
O extends TestBaseOpts | any = any
> = ((t: TestBase, opts: O) => B) | ((t: TestBase) => B)
export interface TestBaseOpts extends BaseOpts {
/**
* The number of jobs to run in parallel. Defaults to 1
*/
jobs?: number
/**
* Test function called when this Test is executed
*/
cb?: (...args: any[]) => any
/**
* Flag to always/never show diagnostics. If unset, then
* diagnostics are shown for failing test points only.
*/
diagnostic?: boolean
}
const normalizeMessageExtra = (
defaultMessage: string,
message?: string | { [k: string]: any },
extra?: { [k: string]: any }
): [string, { [k: string]: any }] => {
if (typeof message === 'string') {
return [message || defaultMessage, extra || {}]
} else {
return [defaultMessage, message || {}]
}
}
/**
* Sigil for implicit end() calls that should not
* trigger an error if the user then calls t.end()
*/
const IMPLICIT = Symbol('implicit end')
/**
* Sigil to put in the queue to signal the end of all things
*/
const EOF = Symbol('EOF')
export type QueueEntry =
| string
| TestPoint
| Base
| typeof EOF
| Waiter
| [method: string, ...args: any[]]
/**
* The TestBaseBase class is the base class for all plugins,
* and eventually thus the Test class.
*
* This implements subtest functionality, TAP stream generation,
* lifecycle events, and only the most basic pass/fail assertions.
*
* All other features are added with plugins.
*/
export class TestBase extends Base {
// NB: generated pluginified Test class needs to declare over this
declare parent?: TestBase
promise?: Promise<any>
jobs: number
// #beforeEnd: [method: string | Symbol, ...args: any[]][] = []
subtests: Base[] = []
pool: Set<Base> = new Set()
queue: QueueEntry[] = ['TAP version 14\n']
cb?: (...args: any[]) => any
count: number = 0
ended: boolean = false
assertAt: CallSiteLike | null = null
assertStack: string | null = null
diagnostic: null | boolean = null
#planEnd: number = -1
#printedResult: boolean = false
#explicitEnded: boolean = false
#multiEndThrew: boolean = false
#n: number = 0
#noparallel: boolean = false
#occupied: null | Waiter | Base = null
#pushedEnd: boolean = false
#nextChildId: number = 1
#currentAssert: null | ((..._: any) => any) = null
#processing: boolean = false
#doingStdinOnly: boolean = false
/**
* true if the test has printed at least one TestPoint
*/
get printedResult(): boolean {
return this.#printedResult
}
constructor(options: TestBaseOpts) {
super(options)
this.jobs =
(options.jobs && Math.max(options.jobs, 1)) || 1
if (typeof options.diagnostic === 'boolean') {
this.diagnostic = options.diagnostic
}
if (options.cb) {
this.#setCB(options.cb)
}
}
#setCB<T extends TestBase>(this: T, cb: (t: T) => any) {
this.cb = (...args: any[]) =>
this.hook.runInAsyncScope(cb, this, ...args)
}
// TAP output generating methods
/**
* immediately exit this and all parent tests with a TAP
* Bail out! message.
*/
bailout(message?: string) {
if (this.parent && (this.results || this.ended)) {
this.parent.bailout(message)
} else {
this.#process()
message = message
? ' ' + ('' + esc(message)).trim()
: ''
message = message.replace(/[\r\n]/g, ' ')
this.parser.write('Bail out!' + message + '\n')
}
this.#end(IMPLICIT)
this.#process()
}
/**
* output a TAP comment, formatted like console.log()
*/
comment(...args: any[]) {
const body = format(...args)
const message =
('# ' + body.split(/\r?\n/).join('\n# ')).trim() +
'\n'
if (this.results) {
this.write(message)
} else {
this.queue.push(message)
}
this.#process()
}
/**
* Called when the test times out.
* Options are passed as diagnostics to the threw() method
*/
timeout(options: { [k: string]: any }) {
options = options || {}
options.expired = options.expired || this.name
if (this.#occupied && this.#occupied instanceof Base) {
this.#occupied.timeout(options)
} else {
super.timeout(options)
}
this.#end(IMPLICIT)
}
/**
* Set TAP pragma configs to affect the behavior of the parser.
* Only `strict` is supported by the parser.
*/
pragma(set: { [k: string]: boolean }) {
const p = Object.keys(set).reduce(
(acc, i) =>
acc + 'pragma ' + (set[i] ? '+' : '-') + i + '\n',
''
)
this.queue.push(p)
this.#process()
}
/**
* Specify the number of Test Points expected by this test.
* Outputs a TAP plan line.
*/
plan(n: number, comment?: string) {
if (this.bailedOut) {
return
}
if (this.#planEnd !== -1) {
throw new Error('Cannot set plan more than once')
}
if (typeof n !== 'number' || n < 0) {
throw new TypeError('plan must be a number')
}
// Cannot get any tests after a trailing plan, or a plan of 0
const ending = this.count !== 0 || n === 0
if (n === 0 && comment && !this.options.skip) {
this.options.skip = comment
}
this.#planEnd = n
comment = comment ? ' # ' + esc(comment.trim()) : ''
this.queue.push('1..' + n + comment + '\n')
if (ending) {
this.#end(IMPLICIT)
} else {
this.#process()
}
}
/**
* A passing (ok) Test Point
*/
pass(message?: string, extra?: { [k: string]: any }) {
this.currentAssert = TestBase.prototype.pass
this.printResult(
true,
...normalizeMessageExtra(
'(unnamed test)',
message,
extra
)
)
return true
}
/**
* A failing (not ok) Test Point
*/
fail(message?: string, extra?: { [k: string]: any }) {
this.currentAssert = TestBase.prototype.fail
const [m, e] = normalizeMessageExtra(
'(unnamed test)',
message,
extra
)
this.printResult(false, m, e)
return !!(e.todo || e.skip)
}
/**
* The current assertion being processed. May only be set if
* not already set.
*/
get currentAssert() {
return this.#currentAssert
}
/**
* The current assertion being processed. May only be set if
* not already set.
*/
set currentAssert(fn: null | ((...a: any[]) => any)) {
if (!this.#currentAssert && typeof fn === 'function') {
this.#currentAssert = fn
}
}
/**
* Print a Test Point
*/
printResult(
ok: boolean,
message: string,
extra: { [k: string]: any },
front: boolean = false
) {
this.#printedResult = true
const n = this.count + 1
this.currentAssert = TestBase.prototype.printResult
const fn = this.#currentAssert
this.#currentAssert = null
if (this.#planEnd !== -1 && n > this.#planEnd) {
if (!this.passing()) return
const failMessage = this.#explicitEnded
? 'test after end() was called'
: 'test count exceeds plan'
const er = new Error(failMessage, {
cause: {
test: this.name,
plan: this.#planEnd,
},
})
Error.captureStackTrace(er, fn || undefined)
this.threw(er)
return
}
extra = extra || {}
if (extra.expectFail) {
ok = !ok
}
if (this.assertAt) {
extra.at = this.assertAt
this.assertAt = null
}
if (this.assertStack) {
extra.stack = this.assertStack
this.assertStack = null
}
if (typeof extra.stack === 'string' && !extra.at) {
extra.at = stack.parseLine(extra.stack.split('\n')[0])
}
if (
!ok &&
!extra.skip &&
!extra.at &&
typeof fn === 'function'
) {
extra.at = stack.at(fn)
if (!extra.todo) {
extra.stack
|
= stack.captureString(80, fn)
}
|
}
const diagnostic =
typeof extra.diagnostic === 'boolean'
? extra.diagnostic
: typeof this.diagnostic === 'boolean'
? this.diagnostic
: extra.skip || extra.todo
? false
: !ok
if (diagnostic) {
extra.diagnostic = true
}
this.count = n
message = message + ''
const res = { ok, message, extra }
const tp = new TestPoint(ok, message, extra)
// when we jump the queue, skip an extra line
if (front) {
tp.message = tp.message.trimEnd() + '\n\n'
}
if (
this.#occupied &&
this.#occupied instanceof Waiter &&
this.#occupied.finishing
) {
front = true
}
if (front) {
if (
extra.tapChildBuffer ||
extra.tapChildBuffer === ''
) {
this.writeSubComment(tp)
this.parser.write(extra.tapChildBuffer)
}
this.emit('result', res)
this.parser.write(tp.ok + ++this.#n + tp.message)
if (this.bail && !ok && !extra.skip && !extra.todo) {
this.parser.write('Bail out! ' + message + '\n')
}
} else {
this.queue.push(tp)
if (this.bail && !ok && !extra.skip && !extra.todo) {
this.queue.push('Bail out! ' + message + '\n')
}
}
if (this.#planEnd === this.count) {
this.#end(IMPLICIT)
}
this.#process()
}
end(): this {
this.#end()
return super.end()
}
/**
* The leading `# Subtest` comment that introduces a child test
*/
writeSubComment<T extends TestPoint | Base>(p: T) {
const comment =
'# Subtest' +
(p.name ? ': ' + esc(p.name) : '') +
'\n'
this.parser.write(comment)
}
// end TAP otput generating methods
// flow control methods
/**
* Await the end of a Promise before proceeding.
* The supplied callback is called with the Waiter object.
*/
waitOn(
promise: Promise<any | void>,
cb: (w: Waiter) => any,
expectReject: boolean = false
): Promise<void> {
const w = new Waiter(
promise,
w => {
assert.equal(this.#occupied, w)
cb(w)
this.#occupied = null
this.#process()
},
expectReject
)
this.queue.push(w)
this.#process()
return w.promise
}
#end(implicit?: typeof IMPLICIT) {
if (this.#doingStdinOnly && implicit !== IMPLICIT)
throw new Error(
'cannot explicitly end while in stdinOnly mode'
)
this.debug('END implicit=%j', implicit === IMPLICIT)
if (this.ended && implicit === IMPLICIT) return
// beyond here we have to be actually done with things, or else
// the semantic checks on counts and such will be off.
if (!queueEmpty(this) || this.#occupied) {
if (!this.#pushedEnd) {
this.queue.push(['#end', implicit])
}
this.#pushedEnd = true
return this.#process()
}
this.ended = true
if (implicit !== IMPLICIT && !this.#multiEndThrew) {
if (this.#explicitEnded) {
this.#multiEndThrew = true
const er = new Error(
'test end() method called more than once'
)
Error.captureStackTrace(
er,
this.#currentAssert || this.#end
)
er.cause = {
test: this.name,
}
this.threw(er)
return
}
this.#explicitEnded = true
}
if (this.#planEnd === -1) {
this.debug(
'END(%s) implicit plan',
this.name,
this.count
)
this.plan(this.count)
}
this.queue.push(EOF)
this.#process()
}
#process() {
if (this.#processing) {
return this.debug(' < already processing')
}
this.debug(
'\nPROCESSING(%s)',
this.name,
this.queue.length
)
this.#processing = true
while (!this.#occupied) {
const p = this.queue.shift()
if (!p) {
this.debug('> end of queue')
break
}
if (p instanceof Base) {
this.debug('> subtest in queue', p.name)
this.#processSubtest(p)
} else if (p === EOF) {
this.debug(' > EOF', this.name)
// I AM BECOME EOF, DESTROYER OF STREAMS
this.parser.end()
} else if (p instanceof TestPoint) {
this.debug(' > TESTPOINT')
if (
p.extra.tapChildBuffer ||
p.extra.tapChildBuffer === ''
) {
this.writeSubComment(p)
this.parser.write(p.extra.tapChildBuffer)
}
this.emit('res', p.res)
this.parser.write(p.ok + ++this.#n + p.message)
} else if (typeof p === 'string') {
this.debug(' > STRING')
this.parser.write(p)
} else if (p instanceof Waiter) {
p.ready = true
this.#occupied = p
p.finish()
} else if (Array.isArray(p)) {
this.debug(' > METHOD')
const m = p.shift() as keyof this
if (typeof this[m] !== 'function') {
this.debug(
' > weird method not found in queue??',
m,
typeof this[m]
)
continue
}
const fn = (m === '#end' ? this.#end : this[m]) as (
...a: any[]
) => any
const ret = fn.call(this, ...p)
if (
ret &&
typeof ret === 'object' &&
typeof ret.then === 'function'
) {
// returned promise
ret.then(
() => {
this.#processing = false
this.#process()
},
(er: unknown) => {
this.#processing = false
this.threw(er)
}
)
return
}
/* c8 ignore start */
} else {
throw new Error('weird thing got in the queue')
}
/* c8 ignore stop */
}
while (
!this.#noparallel &&
this.pool.size < this.jobs
) {
const p = this.subtests.shift()
if (!p) {
break
}
if (!p.buffered) {
this.#noparallel = true
break
}
this.debug('start subtest', p)
this.emit('subtestStart', p)
this.pool.add(p)
if (this.bailedOut) {
this.#onBufferedEnd(p)
} else {
p.runMain(() => this.#onBufferedEnd(p))
}
}
this.debug(
'done processing',
this.queue,
this.#occupied
)
this.#processing = false
// just in case any tests ended, and we have sync stuff still
// waiting around in the queue to be processed
if (!this.#occupied && this.queue.length) {
this.#process()
}
}
#onBufferedEnd<T extends Base>(p: T) {
p.ondone = p.constructor.prototype.ondone
p.results =
p.results || new FinalResults(true, p.parser)
p.readyToProcess = true
const to = p.options.timeout
const dur =
to && p.passing() ? hrtime.bigint() - p.start : null
if (dur && to && dur > to) {
p.timeout()
} else {
p.setTimeout(0)
}
this.debug(
'%s.#onBufferedEnd',
this.name,
p.name,
p.results.bailout
)
this.pool.delete(p)
p.options.tapChildBuffer = p.output || ''
p.options.stack = ''
if (p.time) p.options.time = p.time
if (this.#occupied === p) this.#occupied = null
p.deferred?.resolve(p.results)
this.emit('subtestEnd', p)
this.#process()
}
#onIndentedEnd<T extends Base>(p: T) {
this.emit('subtestProcess', p)
p.ondone = p.constructor.prototype.ondone
p.results =
p.results || new FinalResults(true, p.parser)
this.debug('#onIndentedEnd', this.name, p.name)
this.#noparallel = false
const sti = this.subtests.indexOf(p)
if (sti !== -1) this.subtests.splice(sti, 1)
p.readyToProcess = true
p.options.time = p.time
const to = p.options.timeout
const dur =
to && p.passing() ? hrtime.bigint() - p.start : null
if (dur && to && dur > to) {
p.timeout()
} else {
p.setTimeout(0)
}
this.debug('#onIndentedEnd %s(%s)', this.name, p.name)
this.#occupied = null
this.debug(
'OIE(%s) b>shift into queue',
this.name,
this.queue
)
p.options.stack = ''
this.printResult(p.passing(), p.name, p.options, true)
this.debug(
'OIE(%s) shifted into queue',
this.name,
this.queue
)
p.deferred?.resolve(p.results)
this.emit('subtestEnd', p)
this.#process()
}
/**
* @internal
*/
main(cb: () => void) {
if (typeof this.options.timeout === 'number') {
this.setTimeout(this.options.timeout)
}
this.debug('MAIN pre', this)
const end = () => {
this.debug(' > implicit end for promise')
this.#end(IMPLICIT)
done()
}
const done = (er?: Error) => {
if (er) this.threw(er)
if (this.results || this.bailedOut) cb()
else this.ondone = () => cb()
}
// This bit of overly clever line-noise wraps the call to user-code
// in a try-catch. We can't rely on the domain for this yet, because
// the 'end' event can trigger a throw after the domain is unhooked,
// but before this is no longer the official "active test"
const ret = (() => {
if (!this.cb) return
try {
return this.cb(this)
} catch (er: any) {
if (!er || typeof er !== 'object') {
er = { error: er }
}
er.tapCaught = 'testFunctionThrow'
this.threw(er)
}
})()
if (ret && ret.then) {
this.promise = ret
ret.tapAbortPromise = done
ret.then(end, (er: any) => {
if (!er || typeof er !== 'object') {
er = { error: er }
}
er.tapCaught = 'returnedPromiseRejection'
done(er)
})
} else done()
this.debug('MAIN post', this)
}
#processSubtest<T extends Base>(p: T) {
this.debug(' > subtest')
this.#occupied = p
if (!p.buffered) {
this.emit('subtestStart', p)
this.debug(' > subtest indented')
p.stream.pipe(this.parser, { end: false })
this.writeSubComment(p)
this.debug('calling runMain', p.runMain.toString())
p.runMain(() => {
this.debug('in runMain', p.runMain.toString())
this.#onIndentedEnd(p)
})
} else if (p.readyToProcess) {
this.emit('subtestProcess', p)
this.debug(' > subtest buffered, finished')
// finished! do the thing!
this.#occupied = null
if (!p.passing() || !p.silent) {
this.printResult(
p.passing(),
p.name,
p.options,
true
)
}
} else {
this.#occupied = p
this.debug(' > subtest buffered, unfinished', p)
// unfinished buffered test.
// nothing to do yet, just leave it there.
this.queue.unshift(p)
}
}
/**
* Parse stdin as the only tap stream (ie, not as a child test)
* If used, then no other subtests or assertions are allowed.
*/
stdinOnly<T extends BaseOpts>(
extra?: T & { tapStream?: Readable | Minipass }
) {
const stream = ((extra && extra.tapStream) ||
process.stdin) as Minipass
if (!stream) {
throw new Error(
'cannot read stdin without stdin stream'
)
}
if (
this.queue.length !== 1 ||
this.queue[0] !== 'TAP version 14\n' ||
this.#processing ||
this.results ||
this.#occupied ||
this.pool.size ||
this.subtests.length
) {
throw new Error(
'Cannot use stdinOnly on a test in progress'
)
}
this.#doingStdinOnly = true
this.queue.length = 0
this.parser.on('child', p => {
// pretend to be a rooted parser, so it gets counts.
p.root = p
const t = new Base({
name: p.name,
parent: this,
parser: p,
bail: p.bail,
strict: p.strict,
omitVersion: p.omitVersion,
preserveWhitespace: p.preserveWhitespace,
childId: this.#nextChildId++,
})
this.emit('subtestAdd', t)
this.emit('subtestStart', t)
this.emit('subtestProcess', t)
p.on('complete', () => {
t.time = p.time
this.emit('subtestEnd', t)
})
})
stream.pause()
stream.pipe(this.parser)
stream.resume()
}
/**
* Mount a subtest, using this Test object as a harness.
* Exposed mainly so that it can be used by builtin plugins.
*
* @internal
*/
sub<T extends Base, O extends TestBaseOpts>(
Class: { new (options: O): T },
extra: O,
caller: (...a: any[]) => unknown
): Promise<FinalResults | null> {
if (this.bailedOut) return Promise.resolve(null)
if (this.results || this.ended) {
const er = new Error(
'cannot create subtest after parent test ends'
)
Error.captureStackTrace(er, caller)
this.threw(er)
return Promise.resolve(null)
}
extra.childId = this.#nextChildId++
if (this.shouldSkipChild(extra)) {
this.pass(extra.name, extra)
return Promise.resolve(null)
}
extra.indent = ' '
if (extra.buffered !== undefined) {
if (this.jobs > 1) {
extra.buffered = true
} else {
extra.buffered = false
}
}
extra.bail =
extra.bail !== undefined ? extra.bail : this.bail
extra.parent = this
extra.stack = stack.captureString(80, caller)
extra.context = this.context
const t = new Class(extra)
this.queue.push(t)
this.subtests.push(t)
this.emit('subtestAdd', t)
const d = new Deferred<FinalResults>()
t.deferred = d
this.#process()
return d.promise
}
/**
* Return true if the child test represented by the options object
* should be skipped. Extended by the grep/only filtering plugins.
*/
shouldSkipChild(extra: { [k: string]: any }) {
return !!(extra.skip || extra.todo)
}
// end flow control methods
}
|
src/test-base.ts
|
tapjs-core-edd7403
|
[
{
"filename": "src/extra-from-error.ts",
"retrieved_chunk": " file,\n line: er.loc.line,\n column: er.loc.column + 1,\n }\n } else {\n // parse out the 'at' bit from the first line.\n extra.at = stack.parseLine(splitst[1])\n }\n extra.stack = stack.clean(splitst)\n }",
"score": 0.8293133974075317
},
{
"filename": "src/clean-yaml-object.ts",
"retrieved_chunk": " const res = { ...object }\n if (hasOwn(res, 'stack') && !hasOwn(res, 'at')) {\n res.at = stack.parseLine(res.stack.split('\\n')[0])\n }\n const file = res.at && res.at.file && resolve(res.at.file)\n if (\n !options.stackIncludesTap &&\n file &&\n file.includes(tapDir)\n ) {",
"score": 0.8174048066139221
},
{
"filename": "src/test-point.ts",
"retrieved_chunk": " message += ' ' + esc(extra.skip)\n }\n } else if (extra.todo) {\n message += ' # TODO'\n if (typeof extra.todo === 'string') {\n message += ' ' + esc(extra.todo)\n }\n } else if (extra.time) {\n message += ' # time=' + extra.time + 'ms'\n }",
"score": 0.8101541996002197
},
{
"filename": "src/base.ts",
"retrieved_chunk": " er.stack.split(/\\n/).slice(1).join('\\n')\n )\n console.error(extra)\n }\n } else {\n this.parser.ok = false\n }\n return extra\n }\n passing() {",
"score": 0.8094014525413513
},
{
"filename": "src/parse-test-args.ts",
"retrieved_chunk": " (typeof arg === 'string' || typeof arg === 'number')\n )\n name = '' + arg\n else if (arg && typeof arg === 'object') {\n extra = arg\n if (name === undefined) name = null\n } else if (typeof arg === 'function') {\n if (extra === undefined) extra = {}\n if (name === undefined) name = null\n cb = arg",
"score": 0.8067337274551392
}
] |
typescript
|
= stack.captureString(80, fn)
}
|
import stack from './stack'
import type {BaseOpts} from './base'
export default (er:any, extra?:{[k: string]:any}, options?:BaseOpts) => {
// the yaml module puts big stuff here, pluck it off
if (er.source && typeof er.source === 'object' && er.source.context)
er.source = { ...er.source, context: null }
// pull out all fields from options, other than anything starting
// with tapChild, or anything already set in the extra object.
extra = Object.fromEntries(Object.entries(options || {}).filter(([k]) =>
!/^tapChild/.test(k) && !(k in (extra || {}))))
if (!er || typeof er !== 'object') {
extra.error = er
return extra
}
// pull out error details
const message = er.message ? er.message
: er.stack ? er.stack.split('\n')[0]
: ''
if (er.message) {
try {
Object.defineProperty(er, 'message', {
value: '',
configurable: true
})
} catch {}
}
const st = er.stack && er.stack.substr(
er._babel ? (message + er.codeFrame).length : 0)
if (st) {
const splitst = st.split('\n')
if (er._babel && er.loc) {
const msplit = message.split(': ')
const f = msplit[0].trim()
extra.message = msplit.slice(1).join(': ')
.replace(/ \([0-9]+:[0-9]+\)$/, '').trim()
const file = f.indexOf(process.cwd()) === 0
? f.substr(process.cwd().length + 1) : f
if (file !== 'unknown')
delete er.codeFrame
extra.at = {
file,
line: er.loc.line,
column: er.loc.column + 1,
}
} else {
// parse out the 'at' bit from the first line.
extra.at = stack.parseLine(splitst[1])
}
extra.stack = stack
|
.clean(splitst)
}
|
if (message) {
try {
Object.defineProperty(er, 'message', {
value: message,
configurable: true
})
} catch {}
}
if (er.name && er.name !== 'Error') {
extra.type = er.name
}
Object.assign(extra, Object.fromEntries(Object.entries(er).filter(([k]) =>
k !== 'message')))
return extra
}
|
src/extra-from-error.ts
|
tapjs-core-edd7403
|
[
{
"filename": "src/test-base.ts",
"retrieved_chunk": " extra.at = stack.parseLine(extra.stack.split('\\n')[0])\n }\n if (\n !ok &&\n !extra.skip &&\n !extra.at &&\n typeof fn === 'function'\n ) {\n extra.at = stack.at(fn)\n if (!extra.todo) {",
"score": 0.8831754922866821
},
{
"filename": "src/test-base.ts",
"retrieved_chunk": " }\n if (this.assertAt) {\n extra.at = this.assertAt\n this.assertAt = null\n }\n if (this.assertStack) {\n extra.stack = this.assertStack\n this.assertStack = null\n }\n if (typeof extra.stack === 'string' && !extra.at) {",
"score": 0.8503434658050537
},
{
"filename": "src/base.ts",
"retrieved_chunk": " er.stack.split(/\\n/).slice(1).join('\\n')\n )\n console.error(extra)\n }\n } else {\n this.parser.ok = false\n }\n return extra\n }\n passing() {",
"score": 0.8346441388130188
},
{
"filename": "src/clean-yaml-object.ts",
"retrieved_chunk": " const res = { ...object }\n if (hasOwn(res, 'stack') && !hasOwn(res, 'at')) {\n res.at = stack.parseLine(res.stack.split('\\n')[0])\n }\n const file = res.at && res.at.file && resolve(res.at.file)\n if (\n !options.stackIncludesTap &&\n file &&\n file.includes(tapDir)\n ) {",
"score": 0.8277758955955505
},
{
"filename": "src/base.ts",
"retrieved_chunk": " } else if (!er.stack) {\n console.error(er)\n } else {\n if (message) {\n er.message = message\n }\n delete extra.stack\n delete extra.at\n console.error('%s: %s', er.name || 'Error', message)\n console.error(",
"score": 0.82011878490448
}
] |
typescript
|
.clean(splitst)
}
|
// lifecycle methods like beforeEach, afterEach, teardown
// defined in plugins/lifecycle.ts
import Minipass from 'minipass'
import assert from 'node:assert'
import { hrtime } from 'node:process'
import { Readable } from 'node:stream'
import { format } from 'node:util'
import { CallSiteLike } from 'stack-utils'
import { FinalResults } from 'tap-parser'
import Deferred from 'trivial-deferred'
import { Base, BaseOpts } from './base.js'
import { esc } from './esc.js'
import stack from './stack.js'
import { TestPoint } from './test-point.js'
import { Waiter } from './waiter.js'
const queueEmpty = <T extends TestBase>(t: T) =>
t.queue.length === 0 ||
(t.queue.length === 1 &&
t.queue[0] === 'TAP version 14\n')
export interface ClassOf<T> {
new (): T
}
export type TapPlugin<
B extends Object,
O extends TestBaseOpts | any = any
> = ((t: TestBase, opts: O) => B) | ((t: TestBase) => B)
export interface TestBaseOpts extends BaseOpts {
/**
* The number of jobs to run in parallel. Defaults to 1
*/
jobs?: number
/**
* Test function called when this Test is executed
*/
cb?: (...args: any[]) => any
/**
* Flag to always/never show diagnostics. If unset, then
* diagnostics are shown for failing test points only.
*/
diagnostic?: boolean
}
const normalizeMessageExtra = (
defaultMessage: string,
message?: string | { [k: string]: any },
extra?: { [k: string]: any }
): [string, { [k: string]: any }] => {
if (typeof message === 'string') {
return [message || defaultMessage, extra || {}]
} else {
return [defaultMessage, message || {}]
}
}
/**
* Sigil for implicit end() calls that should not
* trigger an error if the user then calls t.end()
*/
const IMPLICIT = Symbol('implicit end')
/**
* Sigil to put in the queue to signal the end of all things
*/
const EOF = Symbol('EOF')
export type QueueEntry =
| string
| TestPoint
| Base
| typeof EOF
| Waiter
| [method: string, ...args: any[]]
/**
* The TestBaseBase class is the base class for all plugins,
* and eventually thus the Test class.
*
* This implements subtest functionality, TAP stream generation,
* lifecycle events, and only the most basic pass/fail assertions.
*
* All other features are added with plugins.
*/
export class TestBase extends Base {
// NB: generated pluginified Test class needs to declare over this
declare parent?: TestBase
promise?: Promise<any>
jobs: number
// #beforeEnd: [method: string | Symbol, ...args: any[]][] = []
subtests: Base[] = []
pool: Set<Base> = new Set()
queue: QueueEntry[] = ['TAP version 14\n']
cb?: (...args: any[]) => any
count: number = 0
ended: boolean = false
assertAt: CallSiteLike | null = null
assertStack: string | null = null
diagnostic: null | boolean = null
#planEnd: number = -1
#printedResult: boolean = false
#explicitEnded: boolean = false
#multiEndThrew: boolean = false
#n: number = 0
#noparallel: boolean = false
#occupied: null | Waiter | Base = null
#pushedEnd: boolean = false
#nextChildId: number = 1
#currentAssert: null | ((..._: any) => any) = null
#processing: boolean = false
#doingStdinOnly: boolean = false
/**
* true if the test has printed at least one TestPoint
*/
get printedResult(): boolean {
return this.#printedResult
}
constructor(options: TestBaseOpts) {
super(options)
this.jobs =
(options.jobs && Math.max(options.jobs, 1)) || 1
if (typeof options.diagnostic === 'boolean') {
this.diagnostic = options.diagnostic
}
if (options.cb) {
this.#setCB(options.cb)
}
}
#setCB<T extends TestBase>(this: T, cb: (t: T) => any) {
this.cb = (...args: any[]) =>
this.hook.runInAsyncScope(cb, this, ...args)
}
// TAP output generating methods
/**
* immediately exit this and all parent tests with a TAP
* Bail out! message.
*/
bailout(message?: string) {
if (this.parent && (this.results || this.ended)) {
this.parent.bailout(message)
} else {
this.#process()
message = message
? ' ' + ('' + esc(message)).trim()
: ''
message = message.replace(/[\r\n]/g, ' ')
this.parser.write('Bail out!' + message + '\n')
}
this.#end(IMPLICIT)
this.#process()
}
/**
* output a TAP comment, formatted like console.log()
*/
comment(...args: any[]) {
const body = format(...args)
const message =
('# ' + body.split(/\r?\n/).join('\n# ')).trim() +
'\n'
if (this.results) {
this.write(message)
} else {
this.queue.push(message)
}
this.#process()
}
/**
* Called when the test times out.
* Options are passed as diagnostics to the threw() method
*/
timeout(options: { [k: string]: any }) {
options = options || {}
options.expired = options.expired || this.name
if (this.#occupied && this.#occupied instanceof Base) {
this
|
.#occupied.timeout(options)
} else {
|
super.timeout(options)
}
this.#end(IMPLICIT)
}
/**
* Set TAP pragma configs to affect the behavior of the parser.
* Only `strict` is supported by the parser.
*/
pragma(set: { [k: string]: boolean }) {
const p = Object.keys(set).reduce(
(acc, i) =>
acc + 'pragma ' + (set[i] ? '+' : '-') + i + '\n',
''
)
this.queue.push(p)
this.#process()
}
/**
* Specify the number of Test Points expected by this test.
* Outputs a TAP plan line.
*/
plan(n: number, comment?: string) {
if (this.bailedOut) {
return
}
if (this.#planEnd !== -1) {
throw new Error('Cannot set plan more than once')
}
if (typeof n !== 'number' || n < 0) {
throw new TypeError('plan must be a number')
}
// Cannot get any tests after a trailing plan, or a plan of 0
const ending = this.count !== 0 || n === 0
if (n === 0 && comment && !this.options.skip) {
this.options.skip = comment
}
this.#planEnd = n
comment = comment ? ' # ' + esc(comment.trim()) : ''
this.queue.push('1..' + n + comment + '\n')
if (ending) {
this.#end(IMPLICIT)
} else {
this.#process()
}
}
/**
* A passing (ok) Test Point
*/
pass(message?: string, extra?: { [k: string]: any }) {
this.currentAssert = TestBase.prototype.pass
this.printResult(
true,
...normalizeMessageExtra(
'(unnamed test)',
message,
extra
)
)
return true
}
/**
* A failing (not ok) Test Point
*/
fail(message?: string, extra?: { [k: string]: any }) {
this.currentAssert = TestBase.prototype.fail
const [m, e] = normalizeMessageExtra(
'(unnamed test)',
message,
extra
)
this.printResult(false, m, e)
return !!(e.todo || e.skip)
}
/**
* The current assertion being processed. May only be set if
* not already set.
*/
get currentAssert() {
return this.#currentAssert
}
/**
* The current assertion being processed. May only be set if
* not already set.
*/
set currentAssert(fn: null | ((...a: any[]) => any)) {
if (!this.#currentAssert && typeof fn === 'function') {
this.#currentAssert = fn
}
}
/**
* Print a Test Point
*/
printResult(
ok: boolean,
message: string,
extra: { [k: string]: any },
front: boolean = false
) {
this.#printedResult = true
const n = this.count + 1
this.currentAssert = TestBase.prototype.printResult
const fn = this.#currentAssert
this.#currentAssert = null
if (this.#planEnd !== -1 && n > this.#planEnd) {
if (!this.passing()) return
const failMessage = this.#explicitEnded
? 'test after end() was called'
: 'test count exceeds plan'
const er = new Error(failMessage, {
cause: {
test: this.name,
plan: this.#planEnd,
},
})
Error.captureStackTrace(er, fn || undefined)
this.threw(er)
return
}
extra = extra || {}
if (extra.expectFail) {
ok = !ok
}
if (this.assertAt) {
extra.at = this.assertAt
this.assertAt = null
}
if (this.assertStack) {
extra.stack = this.assertStack
this.assertStack = null
}
if (typeof extra.stack === 'string' && !extra.at) {
extra.at = stack.parseLine(extra.stack.split('\n')[0])
}
if (
!ok &&
!extra.skip &&
!extra.at &&
typeof fn === 'function'
) {
extra.at = stack.at(fn)
if (!extra.todo) {
extra.stack = stack.captureString(80, fn)
}
}
const diagnostic =
typeof extra.diagnostic === 'boolean'
? extra.diagnostic
: typeof this.diagnostic === 'boolean'
? this.diagnostic
: extra.skip || extra.todo
? false
: !ok
if (diagnostic) {
extra.diagnostic = true
}
this.count = n
message = message + ''
const res = { ok, message, extra }
const tp = new TestPoint(ok, message, extra)
// when we jump the queue, skip an extra line
if (front) {
tp.message = tp.message.trimEnd() + '\n\n'
}
if (
this.#occupied &&
this.#occupied instanceof Waiter &&
this.#occupied.finishing
) {
front = true
}
if (front) {
if (
extra.tapChildBuffer ||
extra.tapChildBuffer === ''
) {
this.writeSubComment(tp)
this.parser.write(extra.tapChildBuffer)
}
this.emit('result', res)
this.parser.write(tp.ok + ++this.#n + tp.message)
if (this.bail && !ok && !extra.skip && !extra.todo) {
this.parser.write('Bail out! ' + message + '\n')
}
} else {
this.queue.push(tp)
if (this.bail && !ok && !extra.skip && !extra.todo) {
this.queue.push('Bail out! ' + message + '\n')
}
}
if (this.#planEnd === this.count) {
this.#end(IMPLICIT)
}
this.#process()
}
end(): this {
this.#end()
return super.end()
}
/**
* The leading `# Subtest` comment that introduces a child test
*/
writeSubComment<T extends TestPoint | Base>(p: T) {
const comment =
'# Subtest' +
(p.name ? ': ' + esc(p.name) : '') +
'\n'
this.parser.write(comment)
}
// end TAP otput generating methods
// flow control methods
/**
* Await the end of a Promise before proceeding.
* The supplied callback is called with the Waiter object.
*/
waitOn(
promise: Promise<any | void>,
cb: (w: Waiter) => any,
expectReject: boolean = false
): Promise<void> {
const w = new Waiter(
promise,
w => {
assert.equal(this.#occupied, w)
cb(w)
this.#occupied = null
this.#process()
},
expectReject
)
this.queue.push(w)
this.#process()
return w.promise
}
#end(implicit?: typeof IMPLICIT) {
if (this.#doingStdinOnly && implicit !== IMPLICIT)
throw new Error(
'cannot explicitly end while in stdinOnly mode'
)
this.debug('END implicit=%j', implicit === IMPLICIT)
if (this.ended && implicit === IMPLICIT) return
// beyond here we have to be actually done with things, or else
// the semantic checks on counts and such will be off.
if (!queueEmpty(this) || this.#occupied) {
if (!this.#pushedEnd) {
this.queue.push(['#end', implicit])
}
this.#pushedEnd = true
return this.#process()
}
this.ended = true
if (implicit !== IMPLICIT && !this.#multiEndThrew) {
if (this.#explicitEnded) {
this.#multiEndThrew = true
const er = new Error(
'test end() method called more than once'
)
Error.captureStackTrace(
er,
this.#currentAssert || this.#end
)
er.cause = {
test: this.name,
}
this.threw(er)
return
}
this.#explicitEnded = true
}
if (this.#planEnd === -1) {
this.debug(
'END(%s) implicit plan',
this.name,
this.count
)
this.plan(this.count)
}
this.queue.push(EOF)
this.#process()
}
#process() {
if (this.#processing) {
return this.debug(' < already processing')
}
this.debug(
'\nPROCESSING(%s)',
this.name,
this.queue.length
)
this.#processing = true
while (!this.#occupied) {
const p = this.queue.shift()
if (!p) {
this.debug('> end of queue')
break
}
if (p instanceof Base) {
this.debug('> subtest in queue', p.name)
this.#processSubtest(p)
} else if (p === EOF) {
this.debug(' > EOF', this.name)
// I AM BECOME EOF, DESTROYER OF STREAMS
this.parser.end()
} else if (p instanceof TestPoint) {
this.debug(' > TESTPOINT')
if (
p.extra.tapChildBuffer ||
p.extra.tapChildBuffer === ''
) {
this.writeSubComment(p)
this.parser.write(p.extra.tapChildBuffer)
}
this.emit('res', p.res)
this.parser.write(p.ok + ++this.#n + p.message)
} else if (typeof p === 'string') {
this.debug(' > STRING')
this.parser.write(p)
} else if (p instanceof Waiter) {
p.ready = true
this.#occupied = p
p.finish()
} else if (Array.isArray(p)) {
this.debug(' > METHOD')
const m = p.shift() as keyof this
if (typeof this[m] !== 'function') {
this.debug(
' > weird method not found in queue??',
m,
typeof this[m]
)
continue
}
const fn = (m === '#end' ? this.#end : this[m]) as (
...a: any[]
) => any
const ret = fn.call(this, ...p)
if (
ret &&
typeof ret === 'object' &&
typeof ret.then === 'function'
) {
// returned promise
ret.then(
() => {
this.#processing = false
this.#process()
},
(er: unknown) => {
this.#processing = false
this.threw(er)
}
)
return
}
/* c8 ignore start */
} else {
throw new Error('weird thing got in the queue')
}
/* c8 ignore stop */
}
while (
!this.#noparallel &&
this.pool.size < this.jobs
) {
const p = this.subtests.shift()
if (!p) {
break
}
if (!p.buffered) {
this.#noparallel = true
break
}
this.debug('start subtest', p)
this.emit('subtestStart', p)
this.pool.add(p)
if (this.bailedOut) {
this.#onBufferedEnd(p)
} else {
p.runMain(() => this.#onBufferedEnd(p))
}
}
this.debug(
'done processing',
this.queue,
this.#occupied
)
this.#processing = false
// just in case any tests ended, and we have sync stuff still
// waiting around in the queue to be processed
if (!this.#occupied && this.queue.length) {
this.#process()
}
}
#onBufferedEnd<T extends Base>(p: T) {
p.ondone = p.constructor.prototype.ondone
p.results =
p.results || new FinalResults(true, p.parser)
p.readyToProcess = true
const to = p.options.timeout
const dur =
to && p.passing() ? hrtime.bigint() - p.start : null
if (dur && to && dur > to) {
p.timeout()
} else {
p.setTimeout(0)
}
this.debug(
'%s.#onBufferedEnd',
this.name,
p.name,
p.results.bailout
)
this.pool.delete(p)
p.options.tapChildBuffer = p.output || ''
p.options.stack = ''
if (p.time) p.options.time = p.time
if (this.#occupied === p) this.#occupied = null
p.deferred?.resolve(p.results)
this.emit('subtestEnd', p)
this.#process()
}
#onIndentedEnd<T extends Base>(p: T) {
this.emit('subtestProcess', p)
p.ondone = p.constructor.prototype.ondone
p.results =
p.results || new FinalResults(true, p.parser)
this.debug('#onIndentedEnd', this.name, p.name)
this.#noparallel = false
const sti = this.subtests.indexOf(p)
if (sti !== -1) this.subtests.splice(sti, 1)
p.readyToProcess = true
p.options.time = p.time
const to = p.options.timeout
const dur =
to && p.passing() ? hrtime.bigint() - p.start : null
if (dur && to && dur > to) {
p.timeout()
} else {
p.setTimeout(0)
}
this.debug('#onIndentedEnd %s(%s)', this.name, p.name)
this.#occupied = null
this.debug(
'OIE(%s) b>shift into queue',
this.name,
this.queue
)
p.options.stack = ''
this.printResult(p.passing(), p.name, p.options, true)
this.debug(
'OIE(%s) shifted into queue',
this.name,
this.queue
)
p.deferred?.resolve(p.results)
this.emit('subtestEnd', p)
this.#process()
}
/**
* @internal
*/
main(cb: () => void) {
if (typeof this.options.timeout === 'number') {
this.setTimeout(this.options.timeout)
}
this.debug('MAIN pre', this)
const end = () => {
this.debug(' > implicit end for promise')
this.#end(IMPLICIT)
done()
}
const done = (er?: Error) => {
if (er) this.threw(er)
if (this.results || this.bailedOut) cb()
else this.ondone = () => cb()
}
// This bit of overly clever line-noise wraps the call to user-code
// in a try-catch. We can't rely on the domain for this yet, because
// the 'end' event can trigger a throw after the domain is unhooked,
// but before this is no longer the official "active test"
const ret = (() => {
if (!this.cb) return
try {
return this.cb(this)
} catch (er: any) {
if (!er || typeof er !== 'object') {
er = { error: er }
}
er.tapCaught = 'testFunctionThrow'
this.threw(er)
}
})()
if (ret && ret.then) {
this.promise = ret
ret.tapAbortPromise = done
ret.then(end, (er: any) => {
if (!er || typeof er !== 'object') {
er = { error: er }
}
er.tapCaught = 'returnedPromiseRejection'
done(er)
})
} else done()
this.debug('MAIN post', this)
}
#processSubtest<T extends Base>(p: T) {
this.debug(' > subtest')
this.#occupied = p
if (!p.buffered) {
this.emit('subtestStart', p)
this.debug(' > subtest indented')
p.stream.pipe(this.parser, { end: false })
this.writeSubComment(p)
this.debug('calling runMain', p.runMain.toString())
p.runMain(() => {
this.debug('in runMain', p.runMain.toString())
this.#onIndentedEnd(p)
})
} else if (p.readyToProcess) {
this.emit('subtestProcess', p)
this.debug(' > subtest buffered, finished')
// finished! do the thing!
this.#occupied = null
if (!p.passing() || !p.silent) {
this.printResult(
p.passing(),
p.name,
p.options,
true
)
}
} else {
this.#occupied = p
this.debug(' > subtest buffered, unfinished', p)
// unfinished buffered test.
// nothing to do yet, just leave it there.
this.queue.unshift(p)
}
}
/**
* Parse stdin as the only tap stream (ie, not as a child test)
* If used, then no other subtests or assertions are allowed.
*/
stdinOnly<T extends BaseOpts>(
extra?: T & { tapStream?: Readable | Minipass }
) {
const stream = ((extra && extra.tapStream) ||
process.stdin) as Minipass
if (!stream) {
throw new Error(
'cannot read stdin without stdin stream'
)
}
if (
this.queue.length !== 1 ||
this.queue[0] !== 'TAP version 14\n' ||
this.#processing ||
this.results ||
this.#occupied ||
this.pool.size ||
this.subtests.length
) {
throw new Error(
'Cannot use stdinOnly on a test in progress'
)
}
this.#doingStdinOnly = true
this.queue.length = 0
this.parser.on('child', p => {
// pretend to be a rooted parser, so it gets counts.
p.root = p
const t = new Base({
name: p.name,
parent: this,
parser: p,
bail: p.bail,
strict: p.strict,
omitVersion: p.omitVersion,
preserveWhitespace: p.preserveWhitespace,
childId: this.#nextChildId++,
})
this.emit('subtestAdd', t)
this.emit('subtestStart', t)
this.emit('subtestProcess', t)
p.on('complete', () => {
t.time = p.time
this.emit('subtestEnd', t)
})
})
stream.pause()
stream.pipe(this.parser)
stream.resume()
}
/**
* Mount a subtest, using this Test object as a harness.
* Exposed mainly so that it can be used by builtin plugins.
*
* @internal
*/
sub<T extends Base, O extends TestBaseOpts>(
Class: { new (options: O): T },
extra: O,
caller: (...a: any[]) => unknown
): Promise<FinalResults | null> {
if (this.bailedOut) return Promise.resolve(null)
if (this.results || this.ended) {
const er = new Error(
'cannot create subtest after parent test ends'
)
Error.captureStackTrace(er, caller)
this.threw(er)
return Promise.resolve(null)
}
extra.childId = this.#nextChildId++
if (this.shouldSkipChild(extra)) {
this.pass(extra.name, extra)
return Promise.resolve(null)
}
extra.indent = ' '
if (extra.buffered !== undefined) {
if (this.jobs > 1) {
extra.buffered = true
} else {
extra.buffered = false
}
}
extra.bail =
extra.bail !== undefined ? extra.bail : this.bail
extra.parent = this
extra.stack = stack.captureString(80, caller)
extra.context = this.context
const t = new Class(extra)
this.queue.push(t)
this.subtests.push(t)
this.emit('subtestAdd', t)
const d = new Deferred<FinalResults>()
t.deferred = d
this.#process()
return d.promise
}
/**
* Return true if the child test represented by the options object
* should be skipped. Extended by the grep/only filtering plugins.
*/
shouldSkipChild(extra: { [k: string]: any }) {
return !!(extra.skip || extra.todo)
}
// end flow control methods
}
|
src/test-base.ts
|
tapjs-core-edd7403
|
[
{
"filename": "src/base.ts",
"retrieved_chunk": " this.setTimeout(0)\n options = options || {}\n options.expired = options.expired || this.name\n const threw = this.threw(new Error('timeout!'), options)\n if (threw) {\n this.emit('timeout', threw)\n }\n }\n runMain(cb: () => void) {\n this.debug('BASE runMain')",
"score": 0.8292765617370605
},
{
"filename": "src/spawn.ts",
"retrieved_chunk": " !this.options.signal &&\n this.options.exitCode === undefined\n ) {\n super.timeout(options)\n this.proc.kill('SIGKILL')\n }\n }, 1000)\n t.unref()\n }\n }",
"score": 0.8146418929100037
},
{
"filename": "src/base.ts",
"retrieved_chunk": " if (this.timer) {\n clearTimeout(this.timer)\n }\n this.timer = undefined\n } else {\n this.timer = setTimeout(() => this.timeout(), n)\n this.timer.unref()\n }\n }\n timeout(options?: { [k: string]: any }) {",
"score": 0.8059505224227905
},
{
"filename": "src/stdin.ts",
"retrieved_chunk": " }\n threw(er: any, extra?: any, proxy?: boolean) {\n extra = super.threw(er, extra, proxy)\n Object.assign(this.options, extra)\n this.parser.abort(er.message, extra)\n this.parser.end()\n }\n}",
"score": 0.8011005520820618
},
{
"filename": "src/spawn.ts",
"retrieved_chunk": " this.parser.ok = false\n }\n return this.callCb()\n }\n timeout(options?: { [k: string]: any }) {\n if (this.proc) {\n this.proc.kill('SIGTERM')\n const t = setTimeout(() => {\n if (\n this.proc &&",
"score": 0.789941668510437
}
] |
typescript
|
.#occupied.timeout(options)
} else {
|
// lifecycle methods like beforeEach, afterEach, teardown
// defined in plugins/lifecycle.ts
import Minipass from 'minipass'
import assert from 'node:assert'
import { hrtime } from 'node:process'
import { Readable } from 'node:stream'
import { format } from 'node:util'
import { CallSiteLike } from 'stack-utils'
import { FinalResults } from 'tap-parser'
import Deferred from 'trivial-deferred'
import { Base, BaseOpts } from './base.js'
import { esc } from './esc.js'
import stack from './stack.js'
import { TestPoint } from './test-point.js'
import { Waiter } from './waiter.js'
const queueEmpty = <T extends TestBase>(t: T) =>
t.queue.length === 0 ||
(t.queue.length === 1 &&
t.queue[0] === 'TAP version 14\n')
export interface ClassOf<T> {
new (): T
}
export type TapPlugin<
B extends Object,
O extends TestBaseOpts | any = any
> = ((t: TestBase, opts: O) => B) | ((t: TestBase) => B)
export interface TestBaseOpts extends BaseOpts {
/**
* The number of jobs to run in parallel. Defaults to 1
*/
jobs?: number
/**
* Test function called when this Test is executed
*/
cb?: (...args: any[]) => any
/**
* Flag to always/never show diagnostics. If unset, then
* diagnostics are shown for failing test points only.
*/
diagnostic?: boolean
}
const normalizeMessageExtra = (
defaultMessage: string,
message?: string | { [k: string]: any },
extra?: { [k: string]: any }
): [string, { [k: string]: any }] => {
if (typeof message === 'string') {
return [message || defaultMessage, extra || {}]
} else {
return [defaultMessage, message || {}]
}
}
/**
* Sigil for implicit end() calls that should not
* trigger an error if the user then calls t.end()
*/
const IMPLICIT = Symbol('implicit end')
/**
* Sigil to put in the queue to signal the end of all things
*/
const EOF = Symbol('EOF')
export type QueueEntry =
| string
| TestPoint
| Base
| typeof EOF
| Waiter
| [method: string, ...args: any[]]
/**
* The TestBaseBase class is the base class for all plugins,
* and eventually thus the Test class.
*
* This implements subtest functionality, TAP stream generation,
* lifecycle events, and only the most basic pass/fail assertions.
*
* All other features are added with plugins.
*/
export class TestBase extends Base {
// NB: generated pluginified Test class needs to declare over this
declare parent?: TestBase
promise?: Promise<any>
jobs: number
// #beforeEnd: [method: string | Symbol, ...args: any[]][] = []
subtests: Base[] = []
pool: Set<Base> = new Set()
queue: QueueEntry[] = ['TAP version 14\n']
cb?: (...args: any[]) => any
count: number = 0
ended: boolean = false
assertAt: CallSiteLike | null = null
assertStack: string | null = null
diagnostic: null | boolean = null
#planEnd: number = -1
#printedResult: boolean = false
#explicitEnded: boolean = false
#multiEndThrew: boolean = false
#n: number = 0
#noparallel: boolean = false
#occupied: null | Waiter | Base = null
#pushedEnd: boolean = false
#nextChildId: number = 1
#currentAssert: null | ((..._: any) => any) = null
#processing: boolean = false
#doingStdinOnly: boolean = false
/**
* true if the test has printed at least one TestPoint
*/
get printedResult(): boolean {
return this.#printedResult
}
constructor(options: TestBaseOpts) {
super(options)
this.jobs =
(options.jobs && Math.max(options.jobs, 1)) || 1
if (typeof options.diagnostic === 'boolean') {
this.diagnostic = options.diagnostic
}
if (options.cb) {
this.#setCB(options.cb)
}
}
#setCB<T extends TestBase>(this: T, cb: (t: T) => any) {
this.cb = (...args: any[]) =>
this.hook.runInAsyncScope(cb, this, ...args)
}
// TAP output generating methods
/**
* immediately exit this and all parent tests with a TAP
* Bail out! message.
*/
bailout(message?: string) {
if (this.parent && (this.results || this.ended)) {
this.parent.bailout(message)
} else {
this.#process()
message = message
? ' ' + ('' + esc(message)).trim()
: ''
message = message.replace(/[\r\n]/g, ' ')
this.parser.write('Bail out!' + message + '\n')
}
this.#end(IMPLICIT)
this.#process()
}
/**
* output a TAP comment, formatted like console.log()
*/
comment(...args: any[]) {
const body = format(...args)
const message =
('# ' + body.split(/\r?\n/).join('\n# ')).trim() +
'\n'
if (this.results) {
this.write(message)
} else {
this.queue.push(message)
}
this.#process()
}
/**
* Called when the test times out.
* Options are passed as diagnostics to the threw() method
*/
timeout(options: { [k: string]: any }) {
options = options || {}
options.expired = options.expired || this.name
if (this.#occupied && this.#occupied instanceof Base) {
this.#occupied.timeout(options)
} else {
super.timeout(options)
}
this.#end(IMPLICIT)
}
/**
* Set TAP pragma configs to affect the behavior of the parser.
* Only `strict` is supported by the parser.
*/
pragma(set: { [k: string]: boolean }) {
const p = Object.keys(set).reduce(
(acc, i) =>
acc + 'pragma ' + (set[i] ? '+' : '-') + i + '\n',
''
)
this.queue.push(p)
this.#process()
}
/**
* Specify the number of Test Points expected by this test.
* Outputs a TAP plan line.
*/
plan(n: number, comment?: string) {
if (this.bailedOut) {
return
}
if (this.#planEnd !== -1) {
throw new Error('Cannot set plan more than once')
}
if (typeof n !== 'number' || n < 0) {
throw new TypeError('plan must be a number')
}
// Cannot get any tests after a trailing plan, or a plan of 0
const ending = this.count !== 0 || n === 0
if (n === 0 && comment && !this.options.skip) {
this.options.skip = comment
}
this.#planEnd = n
comment = comment ? ' # ' + esc(comment.trim()) : ''
this.queue.push('1..' + n + comment + '\n')
if (ending) {
this.#end(IMPLICIT)
} else {
this.#process()
}
}
/**
* A passing (ok) Test Point
*/
pass(message?: string, extra?: { [k: string]: any }) {
this.currentAssert = TestBase.prototype.pass
this.printResult(
true,
...normalizeMessageExtra(
'(unnamed test)',
message,
extra
)
)
return true
}
/**
* A failing (not ok) Test Point
*/
fail(message?: string, extra?: { [k: string]: any }) {
this.currentAssert = TestBase.prototype.fail
const [m, e] = normalizeMessageExtra(
'(unnamed test)',
message,
extra
)
this.printResult(false, m, e)
return !!(e.todo || e.skip)
}
/**
* The current assertion being processed. May only be set if
* not already set.
*/
get currentAssert() {
return this.#currentAssert
}
/**
* The current assertion being processed. May only be set if
* not already set.
*/
set currentAssert(fn: null | ((...a: any[]) => any)) {
if (!this.#currentAssert && typeof fn === 'function') {
this.#currentAssert = fn
}
}
/**
* Print a Test Point
*/
printResult(
ok: boolean,
message: string,
extra: { [k: string]: any },
front: boolean = false
) {
this.#printedResult = true
const n = this.count + 1
this.currentAssert = TestBase.prototype.printResult
const fn = this.#currentAssert
this.#currentAssert = null
if (this.#planEnd !== -1 && n > this.#planEnd) {
if (!this.passing()) return
const failMessage = this.#explicitEnded
? 'test after end() was called'
: 'test count exceeds plan'
const er = new Error(failMessage, {
cause: {
test: this.name,
plan: this.#planEnd,
},
})
Error.captureStackTrace(er, fn || undefined)
|
this.threw(er)
return
}
|
extra = extra || {}
if (extra.expectFail) {
ok = !ok
}
if (this.assertAt) {
extra.at = this.assertAt
this.assertAt = null
}
if (this.assertStack) {
extra.stack = this.assertStack
this.assertStack = null
}
if (typeof extra.stack === 'string' && !extra.at) {
extra.at = stack.parseLine(extra.stack.split('\n')[0])
}
if (
!ok &&
!extra.skip &&
!extra.at &&
typeof fn === 'function'
) {
extra.at = stack.at(fn)
if (!extra.todo) {
extra.stack = stack.captureString(80, fn)
}
}
const diagnostic =
typeof extra.diagnostic === 'boolean'
? extra.diagnostic
: typeof this.diagnostic === 'boolean'
? this.diagnostic
: extra.skip || extra.todo
? false
: !ok
if (diagnostic) {
extra.diagnostic = true
}
this.count = n
message = message + ''
const res = { ok, message, extra }
const tp = new TestPoint(ok, message, extra)
// when we jump the queue, skip an extra line
if (front) {
tp.message = tp.message.trimEnd() + '\n\n'
}
if (
this.#occupied &&
this.#occupied instanceof Waiter &&
this.#occupied.finishing
) {
front = true
}
if (front) {
if (
extra.tapChildBuffer ||
extra.tapChildBuffer === ''
) {
this.writeSubComment(tp)
this.parser.write(extra.tapChildBuffer)
}
this.emit('result', res)
this.parser.write(tp.ok + ++this.#n + tp.message)
if (this.bail && !ok && !extra.skip && !extra.todo) {
this.parser.write('Bail out! ' + message + '\n')
}
} else {
this.queue.push(tp)
if (this.bail && !ok && !extra.skip && !extra.todo) {
this.queue.push('Bail out! ' + message + '\n')
}
}
if (this.#planEnd === this.count) {
this.#end(IMPLICIT)
}
this.#process()
}
end(): this {
this.#end()
return super.end()
}
/**
* The leading `# Subtest` comment that introduces a child test
*/
writeSubComment<T extends TestPoint | Base>(p: T) {
const comment =
'# Subtest' +
(p.name ? ': ' + esc(p.name) : '') +
'\n'
this.parser.write(comment)
}
// end TAP otput generating methods
// flow control methods
/**
* Await the end of a Promise before proceeding.
* The supplied callback is called with the Waiter object.
*/
waitOn(
promise: Promise<any | void>,
cb: (w: Waiter) => any,
expectReject: boolean = false
): Promise<void> {
const w = new Waiter(
promise,
w => {
assert.equal(this.#occupied, w)
cb(w)
this.#occupied = null
this.#process()
},
expectReject
)
this.queue.push(w)
this.#process()
return w.promise
}
#end(implicit?: typeof IMPLICIT) {
if (this.#doingStdinOnly && implicit !== IMPLICIT)
throw new Error(
'cannot explicitly end while in stdinOnly mode'
)
this.debug('END implicit=%j', implicit === IMPLICIT)
if (this.ended && implicit === IMPLICIT) return
// beyond here we have to be actually done with things, or else
// the semantic checks on counts and such will be off.
if (!queueEmpty(this) || this.#occupied) {
if (!this.#pushedEnd) {
this.queue.push(['#end', implicit])
}
this.#pushedEnd = true
return this.#process()
}
this.ended = true
if (implicit !== IMPLICIT && !this.#multiEndThrew) {
if (this.#explicitEnded) {
this.#multiEndThrew = true
const er = new Error(
'test end() method called more than once'
)
Error.captureStackTrace(
er,
this.#currentAssert || this.#end
)
er.cause = {
test: this.name,
}
this.threw(er)
return
}
this.#explicitEnded = true
}
if (this.#planEnd === -1) {
this.debug(
'END(%s) implicit plan',
this.name,
this.count
)
this.plan(this.count)
}
this.queue.push(EOF)
this.#process()
}
#process() {
if (this.#processing) {
return this.debug(' < already processing')
}
this.debug(
'\nPROCESSING(%s)',
this.name,
this.queue.length
)
this.#processing = true
while (!this.#occupied) {
const p = this.queue.shift()
if (!p) {
this.debug('> end of queue')
break
}
if (p instanceof Base) {
this.debug('> subtest in queue', p.name)
this.#processSubtest(p)
} else if (p === EOF) {
this.debug(' > EOF', this.name)
// I AM BECOME EOF, DESTROYER OF STREAMS
this.parser.end()
} else if (p instanceof TestPoint) {
this.debug(' > TESTPOINT')
if (
p.extra.tapChildBuffer ||
p.extra.tapChildBuffer === ''
) {
this.writeSubComment(p)
this.parser.write(p.extra.tapChildBuffer)
}
this.emit('res', p.res)
this.parser.write(p.ok + ++this.#n + p.message)
} else if (typeof p === 'string') {
this.debug(' > STRING')
this.parser.write(p)
} else if (p instanceof Waiter) {
p.ready = true
this.#occupied = p
p.finish()
} else if (Array.isArray(p)) {
this.debug(' > METHOD')
const m = p.shift() as keyof this
if (typeof this[m] !== 'function') {
this.debug(
' > weird method not found in queue??',
m,
typeof this[m]
)
continue
}
const fn = (m === '#end' ? this.#end : this[m]) as (
...a: any[]
) => any
const ret = fn.call(this, ...p)
if (
ret &&
typeof ret === 'object' &&
typeof ret.then === 'function'
) {
// returned promise
ret.then(
() => {
this.#processing = false
this.#process()
},
(er: unknown) => {
this.#processing = false
this.threw(er)
}
)
return
}
/* c8 ignore start */
} else {
throw new Error('weird thing got in the queue')
}
/* c8 ignore stop */
}
while (
!this.#noparallel &&
this.pool.size < this.jobs
) {
const p = this.subtests.shift()
if (!p) {
break
}
if (!p.buffered) {
this.#noparallel = true
break
}
this.debug('start subtest', p)
this.emit('subtestStart', p)
this.pool.add(p)
if (this.bailedOut) {
this.#onBufferedEnd(p)
} else {
p.runMain(() => this.#onBufferedEnd(p))
}
}
this.debug(
'done processing',
this.queue,
this.#occupied
)
this.#processing = false
// just in case any tests ended, and we have sync stuff still
// waiting around in the queue to be processed
if (!this.#occupied && this.queue.length) {
this.#process()
}
}
#onBufferedEnd<T extends Base>(p: T) {
p.ondone = p.constructor.prototype.ondone
p.results =
p.results || new FinalResults(true, p.parser)
p.readyToProcess = true
const to = p.options.timeout
const dur =
to && p.passing() ? hrtime.bigint() - p.start : null
if (dur && to && dur > to) {
p.timeout()
} else {
p.setTimeout(0)
}
this.debug(
'%s.#onBufferedEnd',
this.name,
p.name,
p.results.bailout
)
this.pool.delete(p)
p.options.tapChildBuffer = p.output || ''
p.options.stack = ''
if (p.time) p.options.time = p.time
if (this.#occupied === p) this.#occupied = null
p.deferred?.resolve(p.results)
this.emit('subtestEnd', p)
this.#process()
}
#onIndentedEnd<T extends Base>(p: T) {
this.emit('subtestProcess', p)
p.ondone = p.constructor.prototype.ondone
p.results =
p.results || new FinalResults(true, p.parser)
this.debug('#onIndentedEnd', this.name, p.name)
this.#noparallel = false
const sti = this.subtests.indexOf(p)
if (sti !== -1) this.subtests.splice(sti, 1)
p.readyToProcess = true
p.options.time = p.time
const to = p.options.timeout
const dur =
to && p.passing() ? hrtime.bigint() - p.start : null
if (dur && to && dur > to) {
p.timeout()
} else {
p.setTimeout(0)
}
this.debug('#onIndentedEnd %s(%s)', this.name, p.name)
this.#occupied = null
this.debug(
'OIE(%s) b>shift into queue',
this.name,
this.queue
)
p.options.stack = ''
this.printResult(p.passing(), p.name, p.options, true)
this.debug(
'OIE(%s) shifted into queue',
this.name,
this.queue
)
p.deferred?.resolve(p.results)
this.emit('subtestEnd', p)
this.#process()
}
/**
* @internal
*/
main(cb: () => void) {
if (typeof this.options.timeout === 'number') {
this.setTimeout(this.options.timeout)
}
this.debug('MAIN pre', this)
const end = () => {
this.debug(' > implicit end for promise')
this.#end(IMPLICIT)
done()
}
const done = (er?: Error) => {
if (er) this.threw(er)
if (this.results || this.bailedOut) cb()
else this.ondone = () => cb()
}
// This bit of overly clever line-noise wraps the call to user-code
// in a try-catch. We can't rely on the domain for this yet, because
// the 'end' event can trigger a throw after the domain is unhooked,
// but before this is no longer the official "active test"
const ret = (() => {
if (!this.cb) return
try {
return this.cb(this)
} catch (er: any) {
if (!er || typeof er !== 'object') {
er = { error: er }
}
er.tapCaught = 'testFunctionThrow'
this.threw(er)
}
})()
if (ret && ret.then) {
this.promise = ret
ret.tapAbortPromise = done
ret.then(end, (er: any) => {
if (!er || typeof er !== 'object') {
er = { error: er }
}
er.tapCaught = 'returnedPromiseRejection'
done(er)
})
} else done()
this.debug('MAIN post', this)
}
#processSubtest<T extends Base>(p: T) {
this.debug(' > subtest')
this.#occupied = p
if (!p.buffered) {
this.emit('subtestStart', p)
this.debug(' > subtest indented')
p.stream.pipe(this.parser, { end: false })
this.writeSubComment(p)
this.debug('calling runMain', p.runMain.toString())
p.runMain(() => {
this.debug('in runMain', p.runMain.toString())
this.#onIndentedEnd(p)
})
} else if (p.readyToProcess) {
this.emit('subtestProcess', p)
this.debug(' > subtest buffered, finished')
// finished! do the thing!
this.#occupied = null
if (!p.passing() || !p.silent) {
this.printResult(
p.passing(),
p.name,
p.options,
true
)
}
} else {
this.#occupied = p
this.debug(' > subtest buffered, unfinished', p)
// unfinished buffered test.
// nothing to do yet, just leave it there.
this.queue.unshift(p)
}
}
/**
* Parse stdin as the only tap stream (ie, not as a child test)
* If used, then no other subtests or assertions are allowed.
*/
stdinOnly<T extends BaseOpts>(
extra?: T & { tapStream?: Readable | Minipass }
) {
const stream = ((extra && extra.tapStream) ||
process.stdin) as Minipass
if (!stream) {
throw new Error(
'cannot read stdin without stdin stream'
)
}
if (
this.queue.length !== 1 ||
this.queue[0] !== 'TAP version 14\n' ||
this.#processing ||
this.results ||
this.#occupied ||
this.pool.size ||
this.subtests.length
) {
throw new Error(
'Cannot use stdinOnly on a test in progress'
)
}
this.#doingStdinOnly = true
this.queue.length = 0
this.parser.on('child', p => {
// pretend to be a rooted parser, so it gets counts.
p.root = p
const t = new Base({
name: p.name,
parent: this,
parser: p,
bail: p.bail,
strict: p.strict,
omitVersion: p.omitVersion,
preserveWhitespace: p.preserveWhitespace,
childId: this.#nextChildId++,
})
this.emit('subtestAdd', t)
this.emit('subtestStart', t)
this.emit('subtestProcess', t)
p.on('complete', () => {
t.time = p.time
this.emit('subtestEnd', t)
})
})
stream.pause()
stream.pipe(this.parser)
stream.resume()
}
/**
* Mount a subtest, using this Test object as a harness.
* Exposed mainly so that it can be used by builtin plugins.
*
* @internal
*/
sub<T extends Base, O extends TestBaseOpts>(
Class: { new (options: O): T },
extra: O,
caller: (...a: any[]) => unknown
): Promise<FinalResults | null> {
if (this.bailedOut) return Promise.resolve(null)
if (this.results || this.ended) {
const er = new Error(
'cannot create subtest after parent test ends'
)
Error.captureStackTrace(er, caller)
this.threw(er)
return Promise.resolve(null)
}
extra.childId = this.#nextChildId++
if (this.shouldSkipChild(extra)) {
this.pass(extra.name, extra)
return Promise.resolve(null)
}
extra.indent = ' '
if (extra.buffered !== undefined) {
if (this.jobs > 1) {
extra.buffered = true
} else {
extra.buffered = false
}
}
extra.bail =
extra.bail !== undefined ? extra.bail : this.bail
extra.parent = this
extra.stack = stack.captureString(80, caller)
extra.context = this.context
const t = new Class(extra)
this.queue.push(t)
this.subtests.push(t)
this.emit('subtestAdd', t)
const d = new Deferred<FinalResults>()
t.deferred = d
this.#process()
return d.promise
}
/**
* Return true if the child test represented by the options object
* should be skipped. Extended by the grep/only filtering plugins.
*/
shouldSkipChild(extra: { [k: string]: any }) {
return !!(extra.skip || extra.todo)
}
// end flow control methods
}
|
src/test-base.ts
|
tapjs-core-edd7403
|
[
{
"filename": "src/base.ts",
"retrieved_chunk": " } else if (!er.stack) {\n console.error(er)\n } else {\n if (message) {\n er.message = message\n }\n delete extra.stack\n delete extra.at\n console.error('%s: %s', er.name || 'Error', message)\n console.error(",
"score": 0.818498969078064
},
{
"filename": "src/plugin/after-each.ts",
"retrieved_chunk": " const onerr = (er: any) => {\n who.threw(er)\n cb()\n }\n const p = this.#t.parent\n const pae = !!p && AfterEach.#refs.get(p)\n const run = () => {\n if (pae) {\n pae.#runAfterEach(who, cb)\n } else {",
"score": 0.8080182075500488
},
{
"filename": "src/base.ts",
"retrieved_chunk": " // a bit excessive.\n if (this.results) {\n const alreadyBailing = !this.results.ok && this.bail\n this.results.ok = false\n if (this.parent) {\n this.parent.threw(er, extra, true)\n } else if (alreadyBailing) {\n // we are already bailing out, and this is the top level,\n // just make our way hastily to the nearest exit.\n return",
"score": 0.807010293006897
},
{
"filename": "src/extra-from-error.ts",
"retrieved_chunk": " if (message) {\n try {\n Object.defineProperty(er, 'message', {\n value: message,\n configurable: true\n })\n } catch {}\n }\n if (er.name && er.name !== 'Error') {\n extra.type = er.name",
"score": 0.8055779933929443
},
{
"filename": "src/extra-from-error.ts",
"retrieved_chunk": " if (!er || typeof er !== 'object') {\n extra.error = er\n return extra\n }\n // pull out error details\n const message = er.message ? er.message\n : er.stack ? er.stack.split('\\n')[0]\n : ''\n if (er.message) {\n try {",
"score": 0.8045239448547363
}
] |
typescript
|
this.threw(er)
return
}
|
// lifecycle methods like beforeEach, afterEach, teardown
// defined in plugins/lifecycle.ts
import Minipass from 'minipass'
import assert from 'node:assert'
import { hrtime } from 'node:process'
import { Readable } from 'node:stream'
import { format } from 'node:util'
import { CallSiteLike } from 'stack-utils'
import { FinalResults } from 'tap-parser'
import Deferred from 'trivial-deferred'
import { Base, BaseOpts } from './base.js'
import { esc } from './esc.js'
import stack from './stack.js'
import { TestPoint } from './test-point.js'
import { Waiter } from './waiter.js'
const queueEmpty = <T extends TestBase>(t: T) =>
t.queue.length === 0 ||
(t.queue.length === 1 &&
t.queue[0] === 'TAP version 14\n')
export interface ClassOf<T> {
new (): T
}
export type TapPlugin<
B extends Object,
O extends TestBaseOpts | any = any
> = ((t: TestBase, opts: O) => B) | ((t: TestBase) => B)
export interface TestBaseOpts extends BaseOpts {
/**
* The number of jobs to run in parallel. Defaults to 1
*/
jobs?: number
/**
* Test function called when this Test is executed
*/
cb?: (...args: any[]) => any
/**
* Flag to always/never show diagnostics. If unset, then
* diagnostics are shown for failing test points only.
*/
diagnostic?: boolean
}
const normalizeMessageExtra = (
defaultMessage: string,
message?: string | { [k: string]: any },
extra?: { [k: string]: any }
): [string, { [k: string]: any }] => {
if (typeof message === 'string') {
return [message || defaultMessage, extra || {}]
} else {
return [defaultMessage, message || {}]
}
}
/**
* Sigil for implicit end() calls that should not
* trigger an error if the user then calls t.end()
*/
const IMPLICIT = Symbol('implicit end')
/**
* Sigil to put in the queue to signal the end of all things
*/
const EOF = Symbol('EOF')
export type QueueEntry =
| string
| TestPoint
| Base
| typeof EOF
| Waiter
| [method: string, ...args: any[]]
/**
* The TestBaseBase class is the base class for all plugins,
* and eventually thus the Test class.
*
* This implements subtest functionality, TAP stream generation,
* lifecycle events, and only the most basic pass/fail assertions.
*
* All other features are added with plugins.
*/
export class TestBase extends Base {
// NB: generated pluginified Test class needs to declare over this
declare parent?: TestBase
promise?: Promise<any>
jobs: number
// #beforeEnd: [method: string | Symbol, ...args: any[]][] = []
subtests: Base[] = []
pool: Set<Base> = new Set()
queue: QueueEntry[] = ['TAP version 14\n']
cb?: (...args: any[]) => any
count: number = 0
ended: boolean = false
assertAt: CallSiteLike | null = null
assertStack: string | null = null
diagnostic: null | boolean = null
#planEnd: number = -1
#printedResult: boolean = false
#explicitEnded: boolean = false
#multiEndThrew: boolean = false
#n: number = 0
#noparallel: boolean = false
#occupied: null | Waiter | Base = null
#pushedEnd: boolean = false
#nextChildId: number = 1
#currentAssert: null | ((..._: any) => any) = null
#processing: boolean = false
#doingStdinOnly: boolean = false
/**
* true if the test has printed at least one TestPoint
*/
get printedResult(): boolean {
return this.#printedResult
}
constructor(options: TestBaseOpts) {
super(options)
this.jobs =
(options.jobs && Math.max(options.jobs, 1)) || 1
if (typeof options.diagnostic === 'boolean') {
this.diagnostic = options.diagnostic
}
if (options.cb) {
this.#setCB(options.cb)
}
}
#setCB<T extends TestBase>(this: T, cb: (t: T) => any) {
this.cb = (...args: any[]) =>
this.hook.runInAsyncScope(cb, this, ...args)
}
// TAP output generating methods
/**
* immediately exit this and all parent tests with a TAP
* Bail out! message.
*/
bailout(message?: string) {
if (this.parent && (this.results || this.ended)) {
this.parent.bailout(message)
} else {
this.#process()
message = message
? ' ' + ('' + esc(message)).trim()
: ''
message = message.replace(/[\r\n]/g, ' ')
this.parser.write('Bail out!' + message + '\n')
}
this.#end(IMPLICIT)
this.#process()
}
/**
* output a TAP comment, formatted like console.log()
*/
comment(...args: any[]) {
const body = format(...args)
const message =
('# ' + body.split(/\r?\n/).join('\n# ')).trim() +
'\n'
if (this.results) {
this.write(message)
} else {
this.queue.push(message)
}
this.#process()
}
/**
* Called when the test times out.
* Options are passed as diagnostics to the threw() method
*/
timeout(options: { [k: string]: any }) {
options = options || {}
options.expired = options.expired || this.name
if (this.#occupied && this.#occupied instanceof Base) {
this.#occupied.timeout(options)
} else {
super.timeout(options)
}
this.#end(IMPLICIT)
}
/**
* Set TAP pragma configs to affect the behavior of the parser.
* Only `strict` is supported by the parser.
*/
pragma(set: { [k: string]: boolean }) {
const p = Object.keys(set).reduce(
(acc, i) =>
acc + 'pragma ' + (set[i] ? '+' : '-') + i + '\n',
''
)
this.queue.push(p)
this.#process()
}
/**
* Specify the number of Test Points expected by this test.
* Outputs a TAP plan line.
*/
plan(n: number, comment?: string) {
if (this.bailedOut) {
return
}
if (this.#planEnd !== -1) {
throw new Error('Cannot set plan more than once')
}
if (typeof n !== 'number' || n < 0) {
throw new TypeError('plan must be a number')
}
// Cannot get any tests after a trailing plan, or a plan of 0
const ending = this.count !== 0 || n === 0
if (n === 0 && comment && !this.options.skip) {
this.options.skip = comment
}
this.#planEnd = n
comment = comment ? ' # ' + esc(comment.trim()) : ''
this.queue.push('1..' + n + comment + '\n')
if (ending) {
this.#end(IMPLICIT)
} else {
this.#process()
}
}
/**
* A passing (ok) Test Point
*/
pass(message?: string, extra?: { [k: string]: any }) {
this.currentAssert = TestBase.prototype.pass
this.printResult(
true,
...normalizeMessageExtra(
'(unnamed test)',
message,
extra
)
)
return true
}
/**
* A failing (not ok) Test Point
*/
fail(message?: string, extra?: { [k: string]: any }) {
this.currentAssert = TestBase.prototype.fail
const [m, e] = normalizeMessageExtra(
'(unnamed test)',
message,
extra
)
this.printResult(false, m, e)
return !!(e.todo || e.skip)
}
/**
* The current assertion being processed. May only be set if
* not already set.
*/
get currentAssert() {
return this.#currentAssert
}
/**
* The current assertion being processed. May only be set if
* not already set.
*/
set currentAssert(fn: null | ((...a: any[]) => any)) {
if (!this.#currentAssert && typeof fn === 'function') {
this.#currentAssert = fn
}
}
/**
* Print a Test Point
*/
printResult(
ok: boolean,
message: string,
extra: { [k: string]: any },
front: boolean = false
) {
this.#printedResult = true
const n = this.count + 1
this.currentAssert = TestBase.prototype.printResult
const fn = this.#currentAssert
this.#currentAssert = null
if (this.#planEnd !== -1 && n > this.#planEnd) {
if (!this.passing()) return
const failMessage = this.#explicitEnded
? 'test after end() was called'
: 'test count exceeds plan'
const er = new Error(failMessage, {
cause: {
test: this.name,
plan: this.#planEnd,
},
})
Error.captureStackTrace(er, fn || undefined)
this.threw(er)
return
}
extra = extra || {}
if (extra.expectFail) {
ok = !ok
}
if (this.assertAt) {
extra.at = this.assertAt
this.assertAt = null
}
if (this.assertStack) {
extra.stack = this.assertStack
this.assertStack = null
}
if (typeof extra.stack === 'string' && !extra.at) {
extra.at = stack.parseLine(extra.stack.split('\n')[0])
}
if (
!ok &&
!extra.skip &&
!extra.at &&
typeof fn === 'function'
) {
extra.at = stack.at(fn)
if (!extra.todo) {
extra.stack = stack.captureString(80, fn)
}
}
const diagnostic =
typeof extra.diagnostic === 'boolean'
? extra.diagnostic
: typeof this.diagnostic === 'boolean'
? this.diagnostic
: extra.skip || extra.todo
? false
: !ok
if (diagnostic) {
extra.diagnostic = true
}
this.count = n
message = message + ''
const res = { ok, message, extra }
const tp = new TestPoint(ok, message, extra)
// when we jump the queue, skip an extra line
if (front) {
tp.message = tp.message.trimEnd() + '\n\n'
}
if (
this.#occupied &&
this.#occupied instanceof Waiter &&
this.#occupied.finishing
) {
front = true
}
if (front) {
if (
extra.tapChildBuffer ||
extra.tapChildBuffer === ''
) {
this.writeSubComment(tp)
this.parser.write(extra.tapChildBuffer)
}
this.emit('result', res)
this.parser.write(tp.ok + ++this.#n + tp.message)
if (this.bail && !ok && !extra.skip && !extra.todo) {
this.parser.write('Bail out! ' + message + '\n')
}
} else {
this.queue.push(tp)
if (this.bail && !ok && !extra.skip && !extra.todo) {
this.queue.push('Bail out! ' + message + '\n')
}
}
if (this.#planEnd === this.count) {
this.#end(IMPLICIT)
}
this.#process()
}
end(): this {
this.#end()
return super.end()
}
/**
* The leading `# Subtest` comment that introduces a child test
*/
writeSubComment<T extends TestPoint | Base>(p: T) {
const comment =
'# Subtest' +
(p.name ? ': ' + esc(p.name) : '') +
'\n'
this.parser.write(comment)
}
// end TAP otput generating methods
// flow control methods
/**
* Await the end of a Promise before proceeding.
* The supplied callback is called with the Waiter object.
*/
waitOn(
promise: Promise<any | void>,
cb: (w: Waiter) => any,
expectReject: boolean = false
): Promise<void> {
const w = new Waiter(
promise,
w => {
assert.equal(this.#occupied, w)
cb(w)
this.#occupied = null
this.#process()
},
expectReject
)
this.queue.push(w)
this.#process()
return w.promise
}
#end(implicit?: typeof IMPLICIT) {
if (this.#doingStdinOnly && implicit !== IMPLICIT)
throw new Error(
'cannot explicitly end while in stdinOnly mode'
)
this.debug('END implicit=%j', implicit === IMPLICIT)
if (this.ended && implicit === IMPLICIT) return
// beyond here we have to be actually done with things, or else
// the semantic checks on counts and such will be off.
if (!queueEmpty(this) || this.#occupied) {
if (!this.#pushedEnd) {
this.queue.push(['#end', implicit])
}
this.#pushedEnd = true
return this.#process()
}
this.ended = true
if (implicit !== IMPLICIT && !this.#multiEndThrew) {
if (this.#explicitEnded) {
this.#multiEndThrew = true
const er = new Error(
'test end() method called more than once'
)
Error.captureStackTrace(
er,
this.#currentAssert || this.#end
)
er.cause = {
test: this.name,
}
this.threw(er)
return
}
this.#explicitEnded = true
}
if (this.#planEnd === -1) {
this.debug(
'END(%s) implicit plan',
this.name,
this.count
)
this.plan(this.count)
}
this.queue.push(EOF)
this.#process()
}
#process() {
if (this.#processing) {
return this.debug(' < already processing')
}
this.debug(
'\nPROCESSING(%s)',
this.name,
this.queue.length
)
this.#processing = true
while (!this.#occupied) {
const p = this.queue.shift()
if (!p) {
this.debug('> end of queue')
break
}
if (p instanceof Base) {
this.debug('> subtest in queue', p.name)
this.#processSubtest(p)
} else if (p === EOF) {
this.debug(' > EOF', this.name)
// I AM BECOME EOF, DESTROYER OF STREAMS
this.parser.end()
} else if (p instanceof TestPoint) {
this.debug(' > TESTPOINT')
if (
p.
|
extra.tapChildBuffer ||
p.extra.tapChildBuffer === ''
) {
|
this.writeSubComment(p)
this.parser.write(p.extra.tapChildBuffer)
}
this.emit('res', p.res)
this.parser.write(p.ok + ++this.#n + p.message)
} else if (typeof p === 'string') {
this.debug(' > STRING')
this.parser.write(p)
} else if (p instanceof Waiter) {
p.ready = true
this.#occupied = p
p.finish()
} else if (Array.isArray(p)) {
this.debug(' > METHOD')
const m = p.shift() as keyof this
if (typeof this[m] !== 'function') {
this.debug(
' > weird method not found in queue??',
m,
typeof this[m]
)
continue
}
const fn = (m === '#end' ? this.#end : this[m]) as (
...a: any[]
) => any
const ret = fn.call(this, ...p)
if (
ret &&
typeof ret === 'object' &&
typeof ret.then === 'function'
) {
// returned promise
ret.then(
() => {
this.#processing = false
this.#process()
},
(er: unknown) => {
this.#processing = false
this.threw(er)
}
)
return
}
/* c8 ignore start */
} else {
throw new Error('weird thing got in the queue')
}
/* c8 ignore stop */
}
while (
!this.#noparallel &&
this.pool.size < this.jobs
) {
const p = this.subtests.shift()
if (!p) {
break
}
if (!p.buffered) {
this.#noparallel = true
break
}
this.debug('start subtest', p)
this.emit('subtestStart', p)
this.pool.add(p)
if (this.bailedOut) {
this.#onBufferedEnd(p)
} else {
p.runMain(() => this.#onBufferedEnd(p))
}
}
this.debug(
'done processing',
this.queue,
this.#occupied
)
this.#processing = false
// just in case any tests ended, and we have sync stuff still
// waiting around in the queue to be processed
if (!this.#occupied && this.queue.length) {
this.#process()
}
}
#onBufferedEnd<T extends Base>(p: T) {
p.ondone = p.constructor.prototype.ondone
p.results =
p.results || new FinalResults(true, p.parser)
p.readyToProcess = true
const to = p.options.timeout
const dur =
to && p.passing() ? hrtime.bigint() - p.start : null
if (dur && to && dur > to) {
p.timeout()
} else {
p.setTimeout(0)
}
this.debug(
'%s.#onBufferedEnd',
this.name,
p.name,
p.results.bailout
)
this.pool.delete(p)
p.options.tapChildBuffer = p.output || ''
p.options.stack = ''
if (p.time) p.options.time = p.time
if (this.#occupied === p) this.#occupied = null
p.deferred?.resolve(p.results)
this.emit('subtestEnd', p)
this.#process()
}
#onIndentedEnd<T extends Base>(p: T) {
this.emit('subtestProcess', p)
p.ondone = p.constructor.prototype.ondone
p.results =
p.results || new FinalResults(true, p.parser)
this.debug('#onIndentedEnd', this.name, p.name)
this.#noparallel = false
const sti = this.subtests.indexOf(p)
if (sti !== -1) this.subtests.splice(sti, 1)
p.readyToProcess = true
p.options.time = p.time
const to = p.options.timeout
const dur =
to && p.passing() ? hrtime.bigint() - p.start : null
if (dur && to && dur > to) {
p.timeout()
} else {
p.setTimeout(0)
}
this.debug('#onIndentedEnd %s(%s)', this.name, p.name)
this.#occupied = null
this.debug(
'OIE(%s) b>shift into queue',
this.name,
this.queue
)
p.options.stack = ''
this.printResult(p.passing(), p.name, p.options, true)
this.debug(
'OIE(%s) shifted into queue',
this.name,
this.queue
)
p.deferred?.resolve(p.results)
this.emit('subtestEnd', p)
this.#process()
}
/**
* @internal
*/
main(cb: () => void) {
if (typeof this.options.timeout === 'number') {
this.setTimeout(this.options.timeout)
}
this.debug('MAIN pre', this)
const end = () => {
this.debug(' > implicit end for promise')
this.#end(IMPLICIT)
done()
}
const done = (er?: Error) => {
if (er) this.threw(er)
if (this.results || this.bailedOut) cb()
else this.ondone = () => cb()
}
// This bit of overly clever line-noise wraps the call to user-code
// in a try-catch. We can't rely on the domain for this yet, because
// the 'end' event can trigger a throw after the domain is unhooked,
// but before this is no longer the official "active test"
const ret = (() => {
if (!this.cb) return
try {
return this.cb(this)
} catch (er: any) {
if (!er || typeof er !== 'object') {
er = { error: er }
}
er.tapCaught = 'testFunctionThrow'
this.threw(er)
}
})()
if (ret && ret.then) {
this.promise = ret
ret.tapAbortPromise = done
ret.then(end, (er: any) => {
if (!er || typeof er !== 'object') {
er = { error: er }
}
er.tapCaught = 'returnedPromiseRejection'
done(er)
})
} else done()
this.debug('MAIN post', this)
}
#processSubtest<T extends Base>(p: T) {
this.debug(' > subtest')
this.#occupied = p
if (!p.buffered) {
this.emit('subtestStart', p)
this.debug(' > subtest indented')
p.stream.pipe(this.parser, { end: false })
this.writeSubComment(p)
this.debug('calling runMain', p.runMain.toString())
p.runMain(() => {
this.debug('in runMain', p.runMain.toString())
this.#onIndentedEnd(p)
})
} else if (p.readyToProcess) {
this.emit('subtestProcess', p)
this.debug(' > subtest buffered, finished')
// finished! do the thing!
this.#occupied = null
if (!p.passing() || !p.silent) {
this.printResult(
p.passing(),
p.name,
p.options,
true
)
}
} else {
this.#occupied = p
this.debug(' > subtest buffered, unfinished', p)
// unfinished buffered test.
// nothing to do yet, just leave it there.
this.queue.unshift(p)
}
}
/**
* Parse stdin as the only tap stream (ie, not as a child test)
* If used, then no other subtests or assertions are allowed.
*/
stdinOnly<T extends BaseOpts>(
extra?: T & { tapStream?: Readable | Minipass }
) {
const stream = ((extra && extra.tapStream) ||
process.stdin) as Minipass
if (!stream) {
throw new Error(
'cannot read stdin without stdin stream'
)
}
if (
this.queue.length !== 1 ||
this.queue[0] !== 'TAP version 14\n' ||
this.#processing ||
this.results ||
this.#occupied ||
this.pool.size ||
this.subtests.length
) {
throw new Error(
'Cannot use stdinOnly on a test in progress'
)
}
this.#doingStdinOnly = true
this.queue.length = 0
this.parser.on('child', p => {
// pretend to be a rooted parser, so it gets counts.
p.root = p
const t = new Base({
name: p.name,
parent: this,
parser: p,
bail: p.bail,
strict: p.strict,
omitVersion: p.omitVersion,
preserveWhitespace: p.preserveWhitespace,
childId: this.#nextChildId++,
})
this.emit('subtestAdd', t)
this.emit('subtestStart', t)
this.emit('subtestProcess', t)
p.on('complete', () => {
t.time = p.time
this.emit('subtestEnd', t)
})
})
stream.pause()
stream.pipe(this.parser)
stream.resume()
}
/**
* Mount a subtest, using this Test object as a harness.
* Exposed mainly so that it can be used by builtin plugins.
*
* @internal
*/
sub<T extends Base, O extends TestBaseOpts>(
Class: { new (options: O): T },
extra: O,
caller: (...a: any[]) => unknown
): Promise<FinalResults | null> {
if (this.bailedOut) return Promise.resolve(null)
if (this.results || this.ended) {
const er = new Error(
'cannot create subtest after parent test ends'
)
Error.captureStackTrace(er, caller)
this.threw(er)
return Promise.resolve(null)
}
extra.childId = this.#nextChildId++
if (this.shouldSkipChild(extra)) {
this.pass(extra.name, extra)
return Promise.resolve(null)
}
extra.indent = ' '
if (extra.buffered !== undefined) {
if (this.jobs > 1) {
extra.buffered = true
} else {
extra.buffered = false
}
}
extra.bail =
extra.bail !== undefined ? extra.bail : this.bail
extra.parent = this
extra.stack = stack.captureString(80, caller)
extra.context = this.context
const t = new Class(extra)
this.queue.push(t)
this.subtests.push(t)
this.emit('subtestAdd', t)
const d = new Deferred<FinalResults>()
t.deferred = d
this.#process()
return d.promise
}
/**
* Return true if the child test represented by the options object
* should be skipped. Extended by the grep/only filtering plugins.
*/
shouldSkipChild(extra: { [k: string]: any }) {
return !!(extra.skip || extra.todo)
}
// end flow control methods
}
|
src/test-base.ts
|
tapjs-core-edd7403
|
[
{
"filename": "src/base.ts",
"retrieved_chunk": " return f\n })\n if (errors.length) {\n this.errors = errors\n }\n this.onbeforeend()\n // XXX old tap had a check here to ensure that buffer and pipes\n // are cleared. But Minipass \"should\" do this now for us, so\n // this ought to be fine, but revisit if it causes problems.\n this.stream.end()",
"score": 0.8057137131690979
},
{
"filename": "src/stdin.ts",
"retrieved_chunk": " }\n threw(er: any, extra?: any, proxy?: boolean) {\n extra = super.threw(er, extra, proxy)\n Object.assign(this.options, extra)\n this.parser.abort(er.message, extra)\n this.parser.end()\n }\n}",
"score": 0.8017924427986145
},
{
"filename": "src/base.ts",
"retrieved_chunk": " }\n // extension points for Test, Spawn, etc.\n onbeforeend() {}\n ondone() {}\n once(ev: string, handler: (...a: any[]) => any) {\n return this.stream.once(ev, handler)\n }\n on(ev: string, handler: (...a: any[]) => any) {\n return this.stream.on(ev, handler)\n }",
"score": 0.796329140663147
},
{
"filename": "src/base.ts",
"retrieved_chunk": " this.stream.end()\n return this\n }\n threw(er: any, extra?: any, proxy?: boolean) {\n this.hook.emitDestroy()\n this.hookDomain.destroy()\n if (typeof er === 'string') {\n er = { message: er }\n } else if (!er || typeof er !== 'object') {\n er = { error: er }",
"score": 0.7942986488342285
},
{
"filename": "src/spawn.ts",
"retrieved_chunk": " /* istanbul ignore next */ '0'\n ),\n TAP: '1',\n TAP_BAIL: this.bail ? '1' : '0',\n }\n this.proc = null\n this.cb = null\n }\n endAll() {\n if (this.proc) {",
"score": 0.7918965816497803
}
] |
typescript
|
extra.tapChildBuffer ||
p.extra.tapChildBuffer === ''
) {
|
// lifecycle methods like beforeEach, afterEach, teardown
// defined in plugins/lifecycle.ts
import Minipass from 'minipass'
import assert from 'node:assert'
import { hrtime } from 'node:process'
import { Readable } from 'node:stream'
import { format } from 'node:util'
import { CallSiteLike } from 'stack-utils'
import { FinalResults } from 'tap-parser'
import Deferred from 'trivial-deferred'
import { Base, BaseOpts } from './base.js'
import { esc } from './esc.js'
import stack from './stack.js'
import { TestPoint } from './test-point.js'
import { Waiter } from './waiter.js'
const queueEmpty = <T extends TestBase>(t: T) =>
t.queue.length === 0 ||
(t.queue.length === 1 &&
t.queue[0] === 'TAP version 14\n')
export interface ClassOf<T> {
new (): T
}
export type TapPlugin<
B extends Object,
O extends TestBaseOpts | any = any
> = ((t: TestBase, opts: O) => B) | ((t: TestBase) => B)
export interface TestBaseOpts extends BaseOpts {
/**
* The number of jobs to run in parallel. Defaults to 1
*/
jobs?: number
/**
* Test function called when this Test is executed
*/
cb?: (...args: any[]) => any
/**
* Flag to always/never show diagnostics. If unset, then
* diagnostics are shown for failing test points only.
*/
diagnostic?: boolean
}
const normalizeMessageExtra = (
defaultMessage: string,
message?: string | { [k: string]: any },
extra?: { [k: string]: any }
): [string, { [k: string]: any }] => {
if (typeof message === 'string') {
return [message || defaultMessage, extra || {}]
} else {
return [defaultMessage, message || {}]
}
}
/**
* Sigil for implicit end() calls that should not
* trigger an error if the user then calls t.end()
*/
const IMPLICIT = Symbol('implicit end')
/**
* Sigil to put in the queue to signal the end of all things
*/
const EOF = Symbol('EOF')
export type QueueEntry =
| string
| TestPoint
| Base
| typeof EOF
| Waiter
| [method: string, ...args: any[]]
/**
* The TestBaseBase class is the base class for all plugins,
* and eventually thus the Test class.
*
* This implements subtest functionality, TAP stream generation,
* lifecycle events, and only the most basic pass/fail assertions.
*
* All other features are added with plugins.
*/
export class TestBase extends Base {
// NB: generated pluginified Test class needs to declare over this
declare parent?: TestBase
promise?: Promise<any>
jobs: number
// #beforeEnd: [method: string | Symbol, ...args: any[]][] = []
subtests: Base[] = []
pool: Set<Base> = new Set()
queue: QueueEntry[] = ['TAP version 14\n']
cb?: (...args: any[]) => any
count: number = 0
ended: boolean = false
assertAt: CallSiteLike | null = null
assertStack: string | null = null
diagnostic: null | boolean = null
#planEnd: number = -1
#printedResult: boolean = false
#explicitEnded: boolean = false
#multiEndThrew: boolean = false
#n: number = 0
#noparallel: boolean = false
#occupied: null | Waiter | Base = null
#pushedEnd: boolean = false
#nextChildId: number = 1
#currentAssert: null | ((..._: any) => any) = null
#processing: boolean = false
#doingStdinOnly: boolean = false
/**
* true if the test has printed at least one TestPoint
*/
get printedResult(): boolean {
return this.#printedResult
}
constructor(options: TestBaseOpts) {
super(options)
this.jobs =
(options.jobs && Math.max(options.jobs, 1)) || 1
if (typeof options.diagnostic === 'boolean') {
this.diagnostic = options.diagnostic
}
if (options.cb) {
this.#setCB(options.cb)
}
}
#setCB<T extends TestBase>(this: T, cb: (t: T) => any) {
this.cb = (...args: any[]) =>
this.hook.runInAsyncScope(cb, this, ...args)
}
// TAP output generating methods
/**
* immediately exit this and all parent tests with a TAP
* Bail out! message.
*/
bailout(message?: string) {
if (this.parent && (this.results || this.ended)) {
this.parent.bailout(message)
} else {
this.#process()
message = message
? ' ' + ('' + esc(message)).trim()
: ''
message = message.replace(/[\r\n]/g, ' ')
this.parser.write('Bail out!' + message + '\n')
}
this.#end(IMPLICIT)
this.#process()
}
/**
* output a TAP comment, formatted like console.log()
*/
comment(...args: any[]) {
const body = format(...args)
const message =
('# ' + body.split(/\r?\n/).join('\n# ')).trim() +
'\n'
if (this.results) {
this.write(message)
} else {
this.queue.push(message)
}
this.#process()
}
/**
* Called when the test times out.
* Options are passed as diagnostics to the threw() method
*/
timeout(options: { [k: string]: any }) {
options = options || {}
options.expired = options.expired || this.name
if (this.#occupied && this.#occupied instanceof Base) {
this.#occupied.timeout(options)
} else {
super.timeout(options)
}
this.#end(IMPLICIT)
}
/**
* Set TAP pragma configs to affect the behavior of the parser.
* Only `strict` is supported by the parser.
*/
pragma(set: { [k: string]: boolean }) {
const p = Object.keys(set).reduce(
(acc, i) =>
acc + 'pragma ' + (set[i] ? '+' : '-') + i + '\n',
''
)
this.queue.push(p)
this.#process()
}
/**
* Specify the number of Test Points expected by this test.
* Outputs a TAP plan line.
*/
plan(n: number, comment?: string) {
if (this.bailedOut) {
return
}
if (this.#planEnd !== -1) {
throw new Error('Cannot set plan more than once')
}
if (typeof n !== 'number' || n < 0) {
throw new TypeError('plan must be a number')
}
// Cannot get any tests after a trailing plan, or a plan of 0
const ending = this.count !== 0 || n === 0
if (n === 0 && comment && !this.options.skip) {
this.options.skip = comment
}
this.#planEnd = n
comment = comment ? ' # ' + esc(comment.trim()) : ''
this.queue.push('1..' + n + comment + '\n')
if (ending) {
this.#end(IMPLICIT)
} else {
this.#process()
}
}
/**
* A passing (ok) Test Point
*/
pass(message?: string, extra?: { [k: string]: any }) {
this.currentAssert = TestBase.prototype.pass
this.printResult(
true,
...normalizeMessageExtra(
'(unnamed test)',
message,
extra
)
)
return true
}
/**
* A failing (not ok) Test Point
*/
fail(message?: string, extra?: { [k: string]: any }) {
this.currentAssert = TestBase.prototype.fail
const [m, e] = normalizeMessageExtra(
'(unnamed test)',
message,
extra
)
this.printResult(false, m, e)
return !!(e.todo || e.skip)
}
/**
* The current assertion being processed. May only be set if
* not already set.
*/
get currentAssert() {
return this.#currentAssert
}
/**
* The current assertion being processed. May only be set if
* not already set.
*/
set currentAssert(fn: null | ((...a: any[]) => any)) {
if (!this.#currentAssert && typeof fn === 'function') {
this.#currentAssert = fn
}
}
/**
* Print a Test Point
*/
printResult(
ok: boolean,
message: string,
extra: { [k: string]: any },
front: boolean = false
) {
this.#printedResult = true
const n = this.count + 1
this.currentAssert = TestBase.prototype.printResult
const fn = this.#currentAssert
this.#currentAssert = null
if (this.#planEnd !== -1 && n > this.#planEnd) {
if (!this.passing()) return
const failMessage = this.#explicitEnded
? 'test after end() was called'
: 'test count exceeds plan'
const er = new Error(failMessage, {
cause: {
test: this.name,
plan: this.#planEnd,
},
})
Error.captureStackTrace(er, fn || undefined)
this.threw(er)
return
}
extra = extra || {}
if (extra.expectFail) {
ok = !ok
}
if (this.assertAt) {
extra.at = this.assertAt
this.assertAt = null
}
if (this.assertStack) {
extra.stack = this.assertStack
this.assertStack = null
}
if (typeof extra.stack === 'string' && !extra.at) {
extra.at = stack.parseLine(extra.stack.split('\n')[0])
}
if (
!ok &&
!extra.skip &&
!extra.at &&
typeof fn === 'function'
) {
extra.at = stack.at(fn)
if (!extra.todo) {
extra.stack = stack.captureString(80, fn)
}
}
const diagnostic =
typeof extra.diagnostic === 'boolean'
? extra.diagnostic
: typeof this.diagnostic === 'boolean'
? this.diagnostic
: extra.skip || extra.todo
? false
: !ok
if (diagnostic) {
extra.diagnostic = true
}
this.count = n
message = message + ''
const res = { ok, message, extra }
const tp = new TestPoint(ok, message, extra)
// when we jump the queue, skip an extra line
if (front) {
tp.message = tp.message.trimEnd() + '\n\n'
}
if (
this.#occupied &&
this.#occupied instanceof Waiter &&
this.#occupied.finishing
) {
front = true
}
if (front) {
if (
extra.tapChildBuffer ||
extra.tapChildBuffer === ''
) {
this.writeSubComment(tp)
this.parser.write(extra.tapChildBuffer)
}
this.emit('result', res)
this.parser.write(tp.ok + ++this.#n + tp.message)
if (this.bail && !ok && !extra.skip && !extra.todo) {
this.parser.write('Bail out! ' + message + '\n')
}
} else {
this.queue.push(tp)
if (this.bail && !ok && !extra.skip && !extra.todo) {
this.queue.push('Bail out! ' + message + '\n')
}
}
if (this.#planEnd === this.count) {
this.#end(IMPLICIT)
}
this.#process()
}
end(): this {
this.#end()
return super.end()
}
/**
* The leading `# Subtest` comment that introduces a child test
*/
writeSubComment<T extends TestPoint | Base>(p: T) {
const comment =
'# Subtest' +
(p.name ? ': ' + esc(p.name) : '') +
'\n'
this.parser.write(comment)
}
// end TAP otput generating methods
// flow control methods
/**
* Await the end of a Promise before proceeding.
* The supplied callback is called with the Waiter object.
*/
waitOn(
promise: Promise<any | void>,
cb: (w: Waiter) => any,
expectReject: boolean = false
): Promise<void> {
const w = new Waiter(
promise,
w => {
assert.equal(this.#occupied, w)
cb(w)
this.#occupied = null
this.#process()
},
expectReject
)
this.queue.push(w)
this.#process()
return w.promise
}
#end(implicit?: typeof IMPLICIT) {
if (this.#doingStdinOnly && implicit !== IMPLICIT)
throw new Error(
'cannot explicitly end while in stdinOnly mode'
)
this.debug('END implicit=%j', implicit === IMPLICIT)
if (this.ended && implicit === IMPLICIT) return
// beyond here we have to be actually done with things, or else
// the semantic checks on counts and such will be off.
if (!queueEmpty(this) || this.#occupied) {
if (!this.#pushedEnd) {
this.queue.push(['#end', implicit])
}
this.#pushedEnd = true
return this.#process()
}
this.ended = true
if (implicit !== IMPLICIT && !this.#multiEndThrew) {
if (this.#explicitEnded) {
this.#multiEndThrew = true
const er = new Error(
'test end() method called more than once'
)
Error.captureStackTrace(
er,
this.#currentAssert || this.#end
)
er.cause = {
test: this.name,
}
this.threw(er)
return
}
this.#explicitEnded = true
}
if (this.#planEnd === -1) {
this.debug(
'END(%s) implicit plan',
this.name,
this.count
)
this.plan(this.count)
}
this.queue.push(EOF)
this.#process()
}
#process() {
if (this.#processing) {
return this.debug(' < already processing')
}
this.debug(
'\nPROCESSING(%s)',
this.name,
this.queue.length
)
this.#processing = true
while (!this.#occupied) {
const p = this.queue.shift()
if (!p) {
this.debug('> end of queue')
break
}
if (p instanceof Base) {
this.debug('> subtest in queue', p.
|
name)
this.#processSubtest(p)
} else if (p === EOF) {
|
this.debug(' > EOF', this.name)
// I AM BECOME EOF, DESTROYER OF STREAMS
this.parser.end()
} else if (p instanceof TestPoint) {
this.debug(' > TESTPOINT')
if (
p.extra.tapChildBuffer ||
p.extra.tapChildBuffer === ''
) {
this.writeSubComment(p)
this.parser.write(p.extra.tapChildBuffer)
}
this.emit('res', p.res)
this.parser.write(p.ok + ++this.#n + p.message)
} else if (typeof p === 'string') {
this.debug(' > STRING')
this.parser.write(p)
} else if (p instanceof Waiter) {
p.ready = true
this.#occupied = p
p.finish()
} else if (Array.isArray(p)) {
this.debug(' > METHOD')
const m = p.shift() as keyof this
if (typeof this[m] !== 'function') {
this.debug(
' > weird method not found in queue??',
m,
typeof this[m]
)
continue
}
const fn = (m === '#end' ? this.#end : this[m]) as (
...a: any[]
) => any
const ret = fn.call(this, ...p)
if (
ret &&
typeof ret === 'object' &&
typeof ret.then === 'function'
) {
// returned promise
ret.then(
() => {
this.#processing = false
this.#process()
},
(er: unknown) => {
this.#processing = false
this.threw(er)
}
)
return
}
/* c8 ignore start */
} else {
throw new Error('weird thing got in the queue')
}
/* c8 ignore stop */
}
while (
!this.#noparallel &&
this.pool.size < this.jobs
) {
const p = this.subtests.shift()
if (!p) {
break
}
if (!p.buffered) {
this.#noparallel = true
break
}
this.debug('start subtest', p)
this.emit('subtestStart', p)
this.pool.add(p)
if (this.bailedOut) {
this.#onBufferedEnd(p)
} else {
p.runMain(() => this.#onBufferedEnd(p))
}
}
this.debug(
'done processing',
this.queue,
this.#occupied
)
this.#processing = false
// just in case any tests ended, and we have sync stuff still
// waiting around in the queue to be processed
if (!this.#occupied && this.queue.length) {
this.#process()
}
}
#onBufferedEnd<T extends Base>(p: T) {
p.ondone = p.constructor.prototype.ondone
p.results =
p.results || new FinalResults(true, p.parser)
p.readyToProcess = true
const to = p.options.timeout
const dur =
to && p.passing() ? hrtime.bigint() - p.start : null
if (dur && to && dur > to) {
p.timeout()
} else {
p.setTimeout(0)
}
this.debug(
'%s.#onBufferedEnd',
this.name,
p.name,
p.results.bailout
)
this.pool.delete(p)
p.options.tapChildBuffer = p.output || ''
p.options.stack = ''
if (p.time) p.options.time = p.time
if (this.#occupied === p) this.#occupied = null
p.deferred?.resolve(p.results)
this.emit('subtestEnd', p)
this.#process()
}
#onIndentedEnd<T extends Base>(p: T) {
this.emit('subtestProcess', p)
p.ondone = p.constructor.prototype.ondone
p.results =
p.results || new FinalResults(true, p.parser)
this.debug('#onIndentedEnd', this.name, p.name)
this.#noparallel = false
const sti = this.subtests.indexOf(p)
if (sti !== -1) this.subtests.splice(sti, 1)
p.readyToProcess = true
p.options.time = p.time
const to = p.options.timeout
const dur =
to && p.passing() ? hrtime.bigint() - p.start : null
if (dur && to && dur > to) {
p.timeout()
} else {
p.setTimeout(0)
}
this.debug('#onIndentedEnd %s(%s)', this.name, p.name)
this.#occupied = null
this.debug(
'OIE(%s) b>shift into queue',
this.name,
this.queue
)
p.options.stack = ''
this.printResult(p.passing(), p.name, p.options, true)
this.debug(
'OIE(%s) shifted into queue',
this.name,
this.queue
)
p.deferred?.resolve(p.results)
this.emit('subtestEnd', p)
this.#process()
}
/**
* @internal
*/
main(cb: () => void) {
if (typeof this.options.timeout === 'number') {
this.setTimeout(this.options.timeout)
}
this.debug('MAIN pre', this)
const end = () => {
this.debug(' > implicit end for promise')
this.#end(IMPLICIT)
done()
}
const done = (er?: Error) => {
if (er) this.threw(er)
if (this.results || this.bailedOut) cb()
else this.ondone = () => cb()
}
// This bit of overly clever line-noise wraps the call to user-code
// in a try-catch. We can't rely on the domain for this yet, because
// the 'end' event can trigger a throw after the domain is unhooked,
// but before this is no longer the official "active test"
const ret = (() => {
if (!this.cb) return
try {
return this.cb(this)
} catch (er: any) {
if (!er || typeof er !== 'object') {
er = { error: er }
}
er.tapCaught = 'testFunctionThrow'
this.threw(er)
}
})()
if (ret && ret.then) {
this.promise = ret
ret.tapAbortPromise = done
ret.then(end, (er: any) => {
if (!er || typeof er !== 'object') {
er = { error: er }
}
er.tapCaught = 'returnedPromiseRejection'
done(er)
})
} else done()
this.debug('MAIN post', this)
}
#processSubtest<T extends Base>(p: T) {
this.debug(' > subtest')
this.#occupied = p
if (!p.buffered) {
this.emit('subtestStart', p)
this.debug(' > subtest indented')
p.stream.pipe(this.parser, { end: false })
this.writeSubComment(p)
this.debug('calling runMain', p.runMain.toString())
p.runMain(() => {
this.debug('in runMain', p.runMain.toString())
this.#onIndentedEnd(p)
})
} else if (p.readyToProcess) {
this.emit('subtestProcess', p)
this.debug(' > subtest buffered, finished')
// finished! do the thing!
this.#occupied = null
if (!p.passing() || !p.silent) {
this.printResult(
p.passing(),
p.name,
p.options,
true
)
}
} else {
this.#occupied = p
this.debug(' > subtest buffered, unfinished', p)
// unfinished buffered test.
// nothing to do yet, just leave it there.
this.queue.unshift(p)
}
}
/**
* Parse stdin as the only tap stream (ie, not as a child test)
* If used, then no other subtests or assertions are allowed.
*/
stdinOnly<T extends BaseOpts>(
extra?: T & { tapStream?: Readable | Minipass }
) {
const stream = ((extra && extra.tapStream) ||
process.stdin) as Minipass
if (!stream) {
throw new Error(
'cannot read stdin without stdin stream'
)
}
if (
this.queue.length !== 1 ||
this.queue[0] !== 'TAP version 14\n' ||
this.#processing ||
this.results ||
this.#occupied ||
this.pool.size ||
this.subtests.length
) {
throw new Error(
'Cannot use stdinOnly on a test in progress'
)
}
this.#doingStdinOnly = true
this.queue.length = 0
this.parser.on('child', p => {
// pretend to be a rooted parser, so it gets counts.
p.root = p
const t = new Base({
name: p.name,
parent: this,
parser: p,
bail: p.bail,
strict: p.strict,
omitVersion: p.omitVersion,
preserveWhitespace: p.preserveWhitespace,
childId: this.#nextChildId++,
})
this.emit('subtestAdd', t)
this.emit('subtestStart', t)
this.emit('subtestProcess', t)
p.on('complete', () => {
t.time = p.time
this.emit('subtestEnd', t)
})
})
stream.pause()
stream.pipe(this.parser)
stream.resume()
}
/**
* Mount a subtest, using this Test object as a harness.
* Exposed mainly so that it can be used by builtin plugins.
*
* @internal
*/
sub<T extends Base, O extends TestBaseOpts>(
Class: { new (options: O): T },
extra: O,
caller: (...a: any[]) => unknown
): Promise<FinalResults | null> {
if (this.bailedOut) return Promise.resolve(null)
if (this.results || this.ended) {
const er = new Error(
'cannot create subtest after parent test ends'
)
Error.captureStackTrace(er, caller)
this.threw(er)
return Promise.resolve(null)
}
extra.childId = this.#nextChildId++
if (this.shouldSkipChild(extra)) {
this.pass(extra.name, extra)
return Promise.resolve(null)
}
extra.indent = ' '
if (extra.buffered !== undefined) {
if (this.jobs > 1) {
extra.buffered = true
} else {
extra.buffered = false
}
}
extra.bail =
extra.bail !== undefined ? extra.bail : this.bail
extra.parent = this
extra.stack = stack.captureString(80, caller)
extra.context = this.context
const t = new Class(extra)
this.queue.push(t)
this.subtests.push(t)
this.emit('subtestAdd', t)
const d = new Deferred<FinalResults>()
t.deferred = d
this.#process()
return d.promise
}
/**
* Return true if the child test represented by the options object
* should be skipped. Extended by the grep/only filtering plugins.
*/
shouldSkipChild(extra: { [k: string]: any }) {
return !!(extra.skip || extra.todo)
}
// end flow control methods
}
|
src/test-base.ts
|
tapjs-core-edd7403
|
[
{
"filename": "src/plugin/after-each.ts",
"retrieved_chunk": " const onerr = (er: any) => {\n who.threw(er)\n cb()\n }\n const p = this.#t.parent\n const pae = !!p && AfterEach.#refs.get(p)\n const run = () => {\n if (pae) {\n pae.#runAfterEach(who, cb)\n } else {",
"score": 0.8017494082450867
},
{
"filename": "src/plugin/stdin.ts",
"retrieved_chunk": " name = undefined\n }\n extra = parseTestArgs<Stdin>(\n name,\n extra,\n false,\n '/dev/stdin'\n )\n return this.#t.sub(Stdin, extra, this.stdin)\n }",
"score": 0.7954085469245911
},
{
"filename": "src/plugin/before-each.ts",
"retrieved_chunk": " }\n #runBeforeEach(who: TestBase, cb: () => void) {\n // run all the beforeEach methods from the parent\n const onerr = (er: any) => {\n who.threw(er)\n cb()\n }\n const p = this.#t.parent\n const pbe = !!p && BeforeEach.#refs.get(p)\n if (pbe) {",
"score": 0.79167640209198
},
{
"filename": "src/spawn.ts",
"retrieved_chunk": " this.proc.kill('SIGKILL')\n }\n this.parser.abort('test unfinished')\n this.callCb()\n }\n callCb() {\n if (this.cb) {\n this.cb()\n }\n this.cb = null",
"score": 0.7914206385612488
},
{
"filename": "src/plugin/after-each.ts",
"retrieved_chunk": " cb()\n }\n }\n if (who !== this.#t) {\n loop(this.#onAfterEach, run, onerr)\n } else {\n run()\n }\n }\n}",
"score": 0.789577841758728
}
] |
typescript
|
name)
this.#processSubtest(p)
} else if (p === EOF) {
|
// Inspired by `https://github.com/jmilldotdev/obsidian-gpt/blob/main/src/models/chatGPT.ts`
import { RequestUrlParam, request } from "obsidian"
import { pythonifyKeys } from "src/utils"
import { Command } from "./commands"
import { Individuals, Topics } from "./mentors"
import { Mentor, Message, supportedLanguage } from "../types"
export enum ModelType {
Default = "gpt-3.5-turbo",
GPT3516k = "gpt-3.5-turbo-16k",
GPT4 = "gpt-4",
Davinci = "text-davinci-003",
}
export interface GPTSettings {
maxTokens: number
temperature: number
topP: number
presencePenalty: number
frequencyPenalty: number
stop: string[]
}
export const defaultSettings: GPTSettings = {
maxTokens: 200,
temperature: 1.0,
topP: 1.0,
presencePenalty: 0,
frequencyPenalty: 0,
stop: [],
}
export class MentorModel {
apiUrl = `https://api.openai.com/v1/chat/completions`
id: string
mentor: Mentor
model: ModelType
apiKey: string
preferredLanguage: supportedLanguage
history: Message[]
suffix: string | undefined = undefined
headers
constructor(
id: string,
mentor: Mentor,
model: ModelType,
apiKey: string,
preferredLanguage: supportedLanguage,
suffix?: string
) {
this.id = id
this.mentor = mentor
this.model = model
this.apiKey = apiKey
this.preferredLanguage = preferredLanguage
this.history = [
{ role: "system", content: mentor.systemPrompt[preferredLanguage] },
]
this.suffix = suffix
this.headers = {
Authorization: `Bearer ${this.apiKey}`,
"Content-Type": "application/json",
}
}
async getCompletion(message: string): Promise<string> {
const params = this.mentor.settings
// Check that API Key is set
if (!this.apiKey) {
return "Please set your OpenAI API key in the settings."
}
// Check that the model is set
if (!this.model) {
return "Please set your OpenAI model in the settings."
}
// Check that the message is not empty
if (!message) {
return "Please enter a message."
}
const messages = [...this.history, { role: "user", content: message }]
const body = {
messages,
model: this.model,
...pythonifyKeys(params),
stop: params.stop.length > 0 ? params.stop : undefined,
suffix: this.suffix,
}
const headers = this.headers
const requestUrlParam: RequestUrlParam = {
url: this.apiUrl,
method: "POST",
contentType: "application/json",
body: JSON.stringify(body),
headers,
}
this.history.push({ role: "user", content: message })
const answer = await request(requestUrlParam)
.then((response) => {
const answer =
JSON.parse(response)?.choices?.[0]?.message?.content
this.history.push({ role: "assistant", content: answer })
return answer
})
.catch((err) => {
console.error(err)
return "I got an error when trying to reply."
})
return answer
}
|
async execute(text: string, command: Command): Promise<string[]> {
|
const params = command.settings
const mentorList: Record<string, Mentor> = {
...Topics,
...Individuals,
}
const requestedMentor = mentorList[command.mentor]
const prompts = command.pattern.map((prompt) => {
return prompt[this.preferredLanguage].replace("*", text)
})
this.history = [
{
role: "system",
content: requestedMentor.systemPrompt[this.preferredLanguage],
},
command.prompt[this.preferredLanguage],
]
const answers: string[] = []
for (const prompt of prompts) {
this.history.push({ role: "user", content: prompt })
const body = {
messages: this.history,
model: this.model,
...pythonifyKeys(params),
stop: params.stop.length > 0 ? params.stop : undefined,
suffix: this.suffix,
}
const headers = this.headers
const requestUrlParam: RequestUrlParam = {
url: this.apiUrl,
method: "POST",
contentType: "application/json",
body: JSON.stringify(body),
headers,
}
const answer = await request(requestUrlParam)
.then((response) => {
return JSON.parse(response)?.choices?.[0]?.message?.content
})
.catch((err) => {
console.error(err)
return "I got an error when trying to reply."
})
this.history.push({ role: "assistant", content: answer })
answers.push(answer)
}
// Reset history
this.reset()
return answers
}
changeIdentity(id: string, newMentor: Mentor) {
this.id = id
this.mentor = newMentor
this.history = [
{
role: "system",
content: newMentor.systemPrompt[this.preferredLanguage],
},
]
}
reset() {
this.history = [
{
role: "system",
content: this.mentor.systemPrompt[this.preferredLanguage],
},
]
}
}
|
src/ai/model.ts
|
clementpoiret-ai-mentor-b62d95a
|
[
{
"filename": "src/components/chatview.ts",
"retrieved_chunk": "\t\t\tthis.mentor.history.length !== 0 &&\n\t\t\tthis.mentor.history[this.mentor.history.length - 1].role === \"user\"\n\t\t) {\n\t\t\tnew Notice(\"Please wait for your mentor to respond.\")\n\t\t\treturn\n\t\t}\n\t\tconst prompt = await this.handleKeywordsInPrompt(this.currentInput)\n\t\t// Display the prompt\n\t\tthis.displayedMessages.push({\n\t\t\trole: \"user\",",
"score": 0.8114468455314636
},
{
"filename": "src/components/chatview.ts",
"retrieved_chunk": "\t\t\t\tthis.currentInput = \"\"\n\t\t\t\t// Display the response.\n\t\t\t\tthis.displayedMessages.pop()\n\t\t\t\tthis.displayedMessages.push({\n\t\t\t\t\trole: \"assistant\",\n\t\t\t\t\tcontent: response,\n\t\t\t\t})\n\t\t\t\t// Refresh the view.\n\t\t\t\tawait this.onOpen()\n\t\t\t})",
"score": 0.8091385960578918
},
{
"filename": "src/components/chatview.ts",
"retrieved_chunk": "\t\t\t.catch(async (error) => {\n\t\t\t\tconsole.log(\"error\", error)\n\t\t\t\t// Clear the input.\n\t\t\t\tthis.currentInput = \"\"\n\t\t\t\t// Display the error message.\n\t\t\t\tthis.displayedMessages.pop()\n\t\t\t\tthis.displayedMessages.push({\n\t\t\t\t\trole: \"assistant\",\n\t\t\t\t\tcontent: \"An error occurred. Please try again.\",\n\t\t\t\t})",
"score": 0.8032835721969604
},
{
"filename": "src/components/chatview.ts",
"retrieved_chunk": "\t\t\t{\n\t\t\t\trole: \"assistant\",\n\t\t\t\tcontent: newMentor.firstMessage[this.preferredLanguage],\n\t\t\t},\n\t\t]\n\t\t// Refresh the view.\n\t\tawait this.onOpen()\n\t}\n\tasync handleKeywordsInPrompt(prompt: string): Promise<string> {\n\t\t// Todo: return a prompt that do not contain the note to be inserted in the chat",
"score": 0.7913008332252502
},
{
"filename": "src/ai/commands.ts",
"retrieved_chunk": "import { GPTSettings } from \"./model\"\nimport { Message, MultiLingualString, supportedLanguage } from \"../types\"\nexport interface Command {\n\tmentor: string\n\tprompt: Record<supportedLanguage, Message>\n\tpattern: MultiLingualString[]\n\tsettings: GPTSettings\n}\nexport const commands: Record<string, Command> = {\n\texplain: {",
"score": 0.7839587926864624
}
] |
typescript
|
async execute(text: string, command: Command): Promise<string[]> {
|
// lifecycle methods like beforeEach, afterEach, teardown
// defined in plugins/lifecycle.ts
import Minipass from 'minipass'
import assert from 'node:assert'
import { hrtime } from 'node:process'
import { Readable } from 'node:stream'
import { format } from 'node:util'
import { CallSiteLike } from 'stack-utils'
import { FinalResults } from 'tap-parser'
import Deferred from 'trivial-deferred'
import { Base, BaseOpts } from './base.js'
import { esc } from './esc.js'
import stack from './stack.js'
import { TestPoint } from './test-point.js'
import { Waiter } from './waiter.js'
const queueEmpty = <T extends TestBase>(t: T) =>
t.queue.length === 0 ||
(t.queue.length === 1 &&
t.queue[0] === 'TAP version 14\n')
export interface ClassOf<T> {
new (): T
}
export type TapPlugin<
B extends Object,
O extends TestBaseOpts | any = any
> = ((t: TestBase, opts: O) => B) | ((t: TestBase) => B)
export interface TestBaseOpts extends BaseOpts {
/**
* The number of jobs to run in parallel. Defaults to 1
*/
jobs?: number
/**
* Test function called when this Test is executed
*/
cb?: (...args: any[]) => any
/**
* Flag to always/never show diagnostics. If unset, then
* diagnostics are shown for failing test points only.
*/
diagnostic?: boolean
}
const normalizeMessageExtra = (
defaultMessage: string,
message?: string | { [k: string]: any },
extra?: { [k: string]: any }
): [string, { [k: string]: any }] => {
if (typeof message === 'string') {
return [message || defaultMessage, extra || {}]
} else {
return [defaultMessage, message || {}]
}
}
/**
* Sigil for implicit end() calls that should not
* trigger an error if the user then calls t.end()
*/
const IMPLICIT = Symbol('implicit end')
/**
* Sigil to put in the queue to signal the end of all things
*/
const EOF = Symbol('EOF')
export type QueueEntry =
| string
| TestPoint
| Base
| typeof EOF
| Waiter
| [method: string, ...args: any[]]
/**
* The TestBaseBase class is the base class for all plugins,
* and eventually thus the Test class.
*
* This implements subtest functionality, TAP stream generation,
* lifecycle events, and only the most basic pass/fail assertions.
*
* All other features are added with plugins.
*/
export class TestBase extends Base {
// NB: generated pluginified Test class needs to declare over this
declare parent?: TestBase
promise?: Promise<any>
jobs: number
// #beforeEnd: [method: string | Symbol, ...args: any[]][] = []
subtests: Base[] = []
pool: Set<Base> = new Set()
queue: QueueEntry[] = ['TAP version 14\n']
cb?: (...args: any[]) => any
count: number = 0
ended: boolean = false
assertAt: CallSiteLike | null = null
assertStack: string | null = null
diagnostic: null | boolean = null
#planEnd: number = -1
#printedResult: boolean = false
#explicitEnded: boolean = false
#multiEndThrew: boolean = false
#n: number = 0
#noparallel: boolean = false
#occupied: null | Waiter | Base = null
#pushedEnd: boolean = false
#nextChildId: number = 1
#currentAssert: null | ((..._: any) => any) = null
#processing: boolean = false
#doingStdinOnly: boolean = false
/**
* true if the test has printed at least one TestPoint
*/
get printedResult(): boolean {
return this.#printedResult
}
constructor(options: TestBaseOpts) {
super(options)
this.jobs =
(options.jobs && Math.max(options.jobs, 1)) || 1
if (typeof options.diagnostic === 'boolean') {
this.diagnostic = options.diagnostic
}
if (options.cb) {
this.#setCB(options.cb)
}
}
#setCB<T extends TestBase>(this: T, cb: (t: T) => any) {
this.cb = (...args: any[]) =>
this.hook.runInAsyncScope(cb, this, ...args)
}
// TAP output generating methods
/**
* immediately exit this and all parent tests with a TAP
* Bail out! message.
*/
bailout(message?: string) {
if (this.parent && (this.results || this.ended)) {
this.parent.bailout(message)
} else {
this.#process()
message = message
? ' ' + ('' + esc(message)).trim()
: ''
message = message.replace(/[\r\n]/g, ' ')
this.parser.write('Bail out!' + message + '\n')
}
this.#end(IMPLICIT)
this.#process()
}
/**
* output a TAP comment, formatted like console.log()
*/
comment(...args: any[]) {
const body = format(...args)
const message =
('# ' + body.split(/\r?\n/).join('\n# ')).trim() +
'\n'
if (this.results) {
this.write(message)
} else {
this.queue.push(message)
}
this.#process()
}
/**
* Called when the test times out.
* Options are passed as diagnostics to the threw() method
*/
timeout(options: { [k: string]: any }) {
options = options || {}
options.expired = options.expired || this.name
if (this.#occupied && this.#occupied instanceof Base) {
this.#occupied.timeout(options)
} else {
super.timeout(options)
}
this.#end(IMPLICIT)
}
/**
* Set TAP pragma configs to affect the behavior of the parser.
* Only `strict` is supported by the parser.
*/
pragma(set: { [k: string]: boolean }) {
const p = Object.keys(set).reduce(
(acc, i) =>
acc + 'pragma ' + (set[i] ? '+' : '-') + i + '\n',
''
)
this.queue.push(p)
this.#process()
}
/**
* Specify the number of Test Points expected by this test.
* Outputs a TAP plan line.
*/
plan(n: number, comment?: string) {
if (this.bailedOut) {
return
}
if (this.#planEnd !== -1) {
throw new Error('Cannot set plan more than once')
}
if (typeof n !== 'number' || n < 0) {
throw new TypeError('plan must be a number')
}
// Cannot get any tests after a trailing plan, or a plan of 0
const ending = this.count !== 0 || n === 0
if (n === 0 && comment && !this.options.skip) {
this.options.skip = comment
}
this.#planEnd = n
comment = comment ? ' # ' + esc(comment.trim()) : ''
this.queue.push('1..' + n + comment + '\n')
if (ending) {
this.#end(IMPLICIT)
} else {
this.#process()
}
}
/**
* A passing (ok) Test Point
*/
pass(message?: string, extra?: { [k: string]: any }) {
this.currentAssert = TestBase.prototype.pass
this.printResult(
true,
...normalizeMessageExtra(
'(unnamed test)',
message,
extra
)
)
return true
}
/**
* A failing (not ok) Test Point
*/
fail(message?: string, extra?: { [k: string]: any }) {
this.currentAssert = TestBase.prototype.fail
const [m, e] = normalizeMessageExtra(
'(unnamed test)',
message,
extra
)
this.printResult(false, m, e)
return !!(e.todo || e.skip)
}
/**
* The current assertion being processed. May only be set if
* not already set.
*/
get currentAssert() {
return this.#currentAssert
}
/**
* The current assertion being processed. May only be set if
* not already set.
*/
set currentAssert(fn: null | ((...a: any[]) => any)) {
if (!this.#currentAssert && typeof fn === 'function') {
this.#currentAssert = fn
}
}
/**
* Print a Test Point
*/
printResult(
ok: boolean,
message: string,
extra: { [k: string]: any },
front: boolean = false
) {
this.#printedResult = true
const n = this.count + 1
this.currentAssert = TestBase.prototype.printResult
const fn = this.#currentAssert
this.#currentAssert = null
if (this.#planEnd !== -1 && n > this.#planEnd) {
if (!this.passing()) return
const failMessage = this.#explicitEnded
? 'test after end() was called'
: 'test count exceeds plan'
const er = new Error(failMessage, {
cause: {
test: this.name,
plan: this.#planEnd,
},
})
Error.captureStackTrace(er, fn || undefined)
this.threw(er)
return
}
extra = extra || {}
if (extra.expectFail) {
ok = !ok
}
if (this.assertAt) {
extra.at = this.assertAt
this.assertAt = null
}
if (this.assertStack) {
extra.stack = this.assertStack
this.assertStack = null
}
if (typeof extra.stack === 'string' && !extra.at) {
extra.at = stack.parseLine(extra.stack.split('\n')[0])
}
if (
!ok &&
!extra.skip &&
!extra.at &&
typeof fn === 'function'
) {
extra.at = stack.at(fn)
if (!extra.todo) {
extra.stack = stack.captureString(80, fn)
}
}
const diagnostic =
typeof extra.diagnostic === 'boolean'
? extra.diagnostic
: typeof this.diagnostic === 'boolean'
? this.diagnostic
: extra.skip || extra.todo
? false
: !ok
if (diagnostic) {
extra.diagnostic = true
}
this.count = n
message = message + ''
const res = { ok, message, extra }
const tp = new TestPoint(ok, message, extra)
// when we jump the queue, skip an extra line
if (front) {
tp.message = tp.message.trimEnd() + '\n\n'
}
if (
this.#occupied &&
this.#occupied instanceof Waiter &&
this.#occupied.finishing
) {
front = true
}
if (front) {
if (
extra.tapChildBuffer ||
extra.tapChildBuffer === ''
) {
this.writeSubComment(tp)
this.parser.write(extra.tapChildBuffer)
}
this.emit('result', res)
this.parser.write(tp.ok + ++this.#n + tp.message)
if (this.bail && !ok && !extra.skip && !extra.todo) {
this.parser.write('Bail out! ' + message + '\n')
}
} else {
this.queue.push(tp)
if (this.bail && !ok && !extra.skip && !extra.todo) {
this.queue.push('Bail out! ' + message + '\n')
}
}
if (this.#planEnd === this.count) {
this.#end(IMPLICIT)
}
this.#process()
}
end(): this {
this.#end()
return super.end()
}
/**
* The leading `# Subtest` comment that introduces a child test
*/
writeSubComment<T extends TestPoint | Base>(p: T) {
const comment =
'# Subtest' +
(p.name ? ': ' + esc(p.name) : '') +
'\n'
this.parser.write(comment)
}
// end TAP otput generating methods
// flow control methods
/**
* Await the end of a Promise before proceeding.
* The supplied callback is called with the Waiter object.
*/
waitOn(
promise: Promise<any | void>,
cb: (w
|
: Waiter) => any,
expectReject: boolean = false
): Promise<void> {
|
const w = new Waiter(
promise,
w => {
assert.equal(this.#occupied, w)
cb(w)
this.#occupied = null
this.#process()
},
expectReject
)
this.queue.push(w)
this.#process()
return w.promise
}
#end(implicit?: typeof IMPLICIT) {
if (this.#doingStdinOnly && implicit !== IMPLICIT)
throw new Error(
'cannot explicitly end while in stdinOnly mode'
)
this.debug('END implicit=%j', implicit === IMPLICIT)
if (this.ended && implicit === IMPLICIT) return
// beyond here we have to be actually done with things, or else
// the semantic checks on counts and such will be off.
if (!queueEmpty(this) || this.#occupied) {
if (!this.#pushedEnd) {
this.queue.push(['#end', implicit])
}
this.#pushedEnd = true
return this.#process()
}
this.ended = true
if (implicit !== IMPLICIT && !this.#multiEndThrew) {
if (this.#explicitEnded) {
this.#multiEndThrew = true
const er = new Error(
'test end() method called more than once'
)
Error.captureStackTrace(
er,
this.#currentAssert || this.#end
)
er.cause = {
test: this.name,
}
this.threw(er)
return
}
this.#explicitEnded = true
}
if (this.#planEnd === -1) {
this.debug(
'END(%s) implicit plan',
this.name,
this.count
)
this.plan(this.count)
}
this.queue.push(EOF)
this.#process()
}
#process() {
if (this.#processing) {
return this.debug(' < already processing')
}
this.debug(
'\nPROCESSING(%s)',
this.name,
this.queue.length
)
this.#processing = true
while (!this.#occupied) {
const p = this.queue.shift()
if (!p) {
this.debug('> end of queue')
break
}
if (p instanceof Base) {
this.debug('> subtest in queue', p.name)
this.#processSubtest(p)
} else if (p === EOF) {
this.debug(' > EOF', this.name)
// I AM BECOME EOF, DESTROYER OF STREAMS
this.parser.end()
} else if (p instanceof TestPoint) {
this.debug(' > TESTPOINT')
if (
p.extra.tapChildBuffer ||
p.extra.tapChildBuffer === ''
) {
this.writeSubComment(p)
this.parser.write(p.extra.tapChildBuffer)
}
this.emit('res', p.res)
this.parser.write(p.ok + ++this.#n + p.message)
} else if (typeof p === 'string') {
this.debug(' > STRING')
this.parser.write(p)
} else if (p instanceof Waiter) {
p.ready = true
this.#occupied = p
p.finish()
} else if (Array.isArray(p)) {
this.debug(' > METHOD')
const m = p.shift() as keyof this
if (typeof this[m] !== 'function') {
this.debug(
' > weird method not found in queue??',
m,
typeof this[m]
)
continue
}
const fn = (m === '#end' ? this.#end : this[m]) as (
...a: any[]
) => any
const ret = fn.call(this, ...p)
if (
ret &&
typeof ret === 'object' &&
typeof ret.then === 'function'
) {
// returned promise
ret.then(
() => {
this.#processing = false
this.#process()
},
(er: unknown) => {
this.#processing = false
this.threw(er)
}
)
return
}
/* c8 ignore start */
} else {
throw new Error('weird thing got in the queue')
}
/* c8 ignore stop */
}
while (
!this.#noparallel &&
this.pool.size < this.jobs
) {
const p = this.subtests.shift()
if (!p) {
break
}
if (!p.buffered) {
this.#noparallel = true
break
}
this.debug('start subtest', p)
this.emit('subtestStart', p)
this.pool.add(p)
if (this.bailedOut) {
this.#onBufferedEnd(p)
} else {
p.runMain(() => this.#onBufferedEnd(p))
}
}
this.debug(
'done processing',
this.queue,
this.#occupied
)
this.#processing = false
// just in case any tests ended, and we have sync stuff still
// waiting around in the queue to be processed
if (!this.#occupied && this.queue.length) {
this.#process()
}
}
#onBufferedEnd<T extends Base>(p: T) {
p.ondone = p.constructor.prototype.ondone
p.results =
p.results || new FinalResults(true, p.parser)
p.readyToProcess = true
const to = p.options.timeout
const dur =
to && p.passing() ? hrtime.bigint() - p.start : null
if (dur && to && dur > to) {
p.timeout()
} else {
p.setTimeout(0)
}
this.debug(
'%s.#onBufferedEnd',
this.name,
p.name,
p.results.bailout
)
this.pool.delete(p)
p.options.tapChildBuffer = p.output || ''
p.options.stack = ''
if (p.time) p.options.time = p.time
if (this.#occupied === p) this.#occupied = null
p.deferred?.resolve(p.results)
this.emit('subtestEnd', p)
this.#process()
}
#onIndentedEnd<T extends Base>(p: T) {
this.emit('subtestProcess', p)
p.ondone = p.constructor.prototype.ondone
p.results =
p.results || new FinalResults(true, p.parser)
this.debug('#onIndentedEnd', this.name, p.name)
this.#noparallel = false
const sti = this.subtests.indexOf(p)
if (sti !== -1) this.subtests.splice(sti, 1)
p.readyToProcess = true
p.options.time = p.time
const to = p.options.timeout
const dur =
to && p.passing() ? hrtime.bigint() - p.start : null
if (dur && to && dur > to) {
p.timeout()
} else {
p.setTimeout(0)
}
this.debug('#onIndentedEnd %s(%s)', this.name, p.name)
this.#occupied = null
this.debug(
'OIE(%s) b>shift into queue',
this.name,
this.queue
)
p.options.stack = ''
this.printResult(p.passing(), p.name, p.options, true)
this.debug(
'OIE(%s) shifted into queue',
this.name,
this.queue
)
p.deferred?.resolve(p.results)
this.emit('subtestEnd', p)
this.#process()
}
/**
* @internal
*/
main(cb: () => void) {
if (typeof this.options.timeout === 'number') {
this.setTimeout(this.options.timeout)
}
this.debug('MAIN pre', this)
const end = () => {
this.debug(' > implicit end for promise')
this.#end(IMPLICIT)
done()
}
const done = (er?: Error) => {
if (er) this.threw(er)
if (this.results || this.bailedOut) cb()
else this.ondone = () => cb()
}
// This bit of overly clever line-noise wraps the call to user-code
// in a try-catch. We can't rely on the domain for this yet, because
// the 'end' event can trigger a throw after the domain is unhooked,
// but before this is no longer the official "active test"
const ret = (() => {
if (!this.cb) return
try {
return this.cb(this)
} catch (er: any) {
if (!er || typeof er !== 'object') {
er = { error: er }
}
er.tapCaught = 'testFunctionThrow'
this.threw(er)
}
})()
if (ret && ret.then) {
this.promise = ret
ret.tapAbortPromise = done
ret.then(end, (er: any) => {
if (!er || typeof er !== 'object') {
er = { error: er }
}
er.tapCaught = 'returnedPromiseRejection'
done(er)
})
} else done()
this.debug('MAIN post', this)
}
#processSubtest<T extends Base>(p: T) {
this.debug(' > subtest')
this.#occupied = p
if (!p.buffered) {
this.emit('subtestStart', p)
this.debug(' > subtest indented')
p.stream.pipe(this.parser, { end: false })
this.writeSubComment(p)
this.debug('calling runMain', p.runMain.toString())
p.runMain(() => {
this.debug('in runMain', p.runMain.toString())
this.#onIndentedEnd(p)
})
} else if (p.readyToProcess) {
this.emit('subtestProcess', p)
this.debug(' > subtest buffered, finished')
// finished! do the thing!
this.#occupied = null
if (!p.passing() || !p.silent) {
this.printResult(
p.passing(),
p.name,
p.options,
true
)
}
} else {
this.#occupied = p
this.debug(' > subtest buffered, unfinished', p)
// unfinished buffered test.
// nothing to do yet, just leave it there.
this.queue.unshift(p)
}
}
/**
* Parse stdin as the only tap stream (ie, not as a child test)
* If used, then no other subtests or assertions are allowed.
*/
stdinOnly<T extends BaseOpts>(
extra?: T & { tapStream?: Readable | Minipass }
) {
const stream = ((extra && extra.tapStream) ||
process.stdin) as Minipass
if (!stream) {
throw new Error(
'cannot read stdin without stdin stream'
)
}
if (
this.queue.length !== 1 ||
this.queue[0] !== 'TAP version 14\n' ||
this.#processing ||
this.results ||
this.#occupied ||
this.pool.size ||
this.subtests.length
) {
throw new Error(
'Cannot use stdinOnly on a test in progress'
)
}
this.#doingStdinOnly = true
this.queue.length = 0
this.parser.on('child', p => {
// pretend to be a rooted parser, so it gets counts.
p.root = p
const t = new Base({
name: p.name,
parent: this,
parser: p,
bail: p.bail,
strict: p.strict,
omitVersion: p.omitVersion,
preserveWhitespace: p.preserveWhitespace,
childId: this.#nextChildId++,
})
this.emit('subtestAdd', t)
this.emit('subtestStart', t)
this.emit('subtestProcess', t)
p.on('complete', () => {
t.time = p.time
this.emit('subtestEnd', t)
})
})
stream.pause()
stream.pipe(this.parser)
stream.resume()
}
/**
* Mount a subtest, using this Test object as a harness.
* Exposed mainly so that it can be used by builtin plugins.
*
* @internal
*/
sub<T extends Base, O extends TestBaseOpts>(
Class: { new (options: O): T },
extra: O,
caller: (...a: any[]) => unknown
): Promise<FinalResults | null> {
if (this.bailedOut) return Promise.resolve(null)
if (this.results || this.ended) {
const er = new Error(
'cannot create subtest after parent test ends'
)
Error.captureStackTrace(er, caller)
this.threw(er)
return Promise.resolve(null)
}
extra.childId = this.#nextChildId++
if (this.shouldSkipChild(extra)) {
this.pass(extra.name, extra)
return Promise.resolve(null)
}
extra.indent = ' '
if (extra.buffered !== undefined) {
if (this.jobs > 1) {
extra.buffered = true
} else {
extra.buffered = false
}
}
extra.bail =
extra.bail !== undefined ? extra.bail : this.bail
extra.parent = this
extra.stack = stack.captureString(80, caller)
extra.context = this.context
const t = new Class(extra)
this.queue.push(t)
this.subtests.push(t)
this.emit('subtestAdd', t)
const d = new Deferred<FinalResults>()
t.deferred = d
this.#process()
return d.promise
}
/**
* Return true if the child test represented by the options object
* should be skipped. Extended by the grep/only filtering plugins.
*/
shouldSkipChild(extra: { [k: string]: any }) {
return !!(extra.skip || extra.todo)
}
// end flow control methods
}
|
src/test-base.ts
|
tapjs-core-edd7403
|
[
{
"filename": "src/waiter.ts",
"retrieved_chunk": " resolve: null | ((value?:any)=>void) = null\n constructor (promise: Promise<any|void>, cb:(w:Waiter)=>any, expectReject:boolean = false) {\n this.cb = cb\n this.expectReject = !!expectReject\n this.promise = new Promise<void>(res => this.resolve = res)\n promise.then(value => {\n if (this.done) {\n return\n }\n this.resolved = true",
"score": 0.8893133401870728
},
{
"filename": "src/waiter.ts",
"retrieved_chunk": "export class Waiter {\n cb: null | ((w:Waiter)=>any)\n ready: boolean = false\n value: any = null\n resolved: boolean = false\n rejected: boolean = false\n done: boolean = false\n finishing: boolean = false\n expectReject: boolean\n promise: Promise<void>",
"score": 0.8628900051116943
},
{
"filename": "src/test-built.ts",
"retrieved_chunk": " t: Test\n test(\n name: string,\n extra: { [k: string]: any },\n cb?: (t: Test) => any\n ): Promise<FinalResults | null>\n test(\n name: string,\n cb?: (t: Test) => any\n ): Promise<FinalResults | null>",
"score": 0.7899848222732544
},
{
"filename": "src/plugin/after-each.ts",
"retrieved_chunk": " cb()\n }\n }\n if (who !== this.#t) {\n loop(this.#onAfterEach, run, onerr)\n } else {\n run()\n }\n }\n}",
"score": 0.7888242602348328
},
{
"filename": "src/test-built.ts",
"retrieved_chunk": " todo(\n name: string,\n cb?: (t: Test) => any\n ): Promise<FinalResults | null>\n todo(\n extra: { [k: string]: any },\n cb?: (t: Test) => any\n ): Promise<FinalResults | null>\n todo(cb?: (t: Test) => any): Promise<FinalResults | null>\n todo(",
"score": 0.787346601486206
}
] |
typescript
|
: Waiter) => any,
expectReject: boolean = false
): Promise<void> {
|
// Inspired by `https://github.com/jmilldotdev/obsidian-gpt/blob/main/src/models/chatGPT.ts`
import { RequestUrlParam, request } from "obsidian"
import { pythonifyKeys } from "src/utils"
import { Command } from "./commands"
import { Individuals, Topics } from "./mentors"
import { Mentor, Message, supportedLanguage } from "../types"
export enum ModelType {
Default = "gpt-3.5-turbo",
GPT3516k = "gpt-3.5-turbo-16k",
GPT4 = "gpt-4",
Davinci = "text-davinci-003",
}
export interface GPTSettings {
maxTokens: number
temperature: number
topP: number
presencePenalty: number
frequencyPenalty: number
stop: string[]
}
export const defaultSettings: GPTSettings = {
maxTokens: 200,
temperature: 1.0,
topP: 1.0,
presencePenalty: 0,
frequencyPenalty: 0,
stop: [],
}
export class MentorModel {
apiUrl = `https://api.openai.com/v1/chat/completions`
id: string
mentor: Mentor
model: ModelType
apiKey: string
preferredLanguage: supportedLanguage
history: Message[]
suffix: string | undefined = undefined
headers
constructor(
id: string,
mentor: Mentor,
model: ModelType,
apiKey: string,
preferredLanguage: supportedLanguage,
suffix?: string
) {
this.id = id
this.mentor = mentor
this.model = model
this.apiKey = apiKey
this.preferredLanguage = preferredLanguage
this.history = [
{ role: "system", content: mentor.systemPrompt[preferredLanguage] },
]
this.suffix = suffix
this.headers = {
Authorization: `Bearer ${this.apiKey}`,
"Content-Type": "application/json",
}
}
async getCompletion(message: string): Promise<string> {
const params = this.mentor.settings
// Check that API Key is set
if (!this.apiKey) {
return "Please set your OpenAI API key in the settings."
}
// Check that the model is set
if (!this.model) {
return "Please set your OpenAI model in the settings."
}
// Check that the message is not empty
if (!message) {
return "Please enter a message."
}
const messages = [...this.history, { role: "user", content: message }]
const body = {
messages,
model: this.model,
...pythonifyKeys(params),
stop: params.stop.length > 0 ? params.stop : undefined,
suffix: this.suffix,
}
const headers = this.headers
const requestUrlParam: RequestUrlParam = {
url: this.apiUrl,
method: "POST",
contentType: "application/json",
body: JSON.stringify(body),
headers,
}
this.history.push({ role: "user", content: message })
const answer = await request(requestUrlParam)
.then((response) => {
const answer =
JSON.parse(response)?.choices?.[0]?.message?.content
this.history.push({ role: "assistant", content: answer })
return answer
})
.catch((err) => {
console.error(err)
return "I got an error when trying to reply."
})
return answer
}
async execute(text: string, command: Command): Promise<string[]> {
const params = command.settings
const mentorList: Record<string, Mentor> = {
...Topics,
...Individuals,
}
const requestedMentor = mentorList[command.mentor]
|
const prompts = command.pattern.map((prompt) => {
|
return prompt[this.preferredLanguage].replace("*", text)
})
this.history = [
{
role: "system",
content: requestedMentor.systemPrompt[this.preferredLanguage],
},
command.prompt[this.preferredLanguage],
]
const answers: string[] = []
for (const prompt of prompts) {
this.history.push({ role: "user", content: prompt })
const body = {
messages: this.history,
model: this.model,
...pythonifyKeys(params),
stop: params.stop.length > 0 ? params.stop : undefined,
suffix: this.suffix,
}
const headers = this.headers
const requestUrlParam: RequestUrlParam = {
url: this.apiUrl,
method: "POST",
contentType: "application/json",
body: JSON.stringify(body),
headers,
}
const answer = await request(requestUrlParam)
.then((response) => {
return JSON.parse(response)?.choices?.[0]?.message?.content
})
.catch((err) => {
console.error(err)
return "I got an error when trying to reply."
})
this.history.push({ role: "assistant", content: answer })
answers.push(answer)
}
// Reset history
this.reset()
return answers
}
changeIdentity(id: string, newMentor: Mentor) {
this.id = id
this.mentor = newMentor
this.history = [
{
role: "system",
content: newMentor.systemPrompt[this.preferredLanguage],
},
]
}
reset() {
this.history = [
{
role: "system",
content: this.mentor.systemPrompt[this.preferredLanguage],
},
]
}
}
|
src/ai/model.ts
|
clementpoiret-ai-mentor-b62d95a
|
[
{
"filename": "src/ai/commands.ts",
"retrieved_chunk": "import { GPTSettings } from \"./model\"\nimport { Message, MultiLingualString, supportedLanguage } from \"../types\"\nexport interface Command {\n\tmentor: string\n\tprompt: Record<supportedLanguage, Message>\n\tpattern: MultiLingualString[]\n\tsettings: GPTSettings\n}\nexport const commands: Record<string, Command> = {\n\texplain: {",
"score": 0.8278685212135315
},
{
"filename": "src/components/chatview.ts",
"retrieved_chunk": "\t\t\t{\n\t\t\t\trole: \"assistant\",\n\t\t\t\tcontent: newMentor.firstMessage[this.preferredLanguage],\n\t\t\t},\n\t\t]\n\t\t// Refresh the view.\n\t\tawait this.onOpen()\n\t}\n\tasync handleKeywordsInPrompt(prompt: string): Promise<string> {\n\t\t// Todo: return a prompt that do not contain the note to be inserted in the chat",
"score": 0.783913791179657
},
{
"filename": "src/components/chatview.ts",
"retrieved_chunk": "\t\t\tthis.mentor.history.length !== 0 &&\n\t\t\tthis.mentor.history[this.mentor.history.length - 1].role === \"user\"\n\t\t) {\n\t\t\tnew Notice(\"Please wait for your mentor to respond.\")\n\t\t\treturn\n\t\t}\n\t\tconst prompt = await this.handleKeywordsInPrompt(this.currentInput)\n\t\t// Display the prompt\n\t\tthis.displayedMessages.push({\n\t\t\trole: \"user\",",
"score": 0.7793036103248596
},
{
"filename": "src/main.ts",
"retrieved_chunk": "\t\t\t\t\t\t\talfred\n\t\t\t\t\t\t\t\t.execute(selection, commands.explain)\n\t\t\t\t\t\t\t\t.then((response) => {\n\t\t\t\t\t\t\t\t\tif (response) {\n\t\t\t\t\t\t\t\t\t\t// Show the explanation\n\t\t\t\t\t\t\t\t\t\tloadingModal.close()\n\t\t\t\t\t\t\t\t\t\tnew MentorModal(\n\t\t\t\t\t\t\t\t\t\t\tthis.app,\n\t\t\t\t\t\t\t\t\t\t\ttitle,\n\t\t\t\t\t\t\t\t\t\t\tresponse[0] // Only one possible response",
"score": 0.7770801186561584
},
{
"filename": "src/ai/commands.ts",
"retrieved_chunk": "\t\tmentor: \"science\",\n\t\tprompt: {\n\t\t\ten: {\n\t\t\t\trole: \"system\",\n\t\t\t\tcontent:\n\t\t\t\t\t\"Now, your only job is to explain any concepts in an easy-to-understand manner. I will give you a text, and you will only reply with an explanation. This could include providing examples or breaking down complex ideas into smaller pieces that are easier to comprehend.\",\n\t\t\t},\n\t\t\tfr: {\n\t\t\t\trole: \"system\",\n\t\t\t\tcontent:",
"score": 0.763383686542511
}
] |
typescript
|
const prompts = command.pattern.map((prompt) => {
|
// lifecycle methods like beforeEach, afterEach, teardown
// defined in plugins/lifecycle.ts
import Minipass from 'minipass'
import assert from 'node:assert'
import { hrtime } from 'node:process'
import { Readable } from 'node:stream'
import { format } from 'node:util'
import { CallSiteLike } from 'stack-utils'
import { FinalResults } from 'tap-parser'
import Deferred from 'trivial-deferred'
import { Base, BaseOpts } from './base.js'
import { esc } from './esc.js'
import stack from './stack.js'
import { TestPoint } from './test-point.js'
import { Waiter } from './waiter.js'
const queueEmpty = <T extends TestBase>(t: T) =>
t.queue.length === 0 ||
(t.queue.length === 1 &&
t.queue[0] === 'TAP version 14\n')
export interface ClassOf<T> {
new (): T
}
export type TapPlugin<
B extends Object,
O extends TestBaseOpts | any = any
> = ((t: TestBase, opts: O) => B) | ((t: TestBase) => B)
export interface TestBaseOpts extends BaseOpts {
/**
* The number of jobs to run in parallel. Defaults to 1
*/
jobs?: number
/**
* Test function called when this Test is executed
*/
cb?: (...args: any[]) => any
/**
* Flag to always/never show diagnostics. If unset, then
* diagnostics are shown for failing test points only.
*/
diagnostic?: boolean
}
const normalizeMessageExtra = (
defaultMessage: string,
message?: string | { [k: string]: any },
extra?: { [k: string]: any }
): [string, { [k: string]: any }] => {
if (typeof message === 'string') {
return [message || defaultMessage, extra || {}]
} else {
return [defaultMessage, message || {}]
}
}
/**
* Sigil for implicit end() calls that should not
* trigger an error if the user then calls t.end()
*/
const IMPLICIT = Symbol('implicit end')
/**
* Sigil to put in the queue to signal the end of all things
*/
const EOF = Symbol('EOF')
export type QueueEntry =
| string
| TestPoint
| Base
| typeof EOF
| Waiter
| [method: string, ...args: any[]]
/**
* The TestBaseBase class is the base class for all plugins,
* and eventually thus the Test class.
*
* This implements subtest functionality, TAP stream generation,
* lifecycle events, and only the most basic pass/fail assertions.
*
* All other features are added with plugins.
*/
export class TestBase extends Base {
// NB: generated pluginified Test class needs to declare over this
declare parent?: TestBase
promise?: Promise<any>
jobs: number
// #beforeEnd: [method: string | Symbol, ...args: any[]][] = []
subtests: Base[] = []
pool: Set<Base> = new Set()
queue: QueueEntry[] = ['TAP version 14\n']
cb?: (...args: any[]) => any
count: number = 0
ended: boolean = false
assertAt: CallSiteLike | null = null
assertStack: string | null = null
diagnostic: null | boolean = null
#planEnd: number = -1
#printedResult: boolean = false
#explicitEnded: boolean = false
#multiEndThrew: boolean = false
#n: number = 0
#noparallel: boolean = false
#occupied: null | Waiter | Base = null
#pushedEnd: boolean = false
#nextChildId: number = 1
#currentAssert: null | ((..._: any) => any) = null
#processing: boolean = false
#doingStdinOnly: boolean = false
/**
* true if the test has printed at least one TestPoint
*/
get printedResult(): boolean {
return this.#printedResult
}
constructor(options: TestBaseOpts) {
super(options)
this.jobs =
(options.jobs && Math.max(options.jobs, 1)) || 1
if (typeof options.diagnostic === 'boolean') {
this.diagnostic = options.diagnostic
}
if (options.cb) {
this.#setCB(options.cb)
}
}
#setCB<T extends TestBase>(this: T, cb: (t: T) => any) {
this.cb = (...args: any[]) =>
this.hook.runInAsyncScope(cb, this, ...args)
}
// TAP output generating methods
/**
* immediately exit this and all parent tests with a TAP
* Bail out! message.
*/
bailout(message?: string) {
if (this.parent && (this.results || this.ended)) {
this.parent.bailout(message)
} else {
this.#process()
message = message
? ' ' + ('' + esc(message)).trim()
: ''
message = message.replace(/[\r\n]/g, ' ')
this.parser.write('Bail out!' + message + '\n')
}
this.#end(IMPLICIT)
this.#process()
}
/**
* output a TAP comment, formatted like console.log()
*/
comment(...args: any[]) {
const body = format(...args)
const message =
('# ' + body.split(/\r?\n/).join('\n# ')).trim() +
'\n'
if (this.results) {
this.write(message)
} else {
this.queue.push(message)
}
this.#process()
}
/**
* Called when the test times out.
* Options are passed as diagnostics to the threw() method
*/
timeout(options: { [k: string]: any }) {
options = options || {}
options.expired = options.expired || this.name
if (this.#occupied && this.#occupied instanceof Base) {
this.#occupied.timeout(options)
} else {
super.timeout(options)
}
this.#end(IMPLICIT)
}
/**
* Set TAP pragma configs to affect the behavior of the parser.
* Only `strict` is supported by the parser.
*/
pragma(set: { [k: string]: boolean }) {
const p = Object.keys(set).reduce(
(acc, i) =>
acc + 'pragma ' + (set[i] ? '+' : '-') + i + '\n',
''
)
this.queue.push(p)
this.#process()
}
/**
* Specify the number of Test Points expected by this test.
* Outputs a TAP plan line.
*/
plan(n: number, comment?: string) {
if (this.bailedOut) {
return
}
if (this.#planEnd !== -1) {
throw new Error('Cannot set plan more than once')
}
if (typeof n !== 'number' || n < 0) {
throw new TypeError('plan must be a number')
}
// Cannot get any tests after a trailing plan, or a plan of 0
const ending = this.count !== 0 || n === 0
if (n
|
=== 0 && comment && !this.options.skip) {
|
this.options.skip = comment
}
this.#planEnd = n
comment = comment ? ' # ' + esc(comment.trim()) : ''
this.queue.push('1..' + n + comment + '\n')
if (ending) {
this.#end(IMPLICIT)
} else {
this.#process()
}
}
/**
* A passing (ok) Test Point
*/
pass(message?: string, extra?: { [k: string]: any }) {
this.currentAssert = TestBase.prototype.pass
this.printResult(
true,
...normalizeMessageExtra(
'(unnamed test)',
message,
extra
)
)
return true
}
/**
* A failing (not ok) Test Point
*/
fail(message?: string, extra?: { [k: string]: any }) {
this.currentAssert = TestBase.prototype.fail
const [m, e] = normalizeMessageExtra(
'(unnamed test)',
message,
extra
)
this.printResult(false, m, e)
return !!(e.todo || e.skip)
}
/**
* The current assertion being processed. May only be set if
* not already set.
*/
get currentAssert() {
return this.#currentAssert
}
/**
* The current assertion being processed. May only be set if
* not already set.
*/
set currentAssert(fn: null | ((...a: any[]) => any)) {
if (!this.#currentAssert && typeof fn === 'function') {
this.#currentAssert = fn
}
}
/**
* Print a Test Point
*/
printResult(
ok: boolean,
message: string,
extra: { [k: string]: any },
front: boolean = false
) {
this.#printedResult = true
const n = this.count + 1
this.currentAssert = TestBase.prototype.printResult
const fn = this.#currentAssert
this.#currentAssert = null
if (this.#planEnd !== -1 && n > this.#planEnd) {
if (!this.passing()) return
const failMessage = this.#explicitEnded
? 'test after end() was called'
: 'test count exceeds plan'
const er = new Error(failMessage, {
cause: {
test: this.name,
plan: this.#planEnd,
},
})
Error.captureStackTrace(er, fn || undefined)
this.threw(er)
return
}
extra = extra || {}
if (extra.expectFail) {
ok = !ok
}
if (this.assertAt) {
extra.at = this.assertAt
this.assertAt = null
}
if (this.assertStack) {
extra.stack = this.assertStack
this.assertStack = null
}
if (typeof extra.stack === 'string' && !extra.at) {
extra.at = stack.parseLine(extra.stack.split('\n')[0])
}
if (
!ok &&
!extra.skip &&
!extra.at &&
typeof fn === 'function'
) {
extra.at = stack.at(fn)
if (!extra.todo) {
extra.stack = stack.captureString(80, fn)
}
}
const diagnostic =
typeof extra.diagnostic === 'boolean'
? extra.diagnostic
: typeof this.diagnostic === 'boolean'
? this.diagnostic
: extra.skip || extra.todo
? false
: !ok
if (diagnostic) {
extra.diagnostic = true
}
this.count = n
message = message + ''
const res = { ok, message, extra }
const tp = new TestPoint(ok, message, extra)
// when we jump the queue, skip an extra line
if (front) {
tp.message = tp.message.trimEnd() + '\n\n'
}
if (
this.#occupied &&
this.#occupied instanceof Waiter &&
this.#occupied.finishing
) {
front = true
}
if (front) {
if (
extra.tapChildBuffer ||
extra.tapChildBuffer === ''
) {
this.writeSubComment(tp)
this.parser.write(extra.tapChildBuffer)
}
this.emit('result', res)
this.parser.write(tp.ok + ++this.#n + tp.message)
if (this.bail && !ok && !extra.skip && !extra.todo) {
this.parser.write('Bail out! ' + message + '\n')
}
} else {
this.queue.push(tp)
if (this.bail && !ok && !extra.skip && !extra.todo) {
this.queue.push('Bail out! ' + message + '\n')
}
}
if (this.#planEnd === this.count) {
this.#end(IMPLICIT)
}
this.#process()
}
end(): this {
this.#end()
return super.end()
}
/**
* The leading `# Subtest` comment that introduces a child test
*/
writeSubComment<T extends TestPoint | Base>(p: T) {
const comment =
'# Subtest' +
(p.name ? ': ' + esc(p.name) : '') +
'\n'
this.parser.write(comment)
}
// end TAP otput generating methods
// flow control methods
/**
* Await the end of a Promise before proceeding.
* The supplied callback is called with the Waiter object.
*/
waitOn(
promise: Promise<any | void>,
cb: (w: Waiter) => any,
expectReject: boolean = false
): Promise<void> {
const w = new Waiter(
promise,
w => {
assert.equal(this.#occupied, w)
cb(w)
this.#occupied = null
this.#process()
},
expectReject
)
this.queue.push(w)
this.#process()
return w.promise
}
#end(implicit?: typeof IMPLICIT) {
if (this.#doingStdinOnly && implicit !== IMPLICIT)
throw new Error(
'cannot explicitly end while in stdinOnly mode'
)
this.debug('END implicit=%j', implicit === IMPLICIT)
if (this.ended && implicit === IMPLICIT) return
// beyond here we have to be actually done with things, or else
// the semantic checks on counts and such will be off.
if (!queueEmpty(this) || this.#occupied) {
if (!this.#pushedEnd) {
this.queue.push(['#end', implicit])
}
this.#pushedEnd = true
return this.#process()
}
this.ended = true
if (implicit !== IMPLICIT && !this.#multiEndThrew) {
if (this.#explicitEnded) {
this.#multiEndThrew = true
const er = new Error(
'test end() method called more than once'
)
Error.captureStackTrace(
er,
this.#currentAssert || this.#end
)
er.cause = {
test: this.name,
}
this.threw(er)
return
}
this.#explicitEnded = true
}
if (this.#planEnd === -1) {
this.debug(
'END(%s) implicit plan',
this.name,
this.count
)
this.plan(this.count)
}
this.queue.push(EOF)
this.#process()
}
#process() {
if (this.#processing) {
return this.debug(' < already processing')
}
this.debug(
'\nPROCESSING(%s)',
this.name,
this.queue.length
)
this.#processing = true
while (!this.#occupied) {
const p = this.queue.shift()
if (!p) {
this.debug('> end of queue')
break
}
if (p instanceof Base) {
this.debug('> subtest in queue', p.name)
this.#processSubtest(p)
} else if (p === EOF) {
this.debug(' > EOF', this.name)
// I AM BECOME EOF, DESTROYER OF STREAMS
this.parser.end()
} else if (p instanceof TestPoint) {
this.debug(' > TESTPOINT')
if (
p.extra.tapChildBuffer ||
p.extra.tapChildBuffer === ''
) {
this.writeSubComment(p)
this.parser.write(p.extra.tapChildBuffer)
}
this.emit('res', p.res)
this.parser.write(p.ok + ++this.#n + p.message)
} else if (typeof p === 'string') {
this.debug(' > STRING')
this.parser.write(p)
} else if (p instanceof Waiter) {
p.ready = true
this.#occupied = p
p.finish()
} else if (Array.isArray(p)) {
this.debug(' > METHOD')
const m = p.shift() as keyof this
if (typeof this[m] !== 'function') {
this.debug(
' > weird method not found in queue??',
m,
typeof this[m]
)
continue
}
const fn = (m === '#end' ? this.#end : this[m]) as (
...a: any[]
) => any
const ret = fn.call(this, ...p)
if (
ret &&
typeof ret === 'object' &&
typeof ret.then === 'function'
) {
// returned promise
ret.then(
() => {
this.#processing = false
this.#process()
},
(er: unknown) => {
this.#processing = false
this.threw(er)
}
)
return
}
/* c8 ignore start */
} else {
throw new Error('weird thing got in the queue')
}
/* c8 ignore stop */
}
while (
!this.#noparallel &&
this.pool.size < this.jobs
) {
const p = this.subtests.shift()
if (!p) {
break
}
if (!p.buffered) {
this.#noparallel = true
break
}
this.debug('start subtest', p)
this.emit('subtestStart', p)
this.pool.add(p)
if (this.bailedOut) {
this.#onBufferedEnd(p)
} else {
p.runMain(() => this.#onBufferedEnd(p))
}
}
this.debug(
'done processing',
this.queue,
this.#occupied
)
this.#processing = false
// just in case any tests ended, and we have sync stuff still
// waiting around in the queue to be processed
if (!this.#occupied && this.queue.length) {
this.#process()
}
}
#onBufferedEnd<T extends Base>(p: T) {
p.ondone = p.constructor.prototype.ondone
p.results =
p.results || new FinalResults(true, p.parser)
p.readyToProcess = true
const to = p.options.timeout
const dur =
to && p.passing() ? hrtime.bigint() - p.start : null
if (dur && to && dur > to) {
p.timeout()
} else {
p.setTimeout(0)
}
this.debug(
'%s.#onBufferedEnd',
this.name,
p.name,
p.results.bailout
)
this.pool.delete(p)
p.options.tapChildBuffer = p.output || ''
p.options.stack = ''
if (p.time) p.options.time = p.time
if (this.#occupied === p) this.#occupied = null
p.deferred?.resolve(p.results)
this.emit('subtestEnd', p)
this.#process()
}
#onIndentedEnd<T extends Base>(p: T) {
this.emit('subtestProcess', p)
p.ondone = p.constructor.prototype.ondone
p.results =
p.results || new FinalResults(true, p.parser)
this.debug('#onIndentedEnd', this.name, p.name)
this.#noparallel = false
const sti = this.subtests.indexOf(p)
if (sti !== -1) this.subtests.splice(sti, 1)
p.readyToProcess = true
p.options.time = p.time
const to = p.options.timeout
const dur =
to && p.passing() ? hrtime.bigint() - p.start : null
if (dur && to && dur > to) {
p.timeout()
} else {
p.setTimeout(0)
}
this.debug('#onIndentedEnd %s(%s)', this.name, p.name)
this.#occupied = null
this.debug(
'OIE(%s) b>shift into queue',
this.name,
this.queue
)
p.options.stack = ''
this.printResult(p.passing(), p.name, p.options, true)
this.debug(
'OIE(%s) shifted into queue',
this.name,
this.queue
)
p.deferred?.resolve(p.results)
this.emit('subtestEnd', p)
this.#process()
}
/**
* @internal
*/
main(cb: () => void) {
if (typeof this.options.timeout === 'number') {
this.setTimeout(this.options.timeout)
}
this.debug('MAIN pre', this)
const end = () => {
this.debug(' > implicit end for promise')
this.#end(IMPLICIT)
done()
}
const done = (er?: Error) => {
if (er) this.threw(er)
if (this.results || this.bailedOut) cb()
else this.ondone = () => cb()
}
// This bit of overly clever line-noise wraps the call to user-code
// in a try-catch. We can't rely on the domain for this yet, because
// the 'end' event can trigger a throw after the domain is unhooked,
// but before this is no longer the official "active test"
const ret = (() => {
if (!this.cb) return
try {
return this.cb(this)
} catch (er: any) {
if (!er || typeof er !== 'object') {
er = { error: er }
}
er.tapCaught = 'testFunctionThrow'
this.threw(er)
}
})()
if (ret && ret.then) {
this.promise = ret
ret.tapAbortPromise = done
ret.then(end, (er: any) => {
if (!er || typeof er !== 'object') {
er = { error: er }
}
er.tapCaught = 'returnedPromiseRejection'
done(er)
})
} else done()
this.debug('MAIN post', this)
}
#processSubtest<T extends Base>(p: T) {
this.debug(' > subtest')
this.#occupied = p
if (!p.buffered) {
this.emit('subtestStart', p)
this.debug(' > subtest indented')
p.stream.pipe(this.parser, { end: false })
this.writeSubComment(p)
this.debug('calling runMain', p.runMain.toString())
p.runMain(() => {
this.debug('in runMain', p.runMain.toString())
this.#onIndentedEnd(p)
})
} else if (p.readyToProcess) {
this.emit('subtestProcess', p)
this.debug(' > subtest buffered, finished')
// finished! do the thing!
this.#occupied = null
if (!p.passing() || !p.silent) {
this.printResult(
p.passing(),
p.name,
p.options,
true
)
}
} else {
this.#occupied = p
this.debug(' > subtest buffered, unfinished', p)
// unfinished buffered test.
// nothing to do yet, just leave it there.
this.queue.unshift(p)
}
}
/**
* Parse stdin as the only tap stream (ie, not as a child test)
* If used, then no other subtests or assertions are allowed.
*/
stdinOnly<T extends BaseOpts>(
extra?: T & { tapStream?: Readable | Minipass }
) {
const stream = ((extra && extra.tapStream) ||
process.stdin) as Minipass
if (!stream) {
throw new Error(
'cannot read stdin without stdin stream'
)
}
if (
this.queue.length !== 1 ||
this.queue[0] !== 'TAP version 14\n' ||
this.#processing ||
this.results ||
this.#occupied ||
this.pool.size ||
this.subtests.length
) {
throw new Error(
'Cannot use stdinOnly on a test in progress'
)
}
this.#doingStdinOnly = true
this.queue.length = 0
this.parser.on('child', p => {
// pretend to be a rooted parser, so it gets counts.
p.root = p
const t = new Base({
name: p.name,
parent: this,
parser: p,
bail: p.bail,
strict: p.strict,
omitVersion: p.omitVersion,
preserveWhitespace: p.preserveWhitespace,
childId: this.#nextChildId++,
})
this.emit('subtestAdd', t)
this.emit('subtestStart', t)
this.emit('subtestProcess', t)
p.on('complete', () => {
t.time = p.time
this.emit('subtestEnd', t)
})
})
stream.pause()
stream.pipe(this.parser)
stream.resume()
}
/**
* Mount a subtest, using this Test object as a harness.
* Exposed mainly so that it can be used by builtin plugins.
*
* @internal
*/
sub<T extends Base, O extends TestBaseOpts>(
Class: { new (options: O): T },
extra: O,
caller: (...a: any[]) => unknown
): Promise<FinalResults | null> {
if (this.bailedOut) return Promise.resolve(null)
if (this.results || this.ended) {
const er = new Error(
'cannot create subtest after parent test ends'
)
Error.captureStackTrace(er, caller)
this.threw(er)
return Promise.resolve(null)
}
extra.childId = this.#nextChildId++
if (this.shouldSkipChild(extra)) {
this.pass(extra.name, extra)
return Promise.resolve(null)
}
extra.indent = ' '
if (extra.buffered !== undefined) {
if (this.jobs > 1) {
extra.buffered = true
} else {
extra.buffered = false
}
}
extra.bail =
extra.bail !== undefined ? extra.bail : this.bail
extra.parent = this
extra.stack = stack.captureString(80, caller)
extra.context = this.context
const t = new Class(extra)
this.queue.push(t)
this.subtests.push(t)
this.emit('subtestAdd', t)
const d = new Deferred<FinalResults>()
t.deferred = d
this.#process()
return d.promise
}
/**
* Return true if the child test represented by the options object
* should be skipped. Extended by the grep/only filtering plugins.
*/
shouldSkipChild(extra: { [k: string]: any }) {
return !!(extra.skip || extra.todo)
}
// end flow control methods
}
|
src/test-base.ts
|
tapjs-core-edd7403
|
[
{
"filename": "src/base.ts",
"retrieved_chunk": " this.counts.skip++\n this.lists.skip.push(res)\n })\n this.parser.on('fail', res => {\n this.counts.fail++\n this.lists.fail.push(res)\n })\n }\n setTimeout(n: number) {\n if (n <= 0) {",
"score": 0.816146969795227
},
{
"filename": "src/spawn.ts",
"retrieved_chunk": " !code &&\n !signal\n ) {\n this.options.skip =\n this.results.plan.skipReason || true\n }\n if (code || signal) {\n if (this.results) {\n this.results.ok = false\n }",
"score": 0.8030873537063599
},
{
"filename": "src/spawn.ts",
"retrieved_chunk": " }\n main(cb: () => void) {\n this.cb = cb\n this.setTimeout(this.options.timeout || 0)\n this.parser.on('comment', c => {\n const tomatch = c.match(/# timeout=([0-9]+)\\n$/)\n if (tomatch) {\n this.setTimeout(+tomatch[1])\n }\n })",
"score": 0.7904884219169617
},
{
"filename": "src/base.ts",
"retrieved_chunk": " // do we need this? couldn't we just call the Minipass\n this.output = ''\n this.indent = options.indent || ''\n this.name = options.name || '(unnamed test)'\n this.hook.runInAsyncScope(\n () =>\n (this.hookDomain = new Domain((er, type) => {\n if (!er || typeof er !== 'object')\n er = { error: er }\n er.tapCaught = type",
"score": 0.7820167541503906
},
{
"filename": "src/base.ts",
"retrieved_chunk": " if (this.timer) {\n clearTimeout(this.timer)\n }\n this.timer = undefined\n } else {\n this.timer = setTimeout(() => this.timeout(), n)\n this.timer.unref()\n }\n }\n timeout(options?: { [k: string]: any }) {",
"score": 0.7792779803276062
}
] |
typescript
|
=== 0 && comment && !this.options.skip) {
|
// lifecycle methods like beforeEach, afterEach, teardown
// defined in plugins/lifecycle.ts
import Minipass from 'minipass'
import assert from 'node:assert'
import { hrtime } from 'node:process'
import { Readable } from 'node:stream'
import { format } from 'node:util'
import { CallSiteLike } from 'stack-utils'
import { FinalResults } from 'tap-parser'
import Deferred from 'trivial-deferred'
import { Base, BaseOpts } from './base.js'
import { esc } from './esc.js'
import stack from './stack.js'
import { TestPoint } from './test-point.js'
import { Waiter } from './waiter.js'
const queueEmpty = <T extends TestBase>(t: T) =>
t.queue.length === 0 ||
(t.queue.length === 1 &&
t.queue[0] === 'TAP version 14\n')
export interface ClassOf<T> {
new (): T
}
export type TapPlugin<
B extends Object,
O extends TestBaseOpts | any = any
> = ((t: TestBase, opts: O) => B) | ((t: TestBase) => B)
export interface TestBaseOpts extends BaseOpts {
/**
* The number of jobs to run in parallel. Defaults to 1
*/
jobs?: number
/**
* Test function called when this Test is executed
*/
cb?: (...args: any[]) => any
/**
* Flag to always/never show diagnostics. If unset, then
* diagnostics are shown for failing test points only.
*/
diagnostic?: boolean
}
const normalizeMessageExtra = (
defaultMessage: string,
message?: string | { [k: string]: any },
extra?: { [k: string]: any }
): [string, { [k: string]: any }] => {
if (typeof message === 'string') {
return [message || defaultMessage, extra || {}]
} else {
return [defaultMessage, message || {}]
}
}
/**
* Sigil for implicit end() calls that should not
* trigger an error if the user then calls t.end()
*/
const IMPLICIT = Symbol('implicit end')
/**
* Sigil to put in the queue to signal the end of all things
*/
const EOF = Symbol('EOF')
export type QueueEntry =
| string
| TestPoint
| Base
| typeof EOF
| Waiter
| [method: string, ...args: any[]]
/**
* The TestBaseBase class is the base class for all plugins,
* and eventually thus the Test class.
*
* This implements subtest functionality, TAP stream generation,
* lifecycle events, and only the most basic pass/fail assertions.
*
* All other features are added with plugins.
*/
export class TestBase extends Base {
// NB: generated pluginified Test class needs to declare over this
declare parent?: TestBase
promise?: Promise<any>
jobs: number
// #beforeEnd: [method: string | Symbol, ...args: any[]][] = []
subtests: Base[] = []
pool: Set<Base> = new Set()
queue: QueueEntry[] = ['TAP version 14\n']
cb?: (...args: any[]) => any
count: number = 0
ended: boolean = false
assertAt: CallSiteLike | null = null
assertStack: string | null = null
diagnostic: null | boolean = null
#planEnd: number = -1
#printedResult: boolean = false
#explicitEnded: boolean = false
#multiEndThrew: boolean = false
#n: number = 0
#noparallel: boolean = false
#occupied: null | Waiter | Base = null
#pushedEnd: boolean = false
#nextChildId: number = 1
#currentAssert: null | ((..._: any) => any) = null
#processing: boolean = false
#doingStdinOnly: boolean = false
/**
* true if the test has printed at least one TestPoint
*/
get printedResult(): boolean {
return this.#printedResult
}
constructor(options: TestBaseOpts) {
super(options)
this.jobs =
(options.jobs && Math.max(options.jobs, 1)) || 1
if (typeof options.diagnostic === 'boolean') {
this.diagnostic = options.diagnostic
}
if (options.cb) {
this.#setCB(options.cb)
}
}
#setCB<T extends TestBase>(this: T, cb: (t: T) => any) {
this.cb = (...args: any[]) =>
this.hook.runInAsyncScope(cb, this, ...args)
}
// TAP output generating methods
/**
* immediately exit this and all parent tests with a TAP
* Bail out! message.
*/
bailout(message?: string) {
if (this.parent && (this.results || this.ended)) {
this.parent.bailout(message)
} else {
this.#process()
message = message
? ' ' + ('' + esc(message)).trim()
: ''
message = message.replace(/[\r\n]/g, ' ')
this.parser.write('Bail out!' + message + '\n')
}
this.#end(IMPLICIT)
this.#process()
}
/**
* output a TAP comment, formatted like console.log()
*/
comment(...args: any[]) {
const body = format(...args)
const message =
('# ' + body.split(/\r?\n/).join('\n# ')).trim() +
'\n'
if (this.results) {
this.write(message)
} else {
this.queue.push(message)
}
this.#process()
}
/**
* Called when the test times out.
* Options are passed as diagnostics to the threw() method
*/
timeout(options: { [k: string]: any }) {
options = options || {}
options.expired = options.expired || this.name
if (this.#occupied && this.#occupied instanceof Base) {
this.#occupied.timeout(options)
} else {
super.timeout(options)
}
this.#end(IMPLICIT)
}
/**
* Set TAP pragma configs to affect the behavior of the parser.
* Only `strict` is supported by the parser.
*/
pragma(set: { [k: string]: boolean }) {
const p = Object.keys(set).reduce(
(acc, i) =>
acc + 'pragma ' + (set[i] ? '+' : '-') + i + '\n',
''
)
this.queue.push(p)
this.#process()
}
/**
* Specify the number of Test Points expected by this test.
* Outputs a TAP plan line.
*/
plan(n: number, comment?: string) {
if (this.bailedOut) {
return
}
if (this.#planEnd !== -1) {
throw new Error('Cannot set plan more than once')
}
if (typeof n !== 'number' || n < 0) {
throw new TypeError('plan must be a number')
}
// Cannot get any tests after a trailing plan, or a plan of 0
const ending = this.count !== 0 || n === 0
if (n === 0 && comment && !this.options.skip) {
this.options.skip = comment
}
this.#planEnd = n
comment = comment ? ' # ' + esc(comment.trim()) : ''
this.queue.push('1..' + n + comment + '\n')
if (ending) {
this.#end(IMPLICIT)
} else {
this.#process()
}
}
/**
* A passing (ok) Test Point
*/
pass(message?: string, extra?: { [k: string]: any }) {
this.currentAssert = TestBase.prototype.pass
this.printResult(
true,
...normalizeMessageExtra(
'(unnamed test)',
message,
extra
)
)
return true
}
/**
* A failing (not ok) Test Point
*/
fail(message?: string, extra?: { [k: string]: any }) {
this.currentAssert = TestBase.prototype.fail
const [m, e] = normalizeMessageExtra(
'(unnamed test)',
message,
extra
)
this.printResult(false, m, e)
return !!(e.todo || e.skip)
}
/**
* The current assertion being processed. May only be set if
* not already set.
*/
get currentAssert() {
return this.#currentAssert
}
/**
* The current assertion being processed. May only be set if
* not already set.
*/
set currentAssert(fn: null | ((...a: any[]) => any)) {
if (!this.#currentAssert && typeof fn === 'function') {
this.#currentAssert = fn
}
}
/**
* Print a Test Point
*/
printResult(
ok: boolean,
message: string,
extra: { [k: string]: any },
front: boolean = false
) {
this.#printedResult = true
const n = this.count + 1
this.currentAssert = TestBase.prototype.printResult
const fn = this.#currentAssert
this.#currentAssert = null
if (this.#planEnd !== -1 && n > this.#planEnd) {
if (!this.passing()) return
const failMessage = this.#explicitEnded
? 'test after end() was called'
: 'test count exceeds plan'
const er = new Error(failMessage, {
cause: {
test: this.name,
plan: this.#planEnd,
},
})
Error.captureStackTrace(er, fn || undefined)
this.threw(er)
return
}
extra = extra || {}
if (extra.expectFail) {
ok = !ok
}
if (this.assertAt) {
extra.at = this.assertAt
this.assertAt = null
}
if (this.assertStack) {
extra.stack = this.assertStack
this.assertStack = null
}
if (typeof extra.stack === 'string' && !extra.at) {
extra.at = stack.parseLine(extra.stack.split('\n')[0])
}
if (
!ok &&
!extra.skip &&
!extra.at &&
typeof fn === 'function'
) {
extra.at = stack.at(fn)
if (!extra.todo) {
extra.stack = stack.captureString(80, fn)
}
}
const diagnostic =
typeof extra.diagnostic === 'boolean'
? extra.diagnostic
: typeof this.diagnostic === 'boolean'
? this.diagnostic
: extra.skip || extra.todo
? false
: !ok
if (diagnostic) {
extra.diagnostic = true
}
this.count = n
message = message + ''
const res = { ok, message, extra }
const tp = new TestPoint(ok, message, extra)
// when we jump the queue, skip an extra line
if (front) {
tp.
|
message = tp.message.trimEnd() + '\n\n'
}
|
if (
this.#occupied &&
this.#occupied instanceof Waiter &&
this.#occupied.finishing
) {
front = true
}
if (front) {
if (
extra.tapChildBuffer ||
extra.tapChildBuffer === ''
) {
this.writeSubComment(tp)
this.parser.write(extra.tapChildBuffer)
}
this.emit('result', res)
this.parser.write(tp.ok + ++this.#n + tp.message)
if (this.bail && !ok && !extra.skip && !extra.todo) {
this.parser.write('Bail out! ' + message + '\n')
}
} else {
this.queue.push(tp)
if (this.bail && !ok && !extra.skip && !extra.todo) {
this.queue.push('Bail out! ' + message + '\n')
}
}
if (this.#planEnd === this.count) {
this.#end(IMPLICIT)
}
this.#process()
}
end(): this {
this.#end()
return super.end()
}
/**
* The leading `# Subtest` comment that introduces a child test
*/
writeSubComment<T extends TestPoint | Base>(p: T) {
const comment =
'# Subtest' +
(p.name ? ': ' + esc(p.name) : '') +
'\n'
this.parser.write(comment)
}
// end TAP otput generating methods
// flow control methods
/**
* Await the end of a Promise before proceeding.
* The supplied callback is called with the Waiter object.
*/
waitOn(
promise: Promise<any | void>,
cb: (w: Waiter) => any,
expectReject: boolean = false
): Promise<void> {
const w = new Waiter(
promise,
w => {
assert.equal(this.#occupied, w)
cb(w)
this.#occupied = null
this.#process()
},
expectReject
)
this.queue.push(w)
this.#process()
return w.promise
}
#end(implicit?: typeof IMPLICIT) {
if (this.#doingStdinOnly && implicit !== IMPLICIT)
throw new Error(
'cannot explicitly end while in stdinOnly mode'
)
this.debug('END implicit=%j', implicit === IMPLICIT)
if (this.ended && implicit === IMPLICIT) return
// beyond here we have to be actually done with things, or else
// the semantic checks on counts and such will be off.
if (!queueEmpty(this) || this.#occupied) {
if (!this.#pushedEnd) {
this.queue.push(['#end', implicit])
}
this.#pushedEnd = true
return this.#process()
}
this.ended = true
if (implicit !== IMPLICIT && !this.#multiEndThrew) {
if (this.#explicitEnded) {
this.#multiEndThrew = true
const er = new Error(
'test end() method called more than once'
)
Error.captureStackTrace(
er,
this.#currentAssert || this.#end
)
er.cause = {
test: this.name,
}
this.threw(er)
return
}
this.#explicitEnded = true
}
if (this.#planEnd === -1) {
this.debug(
'END(%s) implicit plan',
this.name,
this.count
)
this.plan(this.count)
}
this.queue.push(EOF)
this.#process()
}
#process() {
if (this.#processing) {
return this.debug(' < already processing')
}
this.debug(
'\nPROCESSING(%s)',
this.name,
this.queue.length
)
this.#processing = true
while (!this.#occupied) {
const p = this.queue.shift()
if (!p) {
this.debug('> end of queue')
break
}
if (p instanceof Base) {
this.debug('> subtest in queue', p.name)
this.#processSubtest(p)
} else if (p === EOF) {
this.debug(' > EOF', this.name)
// I AM BECOME EOF, DESTROYER OF STREAMS
this.parser.end()
} else if (p instanceof TestPoint) {
this.debug(' > TESTPOINT')
if (
p.extra.tapChildBuffer ||
p.extra.tapChildBuffer === ''
) {
this.writeSubComment(p)
this.parser.write(p.extra.tapChildBuffer)
}
this.emit('res', p.res)
this.parser.write(p.ok + ++this.#n + p.message)
} else if (typeof p === 'string') {
this.debug(' > STRING')
this.parser.write(p)
} else if (p instanceof Waiter) {
p.ready = true
this.#occupied = p
p.finish()
} else if (Array.isArray(p)) {
this.debug(' > METHOD')
const m = p.shift() as keyof this
if (typeof this[m] !== 'function') {
this.debug(
' > weird method not found in queue??',
m,
typeof this[m]
)
continue
}
const fn = (m === '#end' ? this.#end : this[m]) as (
...a: any[]
) => any
const ret = fn.call(this, ...p)
if (
ret &&
typeof ret === 'object' &&
typeof ret.then === 'function'
) {
// returned promise
ret.then(
() => {
this.#processing = false
this.#process()
},
(er: unknown) => {
this.#processing = false
this.threw(er)
}
)
return
}
/* c8 ignore start */
} else {
throw new Error('weird thing got in the queue')
}
/* c8 ignore stop */
}
while (
!this.#noparallel &&
this.pool.size < this.jobs
) {
const p = this.subtests.shift()
if (!p) {
break
}
if (!p.buffered) {
this.#noparallel = true
break
}
this.debug('start subtest', p)
this.emit('subtestStart', p)
this.pool.add(p)
if (this.bailedOut) {
this.#onBufferedEnd(p)
} else {
p.runMain(() => this.#onBufferedEnd(p))
}
}
this.debug(
'done processing',
this.queue,
this.#occupied
)
this.#processing = false
// just in case any tests ended, and we have sync stuff still
// waiting around in the queue to be processed
if (!this.#occupied && this.queue.length) {
this.#process()
}
}
#onBufferedEnd<T extends Base>(p: T) {
p.ondone = p.constructor.prototype.ondone
p.results =
p.results || new FinalResults(true, p.parser)
p.readyToProcess = true
const to = p.options.timeout
const dur =
to && p.passing() ? hrtime.bigint() - p.start : null
if (dur && to && dur > to) {
p.timeout()
} else {
p.setTimeout(0)
}
this.debug(
'%s.#onBufferedEnd',
this.name,
p.name,
p.results.bailout
)
this.pool.delete(p)
p.options.tapChildBuffer = p.output || ''
p.options.stack = ''
if (p.time) p.options.time = p.time
if (this.#occupied === p) this.#occupied = null
p.deferred?.resolve(p.results)
this.emit('subtestEnd', p)
this.#process()
}
#onIndentedEnd<T extends Base>(p: T) {
this.emit('subtestProcess', p)
p.ondone = p.constructor.prototype.ondone
p.results =
p.results || new FinalResults(true, p.parser)
this.debug('#onIndentedEnd', this.name, p.name)
this.#noparallel = false
const sti = this.subtests.indexOf(p)
if (sti !== -1) this.subtests.splice(sti, 1)
p.readyToProcess = true
p.options.time = p.time
const to = p.options.timeout
const dur =
to && p.passing() ? hrtime.bigint() - p.start : null
if (dur && to && dur > to) {
p.timeout()
} else {
p.setTimeout(0)
}
this.debug('#onIndentedEnd %s(%s)', this.name, p.name)
this.#occupied = null
this.debug(
'OIE(%s) b>shift into queue',
this.name,
this.queue
)
p.options.stack = ''
this.printResult(p.passing(), p.name, p.options, true)
this.debug(
'OIE(%s) shifted into queue',
this.name,
this.queue
)
p.deferred?.resolve(p.results)
this.emit('subtestEnd', p)
this.#process()
}
/**
* @internal
*/
main(cb: () => void) {
if (typeof this.options.timeout === 'number') {
this.setTimeout(this.options.timeout)
}
this.debug('MAIN pre', this)
const end = () => {
this.debug(' > implicit end for promise')
this.#end(IMPLICIT)
done()
}
const done = (er?: Error) => {
if (er) this.threw(er)
if (this.results || this.bailedOut) cb()
else this.ondone = () => cb()
}
// This bit of overly clever line-noise wraps the call to user-code
// in a try-catch. We can't rely on the domain for this yet, because
// the 'end' event can trigger a throw after the domain is unhooked,
// but before this is no longer the official "active test"
const ret = (() => {
if (!this.cb) return
try {
return this.cb(this)
} catch (er: any) {
if (!er || typeof er !== 'object') {
er = { error: er }
}
er.tapCaught = 'testFunctionThrow'
this.threw(er)
}
})()
if (ret && ret.then) {
this.promise = ret
ret.tapAbortPromise = done
ret.then(end, (er: any) => {
if (!er || typeof er !== 'object') {
er = { error: er }
}
er.tapCaught = 'returnedPromiseRejection'
done(er)
})
} else done()
this.debug('MAIN post', this)
}
#processSubtest<T extends Base>(p: T) {
this.debug(' > subtest')
this.#occupied = p
if (!p.buffered) {
this.emit('subtestStart', p)
this.debug(' > subtest indented')
p.stream.pipe(this.parser, { end: false })
this.writeSubComment(p)
this.debug('calling runMain', p.runMain.toString())
p.runMain(() => {
this.debug('in runMain', p.runMain.toString())
this.#onIndentedEnd(p)
})
} else if (p.readyToProcess) {
this.emit('subtestProcess', p)
this.debug(' > subtest buffered, finished')
// finished! do the thing!
this.#occupied = null
if (!p.passing() || !p.silent) {
this.printResult(
p.passing(),
p.name,
p.options,
true
)
}
} else {
this.#occupied = p
this.debug(' > subtest buffered, unfinished', p)
// unfinished buffered test.
// nothing to do yet, just leave it there.
this.queue.unshift(p)
}
}
/**
* Parse stdin as the only tap stream (ie, not as a child test)
* If used, then no other subtests or assertions are allowed.
*/
stdinOnly<T extends BaseOpts>(
extra?: T & { tapStream?: Readable | Minipass }
) {
const stream = ((extra && extra.tapStream) ||
process.stdin) as Minipass
if (!stream) {
throw new Error(
'cannot read stdin without stdin stream'
)
}
if (
this.queue.length !== 1 ||
this.queue[0] !== 'TAP version 14\n' ||
this.#processing ||
this.results ||
this.#occupied ||
this.pool.size ||
this.subtests.length
) {
throw new Error(
'Cannot use stdinOnly on a test in progress'
)
}
this.#doingStdinOnly = true
this.queue.length = 0
this.parser.on('child', p => {
// pretend to be a rooted parser, so it gets counts.
p.root = p
const t = new Base({
name: p.name,
parent: this,
parser: p,
bail: p.bail,
strict: p.strict,
omitVersion: p.omitVersion,
preserveWhitespace: p.preserveWhitespace,
childId: this.#nextChildId++,
})
this.emit('subtestAdd', t)
this.emit('subtestStart', t)
this.emit('subtestProcess', t)
p.on('complete', () => {
t.time = p.time
this.emit('subtestEnd', t)
})
})
stream.pause()
stream.pipe(this.parser)
stream.resume()
}
/**
* Mount a subtest, using this Test object as a harness.
* Exposed mainly so that it can be used by builtin plugins.
*
* @internal
*/
sub<T extends Base, O extends TestBaseOpts>(
Class: { new (options: O): T },
extra: O,
caller: (...a: any[]) => unknown
): Promise<FinalResults | null> {
if (this.bailedOut) return Promise.resolve(null)
if (this.results || this.ended) {
const er = new Error(
'cannot create subtest after parent test ends'
)
Error.captureStackTrace(er, caller)
this.threw(er)
return Promise.resolve(null)
}
extra.childId = this.#nextChildId++
if (this.shouldSkipChild(extra)) {
this.pass(extra.name, extra)
return Promise.resolve(null)
}
extra.indent = ' '
if (extra.buffered !== undefined) {
if (this.jobs > 1) {
extra.buffered = true
} else {
extra.buffered = false
}
}
extra.bail =
extra.bail !== undefined ? extra.bail : this.bail
extra.parent = this
extra.stack = stack.captureString(80, caller)
extra.context = this.context
const t = new Class(extra)
this.queue.push(t)
this.subtests.push(t)
this.emit('subtestAdd', t)
const d = new Deferred<FinalResults>()
t.deferred = d
this.#process()
return d.promise
}
/**
* Return true if the child test represented by the options object
* should be skipped. Extended by the grep/only filtering plugins.
*/
shouldSkipChild(extra: { [k: string]: any }) {
return !!(extra.skip || extra.todo)
}
// end flow control methods
}
|
src/test-base.ts
|
tapjs-core-edd7403
|
[
{
"filename": "src/test-point.ts",
"retrieved_chunk": " extra = extra || {}\n message = message\n .trim()\n .replace(/[\\n\\r]/g, ' ')\n .replace(/\\t/g, ' ')\n this.res = { ok, message, extra }\n this.extra = extra\n this.name = message\n this.message = tpMessage(esc(this.name), extra)\n }",
"score": 0.853631854057312
},
{
"filename": "src/test-point.ts",
"retrieved_chunk": "import { diags } from './diags.js'\nimport { esc } from './esc.js'\nimport { TestBaseOpts } from './test-base.js'\nexport interface Result {\n ok: boolean\n message: string\n extra: { [k: string]: any }\n}\nexport class TestPoint {\n ok: 'ok ' | 'not ok '",
"score": 0.8271074295043945
},
{
"filename": "src/test-point.ts",
"retrieved_chunk": "}\nconst tpMessage = (\n description: string,\n extra: { [k: string]: any },\n options: TestBaseOpts = {}\n): string => {\n let message = description ? ` - ${description}` : ''\n if (extra.skip) {\n message += ' # SKIP'\n if (typeof extra.skip === 'string') {",
"score": 0.8270900249481201
},
{
"filename": "src/test-point.ts",
"retrieved_chunk": " name: string\n message: string\n extra: { [key: string]: any }\n res: Result\n constructor(\n ok: boolean,\n message: string,\n extra?: { [key: string]: any }\n ) {\n this.ok = ok ? 'ok ' : 'not ok '",
"score": 0.8234153985977173
},
{
"filename": "src/base.ts",
"retrieved_chunk": " er.stack.split(/\\n/).slice(1).join('\\n')\n )\n console.error(extra)\n }\n } else {\n this.parser.ok = false\n }\n return extra\n }\n passing() {",
"score": 0.8155779838562012
}
] |
typescript
|
message = tp.message.trimEnd() + '\n\n'
}
|
// This file is automatically generated, please do not edit
import { FinalResults } from 'tap-parser'
import parseTestArgs, {
TestArgs,
} from './parse-test-args.js'
import { TestBase, TestBaseOpts } from './test-base.js'
const copyToString = (v: Function) => ({
toString: Object.assign(() => v.toString(), {
toString: () => 'function toString() { [native code] }',
}),
})
import plugin0 from "./plugin/after-each.js"
import plugin1 from "./plugin/before-each.js"
import plugin2 from "./plugin/spawn.js"
import plugin3 from "./plugin/stdin.js"
type PI<O extends TestBaseOpts | any = any> =
| ((t: Test, opts: O) => Plug)
| ((t: Test) => Plug)
const plugins: PI[] = [
plugin0,
plugin1,
plugin2,
plugin3,
]
type Plug =
| TestBase
| { t: Test }
| ReturnType<typeof plugin0>
| ReturnType<typeof plugin1>
| ReturnType<typeof plugin2>
| ReturnType<typeof plugin3>
type PlugKeys =
| keyof TestBase
| 't'
| keyof ReturnType<typeof plugin0>
| keyof ReturnType<typeof plugin1>
| keyof ReturnType<typeof plugin2>
| keyof ReturnType<typeof plugin3>
type SecondParam<
T extends [any] | [any, any],
Fallback extends unknown = unknown
> = T extends [any, any] ? T[1] : Fallback
type Plugin0Opts = SecondParam<
Parameters<typeof plugin0>,
TestBaseOpts
>
type Plugin1Opts = SecondParam<
Parameters<typeof plugin1>,
TestBaseOpts
>
type Plugin2Opts = SecondParam<
Parameters<typeof plugin2>,
TestBaseOpts
>
type Plugin3Opts = SecondParam<
Parameters<typeof plugin3>,
TestBaseOpts
>
type TestOpts = TestBaseOpts
& Plugin0Opts
& Plugin1Opts
& Plugin2Opts
& Plugin3Opts
type TTest = TestBase
& ReturnType<typeof plugin0>
& ReturnType<typeof plugin1>
& ReturnType<typeof plugin2>
& ReturnType<
|
typeof plugin3>
export interface Test extends TTest {
|
end(): this
t: Test
test(
name: string,
extra: { [k: string]: any },
cb?: (t: Test) => any
): Promise<FinalResults | null>
test(
name: string,
cb?: (t: Test) => any
): Promise<FinalResults | null>
test(
extra: { [k: string]: any },
cb?: (t: Test) => any
): Promise<FinalResults | null>
test(cb?: (t: Test) => any): Promise<FinalResults | null>
test(
...args: TestArgs<Test>
): Promise<FinalResults | null>
todo(
name: string,
extra: { [k: string]: any },
cb?: (t: Test) => any
): Promise<FinalResults | null>
todo(
name: string,
cb?: (t: Test) => any
): Promise<FinalResults | null>
todo(
extra: { [k: string]: any },
cb?: (t: Test) => any
): Promise<FinalResults | null>
todo(cb?: (t: Test) => any): Promise<FinalResults | null>
todo(
...args: TestArgs<Test>
): Promise<FinalResults | null>
skip(
name: string,
extra: { [k: string]: any },
cb?: (t: Test) => any
): Promise<FinalResults | null>
skip(
name: string,
cb?: (t: Test) => any
): Promise<FinalResults | null>
skip(
extra: { [k: string]: any },
cb?: (t: Test) => any
): Promise<FinalResults | null>
skip(cb?: (t: Test) => any): Promise<FinalResults | null>
skip(
...args: TestArgs<Test>
): Promise<FinalResults | null>
}
const applyPlugins = (base: Test): Test => {
const ext: Plug[] = [
...plugins.map(p => p(base, base.options)),
base,
]
const getCache = new Map<any, any>()
const t = new Proxy(base, {
has(_, p) {
for (const t of ext) {
if (Reflect.has(t, p)) return true
}
return false
},
ownKeys() {
const k: PlugKeys[] = []
for (const t of ext) {
const keys = Reflect.ownKeys(t) as PlugKeys[]
k.push(...keys)
}
return [...new Set(k)]
},
getOwnPropertyDescriptor(_, p) {
for (const t of ext) {
const prop = Reflect.getOwnPropertyDescriptor(t, p)
if (prop) return prop
}
return undefined
},
set(_, p, v) {
// check to see if there's any setters, and if so, set it there
// otherwise, just set on the base
for (const t of ext) {
let o: Object | null = t
while (o) {
if (Reflect.getOwnPropertyDescriptor(o, p)?.set) {
//@ts-ignore
t[p] = v
return true
}
o = Reflect.getPrototypeOf(o)
}
}
//@ts-ignore
base[p as keyof TestBase] = v
return true
},
get(_, p) {
// cache get results so t.blah === t.blah
// we only cache functions, so that getters aren't memoized
// Of course, a getter that returns a function will be broken,
// at least when accessed from outside the plugin, but that's
// a pretty narrow caveat, and easily documented.
if (getCache.has(p)) return getCache.get(p)
for (const plug of ext) {
if (p in plug) {
//@ts-ignore
const v = plug[p]
// Functions need special handling so that they report
// the correct toString and are called on the correct object
// Otherwise attempting to access #private props will fail.
if (typeof v === 'function') {
const f: (this: Plug, ...args: any) => any =
function (...args: any[]) {
const thisArg = this === t ? plug : this
return v.apply(thisArg, args)
}
const vv = Object.assign(f, copyToString(v))
const nameProp =
Reflect.getOwnPropertyDescriptor(v, 'name')
if (nameProp) {
Reflect.defineProperty(f, 'name', nameProp)
}
getCache.set(p, vv)
return vv
} else {
getCache.set(p, v)
return v
}
}
}
},
})
Object.assign(base, { t })
ext.unshift({ t })
return t
}
export class Test extends TestBase {
constructor(opts: TestOpts) {
super(opts)
return applyPlugins(this)
}
test(
name: string,
extra: { [k: string]: any },
cb?: (t: Test) => any
): Promise<FinalResults | null>
test(
name: string,
cb?: (t: Test) => any
): Promise<FinalResults | null>
test(
extra: { [k: string]: any },
cb?: (t: Test) => any
): Promise<FinalResults | null>
test(cb?: (t: Test) => any): Promise<FinalResults | null>
test(
...args: TestArgs<Test>
): Promise<FinalResults | null> {
const extra = parseTestArgs(...args)
extra.todo = true
return this.sub(Test, extra, this.test)
}
todo(
name: string,
extra: { [k: string]: any },
cb?: (t: Test) => any
): Promise<FinalResults | null>
todo(
name: string,
cb?: (t: Test) => any
): Promise<FinalResults | null>
todo(
extra: { [k: string]: any },
cb?: (t: Test) => any
): Promise<FinalResults | null>
todo(cb?: (t: Test) => any): Promise<FinalResults | null>
todo(
...args: TestArgs<Test>
): Promise<FinalResults | null> {
const extra = parseTestArgs(...args)
extra.todo = true
return this.sub(Test, extra, this.todo)
}
skip(
name: string,
extra: { [k: string]: any },
cb?: (t: Test) => any
): Promise<FinalResults | null>
skip(
name: string,
cb?: (t: Test) => any
): Promise<FinalResults | null>
skip(
extra: { [k: string]: any },
cb?: (t: Test) => any
): Promise<FinalResults | null>
skip(cb?: (t: Test) => any): Promise<FinalResults | null>
skip(
...args: TestArgs<Test>
): Promise<FinalResults | null> {
const extra = parseTestArgs(...args)
extra.skip = true
return this.sub(Test, extra, this.skip)
}
}
|
src/test-built.ts
|
tapjs-core-edd7403
|
[
{
"filename": "src/test-template.ts",
"retrieved_chunk": "//{{PLUGINS CODE START}}\ntype Plug = TestBase | { t: Test }\nconst plugins: PI[] = []\ntype PlugKeys = keyof TestBase | 't'\n//{{PLUGINS CODE END}}\n//{{OPTS START}}\ntype TestOpts = TestBaseOpts\n//{{OPTS END}}\n//{{TEST INTERFACE START}}\ntype TTest = TestBase",
"score": 0.8870342969894409
},
{
"filename": "src/build.ts",
"retrieved_chunk": " .join('')}\ntype TestOpts = TestBaseOpts${plugins\n .map((_, i) => `\\n & Plugin${i}Opts`)\n .join('')}\n`\nconst testInterface = `type TTest = TestBase\n${plugins\n .map((_, i) => ` & ReturnType<typeof plugin${i}>\\n`)\n .join('')}\n`",
"score": 0.8799061179161072
},
{
"filename": "src/build.ts",
"retrieved_chunk": " T extends [any] | [any, any],\n Fallback extends unknown = unknown\n> = T extends [any, any] ? T[1] : Fallback\n${plugins\n .map(\n (_, i) => `type Plugin${i}Opts = SecondParam<\n Parameters<typeof plugin${i}>,\n TestBaseOpts\n>\\n`\n )",
"score": 0.8646910190582275
},
{
"filename": "src/test-template.ts",
"retrieved_chunk": " return t\n}\nexport class Test extends TestBase {\n constructor(opts: TestOpts) {\n super(opts)\n return applyPlugins(this)\n }\n test(\n name: string,\n extra: { [k: string]: any },",
"score": 0.8635913133621216
},
{
"filename": "src/build.ts",
"retrieved_chunk": " .join('')}\ntype PlugKeys =\n | keyof TestBase\n | 't'\n${plugins\n .map(\n (_, i) => ` | keyof ReturnType<typeof plugin${i}>\\n`\n )\n .join('')}`\nconst opts = `type SecondParam<",
"score": 0.854448676109314
}
] |
typescript
|
typeof plugin3>
export interface Test extends TTest {
|
// lifecycle methods like beforeEach, afterEach, teardown
// defined in plugins/lifecycle.ts
import Minipass from 'minipass'
import assert from 'node:assert'
import { hrtime } from 'node:process'
import { Readable } from 'node:stream'
import { format } from 'node:util'
import { CallSiteLike } from 'stack-utils'
import { FinalResults } from 'tap-parser'
import Deferred from 'trivial-deferred'
import { Base, BaseOpts } from './base.js'
import { esc } from './esc.js'
import stack from './stack.js'
import { TestPoint } from './test-point.js'
import { Waiter } from './waiter.js'
const queueEmpty = <T extends TestBase>(t: T) =>
t.queue.length === 0 ||
(t.queue.length === 1 &&
t.queue[0] === 'TAP version 14\n')
export interface ClassOf<T> {
new (): T
}
export type TapPlugin<
B extends Object,
O extends TestBaseOpts | any = any
> = ((t: TestBase, opts: O) => B) | ((t: TestBase) => B)
export interface TestBaseOpts extends BaseOpts {
/**
* The number of jobs to run in parallel. Defaults to 1
*/
jobs?: number
/**
* Test function called when this Test is executed
*/
cb?: (...args: any[]) => any
/**
* Flag to always/never show diagnostics. If unset, then
* diagnostics are shown for failing test points only.
*/
diagnostic?: boolean
}
const normalizeMessageExtra = (
defaultMessage: string,
message?: string | { [k: string]: any },
extra?: { [k: string]: any }
): [string, { [k: string]: any }] => {
if (typeof message === 'string') {
return [message || defaultMessage, extra || {}]
} else {
return [defaultMessage, message || {}]
}
}
/**
* Sigil for implicit end() calls that should not
* trigger an error if the user then calls t.end()
*/
const IMPLICIT = Symbol('implicit end')
/**
* Sigil to put in the queue to signal the end of all things
*/
const EOF = Symbol('EOF')
export type QueueEntry =
| string
| TestPoint
| Base
| typeof EOF
| Waiter
| [method: string, ...args: any[]]
/**
* The TestBaseBase class is the base class for all plugins,
* and eventually thus the Test class.
*
* This implements subtest functionality, TAP stream generation,
* lifecycle events, and only the most basic pass/fail assertions.
*
* All other features are added with plugins.
*/
export class TestBase extends Base {
// NB: generated pluginified Test class needs to declare over this
declare parent?: TestBase
promise?: Promise<any>
jobs: number
// #beforeEnd: [method: string | Symbol, ...args: any[]][] = []
subtests: Base[] = []
pool: Set<Base> = new Set()
queue: QueueEntry[] = ['TAP version 14\n']
cb?: (...args: any[]) => any
count: number = 0
ended: boolean = false
assertAt: CallSiteLike | null = null
assertStack: string | null = null
diagnostic: null | boolean = null
#planEnd: number = -1
#printedResult: boolean = false
#explicitEnded: boolean = false
#multiEndThrew: boolean = false
#n: number = 0
#noparallel: boolean = false
#occupied: null | Waiter | Base = null
#pushedEnd: boolean = false
#nextChildId: number = 1
#currentAssert: null | ((..._: any) => any) = null
#processing: boolean = false
#doingStdinOnly: boolean = false
/**
* true if the test has printed at least one TestPoint
*/
get printedResult(): boolean {
return this.#printedResult
}
constructor(options: TestBaseOpts) {
super(options)
this.jobs =
(options.jobs && Math.max(options.jobs, 1)) || 1
if (typeof options.diagnostic === 'boolean') {
this.diagnostic = options.diagnostic
}
if (options.cb) {
this.#setCB(options.cb)
}
}
#setCB<T extends TestBase>(this: T, cb: (t: T) => any) {
this.cb = (...args: any[]) =>
this.hook.runInAsyncScope(cb, this, ...args)
}
// TAP output generating methods
/**
* immediately exit this and all parent tests with a TAP
* Bail out! message.
*/
bailout(message?: string) {
if (this.parent && (this.results || this.ended)) {
this.parent.bailout(message)
} else {
this.#process()
message = message
? ' ' + ('' + esc(message)).trim()
: ''
message = message.replace(/[\r\n]/g, ' ')
this.parser.write('Bail out!' + message + '\n')
}
this.#end(IMPLICIT)
this.#process()
}
/**
* output a TAP comment, formatted like console.log()
*/
comment(...args: any[]) {
const body = format(...args)
const message =
('# ' + body.split(/\r?\n/).join('\n# ')).trim() +
'\n'
if (this.results) {
this.write(message)
} else {
this.queue.push(message)
}
this.#process()
}
/**
* Called when the test times out.
* Options are passed as diagnostics to the threw() method
*/
timeout(options: { [k: string]: any }) {
options = options || {}
options.expired = options.expired || this.name
if (this.#occupied && this.#occupied instanceof Base) {
this.#occupied.timeout(options)
} else {
super.timeout(options)
}
this.#end(IMPLICIT)
}
/**
* Set TAP pragma configs to affect the behavior of the parser.
* Only `strict` is supported by the parser.
*/
pragma(set: { [k: string]: boolean }) {
const p = Object.keys(set).reduce(
(acc, i) =>
acc + 'pragma ' + (set[i] ? '+' : '-') + i + '\n',
''
)
this.queue.push(p)
this.#process()
}
/**
* Specify the number of Test Points expected by this test.
* Outputs a TAP plan line.
*/
plan(n: number, comment?: string) {
if (this.bailedOut) {
return
}
if (this.#planEnd !== -1) {
throw new Error('Cannot set plan more than once')
}
if (typeof n !== 'number' || n < 0) {
throw new TypeError('plan must be a number')
}
// Cannot get any tests after a trailing plan, or a plan of 0
const ending = this.count !== 0 || n === 0
if (n === 0 && comment && !this.options.skip) {
this.options.skip = comment
}
this.#planEnd = n
comment = comment ? ' # ' + esc(comment.trim()) : ''
this.queue.push('1..' + n + comment + '\n')
if (ending) {
this.#end(IMPLICIT)
} else {
this.#process()
}
}
/**
* A passing (ok) Test Point
*/
pass(message?: string, extra?: { [k: string]: any }) {
this.currentAssert = TestBase.prototype.pass
this.printResult(
true,
...normalizeMessageExtra(
'(unnamed test)',
message,
extra
)
)
return true
}
/**
* A failing (not ok) Test Point
*/
fail(message?: string, extra?: { [k: string]: any }) {
this.currentAssert = TestBase.prototype.fail
const [m, e] = normalizeMessageExtra(
'(unnamed test)',
message,
extra
)
this.printResult(false, m, e)
return !!(e.todo || e.skip)
}
/**
* The current assertion being processed. May only be set if
* not already set.
*/
get currentAssert() {
return this.#currentAssert
}
/**
* The current assertion being processed. May only be set if
* not already set.
*/
set currentAssert(fn: null | ((...a: any[]) => any)) {
if (!this.#currentAssert && typeof fn === 'function') {
this.#currentAssert = fn
}
}
/**
* Print a Test Point
*/
printResult(
ok: boolean,
message: string,
extra: { [k: string]: any },
front: boolean = false
) {
this.#printedResult = true
const n = this.count + 1
this.currentAssert = TestBase.prototype.printResult
const fn = this.#currentAssert
this.#currentAssert = null
if (this.#planEnd !== -1 && n > this.#planEnd) {
if (!this.passing()) return
const failMessage = this.#explicitEnded
? 'test after end() was called'
: 'test count exceeds plan'
const er = new Error(failMessage, {
cause: {
test: this.name,
plan: this.#planEnd,
},
})
Error.captureStackTrace(er, fn || undefined)
this.threw(er)
return
}
extra = extra || {}
if (extra.expectFail) {
ok = !ok
}
if (this.assertAt) {
extra.at = this.assertAt
this.assertAt = null
}
if (this.assertStack) {
extra.stack = this.assertStack
this.assertStack = null
}
if (typeof extra.stack === 'string' && !extra.at) {
extra.at = stack.parseLine(extra.stack.split('\n')[0])
}
if (
!ok &&
!extra.skip &&
!extra.at &&
typeof fn === 'function'
) {
extra.at = stack
|
.at(fn)
if (!extra.todo) {
|
extra.stack = stack.captureString(80, fn)
}
}
const diagnostic =
typeof extra.diagnostic === 'boolean'
? extra.diagnostic
: typeof this.diagnostic === 'boolean'
? this.diagnostic
: extra.skip || extra.todo
? false
: !ok
if (diagnostic) {
extra.diagnostic = true
}
this.count = n
message = message + ''
const res = { ok, message, extra }
const tp = new TestPoint(ok, message, extra)
// when we jump the queue, skip an extra line
if (front) {
tp.message = tp.message.trimEnd() + '\n\n'
}
if (
this.#occupied &&
this.#occupied instanceof Waiter &&
this.#occupied.finishing
) {
front = true
}
if (front) {
if (
extra.tapChildBuffer ||
extra.tapChildBuffer === ''
) {
this.writeSubComment(tp)
this.parser.write(extra.tapChildBuffer)
}
this.emit('result', res)
this.parser.write(tp.ok + ++this.#n + tp.message)
if (this.bail && !ok && !extra.skip && !extra.todo) {
this.parser.write('Bail out! ' + message + '\n')
}
} else {
this.queue.push(tp)
if (this.bail && !ok && !extra.skip && !extra.todo) {
this.queue.push('Bail out! ' + message + '\n')
}
}
if (this.#planEnd === this.count) {
this.#end(IMPLICIT)
}
this.#process()
}
end(): this {
this.#end()
return super.end()
}
/**
* The leading `# Subtest` comment that introduces a child test
*/
writeSubComment<T extends TestPoint | Base>(p: T) {
const comment =
'# Subtest' +
(p.name ? ': ' + esc(p.name) : '') +
'\n'
this.parser.write(comment)
}
// end TAP otput generating methods
// flow control methods
/**
* Await the end of a Promise before proceeding.
* The supplied callback is called with the Waiter object.
*/
waitOn(
promise: Promise<any | void>,
cb: (w: Waiter) => any,
expectReject: boolean = false
): Promise<void> {
const w = new Waiter(
promise,
w => {
assert.equal(this.#occupied, w)
cb(w)
this.#occupied = null
this.#process()
},
expectReject
)
this.queue.push(w)
this.#process()
return w.promise
}
#end(implicit?: typeof IMPLICIT) {
if (this.#doingStdinOnly && implicit !== IMPLICIT)
throw new Error(
'cannot explicitly end while in stdinOnly mode'
)
this.debug('END implicit=%j', implicit === IMPLICIT)
if (this.ended && implicit === IMPLICIT) return
// beyond here we have to be actually done with things, or else
// the semantic checks on counts and such will be off.
if (!queueEmpty(this) || this.#occupied) {
if (!this.#pushedEnd) {
this.queue.push(['#end', implicit])
}
this.#pushedEnd = true
return this.#process()
}
this.ended = true
if (implicit !== IMPLICIT && !this.#multiEndThrew) {
if (this.#explicitEnded) {
this.#multiEndThrew = true
const er = new Error(
'test end() method called more than once'
)
Error.captureStackTrace(
er,
this.#currentAssert || this.#end
)
er.cause = {
test: this.name,
}
this.threw(er)
return
}
this.#explicitEnded = true
}
if (this.#planEnd === -1) {
this.debug(
'END(%s) implicit plan',
this.name,
this.count
)
this.plan(this.count)
}
this.queue.push(EOF)
this.#process()
}
#process() {
if (this.#processing) {
return this.debug(' < already processing')
}
this.debug(
'\nPROCESSING(%s)',
this.name,
this.queue.length
)
this.#processing = true
while (!this.#occupied) {
const p = this.queue.shift()
if (!p) {
this.debug('> end of queue')
break
}
if (p instanceof Base) {
this.debug('> subtest in queue', p.name)
this.#processSubtest(p)
} else if (p === EOF) {
this.debug(' > EOF', this.name)
// I AM BECOME EOF, DESTROYER OF STREAMS
this.parser.end()
} else if (p instanceof TestPoint) {
this.debug(' > TESTPOINT')
if (
p.extra.tapChildBuffer ||
p.extra.tapChildBuffer === ''
) {
this.writeSubComment(p)
this.parser.write(p.extra.tapChildBuffer)
}
this.emit('res', p.res)
this.parser.write(p.ok + ++this.#n + p.message)
} else if (typeof p === 'string') {
this.debug(' > STRING')
this.parser.write(p)
} else if (p instanceof Waiter) {
p.ready = true
this.#occupied = p
p.finish()
} else if (Array.isArray(p)) {
this.debug(' > METHOD')
const m = p.shift() as keyof this
if (typeof this[m] !== 'function') {
this.debug(
' > weird method not found in queue??',
m,
typeof this[m]
)
continue
}
const fn = (m === '#end' ? this.#end : this[m]) as (
...a: any[]
) => any
const ret = fn.call(this, ...p)
if (
ret &&
typeof ret === 'object' &&
typeof ret.then === 'function'
) {
// returned promise
ret.then(
() => {
this.#processing = false
this.#process()
},
(er: unknown) => {
this.#processing = false
this.threw(er)
}
)
return
}
/* c8 ignore start */
} else {
throw new Error('weird thing got in the queue')
}
/* c8 ignore stop */
}
while (
!this.#noparallel &&
this.pool.size < this.jobs
) {
const p = this.subtests.shift()
if (!p) {
break
}
if (!p.buffered) {
this.#noparallel = true
break
}
this.debug('start subtest', p)
this.emit('subtestStart', p)
this.pool.add(p)
if (this.bailedOut) {
this.#onBufferedEnd(p)
} else {
p.runMain(() => this.#onBufferedEnd(p))
}
}
this.debug(
'done processing',
this.queue,
this.#occupied
)
this.#processing = false
// just in case any tests ended, and we have sync stuff still
// waiting around in the queue to be processed
if (!this.#occupied && this.queue.length) {
this.#process()
}
}
#onBufferedEnd<T extends Base>(p: T) {
p.ondone = p.constructor.prototype.ondone
p.results =
p.results || new FinalResults(true, p.parser)
p.readyToProcess = true
const to = p.options.timeout
const dur =
to && p.passing() ? hrtime.bigint() - p.start : null
if (dur && to && dur > to) {
p.timeout()
} else {
p.setTimeout(0)
}
this.debug(
'%s.#onBufferedEnd',
this.name,
p.name,
p.results.bailout
)
this.pool.delete(p)
p.options.tapChildBuffer = p.output || ''
p.options.stack = ''
if (p.time) p.options.time = p.time
if (this.#occupied === p) this.#occupied = null
p.deferred?.resolve(p.results)
this.emit('subtestEnd', p)
this.#process()
}
#onIndentedEnd<T extends Base>(p: T) {
this.emit('subtestProcess', p)
p.ondone = p.constructor.prototype.ondone
p.results =
p.results || new FinalResults(true, p.parser)
this.debug('#onIndentedEnd', this.name, p.name)
this.#noparallel = false
const sti = this.subtests.indexOf(p)
if (sti !== -1) this.subtests.splice(sti, 1)
p.readyToProcess = true
p.options.time = p.time
const to = p.options.timeout
const dur =
to && p.passing() ? hrtime.bigint() - p.start : null
if (dur && to && dur > to) {
p.timeout()
} else {
p.setTimeout(0)
}
this.debug('#onIndentedEnd %s(%s)', this.name, p.name)
this.#occupied = null
this.debug(
'OIE(%s) b>shift into queue',
this.name,
this.queue
)
p.options.stack = ''
this.printResult(p.passing(), p.name, p.options, true)
this.debug(
'OIE(%s) shifted into queue',
this.name,
this.queue
)
p.deferred?.resolve(p.results)
this.emit('subtestEnd', p)
this.#process()
}
/**
* @internal
*/
main(cb: () => void) {
if (typeof this.options.timeout === 'number') {
this.setTimeout(this.options.timeout)
}
this.debug('MAIN pre', this)
const end = () => {
this.debug(' > implicit end for promise')
this.#end(IMPLICIT)
done()
}
const done = (er?: Error) => {
if (er) this.threw(er)
if (this.results || this.bailedOut) cb()
else this.ondone = () => cb()
}
// This bit of overly clever line-noise wraps the call to user-code
// in a try-catch. We can't rely on the domain for this yet, because
// the 'end' event can trigger a throw after the domain is unhooked,
// but before this is no longer the official "active test"
const ret = (() => {
if (!this.cb) return
try {
return this.cb(this)
} catch (er: any) {
if (!er || typeof er !== 'object') {
er = { error: er }
}
er.tapCaught = 'testFunctionThrow'
this.threw(er)
}
})()
if (ret && ret.then) {
this.promise = ret
ret.tapAbortPromise = done
ret.then(end, (er: any) => {
if (!er || typeof er !== 'object') {
er = { error: er }
}
er.tapCaught = 'returnedPromiseRejection'
done(er)
})
} else done()
this.debug('MAIN post', this)
}
#processSubtest<T extends Base>(p: T) {
this.debug(' > subtest')
this.#occupied = p
if (!p.buffered) {
this.emit('subtestStart', p)
this.debug(' > subtest indented')
p.stream.pipe(this.parser, { end: false })
this.writeSubComment(p)
this.debug('calling runMain', p.runMain.toString())
p.runMain(() => {
this.debug('in runMain', p.runMain.toString())
this.#onIndentedEnd(p)
})
} else if (p.readyToProcess) {
this.emit('subtestProcess', p)
this.debug(' > subtest buffered, finished')
// finished! do the thing!
this.#occupied = null
if (!p.passing() || !p.silent) {
this.printResult(
p.passing(),
p.name,
p.options,
true
)
}
} else {
this.#occupied = p
this.debug(' > subtest buffered, unfinished', p)
// unfinished buffered test.
// nothing to do yet, just leave it there.
this.queue.unshift(p)
}
}
/**
* Parse stdin as the only tap stream (ie, not as a child test)
* If used, then no other subtests or assertions are allowed.
*/
stdinOnly<T extends BaseOpts>(
extra?: T & { tapStream?: Readable | Minipass }
) {
const stream = ((extra && extra.tapStream) ||
process.stdin) as Minipass
if (!stream) {
throw new Error(
'cannot read stdin without stdin stream'
)
}
if (
this.queue.length !== 1 ||
this.queue[0] !== 'TAP version 14\n' ||
this.#processing ||
this.results ||
this.#occupied ||
this.pool.size ||
this.subtests.length
) {
throw new Error(
'Cannot use stdinOnly on a test in progress'
)
}
this.#doingStdinOnly = true
this.queue.length = 0
this.parser.on('child', p => {
// pretend to be a rooted parser, so it gets counts.
p.root = p
const t = new Base({
name: p.name,
parent: this,
parser: p,
bail: p.bail,
strict: p.strict,
omitVersion: p.omitVersion,
preserveWhitespace: p.preserveWhitespace,
childId: this.#nextChildId++,
})
this.emit('subtestAdd', t)
this.emit('subtestStart', t)
this.emit('subtestProcess', t)
p.on('complete', () => {
t.time = p.time
this.emit('subtestEnd', t)
})
})
stream.pause()
stream.pipe(this.parser)
stream.resume()
}
/**
* Mount a subtest, using this Test object as a harness.
* Exposed mainly so that it can be used by builtin plugins.
*
* @internal
*/
sub<T extends Base, O extends TestBaseOpts>(
Class: { new (options: O): T },
extra: O,
caller: (...a: any[]) => unknown
): Promise<FinalResults | null> {
if (this.bailedOut) return Promise.resolve(null)
if (this.results || this.ended) {
const er = new Error(
'cannot create subtest after parent test ends'
)
Error.captureStackTrace(er, caller)
this.threw(er)
return Promise.resolve(null)
}
extra.childId = this.#nextChildId++
if (this.shouldSkipChild(extra)) {
this.pass(extra.name, extra)
return Promise.resolve(null)
}
extra.indent = ' '
if (extra.buffered !== undefined) {
if (this.jobs > 1) {
extra.buffered = true
} else {
extra.buffered = false
}
}
extra.bail =
extra.bail !== undefined ? extra.bail : this.bail
extra.parent = this
extra.stack = stack.captureString(80, caller)
extra.context = this.context
const t = new Class(extra)
this.queue.push(t)
this.subtests.push(t)
this.emit('subtestAdd', t)
const d = new Deferred<FinalResults>()
t.deferred = d
this.#process()
return d.promise
}
/**
* Return true if the child test represented by the options object
* should be skipped. Extended by the grep/only filtering plugins.
*/
shouldSkipChild(extra: { [k: string]: any }) {
return !!(extra.skip || extra.todo)
}
// end flow control methods
}
|
src/test-base.ts
|
tapjs-core-edd7403
|
[
{
"filename": "src/extra-from-error.ts",
"retrieved_chunk": " file,\n line: er.loc.line,\n column: er.loc.column + 1,\n }\n } else {\n // parse out the 'at' bit from the first line.\n extra.at = stack.parseLine(splitst[1])\n }\n extra.stack = stack.clean(splitst)\n }",
"score": 0.8373392224311829
},
{
"filename": "src/clean-yaml-object.ts",
"retrieved_chunk": " const res = { ...object }\n if (hasOwn(res, 'stack') && !hasOwn(res, 'at')) {\n res.at = stack.parseLine(res.stack.split('\\n')[0])\n }\n const file = res.at && res.at.file && resolve(res.at.file)\n if (\n !options.stackIncludesTap &&\n file &&\n file.includes(tapDir)\n ) {",
"score": 0.8188691139221191
},
{
"filename": "src/parse-test-args.ts",
"retrieved_chunk": " if (!extra) extra = {}\n if (!cb && defaultName !== '/dev/stdin')\n extra.todo = extra.todo || true\n if (!name && extra.name) name = extra.name\n if (!name && cb && cb.name) name = cb.name\n name = name || defaultName\n extra.name = name\n extra.cb = cb || todoCb\n return extra\n}",
"score": 0.8075278997421265
},
{
"filename": "src/extra-from-error.ts",
"retrieved_chunk": " if (er._babel && er.loc) {\n const msplit = message.split(': ')\n const f = msplit[0].trim()\n extra.message = msplit.slice(1).join(': ')\n .replace(/ \\([0-9]+:[0-9]+\\)$/, '').trim()\n const file = f.indexOf(process.cwd()) === 0\n ? f.substr(process.cwd().length + 1) : f\n if (file !== 'unknown')\n delete er.codeFrame\n extra.at = {",
"score": 0.807094395160675
},
{
"filename": "src/base.ts",
"retrieved_chunk": " er.stack.split(/\\n/).slice(1).join('\\n')\n )\n console.error(extra)\n }\n } else {\n this.parser.ok = false\n }\n return extra\n }\n passing() {",
"score": 0.8028371334075928
}
] |
typescript
|
.at(fn)
if (!extra.todo) {
|
import { ItemView, Notice, WorkspaceLeaf } from "obsidian"
import { Individuals, Topics } from "../ai/mentors"
import { MentorModel, ModelType } from "../ai/model"
import { CleanIcon } from "../assets/icons/clean"
import { CopyIcon } from "../assets/icons/copy"
import { SendIcon } from "../assets/icons/send"
import { Mentor, Message, supportedLanguage } from "../types"
export const VIEW_TYPE_CHAT = "mentor-chat-view"
export class ChatView extends ItemView {
preferredMentorId = "default"
preferredLanguage = "en"
model: ModelType
firstOpen = true
// isTyping = false
displayedMessages: Message[] = []
// Merge the two Record<string, Mentor> objects into one.
mentorList: Record<string, Mentor> = {
...Topics,
...Individuals,
}
mentor: MentorModel
constructor(
leaf: WorkspaceLeaf,
token: string,
preferredMentorId: string,
model: ModelType,
preferredLanguage: supportedLanguage
) {
super(leaf)
this.preferredMentorId = preferredMentorId
this.preferredLanguage = preferredLanguage
this.model = model
// Mentor selection.
const selectedMentor = this.mentorList[preferredMentorId]
this.mentor = new MentorModel(
preferredMentorId,
selectedMentor,
this.model,
token,
preferredLanguage
)
}
currentInput = ""
loadingMessage: Message = { role: "assistant", content: "..." }
getViewType() {
return VIEW_TYPE_CHAT
}
getDisplayText() {
return "AI Mentor"
}
getIcon(): string {
return "aimentor"
}
async onOpen() {
// if this is the first time the view is opened, we need to load the choosen mentor from the settings
if (this.firstOpen) {
this.firstOpen = false
this.handleMentorChange(this.preferredMentorId)
}
const chatView = this.containerEl.children[1]
chatView.empty()
chatView.addClass("main-container")
const container = chatView.createDiv()
container.addClass("chat")
container.createEl("h4", { text: "Your AI Mentor" })
const mentorDiv = container.createDiv()
mentorDiv.addClass("chat__mentor")
const mentorText = mentorDiv.createEl("p", { text: "Select a mentor:" })
mentorText.addClass("chat__mentor-text")
const selectEl = mentorDiv.createEl("select")
selectEl.addClass("chat__mentor-select")
// Create groups for categories of AI mentors.
const topicsGroup = selectEl.createEl("optgroup")
topicsGroup.label = "By Topic"
const individualsGroup = selectEl.createEl("optgroup")
individualsGroup.label = "Famous Individuals"
for (const mentor of Object.entries(Topics)) {
const optionEl = topicsGroup.createEl("option")
optionEl.value = mentor[0]
optionEl.text = mentor[1].name[this.preferredLanguage]
}
for (const mentor of Object.entries(Individuals)) {
const optionEl = individualsGroup.createEl("option")
optionEl.value = mentor[0]
optionEl.text = mentor[1].name[this.preferredLanguage]
}
selectEl.onchange = (evt) => {
this.handleMentorChange((evt.target as HTMLSelectElement).value)
}
selectEl.value = this.mentor.id
// Display messages in the chat.
const chatDiv = container.createDiv()
chatDiv.addClass("chat__messages")
// Add history to selectedMentor.firstMessage
// const firstMessage: Message = {
// role: "assistant",
// content: selectedMentor.firstMessage[this.preferredLanguage],
// }
// Add the first message to the chat.
const history =
this.mentor.history.filter(
(message: Message) => message.role !== "system"
) || []
for (const message of this.displayedMessages) {
// Contains text and icon.
const messageDiv = chatDiv.createDiv()
messageDiv.addClass("chat__message-container")
messageDiv.addClass(`chat__message-container--${message.role}`)
// Add the message text.
const messageEl = messageDiv.createEl("p", {
text: message.content,
})
messageEl.addClass("chat__message")
messageEl.addClass(`chat__message--${message.role}`)
// Add an icon button to next to the message to copy it.
// Defaults to hidden.
const actionButton = messageDiv.createEl("button")
actionButton.addClass("icon-button")
actionButton.addClass("clickable-icon")
actionButton.addClass("icon-button--hidden")
actionButton.innerHTML = CopyIcon
actionButton.onclick = () => {
navigator.clipboard.writeText(message.content)
new Notice("Copied to clipboard.")
}
// When the user hovers over the message, show the copy button.
messageDiv.onmouseenter = () => {
actionButton.removeClass("icon-button--hidden")
}
messageDiv.onmouseleave = () => {
actionButton.addClass("icon-button--hidden")
}
}
// Add a text input.
// Dealing with Textarea Height
function calcHeight(value: string) {
const numberOfLineBreaks = (value.match(/\n/g) || []).length
// min-height + lines x line-height + padding + border
const newHeight = 16 + numberOfLineBreaks * 16 + 12 + 2
return newHeight
}
const interationDiv = container.createDiv()
interationDiv.addClass("chat__interaction-container")
const inputEl = interationDiv.createEl("textarea")
inputEl.placeholder = "Ask a question..."
inputEl.addClass("chat__input")
inputEl.oninput = (evt) => {
this.currentInput = (evt.target as HTMLInputElement).value
}
inputEl.onkeydown = (evt) => {
if (!evt.shiftKey) {
if (evt.key === "Enter") {
this.handleSend()
}
}
}
inputEl.onkeyup = (evt) => {
// Resize the input element to fit the text.
inputEl.style.height = calcHeight(this.currentInput) + "px"
}
// Add a send button.
const sendButton = interationDiv.createEl("button")
sendButton.addClass("icon-button")
sendButton.addClass("clickable-icon")
sendButton.innerHTML = SendIcon
sendButton.onclick = () => this.handleSend()
// Add a button to clear the chat.
const clearButton = interationDiv.createEl("button")
clearButton.addClass("icon-button")
clearButton.addClass("clickable-icon")
clearButton.
|
innerHTML = CleanIcon
clearButton.onclick = () => this.handleClear()
}
|
async onClose() {
// Nothing to clean up.
}
async handleMentorChange(id: string) {
const newMentor = this.mentorList[id]
this.mentor.changeIdentity(id, newMentor)
this.displayedMessages = [
{
role: "assistant",
content: newMentor.firstMessage[this.preferredLanguage],
},
]
// Refresh the view.
await this.onOpen()
}
async handleKeywordsInPrompt(prompt: string): Promise<string> {
// Todo: return a prompt that do not contain the note to be inserted in the chat
if (prompt.includes("@current-note")) {
const noteFile = this.app.workspace.getActiveFile()
if (!noteFile || !noteFile.name) {
new Notice("Please open a note to use @current-note.")
return prompt
}
const text = await this.app.vault.read(noteFile)
prompt = prompt.replace("@current-note", text)
return prompt
}
return prompt
}
async handleSend() {
// Don't send empty messages.
if (this.currentInput === "") {
new Notice("Cannot send empty messages.")
return
}
// Wait for the mentor to respond.
if (
this.mentor.history.length !== 0 &&
this.mentor.history[this.mentor.history.length - 1].role === "user"
) {
new Notice("Please wait for your mentor to respond.")
return
}
const prompt = await this.handleKeywordsInPrompt(this.currentInput)
// Display the prompt
this.displayedMessages.push({
role: "user",
content: prompt,
})
// Add the loading message
this.displayedMessages.push(this.loadingMessage)
// Refresh the view.
await this.onOpen()
this.mentor
.getCompletion(prompt)
.then(async (response) => {
// Clear the input.
this.currentInput = ""
// Display the response.
this.displayedMessages.pop()
this.displayedMessages.push({
role: "assistant",
content: response,
})
// Refresh the view.
await this.onOpen()
})
.catch(async (error) => {
console.log("error", error)
// Clear the input.
this.currentInput = ""
// Display the error message.
this.displayedMessages.pop()
this.displayedMessages.push({
role: "assistant",
content: "An error occurred. Please try again.",
})
// Refresh the view.
await this.onOpen()
})
}
async handleClear() {
// Keep only the first message.
this.mentor.reset()
// Clear the displayed messages.
this.displayedMessages = [
{
role: "assistant",
content:
this.mentor.mentor.firstMessage[this.preferredLanguage],
},
]
// Refresh the view.
await this.onOpen()
}
}
|
src/components/chatview.ts
|
clementpoiret-ai-mentor-b62d95a
|
[
{
"filename": "src/assets/icons/send.ts",
"retrieved_chunk": "export const SendIcon =\n\t'<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"32\" height=\"32\" viewBox=\"0 0 32 32\"><path fill=\"currentColor\" d=\"m27.45 15.11l-22-11a1 1 0 0 0-1.08.12a1 1 0 0 0-.33 1L7 16L4 26.74A1 1 0 0 0 5 28a1 1 0 0 0 .45-.11l22-11a1 1 0 0 0 0-1.78Zm-20.9 10L8.76 17H18v-2H8.76L6.55 6.89L24.76 16Z\"/></svg>'",
"score": 0.7891011238098145
},
{
"filename": "src/settings.ts",
"retrieved_chunk": "\t\t\t\t\t\tthis.plugin.settings.token = change\n\t\t\t\t\t\tthis.plugin.saveSettings()\n\t\t\t\t\t})\n\t\t\t})\n\t\t\t.addButton((button: ButtonComponent) => {\n\t\t\t\tbutton.setButtonText(\"Generate token\")\n\t\t\t\tbutton.onClick((evt: MouseEvent) => {\n\t\t\t\t\twindow.open(\"https://platform.openai.com/account/api-keys\")\n\t\t\t\t})\n\t\t\t})",
"score": 0.786132276058197
},
{
"filename": "src/components/modals.ts",
"retrieved_chunk": "\t\tconst { contentEl } = this\n\t\tconst titleEl = contentEl.createDiv(\"title\")\n\t\ttitleEl.addClass(\"modal__title\")\n\t\ttitleEl.setText(this.title)\n\t\tconst textEl = contentEl.createDiv(\"text\")\n\t\ttextEl.addClass(\"modal__text\")\n\t\ttextEl.setText(this.displayedText)\n\t\t// Copy text when clicked\n\t\ttextEl.addEventListener(\"click\", () => {\n\t\t\tnavigator.clipboard.writeText(this.displayedText)",
"score": 0.7816333770751953
},
{
"filename": "src/components/modals.ts",
"retrieved_chunk": "\t\t\tnew Notice(\"Copied to clipboard\")\n\t\t})\n\t\ttextEl.addEventListener(\"contextmenu\", () => {\n\t\t\tnavigator.clipboard.writeText(this.displayedText)\n\t\t\tnew Notice(\"Copied to clipboard\")\n\t\t})\n\t}\n\tonClose() {\n\t\tconst { contentEl } = this\n\t\tcontentEl.empty()",
"score": 0.7684285640716553
},
{
"filename": "src/main.ts",
"retrieved_chunk": "\t\t\t\"Mentor\",\n\t\t\t(evt: MouseEvent) => {\n\t\t\t\t// Called when the user clicks the icon.\n\t\t\t\tthis.activateView()\n\t\t\t}\n\t\t)\n\t\t// Perform additional things with the ribbon\n\t\tribbonIconEl.addClass(\"mentor-ribbon\")\n\t\t// This adds a settings tab so the user can configure various aspects of the plugin\n\t\tthis.addSettingTab(new SettingTab(this.app, this))",
"score": 0.7622029781341553
}
] |
typescript
|
innerHTML = CleanIcon
clearButton.onclick = () => this.handleClear()
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.