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/Button.tsx",
"retrieved_chunk": "import { ComponentProps, ElementType, SVGProps } from 'react';\ninterface ButtonProps extends ComponentProps<'button'> {\n icon?: ElementType<SVGProps<SVGSVGElement>>;\n}\nconst Button = (props: ButtonProps): JSX.Element => {\n const { icon: Icon, ...buttonProps } = props;\n return (\n <button\n {...buttonProps}\n className={`inline-flex justify-center rounded-lg border border-transparent bg-blue-100 px-4 py-2 text-sm font-medium text-blue-900 transition-transform hover:bg-blue-200 focus:outline-none focus:ring-2 focus:ring-sky-500 active:scale-95 ${",
"score": 27.052786063380857
},
{
"filename": "src/components/TerminalMenu.tsx",
"retrieved_chunk": " className={`${\n active ? 'bg-blue-200 text-blue-900' : 'text-white'\n } group flex w-full items-center whitespace-nowrap rounded-md p-2 text-sm ${\n props.className ?? ''\n }`}\n onClick={props.onClick}\n >\n {props.icon && (\n <props.icon\n aria-hidden=\"true\"",
"score": 25.215249461846017
},
{
"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": 17.85332959530931
},
{
"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": 17.06323275252054
},
{
"filename": "src/hooks/useFilesMutations.ts",
"retrieved_chunk": " save: (name: string, content: string) => void;\n destroy: (name: string) => void;\n draft: (autoSelect?: boolean) => void;\n select: (name: string) => void;\n update: (content: string) => void;\n create: (name: string, content: string) => void;\n}\nconst useFilesMutations = (): UseFilesMutationsHook => {\n const dispatch = useAppDispatch();\n return {",
"score": 16.08699437534377
}
] | 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/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": 33.72939665870862
},
{
"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": 33.71288308213902
},
{
"filename": "src/components/UnsavedBadge.tsx",
"retrieved_chunk": " <div className=\"h-2 w-2 rounded-full bg-amber-400\" />\n <p className=\"select-none text-xs text-amber-400\">Unsaved</p>\n </div>\n );\n};\nexport default UnsavedBadge;",
"score": 29.969403937061642
},
{
"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": 28.7253089827092
},
{
"filename": "src/components/Navigator.tsx",
"retrieved_chunk": " return () => window.removeEventListener('keydown', handleShortcut);\n }, [handleShortcut]);\n return (\n <>\n <nav className=\"flex items-center justify-between space-x-2\">\n <FileName />\n <div className=\"flex flex-row items-center space-x-2\">\n {name && (\n <Item\n className=\"text-slate-400\"",
"score": 28.00822804354611
}
] | 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": 17.61422426426714
},
{
"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": 14.494668892378556
},
{
"filename": "src/hooks/useFile.ts",
"retrieved_chunk": " NamesWithUnsaved,\n IsUnsavedOf,\n Exports,\n};\nexport default useFile;",
"score": 14.276795005605525
},
{
"filename": "src/hooks/useFile.ts",
"retrieved_chunk": " return fileInFiles !== fileInVault;\n });\nconst Exports = () => {\n const { files, list } = getState().vault;\n return list.map((name) => ({ name, content: files[name] }));\n};\nconst useFile = {\n SelectedName,\n Selected,\n NamesSet,",
"score": 13.961379645403518
},
{
"filename": "src/components/Library.tsx",
"retrieved_chunk": " </p>\n </div>\n <div className=\"mt-6 flex flex-col space-y-2\">\n {files.map(({ name, unsaved }) => (\n <FileItem\n key={name}\n name={name}\n onClick={props.onClose}\n unsaved={unsaved}\n />",
"score": 12.684665739918758
}
] | 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/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": 23.705052212598513
},
{
"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": 23.23428024121234
},
{
"filename": "src/components/Navigator.tsx",
"retrieved_chunk": " return () => window.removeEventListener('keydown', handleShortcut);\n }, [handleShortcut]);\n return (\n <>\n <nav className=\"flex items-center justify-between space-x-2\">\n <FileName />\n <div className=\"flex flex-row items-center space-x-2\">\n {name && (\n <Item\n className=\"text-slate-400\"",
"score": 16.74276777855328
},
{
"filename": "src/components/Editor.tsx",
"retrieved_chunk": " <Button icon={PlayIcon} onClick={saveThenRunCode}>\n Run\n <K className=\"ml-2 text-blue-900/60 ring-blue-900/60\" of=\"F5\" />\n </Button>\n </div>\n )}\n </section>\n );\n};\nconst Editor = (props: EditorProps): JSX.Element | null => {",
"score": 16.21875881452835
},
{
"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": 14.650707884059308
}
] | 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/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": 22.9487131343633
},
{
"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": 18.80881190785069
},
{
"filename": "src/hooks/useInterpreter.ts",
"retrieved_chunk": " let interruptBuffer: Uint8Array | null = null;\n if (typeof SharedArrayBuffer !== 'undefined') {\n interruptBuffer = new Uint8Array(new SharedArrayBuffer(1));\n interruptBufferRef.current = interruptBuffer;\n }\n worker.postMessage({ type: 'initialize', payload: interruptBuffer });\n workerRef.current = worker;\n };\n useEffect(() => {\n if (workerRef.current) return;",
"score": 18.75445694309745
},
{
"filename": "src/components/Hotkey.tsx",
"retrieved_chunk": "const convert = (key: string): string =>\n key in CONVERTED_KEYS ? CONVERTED_KEYS[key as ConvertibleKeys] : key;\nconst Hotkey = (props: HotkeyProps): JSX.Element => {\n const { of: hotkey } = props;\n const keys = hotkey.split(SEPARATOR);\n if (isMac)\n return <kbd className={props.className}>{keys.map(convert).join('')}</kbd>;\n return (\n <>\n {keys",
"score": 18.00390629532207
},
{
"filename": "src/components/Hotkey.tsx",
"retrieved_chunk": " .flatMap((key) => [\n <kbd key={key} className={props.className}>\n {convert(key)}\n </kbd>,\n SEPARATOR,\n ])\n .slice(0, -1)}\n </>\n );\n};",
"score": 17.948514789958224
}
] | typescript | promptRef.current?.focusWith(key); |
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": "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": 16.28270731302097
},
{
"filename": "src/components/FileUploader.tsx",
"retrieved_chunk": " </Button>\n );\n};\nexport default FileUploader;",
"score": 11.20173354298266
},
{
"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": 8.509944094387782
},
{
"filename": "src/hooks/useFilesMutations.ts",
"retrieved_chunk": " save: (name: string, content: string) => void;\n destroy: (name: string) => void;\n draft: (autoSelect?: boolean) => void;\n select: (name: string) => void;\n update: (content: string) => void;\n create: (name: string, content: string) => void;\n}\nconst useFilesMutations = (): UseFilesMutationsHook => {\n const dispatch = useAppDispatch();\n return {",
"score": 8.377692722690197
},
{
"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": 8.079653822179615
}
] | 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/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": 37.43030965173541
},
{
"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": 36.10760599261082
},
{
"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": 35.977923610260795
},
{
"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": 23.168624288630895
},
{
"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": 19.799000534305502
}
] | typescript | const promptRef = useRef<ComponentRef<typeof Prompt>>(null); |
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": " setCommand((state) => ({ dirty: true, command: state.command + key }));\n inputRef.current?.focus();\n },\n }));\n return (\n <div className=\"flex w-full items-center rounded-lg bg-slate-800 px-2 text-slate-300 shadow-2xl shadow-slate-900 focus-within:ring-2 focus-within:ring-slate-500\">\n <ChevronRightIcon className=\"h-5\" />\n <div className=\"relative ml-2 w-full\">\n {!command.length && (\n <div className=\"pointer-events-none absolute left-0 top-0 flex h-full w-full items-center overflow-hidden\">",
"score": 52.300002742165184
},
{
"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": 46.90030131162756
},
{
"filename": "src/workers/interpreter.worker.ts",
"retrieved_chunk": "const RUN_CODE = '\\u001b[3m\\u001b[32m<run code>\\u001b[0m' as const;\nconst post = {\n write: (text: string) => postMessage({ type: 'write', payload: text }),\n writeln: (line: string) => postMessage({ type: 'writeln', payload: line }),\n error: (message: string) => postMessage({ type: 'error', payload: message }),\n system: (message: string) =>\n postMessage({ type: 'system', payload: message }),\n lock: () => postMessage({ type: 'lock' }),\n unlock: () => postMessage({ type: 'unlock' }),\n prompt: (newLine = true) => post.write(`${newLine ? '\\n' : ''}${PS1}`),",
"score": 41.38213318670738
},
{
"filename": "src/components/Between.tsx",
"retrieved_chunk": " className={`h-full ${direction === 'horizontal' ? 'flex' : ''}`}\n direction={direction}\n gutterSize={15}\n sizes={sizes}\n >\n <div ref={oneRef}>{props.first}</div>\n <div ref={twoRef}>{props.second}</div>\n </Split>\n );\n};",
"score": 39.69849979836329
},
{
"filename": "src/workers/interpreter.worker.ts",
"retrieved_chunk": "}\nlet pyodide: PyodideInterface;\nlet interruptBuffer: Uint8Array | null;\nlet await_fut: PyProxyCallable;\nlet repr_shorten: PyProxyCallable;\nlet pyconsole: PyProxy;\nlet clear_console: PyProxyCallable;\nlet create_console: PyProxyCallable;\nconst PS1 = '\\u001b[32;1m>>> \\u001b[0m' as const;\nconst PS2 = '\\u001b[32m... \\u001b[0m' as const;",
"score": 38.93357937792024
}
] | typescript | <Prompt
ref={promptRef} |
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": 16.270212166240665
},
{
"filename": "src/components/Library.tsx",
"retrieved_chunk": " ))}\n </div>\n <div className=\"mt-10 space-x-2\">\n <Button\n icon={PlusIcon}\n onClick={() => {\n draft(true);\n props.onClose();\n }}\n >",
"score": 13.185685270394808
},
{
"filename": "src/components/Library.tsx",
"retrieved_chunk": "};\nexport default Library;",
"score": 12.920783935671288
},
{
"filename": "src/components/Editor.tsx",
"retrieved_chunk": " <Button icon={PlayIcon} onClick={saveThenRunCode}>\n Run\n <K className=\"ml-2 text-blue-900/60 ring-blue-900/60\" of=\"F5\" />\n </Button>\n </div>\n )}\n </section>\n );\n};\nconst Editor = (props: EditorProps): JSX.Element | null => {",
"score": 11.156579574617249
},
{
"filename": "src/components/Hotkey.tsx",
"retrieved_chunk": "interface HotkeyProps {\n of: string;\n className?: string;\n}\nconst isMac = navigator.platform.startsWith('Mac');\nconst CONVERTED_KEYS = isMac\n ? {\n Mod: '⌘',\n Alt: '⌥',\n Shift: '⇧',",
"score": 9.22606837776489
}
] | typescript | Library onClose={() => setOpenLibrary(false)} open={openLibrary} />
</>
); |
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/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": 32.954282378743635
},
{
"filename": "src/components/Library.tsx",
"retrieved_chunk": " ))}\n </div>\n <div className=\"mt-10 space-x-2\">\n <Button\n icon={PlusIcon}\n onClick={() => {\n draft(true);\n props.onClose();\n }}\n >",
"score": 32.28661819151427
},
{
"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": 31.230125996468054
},
{
"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": 25.16743478939613
},
{
"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": 24.61725928825739
}
] | typescript | Button icon={StopIcon} onClick={props.onStop}>
Stop
</Button>
</div>
)} |
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": 33.59189416078578
},
{
"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": 27.78419424692749
},
{
"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": 23.9490815847155
},
{
"filename": "src/lib/createCollectionRef.d.ts",
"retrieved_chunk": "import { firestore } from 'firebase-admin';\nimport { DocumentData } from 'firebase/firestore';\nexport declare const createCollectionRef: <T extends DocumentData>(db: firestore.Firestore, collectionPath: string) => firestore.CollectionReference<T>;",
"score": 23.092547512033523
},
{
"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": 22.789700382186776
}
] | typescript | const collectionRef = createCollectionRef<T>(db, collectionPath)
if (id) { |
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": "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": 26.30390344174599
},
{
"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": 25.178263648859126
},
{
"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": 19.866039361060334
},
{
"filename": "src/lib/addMultipleCollectionItems.d.ts",
"retrieved_chunk": " * @returns An array of WriteResult arrays corresponding to each batch.\n *\n * @throws Throws an exception with an error message if an error occurs.\n *\n * @example\n * ```typescript\n * import { firestore } from 'firebase-admin'\n * import { adds } from '@skeet-framework/firestore'\n *\n * const db = firestore();",
"score": 17.335168996762228
},
{
"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": 13.55636119874122
}
] | 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/index.ts",
"retrieved_chunk": " }),\n});\nexport const persistor = persistStore(store, null, () => {\n const vault = store.getState().vault;\n store.dispatch(filesActions.rehydrate(vault));\n});\nexport const getState = store.getState;\nexport type RootState = ReturnType<typeof store.getState>;\nexport type AppDispatch = typeof store.dispatch;",
"score": 40.85267769740616
},
{
"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": 22.309222597118808
},
{
"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": 15.97503672753478
},
{
"filename": "src/App.tsx",
"retrieved_chunk": "import { Provider } from 'react-redux';\nimport { PersistGate } from 'redux-persist/integration/react';\nimport IDEPage from './pages/IDEPage';\nimport { persistor, store } from './store';\nconst App = (): JSX.Element => {\n return (\n <Provider store={store}>\n <PersistGate loading={null} persistor={persistor}>\n <IDEPage />\n </PersistGate>",
"score": 15.698337194389044
},
{
"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": 14.979013130430344
}
] | 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/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": 15.820315724473193
},
{
"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": 14.403791180080407
},
{
"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": 10.403516058102396
},
{
"filename": "src/routes/EmailSend.ts",
"retrieved_chunk": "\t\t\t\t\t\tdata: {\n\t\t\t\t\t\t\t\tmessageId: receivedMailId,\n\t\t\t\t\t\t},\n\t\t\t\t\t\tstatus: 200,\n\t\t\t\t}, 200)\n\t\t} catch (error) {\n\t\t\t\tsendErrorResponse(res, {\n\t\t\t\t\t\terror: {\n\t\t\t\t\t\t\t\tcode: ErrorCodes.INTERNAL_ERROR,\n\t\t\t\t\t\t\t\tmessage: \"Internall error while sending mail\",",
"score": 10.01969699080048
},
{
"filename": "src/const/errors.ts",
"retrieved_chunk": "\t\terror: {\n\t\t\t\tcode: ErrorCodes,\n\t\t\t\tmessage: string,\n\t\t\t\tdetails?: any,\n\t\t}\n\t\tstatus: number,\n}",
"score": 9.604484887480885
}
] | typescript | const 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": 37.558403479986346
},
{
"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": 27.035041987287233
},
{
"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": 26.672355493268192
},
{
"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": 25.90588228199177
},
{
"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": 23.99280756553073
}
] | 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 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/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": 13.197929502836136
},
{
"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": 11.687901033733592
},
{
"filename": "src/const/errors.ts",
"retrieved_chunk": "\t\terror: {\n\t\t\t\tcode: ErrorCodes,\n\t\t\t\tmessage: string,\n\t\t\t\tdetails?: any,\n\t\t}\n\t\tstatus: number,\n}",
"score": 9.604484887480885
},
{
"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": 9.045570984928991
},
{
"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": 8.569037908384209
}
] | typescript | cachedEmailData = await EmailCache.getEmail(queryEmail as string); |
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/useFilesMutations.ts",
"retrieved_chunk": " },\n destroy: (name: string) => {\n dispatch(filesActions.destroy(name));\n dispatch(vaultActions.destroy(name));\n persistor.flush();\n },\n draft: (autoSelect?: boolean) => {\n dispatch(filesActions.draft(autoSelect));\n },\n select: (name: string) => {",
"score": 5.501534616998128
},
{
"filename": "src/components/Terminal.tsx",
"retrieved_chunk": " }, []);\n const write = (text: string, line = true) => {\n const trimmed = text.replace(/\\n/g, '\\r\\n');\n const xterm = xtermRef.current;\n if (!xterm) return;\n const writer = (text: string) =>\n line ? xterm.writeln(text) : xterm.write(text);\n try {\n writer(trimmed);\n } catch (error) {",
"score": 5.264229516440562
},
{
"filename": "src/components/Terminal.tsx",
"retrieved_chunk": " if (!(error instanceof Error)) throw error;\n console.log('oops', error.message);\n xterm.clear();\n writer(trimmed);\n }\n };\n useImperativeHandle(ref, () => ({\n append: (result?: string) => write(result ?? ''),\n write: (result?: string) => write(result ?? '', false),\n error: (result?: string) =>",
"score": 5.131988004595224
},
{
"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": 4.520669062444181
},
{
"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": 3.8103574484249045
}
] | typescript | runPython(consoleScript, { globals }); |
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": 18.54108279577388
},
{
"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": 18.109265032029857
},
{
"filename": "src/const/errors.ts",
"retrieved_chunk": "\t\terror: {\n\t\t\t\tcode: ErrorCodes,\n\t\t\t\tmessage: string,\n\t\t\t\tdetails?: any,\n\t\t}\n\t\tstatus: number,\n}",
"score": 11.422145503644261
},
{
"filename": "src/utils.ts",
"retrieved_chunk": "import Express from \"express\";\nimport { ApiError } from \"./const/errors\";\nexport function sendErrorResponse(res: Express.Response, error: ApiError) {\n res.status(error.status);\n res.json(error)\n}\nexport function sendJSONResponse(res: Express.Response, obj: any, status?: number) {\n res.status(obj.status ?? status ?? 200);\n res.json(obj)\n}",
"score": 8.697424759252876
},
{
"filename": "src/routes/EmailValidate.ts",
"retrieved_chunk": "\t\t\t\t})\n })\n}\nexport default async function (req: Express.Request, res: Express.Response) {\n\t\tconst queryEmail = req.query?.email;\n\t\tif (RATE_LIMITER.checkIfTimedOut(req)) {\n\t\t\t\tsendErrorResponse(res, {\n\t\t\t\t\t\terror: {\n\t\t\t\t\t\t\t\tcode: ErrorCodes.TOO_MANY_REQUESTS,\n\t\t\t\t\t\t\t\tdetails: {",
"score": 8.254401555880976
}
] | 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/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": 33.427597515149415
},
{
"filename": "src/webhook/index.ts",
"retrieved_chunk": " order.paymentStatus = \"failed\"\n order.paymentDetails = charge\n await order.save()\n }\n }\n response.send({ received: true })\n } catch (error) {\n console.log(\"error in webhookHandler\", error)\n throw error\n }",
"score": 21.46564701833365
},
{
"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": 21.402728027161654
},
{
"filename": "src/db.ts",
"retrieved_chunk": "import mongoose from \"mongoose\"\nconst connectToDatabase = async () => {\n try {\n const connection = await mongoose.connect(process.env.MONGO_URI)\n console.log(\"Connection established\")\n } catch (error) {\n console.log(\"error in connectToDatabase\", error)\n throw error\n }\n}",
"score": 16.131013200908946
},
{
"filename": "src/controller/order.ts",
"retrieved_chunk": " * @param request\n * @param response\n *\n * 1. To make a request to stripe, it's gonna return paymentIntent,we've to pass currency and order amount\n * 2. Save paymentIntentId in order model\n * 3. Return paymentIntentId.client_secret\n *\n */\nexport const createOrder = async (request: Request, response: Response) => {\n try {",
"score": 16.021120842657112
}
] | typescript | const product = await Product.findById(id)
response.send(product)
} catch (error) { |
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": 20.520563870789054
},
{
"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": 14.660553006466031
},
{
"filename": "src/connectors/injected.ts",
"retrieved_chunk": " }\n deactivate(): void {\n // no-op\n // Disconnect event listeners here once window.ai upstream has removeEventListener\n }\n async getModel(): Promise<ModelID> {\n if (!window.ai) throw Error(`window.ai not found`)\n try {\n return await window.ai.getCurrentModel()\n } catch {",
"score": 11.468270117119616
},
{
"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": 11.01702701649851
},
{
"filename": "src/connectors/injected.ts",
"retrieved_chunk": " } else if (event === EventType.Error) {\n this.emit('error', Error(data as ErrorCode))\n }\n }\n}",
"score": 5.283443204969573
}
] | typescript | abstract getProvider(): Promise<WindowAiProvider>
} |
|
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/index.ts",
"retrieved_chunk": " }),\n});\nexport const persistor = persistStore(store, null, () => {\n const vault = store.getState().vault;\n store.dispatch(filesActions.rehydrate(vault));\n});\nexport const getState = store.getState;\nexport type RootState = ReturnType<typeof store.getState>;\nexport type AppDispatch = typeof store.dispatch;",
"score": 40.20769653267146
},
{
"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": 34.13223876580687
},
{
"filename": "src/workers/interpreter.worker.ts",
"retrieved_chunk": " post.unlock();\n return newPyodide;\n};\nconst prepareExports = (exports?: { name: string; content: string }[]) => {\n let newExports = new Set<string>();\n exports?.forEach(({ name, content }) => {\n pyodide.FS.writeFile(name, content, { encoding: 'utf-8' });\n newExports.add(name);\n });\n const oldExports = pyodide.FS.readdir('.') as string[];",
"score": 30.379031530857123
},
{
"filename": "src/store/filesSlice.ts",
"retrieved_chunk": " action: PayloadAction<{ name: string; content: string }>,\n ) => {\n const { name, content } = action.payload;\n const newName = findSuitableName(\n name,\n state.list,\n (counter) => `Copy${counter ? ` ${counter}` : ''} of ${name}`,\n );\n state.files[newName] = content;\n state.list.push(newName);",
"score": 30.183586892632892
},
{
"filename": "src/components/Editor.tsx",
"retrieved_chunk": " const { update, save } = useFilesMutations();\n const { name, content } = useFile.Selected();\n useLayoutEffect(() => {\n document.title = `${name ? `${name} | ` : ''}Glide`;\n }, [name]);\n if (name === undefined || content === undefined) return null;\n return (\n <CoreEditor\n {...props}\n onChange={update}",
"score": 29.524144239400997
}
] | typescript | dispatch(filesActions.create({ name, content })); |
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": 19.13326903618099
},
{
"filename": "src/types/index.ts",
"retrieved_chunk": " model?: ModelID\n onStreamResult?: (\n result: T extends PromptInput ? TextOutput : MessageOutput,\n error: string | null,\n ) => unknown\n}",
"score": 14.179299105091202
},
{
"filename": "src/types/index.ts",
"retrieved_chunk": "export type Input = PromptInput | MessagesInput\nexport type TextOutput = {\n text: string\n}\nexport type MessageOutput = {\n message: Message\n}\nexport enum EventType {\n ModelChanged = 'model_changed',\n Error = 'error',",
"score": 13.735898695021659
},
{
"filename": "src/types/declarations.d.ts",
"retrieved_chunk": "declare global {\n interface Window {\n ai?: WindowAiProvider\n }\n}",
"score": 13.35255922811973
},
{
"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": 12.846447896829668
}
] | 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": 20.520563870789054
},
{
"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": 14.660553006466031
},
{
"filename": "src/connectors/injected.ts",
"retrieved_chunk": " }\n deactivate(): void {\n // no-op\n // Disconnect event listeners here once window.ai upstream has removeEventListener\n }\n async getModel(): Promise<ModelID> {\n if (!window.ai) throw Error(`window.ai not found`)\n try {\n return await window.ai.getCurrentModel()\n } catch {",
"score": 11.468270117119616
},
{
"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": 11.01702701649851
},
{
"filename": "src/connectors/injected.ts",
"retrieved_chunk": " } else if (event === EventType.Error) {\n this.emit('error', Error(data as ErrorCode))\n }\n }\n}",
"score": 5.283443204969573
}
] | 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/hooks/useCompletion.ts",
"retrieved_chunk": " throw Error('No provider found')\n }\n return provider.getCompletion(input, options)\n }\n return { getCompletion }\n}",
"score": 18.26176121032395
},
{
"filename": "src/types/declarations.d.ts",
"retrieved_chunk": "declare global {\n interface Window {\n ai?: WindowAiProvider\n }\n}",
"score": 16.00172353946443
},
{
"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": 15.13506747862975
},
{
"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": 12.263201157102914
},
{
"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": 11.596911905126026
}
] | 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/hooks/useCompletion.ts",
"retrieved_chunk": " throw Error('No provider found')\n }\n return provider.getCompletion(input, options)\n }\n return { getCompletion }\n}",
"score": 18.261761210323947
},
{
"filename": "src/types/declarations.d.ts",
"retrieved_chunk": "declare global {\n interface Window {\n ai?: WindowAiProvider\n }\n}",
"score": 16.001723539464425
},
{
"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": 10.086488765300018
},
{
"filename": "src/hooks/useContext.ts",
"retrieved_chunk": "import React from 'react'\nimport { Context } from '../context'\nexport const useContext = () => {\n const context = React.useContext(Context)\n if (!context) throw Error(`useContext must be used within a Provider`)\n return context\n}",
"score": 8.5735353826902
},
{
"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": 7.5235443547148595
}
] | 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/hooks/useCompletion.ts",
"retrieved_chunk": " throw Error('No provider found')\n }\n return provider.getCompletion(input, options)\n }\n return { getCompletion }\n}",
"score": 18.261761210323947
},
{
"filename": "src/types/declarations.d.ts",
"retrieved_chunk": "declare global {\n interface Window {\n ai?: WindowAiProvider\n }\n}",
"score": 16.001723539464425
},
{
"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": 14.482912969771245
},
{
"filename": "src/hooks/useContext.ts",
"retrieved_chunk": "import React from 'react'\nimport { Context } from '../context'\nexport const useContext = () => {\n const context = React.useContext(Context)\n if (!context) throw Error(`useContext must be used within a Provider`)\n return context\n}",
"score": 9.935112890226279
},
{
"filename": "src/types/index.ts",
"retrieved_chunk": "export type Input = PromptInput | MessagesInput\nexport type TextOutput = {\n text: string\n}\nexport type MessageOutput = {\n message: Message\n}\nexport enum EventType {\n ModelChanged = 'model_changed',\n Error = 'error',",
"score": 9.505661769796966
}
] | 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": 37.22800155628665
},
{
"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": 28.941208820183228
},
{
"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": 23.25659415521096
},
{
"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": 21.71275408893799
},
{
"filename": "src/hooks/useCompletion.ts",
"retrieved_chunk": "import { useContext } from './useContext'\nimport { CompletionOptions, Input } from '../types'\nexport const useCompletion = () => {\n const [state] = useContext()\n const getCompletion = async <T extends Input>(\n input: T,\n options?: CompletionOptions<T>,\n ) => {\n const provider = await state.connector?.getProvider()\n if (!provider) {",
"score": 19.370161854832872
}
] | typescript | state.connector.off('change', handleChange)
} |
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/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": 34.686706768692964
},
{
"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": 32.268389552590236
},
{
"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": 24.01570699909615
},
{
"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": 23.76122790356237
},
{
"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": 18.482285095009964
}
] | 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": "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": 26.30390344174599
},
{
"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": 25.178263648859126
},
{
"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": 19.866039361060334
},
{
"filename": "src/lib/addMultipleCollectionItems.d.ts",
"retrieved_chunk": " * @returns An array of WriteResult arrays corresponding to each batch.\n *\n * @throws Throws an exception with an error message if an error occurs.\n *\n * @example\n * ```typescript\n * import { firestore } from 'firebase-admin'\n * import { adds } from '@skeet-framework/firestore'\n *\n * const db = firestore();",
"score": 17.335168996762228
},
{
"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": 13.55636119874122
}
] | typescript | = createCollectionRef<T>(db, collectionPath)
chunk.forEach((item) => { |
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": 25.639445790110923
},
{
"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": 18.913728349920625
},
{
"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": 18.46616645629199
},
{
"filename": "src/lib/queryCollectionItems.d.ts",
"retrieved_chunk": "};\n/**\n * Queries the specified collection in Firestore based on the provided conditions\n * and returns an array of documents that match the conditions.\n *\n * @param db - The instance of the Firestore database to use.\n * @param collectionPath - The path of the collection to be queried.\n * @param conditions - An array of conditions to apply to the query.\n *\n * @returns An array of documents from the collection that match the conditions.",
"score": 18.160752418646496
},
{
"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": 17.755053432273456
}
] | typescript | (createFirestoreDataConverter<T>())
for (const condition of conditions) { |
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/cookie.ts",
"retrieved_chunk": " const cookies = cookieString.split(';')\n const result: Record<string, string> = {}\n for (const cookie of cookies) {\n const [name, value] = cookie.split('=')\n result[name.trim()] = decodeURIComponent(value)\n }\n return result\n}\ninterface StringifyOptions {\n value: string",
"score": 18.963826351281767
},
{
"filename": "src/response.ts",
"retrieved_chunk": "/**\n * Shorthand for creating a JSON response with an error message.\n *\n * @param message error message\n * @param options {\n * type: error type, defaults to 'invalid_request'\n * status: status code, defaults to 400\n * }\n * @returns Response\n */",
"score": 12.698830422639755
},
{
"filename": "src/middleware/zod-validation.test.ts",
"retrieved_chunk": " {\n \"error\": {\n \"message\": \"name required\",\n \"type\": \"invalid_type\",\n },\n }\n `)\n })\n})",
"score": 11.88031415471253
},
{
"filename": "src/router.ts",
"retrieved_chunk": " **/\n handle(rawRequest: Request, env: Env, ctx: ExecutionContext) {\n const request = new BasicRequest(rawRequest)\n for (const route of this.routes) {\n const match = route[0](request)\n if (match) {\n return route[1]({ request, env, ctx, params: match.params })\n }\n }\n const match = this.routes.find(([matcher]) => matcher(request))",
"score": 11.674640412049378
},
{
"filename": "src/response.ts",
"retrieved_chunk": "export function error(\n message: string,\n { type = 'invalid_request', status = 400 } = {}\n) {\n return json({ error: { message, type } }, status)\n}\n/**\n * A shortcut for creating a JSON response.\n *\n * @param data An object to be JSON stringified.",
"score": 11.22663385376033
}
] | typescript | return error(`${firstError.path} ${firstError.message}`.toLowerCase(), { |
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": 26.98748198967065
},
{
"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": 21.640686562095382
},
{
"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": 12.164879187487816
},
{
"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": 11.21769173160635
},
{
"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": 10.943644918175131
}
] | 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": 26.98748198967065
},
{
"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": 21.640686562095382
},
{
"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": 12.164879187487816
},
{
"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": 11.21769173160635
},
{
"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": 10.943644918175131
}
] | 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": 30.97192407757123
},
{
"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": 24.501150328431414
},
{
"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": 12.212202075688134
},
{
"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": 11.485531129934557
},
{
"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": 11.21769173160635
}
] | 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": 20.33127767705196
},
{
"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": 16.727478328827853
},
{
"filename": "src/request.ts",
"retrieved_chunk": " * Returns the request method as a lowercase string.\n */\n get method(): RequestMethod {\n return enumFromString<RequestMethodEnum>(\n RequestMethodEnum,\n this.request.method.toLowerCase()\n )\n }\n /**\n * Returns the cookies sent by the client.",
"score": 10.419049289029779
},
{
"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": 9.211819845612878
},
{
"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": 8.962951458783937
}
] | 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/middleware/zod-validation.test.ts",
"retrieved_chunk": " const response = await execRoute(\n route,\n buildRequest('https://example.com', {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify({ bar: 'test' }),\n })\n )\n expect(response.status).toBe(400)\n expect(await response.json()).toMatchInlineSnapshot(`",
"score": 27.672354997782197
},
{
"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": 25.97145116305093
},
{
"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": 25.950547200599235
},
{
"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": 21.098820819101096
},
{
"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": 20.116948076979902
}
] | 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": 46.611314764673544
},
{
"filename": "src/base.ts",
"retrieved_chunk": "// ok, so, export the root PluginBase, PluginHost, and the Base\n// Both have the stream stuff, and basic TAP parser stuff\n// PluginHost has all the default assertions, so a Plugin can\n// do stuff like `return t.ok()`\n// Base is a parent of PluginBase, and used for stuff like Spawn,\n// Stdin, and Worker subclasses\n//\n// tap.Test is extended from the generated source, so it has all plugins\n/*\n## Class heirarchy",
"score": 42.88689105337286
},
{
"filename": "src/base.ts",
"retrieved_chunk": "Base - streaming, parsing, test status, config loading\n+-- Spawn - run a child proc, consume output as tap stream\n+-- Stdin - consume stdin as tap stream\n+-- Worker - run a worker thread, consume output as tap stream\n+-- TestBase - generate tap stream, built-in set of assertions\n +-- (builtin plugins...) - add functions for spawn, assertions, snapshot, mock, etc\n +-- (user plugins...) - whatever the config says to load\n +-- Test - the test class exposed to user\n +-- TAP - the root test runner\n*/",
"score": 32.98649732321402
},
{
"filename": "src/worker.ts",
"retrieved_chunk": "// the .worker() method is only added to the root test object\n// See https://github.com/tapjs/node-tap/issues/812\nexport class Worker {}",
"score": 32.21260188971948
},
{
"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": 26.808939225588773
}
] | typescript | export class TestBase extends Base { |
// 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": 41.02470351119063
},
{
"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": 39.16241027438499
},
{
"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": 37.34164708738272
},
{
"filename": "src/stdin.ts",
"retrieved_chunk": " name: options.name || '/dev/stdin',\n })\n this.inputStream = options.tapStream || process.stdin\n this.inputStream.pause()\n }\n main(cb: () => void) {\n this.inputStream.on('error', er => {\n er.tapCaught = 'stdinError'\n this.threw(er)\n })",
"score": 28.4888678187921
},
{
"filename": "src/test-base.ts",
"retrieved_chunk": " try {\n return this.cb(this)\n } catch (er: any) {\n if (!er || typeof er !== 'object') {\n er = { error: er }\n }\n er.tapCaught = 'testFunctionThrow'\n this.threw(er)\n }\n })()",
"score": 28.24069497275599
}
] | typescript | = extraFromError(er, extra, this.options)
} |
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": 46.43089562238735
},
{
"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": 37.92201436332782
},
{
"filename": "src/spawn.ts",
"retrieved_chunk": " const options = {\n cwd: this.cwd,\n env: this.env,\n stdio: this.stdio,\n externalID: this.name,\n }\n queueMicrotask(async () => {\n this.emit('preprocess', options)\n const proc = ProcessInfo.spawn(\n this.command,",
"score": 32.653705161468245
},
{
"filename": "src/spawn.ts",
"retrieved_chunk": " this.args,\n options\n )\n /* istanbul ignore next */\n if (!proc.stdout) {\n return this.threw(\n 'failed to open child process stdout',\n this.options\n )\n }",
"score": 30.01644649475667
},
{
"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": 29.64553664421294
}
] | typescript | return this.#t.sub(Spawn, options, this.spawn)
} |
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/clean-yaml-object.ts",
"retrieved_chunk": " res.at.column &&\n res.at.column <= lines[res.at.line - 1].length\n ? [new Array(res.at.column).join('-') + '^']\n : []\n const context = lines\n .slice(startLine, res.at.line)\n .concat(caret)\n .concat(lines.slice(res.at.line, endLine))\n const csplit = context.join('\\n').trimEnd()\n if (csplit) res.source = csplit + '\\n'",
"score": 51.26784633633396
},
{
"filename": "src/clean-yaml-object.ts",
"retrieved_chunk": " const content = tryReadFile(file)\n if (content) {\n const lines = content.split('\\n')\n if (res.at.line <= lines.length) {\n const startLine = Math.max(res.at.line - 2, 0)\n const endLine = Math.min(\n res.at.line + 2,\n lines.length\n )\n const caret =",
"score": 33.82750124586598
},
{
"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": 33.251487938992526
},
{
"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": 33.11643219253391
},
{
"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": 32.622296918714916
}
] | 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": 34.50368787312953
},
{
"filename": "src/plugin/after-each.ts",
"retrieved_chunk": "const plugin: TapPlugin<AfterEach> = (t: TestBase) => new AfterEach(t)\nexport default plugin",
"score": 34.50368787312953
},
{
"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": 31.934680856539778
},
{
"filename": "src/plugin/before-each.ts",
"retrieved_chunk": "const plugin = (t: TestBase) => new BeforeEach(t)\nexport default plugin",
"score": 30.11974747876787
},
{
"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": 26.0492803608996
}
] | typescript | const plugin: TapPlugin<SpawnPlugin> = (t: TestBase) =>
new SpawnPlugin(t)
export default plugin
|
|
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": 59.683176934709145
},
{
"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": 51.78900721551064
},
{
"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": 43.67887415043875
},
{
"filename": "src/services/dispatcher/dispatcher.d.ts",
"retrieved_chunk": "declare class Event {\n}\ndeclare class Listener {\n}\ndeclare class Klient {\n}\nexport type Callback<T extends Event> = (e: T) => Promise<void> | void;\nexport type Listeners = {\n [event: string]: Listener<never>[];\n};",
"score": 24.918577315824045
},
{
"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": 18.181424199437732
}
] | typescript | handler: Listener<never> | Listener<never>[],
error: Error | null = null
): 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/parse-test-args.ts",
"retrieved_chunk": " cb?: ((t: T) => any) | false\n ]\n | [name: string | number, cb?: ((t: T) => any) | false]\n | [cb?: ((t: T) => any) | false]\n | [name: string]\n | [extra: { [k: string]: any }]\nexport default function parseTestArgs<T extends Base>(\n ...args: TestArgs<T>\n) {\n let name: string | null | undefined = undefined",
"score": 35.49044386053697
},
{
"filename": "src/parse-test-args.ts",
"retrieved_chunk": "import type { Base } from './base.js'\nexport type TestArgs<T extends Base> =\n | [\n name?: string | number,\n extra?: { [k: string]: any },\n cb?: false | ((t: T) => any),\n defaultName?: string\n ]\n | [\n extra: { [k: string]: any },",
"score": 25.748965388536373
},
{
"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": 23.70483017343374
},
{
"filename": "src/base.ts",
"retrieved_chunk": " this.start = hrtime.bigint()\n this.hook.runInAsyncScope(this.main, this, cb)\n }\n main(cb: () => void) {\n cb()\n }\n onbail(reason?: string) {\n this.bailedOut = reason || true\n this.emit('bailout', reason)\n }",
"score": 22.996817355742095
},
{
"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": 21.527909515382312
}
] | typescript | hook.runInAsyncScope(cb, this, ...args)
} |
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": 86.6700227549495
},
{
"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": 51.15825158701585
},
{
"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": 37.52929278582572
},
{
"filename": "src/events/request/success.ts",
"retrieved_chunk": "import type { AxiosResponse } from 'axios';\nimport RequestEvent from './request';\nexport default class RequestSuccessEvent<T = unknown> extends RequestEvent {\n static NAME = 'request:success';\n constructor(public relatedEvent: RequestEvent<T>) {\n super(relatedEvent.request);\n }\n get response(): AxiosResponse<T> {\n return this.request.result as AxiosResponse<T>;\n }",
"score": 36.74345722969182
},
{
"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": 35.12901594716978
}
] | typescript | = new RequestEvent<T>(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": " 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": 70.04076684323009
},
{
"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": 64.21274132401322
},
{
"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": 63.39071982072537
},
{
"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": 63.007158635170754
},
{
"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": 56.39796178886333
}
] | 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": "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": 81.18126937861666
},
{
"filename": "src/services/bag/watch.ts",
"retrieved_chunk": " watchers[id] = getWatchers(watchable);\n const collection = watchers[id][path] || [];\n let index: number | null = null;\n for (let i = 0, len = collection.length; i < len; i += 1) {\n if (collection[i].callback === onChange) {\n index = i;\n break;\n }\n }\n if (index === null) {",
"score": 67.70637568472692
},
{
"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": 62.341917770421496
},
{
"filename": "src/services/bag/watch.ts",
"retrieved_chunk": "const watchers: Record<string, Record<string, WatcherItem[]>> = {};\n/**\n * Determine the instance ID for given watchable object.\n */\nfunction getInstanceId(watchable: Watchable) {\n const ids = Object.keys(instances);\n let id = null;\n for (let i = 0, len = ids.length; i < len; i += 1) {\n if (instances[ids[i]] === watchable) {\n id = ids[i];",
"score": 55.97277914475624
},
{
"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": 55.31803450368665
}
] | 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": 34.50368787312953
},
{
"filename": "src/plugin/after-each.ts",
"retrieved_chunk": "const plugin: TapPlugin<AfterEach> = (t: TestBase) => new AfterEach(t)\nexport default plugin",
"score": 34.50368787312953
},
{
"filename": "src/plugin/before-each.ts",
"retrieved_chunk": "const plugin = (t: TestBase) => new BeforeEach(t)\nexport default plugin",
"score": 30.11974747876787
},
{
"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": 25.009756916097384
},
{
"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": 23.069729098038756
}
] | 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": 33.45534467570238
},
{
"filename": "src/klient.ts",
"retrieved_chunk": " return this.factory.file(urlOrConfig);\n }\n cancelPendingRequests(): this {\n this.factory.cancelPendingRequests();\n return this;\n }\n isCancel(e: Error) {\n return this.factory.isCancel(e);\n }\n}",
"score": 25.43784102174609
},
{
"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": 24.053636202128214
},
{
"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": 20.356573905997287
},
{
"filename": "src/klient.d.ts",
"retrieved_chunk": " isCancel(e: Error): any;\n}\nexport {};",
"score": 17.360100098549104
}
] | 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": 65.7560188258088
},
{
"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": 57.36141271083186
},
{
"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": 50.95153502666743
},
{
"filename": "src/services/dispatcher/dispatcher.d.ts",
"retrieved_chunk": "declare class Event {\n}\ndeclare class Listener {\n}\ndeclare class Klient {\n}\nexport type Callback<T extends Event> = (e: T) => Promise<void> | void;\nexport type Listeners = {\n [event: string]: Listener<never>[];\n};",
"score": 24.918577315824045
},
{
"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": 19.872115396488837
}
] | 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/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": 44.394042075158985
},
{
"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": 36.10886077127516
},
{
"filename": "src/spawn.ts",
"retrieved_chunk": " this.args,\n options\n )\n /* istanbul ignore next */\n if (!proc.stdout) {\n return this.threw(\n 'failed to open child process stdout',\n this.options\n )\n }",
"score": 27.566859710901124
},
{
"filename": "src/test-base.ts",
"retrieved_chunk": " constructor(options: TestBaseOpts) {\n super(options)\n this.jobs =\n (options.jobs && Math.max(options.jobs, 1)) || 1\n if (typeof options.diagnostic === 'boolean') {\n this.diagnostic = options.diagnostic\n }\n if (options.cb) {\n this.#setCB(options.cb)\n }",
"score": 27.394294189460847
},
{
"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": 26.704166200723073
}
] | 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/bag.d.ts",
"retrieved_chunk": " get(path: string): any;\n all(): import(\"../../toolbox/object\").AnyObject;\n set(path: string, value: unknown): this;\n merge(...items: BagItems[]): this;\n watch(path: string, onChange: WatchCallback, deep?: boolean): this;\n unwatch(path: string, onChange: WatchCallback): this;\n}\nexport {};",
"score": 34.26243813392618
},
{
"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": 25.785201771237148
},
{
"filename": "src/services/bag/bag.d.ts",
"retrieved_chunk": "import { Watchable, WatchCallback } from './watch';\ntype BagItems = Record<string, unknown>;\nexport default class Bag implements BagItems, Watchable {\n [x: string]: unknown;\n constructor(items?: BagItems);\n get watchers(): Record<string, {\n callback: WatchCallback<unknown, unknown>;\n deep: boolean;\n }[]>;\n has(path: string): boolean;",
"score": 20.779918664200494
},
{
"filename": "src/toolbox/object.ts",
"retrieved_chunk": "export function isPlainArray(value: unknown) {\n return Array.isArray(value) && value.constructor.name === 'Array';\n}\n/**\n * Deep clone object properties (traverse only native plain objects)\n */\nexport function softClone(obj: AnyObject) {\n const values: AnyObject = {};\n Object.keys(obj).forEach((prop) => {\n const value = obj[prop];",
"score": 19.93194410343174
},
{
"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": 18.09260015553
}
] | 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/bag.d.ts",
"retrieved_chunk": " get(path: string): any;\n all(): import(\"../../toolbox/object\").AnyObject;\n set(path: string, value: unknown): this;\n merge(...items: BagItems[]): this;\n watch(path: string, onChange: WatchCallback, deep?: boolean): this;\n unwatch(path: string, onChange: WatchCallback): this;\n}\nexport {};",
"score": 51.99456766654322
},
{
"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": 37.04712461455434
},
{
"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": 30.89170640166133
},
{
"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": 30.714380526589686
},
{
"filename": "src/services/bag/bag.d.ts",
"retrieved_chunk": "import { Watchable, WatchCallback } from './watch';\ntype BagItems = Record<string, unknown>;\nexport default class Bag implements BagItems, Watchable {\n [x: string]: unknown;\n constructor(items?: BagItems);\n get watchers(): Record<string, {\n callback: WatchCallback<unknown, unknown>;\n deep: boolean;\n }[]>;\n has(path: string): boolean;",
"score": 29.05764836268315
}
] | 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/bag.d.ts",
"retrieved_chunk": " get(path: string): any;\n all(): import(\"../../toolbox/object\").AnyObject;\n set(path: string, value: unknown): this;\n merge(...items: BagItems[]): this;\n watch(path: string, onChange: WatchCallback, deep?: boolean): this;\n unwatch(path: string, onChange: WatchCallback): this;\n}\nexport {};",
"score": 34.26243813392618
},
{
"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": 25.785201771237148
},
{
"filename": "src/services/bag/bag.d.ts",
"retrieved_chunk": "import { Watchable, WatchCallback } from './watch';\ntype BagItems = Record<string, unknown>;\nexport default class Bag implements BagItems, Watchable {\n [x: string]: unknown;\n constructor(items?: BagItems);\n get watchers(): Record<string, {\n callback: WatchCallback<unknown, unknown>;\n deep: boolean;\n }[]>;\n has(path: string): boolean;",
"score": 20.779918664200494
},
{
"filename": "src/toolbox/object.ts",
"retrieved_chunk": "export function isPlainArray(value: unknown) {\n return Array.isArray(value) && value.constructor.name === 'Array';\n}\n/**\n * Deep clone object properties (traverse only native plain objects)\n */\nexport function softClone(obj: AnyObject) {\n const values: AnyObject = {};\n Object.keys(obj).forEach((prop) => {\n const value = obj[prop];",
"score": 19.93194410343174
},
{
"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": 18.09260015553
}
] | 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": 41.94718300852012
},
{
"filename": "src/services/bag/bag.ts",
"retrieved_chunk": " });\n }\n get watchers() {\n return getWatchers(this);\n }\n has(path: string) {\n return objectPath.get(this, path) !== undefined;\n }\n get(path: string) {\n return objectPath.get(this.all(), path);",
"score": 31.522946806375476
},
{
"filename": "src/services/request/factory.ts",
"retrieved_chunk": " });\n return request;\n }\n isCancel(e: Error) {\n return this.model.isCancel(e);\n }\n protected prepare(config: KlientRequestConfig): KlientRequestConfig {\n return deepmerge.all([\n { baseURL: this.klient.url },\n (this.klient.parameters.get('request') as AxiosRequestConfig) || {},",
"score": 30.861997927458287
},
{
"filename": "src/events/request/error.ts",
"retrieved_chunk": " }\n get result() {\n return this.request.result;\n }\n get data() {\n return this.relatedEvent.data;\n }\n}",
"score": 29.937547913449574
},
{
"filename": "src/events/request/done.ts",
"retrieved_chunk": " get response() {\n return this.error.response;\n }\n get data() {\n return this.response?.data;\n }\n}",
"score": 29.937547913449574
}
] | 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": 33.45534467570238
},
{
"filename": "src/klient.ts",
"retrieved_chunk": " return this.factory.file(urlOrConfig);\n }\n cancelPendingRequests(): this {\n this.factory.cancelPendingRequests();\n return this;\n }\n isCancel(e: Error) {\n return this.factory.isCancel(e);\n }\n}",
"score": 25.43784102174609
},
{
"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": 24.053636202128214
},
{
"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": 20.356573905997287
},
{
"filename": "src/klient.d.ts",
"retrieved_chunk": " isCancel(e: Error): any;\n}\nexport {};",
"score": 17.360100098549104
}
] | 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/bag.d.ts",
"retrieved_chunk": " get(path: string): any;\n all(): import(\"../../toolbox/object\").AnyObject;\n set(path: string, value: unknown): this;\n merge(...items: BagItems[]): this;\n watch(path: string, onChange: WatchCallback, deep?: boolean): this;\n unwatch(path: string, onChange: WatchCallback): this;\n}\nexport {};",
"score": 34.26243813392618
},
{
"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": 25.785201771237148
},
{
"filename": "src/services/bag/bag.d.ts",
"retrieved_chunk": "import { Watchable, WatchCallback } from './watch';\ntype BagItems = Record<string, unknown>;\nexport default class Bag implements BagItems, Watchable {\n [x: string]: unknown;\n constructor(items?: BagItems);\n get watchers(): Record<string, {\n callback: WatchCallback<unknown, unknown>;\n deep: boolean;\n }[]>;\n has(path: string): boolean;",
"score": 20.779918664200494
},
{
"filename": "src/toolbox/object.ts",
"retrieved_chunk": "export function isPlainArray(value: unknown) {\n return Array.isArray(value) && value.constructor.name === 'Array';\n}\n/**\n * Deep clone object properties (traverse only native plain objects)\n */\nexport function softClone(obj: AnyObject) {\n const values: AnyObject = {};\n Object.keys(obj).forEach((prop) => {\n const value = obj[prop];",
"score": 19.93194410343174
},
{
"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": 18.09260015553
}
] | 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": 79.59163796071034
},
{
"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": 62.18212771437354
},
{
"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": 43.29061623800392
},
{
"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": 40.16921588166154
},
{
"filename": "src/services/request/factory.d.ts",
"retrieved_chunk": "declare class Klient {\n}\ndeclare class Request {\n}\ndeclare class KlientRequestConfig {\n}\nexport default class RequestFactory {\n protected readonly klient: Klient;\n model: typeof Request;\n readonly requests: Request[];",
"score": 32.433452305893866
}
] | 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": 55.948175555845175
},
{
"filename": "src/services/bag/bag.ts",
"retrieved_chunk": " }\n all() {\n return softClone(this);\n }\n set(path: string, value: unknown): this {\n const prevState = this.all();\n objectPath.set(this, path, value);\n return invokeWatchers(this, this.all(), prevState);\n }\n merge(...items: BagItems[]): this {",
"score": 27.69489663400227
},
{
"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": 26.810176904892227
},
{
"filename": "src/services/bag/bag.d.ts",
"retrieved_chunk": " get(path: string): any;\n all(): import(\"../../toolbox/object\").AnyObject;\n set(path: string, value: unknown): this;\n merge(...items: BagItems[]): this;\n watch(path: string, onChange: WatchCallback, deep?: boolean): this;\n unwatch(path: string, onChange: WatchCallback): this;\n}\nexport {};",
"score": 25.768649506850853
},
{
"filename": "src/__tests__/extension.test.ts",
"retrieved_chunk": "import 'jest-extended';\nimport { mockAxiosWithRestApi } from '@klient/testing';\nimport Klient, { Extensions } from '..';\njest.mock('axios');\nmockAxiosWithRestApi();\ninterface KlientExtended extends Klient {\n writable: string;\n readonly unwritable: boolean;\n}\ntest('extension:load', () => {",
"score": 25.373376219552252
}
] | 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": 61.246838821787385
},
{
"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": 40.851362551594306
},
{
"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": 37.68072252872146
},
{
"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": 35.504598542841165
},
{
"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": 35.07406919053196
}
] | 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": " 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": 52.87356549889026
},
{
"filename": "src/services/dispatcher/dispatcher.ts",
"retrieved_chunk": " return this.on(event, callback, priority, true);\n }\n off<T extends Event>(event: string, callback: Callback<T>): this {\n const index = this.findListenerIndex(event, callback);\n if (index !== undefined) {\n this.listeners[event].splice(index, 1);\n }\n return this;\n }\n /**",
"score": 51.07556731458586
},
{
"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": 48.39069037038663
},
{
"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": 45.918367614877894
},
{
"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": 45.69780333855687
}
] | 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/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": 102.76375747176554
},
{
"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": 93.24684677774549
},
{
"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": 79.01101550108133
},
{
"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": 67.64806189136846
},
{
"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": 47.89104611891705
}
] | typescript | factory.file(urlOrConfig); |
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.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": 12.214348484891103
},
{
"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": 10.881864046737336
},
{
"filename": "src/util/swagger.util.ts",
"retrieved_chunk": " type: 'apiKey',\n in: 'header',\n name: 'Authorization',\n description: '',\n },\n },\n },\n },\n apis: routeFiles,\n};",
"score": 10.133990648637678
},
{
"filename": "src/util/swagger.util.ts",
"retrieved_chunk": " securitySchemes: {\n JWT: {\n type: 'apiKey',\n in: 'header',\n name: 'Authorization',\n description: '',\n },\n },\n securityDefinitions: {\n JWT: {",
"score": 9.618398144723553
},
{
"filename": "src/util/base-errors.ts",
"retrieved_chunk": " type CustomErrors = {\n [key: string]: {\n parentError: typeof CustomError;\n message: string;\n code: number;\n httpCode: number;\n };\n };\nclass CustomError extends Error {\n constructor(",
"score": 8.139857734146132
}
] | typescript | this.router.get('/example', celebrate(schemas.getFoo), this.exampleController.getExampleValue); |
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": 47.48671470971184
},
{
"filename": "src/services/dispatcher/dispatcher.ts",
"retrieved_chunk": " if (!e.dispatch.propagation) {\n this.debug('stopped', e, listener);\n // Stop listeners invokation\n break;\n }\n }\n this.debug('end', e, listeners);\n return Promise.resolve();\n }\n protected findListenerIndex<T extends Event>(event: string, callback: Callback<T>): number | undefined {",
"score": 37.925885007780245
},
{
"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": 37.27022184298378
},
{
"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": 32.99199112162783
},
{
"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": 29.50958031676322
}
] | typescript | this.dispatcher.dispatch(new RequestDoneEvent(event), false).then(resolve); |
/* 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/interfaces/IRouteBase.interface.ts",
"retrieved_chunk": "interface IRouteBase {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n initializeRoutes(): any\n}\nexport default IRouteBase;",
"score": 34.192122003980906
},
{
"filename": "src/util/error.util.ts",
"retrieved_chunk": " super(message, code, 400);\n this.name = errorKey;\n }\n };\n}\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport const ERROR_CLASSES: Record<string, any> = Object.entries(CUSTOM_ERRORS).reduce(\n (errorClasses, [errorKey, errorDetails]) => {\n const { parentError, message, code } = errorDetails;\n const CustomErrorClass = generateCustomError(",
"score": 25.934565389101977
},
{
"filename": "src/config/enviroments/tests.ts",
"retrieved_chunk": "import BaseConfig from './base';\nclass TestConfig extends BaseConfig {\n // eslint-disable-next-line no-useless-constructor\n constructor() {\n super();\n }\n}\nexport default TestConfig;",
"score": 23.143160070825793
},
{
"filename": "src/config/enviroments/dev.ts",
"retrieved_chunk": "import BaseConfig from './base';\nclass DevConfig extends BaseConfig {\n // eslint-disable-next-line no-useless-constructor\n constructor() {\n super();\n }\n}\nexport default DevConfig;",
"score": 23.143160070825793
},
{
"filename": "src/logic/container.logic.ts",
"retrieved_chunk": "import 'reflect-metadata';\nimport { container } from 'tsyringe';\nimport * as glob from 'glob';\nimport * as path from 'path';\nexport class ContainerLogic {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n public static getRouteClasses(): any[] {\n const moduleFolder = path.join(__dirname, '../modules');\n const routeFiles = glob.sync(`${moduleFolder}/**/*.route.{ts,js}`);\n return routeFiles.map((routeFile) => container.resolve(require(routeFile).default));",
"score": 19.57541668410895
}
] | 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/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": 25.387327187364058
},
{
"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": 24.36890256993378
},
{
"filename": "src/diags.ts",
"retrieved_chunk": " .map(l => (l.trim() ? ' ' + l : l.trim()))\n .join('\\n') +\n ' ...\\n'\n )\n}",
"score": 19.32081608799848
},
{
"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": 18.905587574190076
},
{
"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": 18.4552752994245
}
] | 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": 41.27461742073677
},
{
"filename": "src/spawn.ts",
"retrieved_chunk": " this.args,\n options\n )\n /* istanbul ignore next */\n if (!proc.stdout) {\n return this.threw(\n 'failed to open child process stdout',\n this.options\n )\n }",
"score": 20.95178868386776
},
{
"filename": "src/stdin.ts",
"retrieved_chunk": " if (this.options.timeout) {\n this.setTimeout(this.options.timeout)\n }\n const s = this.inputStream as Minipass\n s.pipe(this.parser)\n if (this.parent) {\n this.parent.emit('stdin', this)\n }\n this.inputStream.resume()\n this.once('end', cb)",
"score": 20.749270686960664
},
{
"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": 20.131354097005133
},
{
"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": 20.06429232442384
}
] | 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/spawn.ts",
"retrieved_chunk": " }\n #onprocclose(code: number | null, signal: string | null) {\n this.debug('SPAWN close %j %s', code, signal)\n this.options.exitCode = code\n this.options.signal = signal\n // spawn closing with no tests is treated as a skip.\n if (\n this.results &&\n this.results.plan &&\n this.results.plan.skipAll &&",
"score": 43.99759294651564
},
{
"filename": "src/base.ts",
"retrieved_chunk": " this.test = test\n }\n}\nexport class Counts {\n total: number = 0\n pass: number = 0\n fail: number = 0\n skip: number = 0\n todo: number = 0\n}",
"score": 40.13217941325598
},
{
"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": 37.5235614243859
},
{
"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": 36.146586603952855
},
{
"filename": "src/spawn.ts",
"retrieved_chunk": " .map(a =>\n a.indexOf(cwd) === 0\n ? './' +\n a\n .substring(cwd.length + 1)\n .replace(/\\\\/g, '/')\n : a\n )\n .join(' ')\n .trim()",
"score": 33.50244856144961
}
] | 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 dispatchResultEvent(EventClass: RequestEventTypes): Promise<void>;\n protected get dispatcher(): any;\n}\nexport {};",
"score": 55.35906670712618
},
{
"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": 52.966344179891365
},
{
"filename": "src/services/dispatcher/listener.ts",
"retrieved_chunk": " }\n } catch (error) {\n result = Promise.reject(error);\n }\n return result;\n }\n}",
"score": 40.42613764549621
},
{
"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": 35.39246542812529
},
{
"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": 31.486157784614676
}
] | 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": 86.6700227549495
},
{
"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": 51.15825158701585
},
{
"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": 37.52929278582572
},
{
"filename": "src/events/request/success.ts",
"retrieved_chunk": "import type { AxiosResponse } from 'axios';\nimport RequestEvent from './request';\nexport default class RequestSuccessEvent<T = unknown> extends RequestEvent {\n static NAME = 'request:success';\n constructor(public relatedEvent: RequestEvent<T>) {\n super(relatedEvent.request);\n }\n get response(): AxiosResponse<T> {\n return this.request.result as AxiosResponse<T>;\n }",
"score": 36.74345722969182
},
{
"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": 35.12901594716978
}
] | 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": 65.7560188258088
},
{
"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": 57.36141271083186
},
{
"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": 50.95153502666743
},
{
"filename": "src/services/dispatcher/dispatcher.d.ts",
"retrieved_chunk": "declare class Event {\n}\ndeclare class Listener {\n}\ndeclare class Klient {\n}\nexport type Callback<T extends Event> = (e: T) => Promise<void> | void;\nexport type Listeners = {\n [event: string]: Listener<never>[];\n};",
"score": 24.918577315824045
},
{
"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": 19.872115396488837
}
] | 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": 31.507948421325327
},
{
"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": 25.426405805245125
},
{
"filename": "src/klient.ts",
"retrieved_chunk": " delete<T = unknown>(url: string, config?: KlientRequestConfig): Request<T> {\n return this.request<T>({ ...config, method: 'DELETE', url });\n }\n head<T = unknown>(url: string, config?: KlientRequestConfig): Request<T> {\n return this.request<T>({ ...config, method: 'HEAD', url });\n }\n options<T = unknown>(url: string, config?: KlientRequestConfig): Request<T> {\n return this.request<T>({ ...config, method: 'OPTIONS', url });\n }\n file(urlOrConfig: KlientRequestConfig | string): Promise<Blob> {",
"score": 25.334542282481035
},
{
"filename": "src/klient.ts",
"retrieved_chunk": " return this.factory.file(urlOrConfig);\n }\n cancelPendingRequests(): this {\n this.factory.cancelPendingRequests();\n return this;\n }\n isCancel(e: Error) {\n return this.factory.isCancel(e);\n }\n}",
"score": 24.628682522739513
},
{
"filename": "src/klient.ts",
"retrieved_chunk": " }\n post<T = unknown>(url: string, data: unknown, config?: KlientRequestConfig): Request<T> {\n return this.request<T>({ ...config, method: 'POST', url, data });\n }\n put<T = unknown>(url: string, data: unknown, config?: KlientRequestConfig): Request<T> {\n return this.request<T>({ ...config, method: 'PUT', url, data });\n }\n patch<T = unknown>(url: string, data: unknown, config?: KlientRequestConfig): Request<T> {\n return this.request<T>({ ...config, method: 'PATCH', url, data });\n }",
"score": 24.14506776868755
}
] | 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/__tests__/extension.test.ts",
"retrieved_chunk": " expect(klient.writable).toBe('else');\n try {\n // eslint-disable-next-line\n (klient as any).unwritable = false;\n // Force to go in catch block\n throw new Error('Property is writable');\n } catch (e) {\n expect((e as Error).message).toBe(\"Cannot assign to read only property 'unwritable' of object '#<Klient>'\");\n }\n const emptyKlient = new Klient({ extensions: [] });",
"score": 27.709165554850287
},
{
"filename": "src/services/request/request.ts",
"retrieved_chunk": " this.abortController.abort();\n return this;\n }\n execute(): this {\n this.dispatcher\n .dispatch(this.primaryEvent)\n .then(() => {\n this.doRequest();\n })\n .catch((e) => {",
"score": 23.394120978634643
},
{
"filename": "src/services/request/request.ts",
"retrieved_chunk": " .catch((e) => {\n this.reject(e);\n });\n }\n return this;\n }\n protected resolve(response: AxiosResponse<T>): Promise<void> {\n this.result = response;\n return this.dispatchResultEvent(RequestSuccessEvent).then(() => {\n this.callbacks.resolve(this.result as AxiosResponse<T>);",
"score": 22.711918031180716
},
{
"filename": "src/__tests__/request.test.ts",
"retrieved_chunk": " e.request.handler = () => {\n spyRequestHandler();\n return Promise.reject(new Error());\n };\n });\n await klient\n .request('/')\n .then(() => {\n throw new Error('This request must failed');\n })",
"score": 22.123098710166687
},
{
"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": 21.603429772656835
}
] | 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/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": 45.55053992138858
},
{
"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": 44.56638055985447
},
{
"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": 36.08345655314067
},
{
"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": 35.23601903352554
},
{
"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": 33.53788995943004
}
] | typescript | extra.at = stack.parseLine(extra.stack.split('\n')[0])
} |
// 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": "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": 47.26473110730453
},
{
"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": 45.40239943452033
},
{
"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": 24.480569372896305
},
{
"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": 17.06248616591568
},
{
"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": 16.42630834500184
}
] | typescript | cb: (w: Waiter) => any,
expectReject: boolean = false
): Promise<void> { |
// 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/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": 39.411112842705144
},
{
"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": 34.0731816094973
},
{
"filename": "src/build.ts",
"retrieved_chunk": " `import plugin${i} from ${JSON.stringify(p)}\\n`\n )\n .join('')\nconst pluginsCode = `const plugins: PI[] = [\n${plugins.map((_, i) => ` plugin${i},\\n`).join('')}]\ntype Plug =\n | TestBase\n | { t: Test }\n${plugins\n .map((_, i) => ` | ReturnType<typeof plugin${i}>\\n`)",
"score": 27.930279187477534
},
{
"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": 20.125912105414653
},
{
"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": 18.662906874977892
}
] | 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/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": 14.977235045020135
},
{
"filename": "src/stdin.ts",
"retrieved_chunk": " name: options.name || '/dev/stdin',\n })\n this.inputStream = options.tapStream || process.stdin\n this.inputStream.pause()\n }\n main(cb: () => void) {\n this.inputStream.on('error', er => {\n er.tapCaught = 'stdinError'\n this.threw(er)\n })",
"score": 14.285945205341308
},
{
"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": 13.977252468506007
},
{
"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": 13.855296013991744
},
{
"filename": "src/waiter.ts",
"retrieved_chunk": " this.rejected = true\n this.done = true\n this.finish()\n }\n abort (er:Error) {\n if (this.done) {\n return\n }\n this.ready = true\n this.finishing = false",
"score": 13.256972342519568
}
] | 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": 31.49069532617988
},
{
"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": 29.40858048754854
},
{
"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": 27.351704006376785
},
{
"filename": "src/base.ts",
"retrieved_chunk": " this.parser.on('result', () => this.counts.total++)\n this.parser.on('pass', () => this.counts.pass++)\n this.parser.on('todo', res => {\n this.counts.todo++\n this.lists.todo.push(res)\n })\n this.parser.on('skip', res => {\n // it is uselessly noisy to print out lists of tests skipped\n // because of a --grep or --only argument.\n if (/^filter: (only|\\/.*\\/)$/.test(res.skip)) return",
"score": 24.999678183506138
},
{
"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": 24.856756912717366
}
] | typescript | if (this.bail && !ok && !extra.skip && !extra.todo) { |
// 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/parse-test-args.ts",
"retrieved_chunk": " cb?: ((t: T) => any) | false\n ]\n | [name: string | number, cb?: ((t: T) => any) | false]\n | [cb?: ((t: T) => any) | false]\n | [name: string]\n | [extra: { [k: string]: any }]\nexport default function parseTestArgs<T extends Base>(\n ...args: TestArgs<T>\n) {\n let name: string | null | undefined = undefined",
"score": 19.877993750700522
},
{
"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": 19.575436404970304
},
{
"filename": "src/parse-test-args.ts",
"retrieved_chunk": "import type { Base } from './base.js'\nexport type TestArgs<T extends Base> =\n | [\n name?: string | number,\n extra?: { [k: string]: any },\n cb?: false | ((t: T) => any),\n defaultName?: string\n ]\n | [\n extra: { [k: string]: any },",
"score": 17.97134659040892
},
{
"filename": "src/test-built.ts",
"retrieved_chunk": " // cache get results so t.blah === t.blah\n // we only cache functions, so that getters aren't memoized\n // Of course, a getter that returns a function will be broken,\n // at least when accessed from outside the plugin, but that's\n // a pretty narrow caveat, and easily documented.\n if (getCache.has(p)) return getCache.get(p)\n for (const plug of ext) {\n if (p in plug) {\n //@ts-ignore\n const v = plug[p]",
"score": 17.19402977037134
},
{
"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": 16.822275385155105
}
] | typescript | name ? ': ' + esc(p.name) : '') +
'\n'
this.parser.write(comment)
} |
// 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/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": 39.411112842705144
},
{
"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": 34.0731816094973
},
{
"filename": "src/build.ts",
"retrieved_chunk": " `import plugin${i} from ${JSON.stringify(p)}\\n`\n )\n .join('')\nconst pluginsCode = `const plugins: PI[] = [\n${plugins.map((_, i) => ` plugin${i},\\n`).join('')}]\ntype Plug =\n | TestBase\n | { t: Test }\n${plugins\n .map((_, i) => ` | ReturnType<typeof plugin${i}>\\n`)",
"score": 27.930279187477534
},
{
"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": 20.125912105414653
},
{
"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": 18.662906874977892
}
] | 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/base.ts",
"retrieved_chunk": " emit(ev: string, ...data: any[]) {\n const ret = this.stream.emit(ev, ...data)\n if (ev === 'end') {\n this.ondone()\n this.hook.emitDestroy()\n this.hookDomain.destroy()\n }\n return ret\n }\n end() {",
"score": 17.362716007346986
},
{
"filename": "src/parse-test-args.ts",
"retrieved_chunk": " cb?: ((t: T) => any) | false\n ]\n | [name: string | number, cb?: ((t: T) => any) | false]\n | [cb?: ((t: T) => any) | false]\n | [name: string]\n | [extra: { [k: string]: any }]\nexport default function parseTestArgs<T extends Base>(\n ...args: TestArgs<T>\n) {\n let name: string | null | undefined = undefined",
"score": 16.79750326005443
},
{
"filename": "src/parse-test-args.ts",
"retrieved_chunk": "import type { Base } from './base.js'\nexport type TestArgs<T extends Base> =\n | [\n name?: string | number,\n extra?: { [k: string]: any },\n cb?: false | ((t: T) => any),\n defaultName?: string\n ]\n | [\n extra: { [k: string]: any },",
"score": 15.97015873148255
},
{
"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": 15.835455408649036
},
{
"filename": "src/base.ts",
"retrieved_chunk": " strict: this.strict,\n omitVersion: this.omitVersion,\n preserveWhitespace: this.preserveWhitespace,\n name: this.name,\n })\n this.setupParser()\n // ensure that a skip or todo on a child class reverts\n // back to Base's no-op main.\n if (options.skip || options.todo) {\n this.main = Base.prototype.main",
"score": 15.418341626695774
}
] | 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/parse-test-args.ts",
"retrieved_chunk": " cb?: ((t: T) => any) | false\n ]\n | [name: string | number, cb?: ((t: T) => any) | false]\n | [cb?: ((t: T) => any) | false]\n | [name: string]\n | [extra: { [k: string]: any }]\nexport default function parseTestArgs<T extends Base>(\n ...args: TestArgs<T>\n) {\n let name: string | null | undefined = undefined",
"score": 35.49044386053697
},
{
"filename": "src/parse-test-args.ts",
"retrieved_chunk": "import type { Base } from './base.js'\nexport type TestArgs<T extends Base> =\n | [\n name?: string | number,\n extra?: { [k: string]: any },\n cb?: false | ((t: T) => any),\n defaultName?: string\n ]\n | [\n extra: { [k: string]: any },",
"score": 25.748965388536373
},
{
"filename": "src/base.ts",
"retrieved_chunk": " this.start = hrtime.bigint()\n this.hook.runInAsyncScope(this.main, this, cb)\n }\n main(cb: () => void) {\n cb()\n }\n onbail(reason?: string) {\n this.bailedOut = reason || true\n this.emit('bailout', reason)\n }",
"score": 24.022708022285272
},
{
"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": 23.70483017343374
},
{
"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": 21.918423370774658
}
] | 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/parse-test-args.ts",
"retrieved_chunk": " cb?: ((t: T) => any) | false\n ]\n | [name: string | number, cb?: ((t: T) => any) | false]\n | [cb?: ((t: T) => any) | false]\n | [name: string]\n | [extra: { [k: string]: any }]\nexport default function parseTestArgs<T extends Base>(\n ...args: TestArgs<T>\n) {\n let name: string | null | undefined = undefined",
"score": 16.79750326005443
},
{
"filename": "src/base.ts",
"retrieved_chunk": " emit(ev: string, ...data: any[]) {\n const ret = this.stream.emit(ev, ...data)\n if (ev === 'end') {\n this.ondone()\n this.hook.emitDestroy()\n this.hookDomain.destroy()\n }\n return ret\n }\n end() {",
"score": 16.423300343145176
},
{
"filename": "src/parse-test-args.ts",
"retrieved_chunk": "import type { Base } from './base.js'\nexport type TestArgs<T extends Base> =\n | [\n name?: string | number,\n extra?: { [k: string]: any },\n cb?: false | ((t: T) => any),\n defaultName?: string\n ]\n | [\n extra: { [k: string]: any },",
"score": 15.97015873148255
},
{
"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": 15.309691105911885
},
{
"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": 15.155758649147428
}
] | typescript | 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/test-point.ts",
"retrieved_chunk": " const diagYaml = extra.diagnostic\n ? diags(extra, options)\n : ''\n message += diagYaml + '\\n'\n return message\n}",
"score": 40.870013167471896
},
{
"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": 38.82133191365216
},
{
"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": 36.30405091956334
},
{
"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": 31.13903864166341
},
{
"filename": "src/base.ts",
"retrieved_chunk": " }\n if (this.name && !proxy) {\n er.test = this.name\n }\n const message = er.message\n if (!extra) {\n extra = extraFromError(er, extra, this.options)\n }\n // if we ended, we have to report it SOMEWHERE, unless we're\n // already in the process of bailing out, in which case it's",
"score": 28.5092582863184
}
] | typescript | = new TestPoint(ok, message, extra)
// when we jump the queue, skip an extra line
if (front) { |
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/clean-yaml-object.ts",
"retrieved_chunk": " res.at.column &&\n res.at.column <= lines[res.at.line - 1].length\n ? [new Array(res.at.column).join('-') + '^']\n : []\n const context = lines\n .slice(startLine, res.at.line)\n .concat(caret)\n .concat(lines.slice(res.at.line, endLine))\n const csplit = context.join('\\n').trimEnd()\n if (csplit) res.source = csplit + '\\n'",
"score": 51.26784633633396
},
{
"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": 37.961348616115735
},
{
"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": 37.1144315966592
},
{
"filename": "src/clean-yaml-object.ts",
"retrieved_chunk": " const content = tryReadFile(file)\n if (content) {\n const lines = content.split('\\n')\n if (res.at.line <= lines.length) {\n const startLine = Math.max(res.at.line - 2, 0)\n const endLine = Math.min(\n res.at.line + 2,\n lines.length\n )\n const caret =",
"score": 33.82750124586598
},
{
"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": 33.11643219253391
}
] | 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/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": 41.27461742073677
},
{
"filename": "src/spawn.ts",
"retrieved_chunk": " this.args,\n options\n )\n /* istanbul ignore next */\n if (!proc.stdout) {\n return this.threw(\n 'failed to open child process stdout',\n this.options\n )\n }",
"score": 20.95178868386776
},
{
"filename": "src/stdin.ts",
"retrieved_chunk": " if (this.options.timeout) {\n this.setTimeout(this.options.timeout)\n }\n const s = this.inputStream as Minipass\n s.pipe(this.parser)\n if (this.parent) {\n this.parent.emit('stdin', this)\n }\n this.inputStream.resume()\n this.once('end', cb)",
"score": 20.749270686960664
},
{
"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": 20.131354097005133
},
{
"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": 20.06429232442384
}
] | 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/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": 25.387327187364058
},
{
"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": 24.36890256993378
},
{
"filename": "src/diags.ts",
"retrieved_chunk": " .map(l => (l.trim() ? ' ' + l : l.trim()))\n .join('\\n') +\n ' ...\\n'\n )\n}",
"score": 19.32081608799848
},
{
"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": 18.905587574190076
},
{
"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": 18.4552752994245
}
] | 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": 34.05034119674122
},
{
"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": 30.056157938210436
},
{
"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": 29.707760052004733
},
{
"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": 22.51073209424936
},
{
"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": 21.98040704729835
}
] | typescript | = stack.captureString(80, fn)
} |
// 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": 49.48302270326029
},
{
"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": 29.435190180352073
},
{
"filename": "src/stdin.ts",
"retrieved_chunk": " if (this.options.timeout) {\n this.setTimeout(this.options.timeout)\n }\n const s = this.inputStream as Minipass\n s.pipe(this.parser)\n if (this.parent) {\n this.parent.emit('stdin', this)\n }\n this.inputStream.resume()\n this.once('end', cb)",
"score": 28.231763414605716
},
{
"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": 27.769754665384426
},
{
"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": 26.667883893869497
}
] | typescript | .#occupied.timeout(options)
} else { |
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/clean-yaml-object.ts",
"retrieved_chunk": " res.at.column &&\n res.at.column <= lines[res.at.line - 1].length\n ? [new Array(res.at.column).join('-') + '^']\n : []\n const context = lines\n .slice(startLine, res.at.line)\n .concat(caret)\n .concat(lines.slice(res.at.line, endLine))\n const csplit = context.join('\\n').trimEnd()\n if (csplit) res.source = csplit + '\\n'",
"score": 45.46270436106889
},
{
"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": 36.51434197530803
},
{
"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": 33.34278910755086
},
{
"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": 29.319585166436234
},
{
"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": 27.75783273888984
}
] | 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/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": 21.92028096890448
},
{
"filename": "src/waiter.ts",
"retrieved_chunk": " this.rejected = true\n this.done = true\n this.finish()\n }\n abort (er:Error) {\n if (this.done) {\n return\n }\n this.ready = true\n this.finishing = false",
"score": 19.794565086141468
},
{
"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": 19.700629786400526
},
{
"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": 19.290441595774666
},
{
"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": 18.673182255477407
}
] | 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": " 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": 20.258968281824096
},
{
"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": 15.762425344751339
},
{
"filename": "src/test-built.ts",
"retrieved_chunk": " const nameProp =\n Reflect.getOwnPropertyDescriptor(v, 'name')\n if (nameProp) {\n Reflect.defineProperty(f, 'name', nameProp)\n }\n getCache.set(p, vv)\n return vv\n } else {\n getCache.set(p, v)\n return v",
"score": 14.197337198458586
},
{
"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": 14.054304073431426
},
{
"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": 12.785250429148029
}
] | 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": 27.490969774107786
},
{
"filename": "src/test-built.ts",
"retrieved_chunk": " const nameProp =\n Reflect.getOwnPropertyDescriptor(v, 'name')\n if (nameProp) {\n Reflect.defineProperty(f, 'name', nameProp)\n }\n getCache.set(p, vv)\n return vv\n } else {\n getCache.set(p, v)\n return v",
"score": 24.468186409793184
},
{
"filename": "src/build.ts",
"retrieved_chunk": " p =>\n './' +\n relative(\n dirname(out),\n resolve(pluginsDir, p).replace(/\\.ts/, '.js')\n )\n)\nconst pluginImport = plugins\n .map(\n (p, i) =>",
"score": 24.062959098054044
},
{
"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": 23.87391247886609
},
{
"filename": "src/test-template.ts",
"retrieved_chunk": " if (Reflect.getOwnPropertyDescriptor(o, p)?.set) {\n //@ts-ignore\n t[p] = v\n return true\n }\n o = Reflect.getPrototypeOf(o)\n }\n }\n //@ts-ignore\n base[p as keyof TestBase] = v",
"score": 23.33727031529129
}
] | typescript | name)
this.#processSubtest(p)
} else if (p === EOF) { |
// 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": "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": 47.26473110730453
},
{
"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": 45.40239943452033
},
{
"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": 20.972150865657838
},
{
"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": 16.42630834500184
},
{
"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": 13.308797295589846
}
] | 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/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": 35.003704822312464
},
{
"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": 30.46475950095522
},
{
"filename": "src/components/chatview.ts",
"retrieved_chunk": "\t\t)\n\t}\n\tcurrentInput = \"\"\n\tloadingMessage: Message = { role: \"assistant\", content: \"...\" }\n\tgetViewType() {\n\t\treturn VIEW_TYPE_CHAT\n\t}\n\tgetDisplayText() {\n\t\treturn \"AI Mentor\"\n\t}",
"score": 22.665627512924317
},
{
"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": 22.651889115888604
},
{
"filename": "src/components/chatview.ts",
"retrieved_chunk": "\t\treturn prompt\n\t}\n\tasync handleSend() {\n\t\t// Don't send empty messages.\n\t\tif (this.currentInput === \"\") {\n\t\t\tnew Notice(\"Cannot send empty messages.\")\n\t\t\treturn\n\t\t}\n\t\t// Wait for the mentor to respond.\n\t\tif (",
"score": 16.42548067454047
}
] | 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/spawn.ts",
"retrieved_chunk": " }\n #onprocclose(code: number | null, signal: string | null) {\n this.debug('SPAWN close %j %s', code, signal)\n this.options.exitCode = code\n this.options.signal = signal\n // spawn closing with no tests is treated as a skip.\n if (\n this.results &&\n this.results.plan &&\n this.results.plan.skipAll &&",
"score": 43.99759294651564
},
{
"filename": "src/base.ts",
"retrieved_chunk": " this.test = test\n }\n}\nexport class Counts {\n total: number = 0\n pass: number = 0\n fail: number = 0\n skip: number = 0\n todo: number = 0\n}",
"score": 40.13217941325598
},
{
"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": 37.5235614243859
},
{
"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": 36.146586603952855
},
{
"filename": "src/spawn.ts",
"retrieved_chunk": " .map(a =>\n a.indexOf(cwd) === 0\n ? './' +\n a\n .substring(cwd.length + 1)\n .replace(/\\\\/g, '/')\n : a\n )\n .join(' ')\n .trim()",
"score": 33.50244856144961
}
] | typescript | === 0 && comment && !this.options.skip) { |
// 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/settings.ts",
"retrieved_chunk": "\t\tcontainerEl.createEl(\"h2\", { text: \"Settings for your mentor\" })\n\t\tconst mentorList: Record<string, Mentor> = {\n\t\t\t...Topics,\n\t\t\t...Individuals,\n\t\t}\n\t\tconst mentorIds = mentorList ? Object.keys(mentorList) : []\n\t\tnew Setting(containerEl)\n\t\t\t.setName(\"Language\")\n\t\t\t.setDesc(\"The language you'd like to talk to your mentor in.\")\n\t\t\t.addDropdown((dropdown) => {",
"score": 32.299585073283616
},
{
"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": 31.775750048229966
},
{
"filename": "src/components/chatview.ts",
"retrieved_chunk": "\tpreferredLanguage = \"en\"\n\tmodel: ModelType\n\tfirstOpen = true\n\t// isTyping = false\n\tdisplayedMessages: Message[] = []\n\t// Merge the two Record<string, Mentor> objects into one.\n\tmentorList: Record<string, Mentor> = {\n\t\t...Topics,\n\t\t...Individuals,\n\t}",
"score": 31.202714141820806
},
{
"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": 21.944078679608737
},
{
"filename": "src/main.ts",
"retrieved_chunk": "\t\t\t\"default\",\n\t\t\tIndividuals[\"default\"],\n\t\t\tthis.settings.model,\n\t\t\tthis.settings.token,\n\t\t\tthis.settings.language\n\t\t)\n\t\t// This adds the \"ELI5\" command.\n\t\tthis.addCommand({\n\t\t\tid: \"eli5\",\n\t\t\tname: \"ELI5\",",
"score": 21.46996452952931
}
] | 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/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": 49.57703740276592
},
{
"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": 42.155106412843125
},
{
"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": 40.37169021862954
},
{
"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": 38.16410411631761
},
{
"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": 37.23941745472684
}
] | typescript | message = tp.message.trimEnd() + '\n\n'
} |
// 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": 23.202078130668855
},
{
"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": 21.875407112854884
},
{
"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": 20.726454483935253
},
{
"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": 18.106418005801547
},
{
"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": 17.107954588711507
}
] | typescript | .at(fn)
if (!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/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": 39.411112842705144
},
{
"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": 34.0731816094973
},
{
"filename": "src/build.ts",
"retrieved_chunk": " `import plugin${i} from ${JSON.stringify(p)}\\n`\n )\n .join('')\nconst pluginsCode = `const plugins: PI[] = [\n${plugins.map((_, i) => ` plugin${i},\\n`).join('')}]\ntype Plug =\n | TestBase\n | { t: Test }\n${plugins\n .map((_, i) => ` | ReturnType<typeof plugin${i}>\\n`)",
"score": 27.930279187477534
},
{
"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": 20.125912105414653
},
{
"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": 18.662906874977892
}
] | typescript | typeof plugin3>
export interface Test extends TTest { |
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/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": 26.25554618697359
},
{
"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": 21.707117257559897
},
{
"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": 15.557853430180819
},
{
"filename": "src/main.ts",
"retrieved_chunk": "\t\t\t\t\tthis.settings.token,\n\t\t\t\t\tthis.settings.preferredMentorId,\n\t\t\t\t\tthis.settings.model,\n\t\t\t\t\tthis.settings.language\n\t\t\t\t)\n\t\t)\n\t\t// This creates an icon in the left ribbon.\n\t\taddIcon(\"aimentor\", MentorIcon)\n\t\tconst ribbonIconEl = this.addRibbonIcon(\n\t\t\t\"aimentor\",",
"score": 14.300960719916702
},
{
"filename": "src/settings.ts",
"retrieved_chunk": "\t\tcontainerEl.createEl(\"h2\", { text: \"Settings for your mentor\" })\n\t\tconst mentorList: Record<string, Mentor> = {\n\t\t\t...Topics,\n\t\t\t...Individuals,\n\t\t}\n\t\tconst mentorIds = mentorList ? Object.keys(mentorList) : []\n\t\tnew Setting(containerEl)\n\t\t\t.setName(\"Language\")\n\t\t\t.setDesc(\"The language you'd like to talk to your mentor in.\")\n\t\t\t.addDropdown((dropdown) => {",
"score": 7.033500766943882
}
] | 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.