hunk
dict | file
stringlengths 0
11.8M
| file_path
stringlengths 2
234
| label
int64 0
1
| commit_url
stringlengths 74
103
| dependency_score
sequencelengths 5
5
|
---|---|---|---|---|---|
{
"id": 5,
"code_window": [
" <SheetTrigger>Open</SheetTrigger>\n",
" <SheetContent className=\"w-[400px] sm:w-[540px]\">\n",
" <SheetHeader>\n",
" <SheetTitle>Are you sure absolutely sure?</SheetTitle>\n",
" <SheetDescription>\n",
" This action cannot be undone. This will permanently delete your account\n",
" and remove your data from our servers.\n",
" </SheetDescription>\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" <SheetTitle>Are you absolutely sure?</SheetTitle>\n"
],
"file_path": "apps/www/content/docs/components/sheet.mdx",
"type": "replace",
"edit_start_line_idx": 94
} | import * as React from "react"
import { Card, CardContent } from "@/registry/default/ui/card"
import {
Carousel,
CarouselContent,
CarouselItem,
CarouselNext,
CarouselPrevious,
} from "@/registry/default/ui/carousel"
export default function CarouselOrientation() {
return (
<Carousel
opts={{
align: "start",
}}
orientation="vertical"
className="w-full max-w-xs"
>
<CarouselContent className="-mt-1 h-[200px]">
{Array.from({ length: 5 }).map((_, index) => (
<CarouselItem key={index} className="pt-1 md:basis-1/2">
<div className="p-1">
<Card>
<CardContent className="flex items-center justify-center p-6">
<span className="text-3xl font-semibold">{index + 1}</span>
</CardContent>
</Card>
</div>
</CarouselItem>
))}
</CarouselContent>
<CarouselPrevious />
<CarouselNext />
</Carousel>
)
}
| apps/www/registry/default/example/carousel-orientation.tsx | 0 | https://github.com/shadcn-ui/ui/commit/4b200ebf5973602ec017294bbdaaee59cd632d0f | [
0.00017184167518280447,
0.0001693282974883914,
0.00016449163376819342,
0.0001704899623291567,
0.0000028985705284867436
] |
{
"id": 5,
"code_window": [
" <SheetTrigger>Open</SheetTrigger>\n",
" <SheetContent className=\"w-[400px] sm:w-[540px]\">\n",
" <SheetHeader>\n",
" <SheetTitle>Are you sure absolutely sure?</SheetTitle>\n",
" <SheetDescription>\n",
" This action cannot be undone. This will permanently delete your account\n",
" and remove your data from our servers.\n",
" </SheetDescription>\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" <SheetTitle>Are you absolutely sure?</SheetTitle>\n"
],
"file_path": "apps/www/content/docs/components/sheet.mdx",
"type": "replace",
"edit_start_line_idx": 94
} | {
"name": "tooltip",
"dependencies": [
"@radix-ui/react-tooltip"
],
"files": [
{
"name": "tooltip.tsx",
"content": "\"use client\"\n\nimport * as React from \"react\"\nimport * as TooltipPrimitive from \"@radix-ui/react-tooltip\"\n\nimport { cn } from \"@/lib/utils\"\n\nconst TooltipProvider = TooltipPrimitive.Provider\n\nconst Tooltip = TooltipPrimitive.Root\n\nconst TooltipTrigger = TooltipPrimitive.Trigger\n\nconst TooltipContent = React.forwardRef<\n React.ElementRef<typeof TooltipPrimitive.Content>,\n React.ComponentPropsWithoutRef<typeof TooltipPrimitive.Content>\n>(({ className, sideOffset = 4, ...props }, ref) => (\n <TooltipPrimitive.Content\n ref={ref}\n sideOffset={sideOffset}\n className={cn(\n \"z-50 overflow-hidden rounded-md border bg-popover px-3 py-1.5 text-sm text-popover-foreground shadow-md animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2\",\n className\n )}\n {...props}\n />\n))\nTooltipContent.displayName = TooltipPrimitive.Content.displayName\n\nexport { Tooltip, TooltipTrigger, TooltipContent, TooltipProvider }\n"
}
],
"type": "components:ui"
} | apps/www/public/registry/styles/default/tooltip.json | 0 | https://github.com/shadcn-ui/ui/commit/4b200ebf5973602ec017294bbdaaee59cd632d0f | [
0.00017582687723916024,
0.0001752910320647061,
0.0001747551723383367,
0.0001752910320647061,
5.358524504117668e-7
] |
{
"id": 6,
"code_window": [
"export default function TypographyLarge() {\n",
" return (\n",
" <div className=\"text-lg font-semibold\">Are you sure absolutely sure?</div>\n",
" )\n",
"}"
],
"labels": [
"keep",
"replace",
"replace",
"replace",
"keep"
],
"after_edit": [
" return <div className=\"text-lg font-semibold\">Are you absolutely sure?</div>\n"
],
"file_path": "apps/www/registry/default/example/typography-large.tsx",
"type": "replace",
"edit_start_line_idx": 1
} | export default function TypographyLarge() {
return (
<div className="text-lg font-semibold">Are you sure absolutely sure?</div>
)
}
| apps/www/registry/new-york/example/typography-large.tsx | 1 | https://github.com/shadcn-ui/ui/commit/4b200ebf5973602ec017294bbdaaee59cd632d0f | [
0.9613650441169739,
0.9613650441169739,
0.9613650441169739,
0.9613650441169739,
0
] |
{
"id": 6,
"code_window": [
"export default function TypographyLarge() {\n",
" return (\n",
" <div className=\"text-lg font-semibold\">Are you sure absolutely sure?</div>\n",
" )\n",
"}"
],
"labels": [
"keep",
"replace",
"replace",
"replace",
"keep"
],
"after_edit": [
" return <div className=\"text-lg font-semibold\">Are you absolutely sure?</div>\n"
],
"file_path": "apps/www/registry/default/example/typography-large.tsx",
"type": "replace",
"edit_start_line_idx": 1
} | import { UnderlineIcon } from "@radix-ui/react-icons"
import { Toggle } from "@/registry/new-york/ui/toggle"
export default function ToggleDisabled() {
return (
<Toggle aria-label="Toggle italic" disabled>
<UnderlineIcon className="h-4 w-4" />
</Toggle>
)
}
| apps/www/registry/new-york/example/toggle-disabled.tsx | 0 | https://github.com/shadcn-ui/ui/commit/4b200ebf5973602ec017294bbdaaee59cd632d0f | [
0.0002784431853797287,
0.00022805086337029934,
0.00017765855591278523,
0.00022805086337029934,
0.00005039231473347172
] |
{
"id": 6,
"code_window": [
"export default function TypographyLarge() {\n",
" return (\n",
" <div className=\"text-lg font-semibold\">Are you sure absolutely sure?</div>\n",
" )\n",
"}"
],
"labels": [
"keep",
"replace",
"replace",
"replace",
"keep"
],
"after_edit": [
" return <div className=\"text-lg font-semibold\">Are you absolutely sure?</div>\n"
],
"file_path": "apps/www/registry/default/example/typography-large.tsx",
"type": "replace",
"edit_start_line_idx": 1
} | "use client"
import * as React from "react"
import {
CalendarIcon,
EnvelopeClosedIcon,
FaceIcon,
GearIcon,
PersonIcon,
RocketIcon,
} from "@radix-ui/react-icons"
import {
CommandDialog,
CommandEmpty,
CommandGroup,
CommandInput,
CommandItem,
CommandList,
CommandSeparator,
CommandShortcut,
} from "@/registry/new-york/ui/command"
export default function CommandDialogDemo() {
const [open, setOpen] = React.useState(false)
React.useEffect(() => {
const down = (e: KeyboardEvent) => {
if (e.key === "j" && (e.metaKey || e.ctrlKey)) {
e.preventDefault()
setOpen((open) => !open)
}
}
document.addEventListener("keydown", down)
return () => document.removeEventListener("keydown", down)
}, [])
return (
<>
<p className="text-sm text-muted-foreground">
Press{" "}
<kbd className="pointer-events-none inline-flex h-5 select-none items-center gap-1 rounded border bg-muted px-1.5 font-mono text-[10px] font-medium text-muted-foreground opacity-100">
<span className="text-xs">⌘</span>J
</kbd>
</p>
<CommandDialog open={open} onOpenChange={setOpen}>
<CommandInput placeholder="Type a command or search..." />
<CommandList>
<CommandEmpty>No results found.</CommandEmpty>
<CommandGroup heading="Suggestions">
<CommandItem>
<CalendarIcon className="mr-2 h-4 w-4" />
<span>Calendar</span>
</CommandItem>
<CommandItem>
<FaceIcon className="mr-2 h-4 w-4" />
<span>Search Emoji</span>
</CommandItem>
<CommandItem>
<RocketIcon className="mr-2 h-4 w-4" />
<span>Launch</span>
</CommandItem>
</CommandGroup>
<CommandSeparator />
<CommandGroup heading="Settings">
<CommandItem>
<PersonIcon className="mr-2 h-4 w-4" />
<span>Profile</span>
<CommandShortcut>⌘P</CommandShortcut>
</CommandItem>
<CommandItem>
<EnvelopeClosedIcon className="mr-2 h-4 w-4" />
<span>Mail</span>
<CommandShortcut>⌘B</CommandShortcut>
</CommandItem>
<CommandItem>
<GearIcon className="mr-2 h-4 w-4" />
<span>Settings</span>
<CommandShortcut>⌘S</CommandShortcut>
</CommandItem>
</CommandGroup>
</CommandList>
</CommandDialog>
</>
)
}
| apps/www/registry/new-york/example/command-dialog.tsx | 0 | https://github.com/shadcn-ui/ui/commit/4b200ebf5973602ec017294bbdaaee59cd632d0f | [
0.0002149787324015051,
0.0001737299608066678,
0.00016574282199144363,
0.00016920475172810256,
0.000014683319932373706
] |
{
"id": 6,
"code_window": [
"export default function TypographyLarge() {\n",
" return (\n",
" <div className=\"text-lg font-semibold\">Are you sure absolutely sure?</div>\n",
" )\n",
"}"
],
"labels": [
"keep",
"replace",
"replace",
"replace",
"keep"
],
"after_edit": [
" return <div className=\"text-lg font-semibold\">Are you absolutely sure?</div>\n"
],
"file_path": "apps/www/registry/default/example/typography-large.tsx",
"type": "replace",
"edit_start_line_idx": 1
} | {
"typescript.tsdk": "../../node_modules/.pnpm/[email protected]/node_modules/typescript/lib",
"typescript.enablePromptUseWorkspaceTsdk": true
}
| templates/next-template/.vscode/settings.json | 0 | https://github.com/shadcn-ui/ui/commit/4b200ebf5973602ec017294bbdaaee59cd632d0f | [
0.00016588401922490448,
0.00016588401922490448,
0.00016588401922490448,
0.00016588401922490448,
0
] |
{
"id": 7,
"code_window": [
"export default function TypographyLarge() {\n",
" return (\n",
" <div className=\"text-lg font-semibold\">Are you sure absolutely sure?</div>\n",
" )\n",
"}"
],
"labels": [
"keep",
"replace",
"replace",
"replace",
"keep"
],
"after_edit": [
" return <div className=\"text-lg font-semibold\">Are you absolutely sure?</div>\n"
],
"file_path": "apps/www/registry/new-york/example/typography-large.tsx",
"type": "replace",
"edit_start_line_idx": 1
} | ---
title: Dialog
description: A window overlaid on either the primary window or another dialog window, rendering the content underneath inert.
featured: true
component: true
links:
doc: https://www.radix-ui.com/docs/primitives/components/dialog
api: https://www.radix-ui.com/docs/primitives/components/dialog#api-reference
---
<ComponentPreview name="dialog-demo" />
## Installation
<Tabs defaultValue="cli">
<TabsList>
<TabsTrigger value="cli">CLI</TabsTrigger>
<TabsTrigger value="manual">Manual</TabsTrigger>
</TabsList>
<TabsContent value="cli">
```bash
npx shadcn-ui@latest add dialog
```
</TabsContent>
<TabsContent value="manual">
<Steps>
<Step>Install the following dependencies:</Step>
```bash
npm install @radix-ui/react-dialog
```
<Step>Copy and paste the following code into your project.</Step>
<ComponentSource name="dialog" />
<Step>Update the import paths to match your project setup.</Step>
</Steps>
</TabsContent>
</Tabs>
## Usage
```tsx
import {
Dialog,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle,
DialogTrigger,
} from "@/components/ui/dialog"
```
```tsx
<Dialog>
<DialogTrigger>Open</DialogTrigger>
<DialogContent>
<DialogHeader>
<DialogTitle>Are you sure absolutely sure?</DialogTitle>
<DialogDescription>
This action cannot be undone. This will permanently delete your account
and remove your data from our servers.
</DialogDescription>
</DialogHeader>
</DialogContent>
</Dialog>
```
## Examples
### Custom close button
<ComponentPreview name="dialog-close-button" />
## Notes
To activate the `Dialog` component from within a `Context Menu` or `Dropdown Menu`, you must encase the `Context Menu` or
`Dropdown Menu` component in the `Dialog` component. For more information, refer to the linked issue [here](https://github.com/radix-ui/primitives/issues/1836).
```tsx {14-25}
<Dialog>
<ContextMenu>
<ContextMenuTrigger>Right click</ContextMenuTrigger>
<ContextMenuContent>
<ContextMenuItem>Open</ContextMenuItem>
<ContextMenuItem>Download</ContextMenuItem>
<DialogTrigger asChild>
<ContextMenuItem>
<span>Delete</span>
</ContextMenuItem>
</DialogTrigger>
</ContextMenuContent>
</ContextMenu>
<DialogContent>
<DialogHeader>
<DialogTitle>Are you sure absolutely sure?</DialogTitle>
<DialogDescription>
This action cannot be undone. Are you sure you want to permanently
delete this file from our servers?
</DialogDescription>
</DialogHeader>
<DialogFooter>
<Button type="submit">Confirm</Button>
</DialogFooter>
</DialogContent>
</Dialog>
```
| apps/www/content/docs/components/dialog.mdx | 1 | https://github.com/shadcn-ui/ui/commit/4b200ebf5973602ec017294bbdaaee59cd632d0f | [
0.00025417530559934676,
0.00017781411588657647,
0.00016201815742533654,
0.00016921690257731825,
0.00002442365985189099
] |
{
"id": 7,
"code_window": [
"export default function TypographyLarge() {\n",
" return (\n",
" <div className=\"text-lg font-semibold\">Are you sure absolutely sure?</div>\n",
" )\n",
"}"
],
"labels": [
"keep",
"replace",
"replace",
"replace",
"keep"
],
"after_edit": [
" return <div className=\"text-lg font-semibold\">Are you absolutely sure?</div>\n"
],
"file_path": "apps/www/registry/new-york/example/typography-large.tsx",
"type": "replace",
"edit_start_line_idx": 1
} | "use client"
import * as React from "react"
import * as AccordionPrimitive from "@radix-ui/react-accordion"
import { ChevronDown } from "lucide-react"
import { cn } from "@/lib/utils"
const Accordion = AccordionPrimitive.Root
const AccordionItem = React.forwardRef<
React.ElementRef<typeof AccordionPrimitive.Item>,
React.ComponentPropsWithoutRef<typeof AccordionPrimitive.Item>
>(({ className, ...props }, ref) => (
<AccordionPrimitive.Item
ref={ref}
className={cn("border-b", className)}
{...props}
/>
))
AccordionItem.displayName = "AccordionItem"
const AccordionTrigger = React.forwardRef<
React.ElementRef<typeof AccordionPrimitive.Trigger>,
React.ComponentPropsWithoutRef<typeof AccordionPrimitive.Trigger>
>(({ className, children, ...props }, ref) => (
<AccordionPrimitive.Header className="flex">
<AccordionPrimitive.Trigger
ref={ref}
className={cn(
"flex flex-1 items-center justify-between py-4 font-medium transition-all hover:underline [&[data-state=open]>svg]:rotate-180",
className
)}
{...props}
>
{children}
<ChevronDown className="h-4 w-4 shrink-0 transition-transform duration-200" />
</AccordionPrimitive.Trigger>
</AccordionPrimitive.Header>
))
AccordionTrigger.displayName = AccordionPrimitive.Trigger.displayName
const AccordionContent = React.forwardRef<
React.ElementRef<typeof AccordionPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof AccordionPrimitive.Content>
>(({ className, children, ...props }, ref) => (
<AccordionPrimitive.Content
ref={ref}
className="overflow-hidden text-sm transition-all data-[state=closed]:animate-accordion-up data-[state=open]:animate-accordion-down"
{...props}
>
<div className={cn("pb-4 pt-0", className)}>{children}</div>
</AccordionPrimitive.Content>
))
AccordionContent.displayName = AccordionPrimitive.Content.displayName
export { Accordion, AccordionItem, AccordionTrigger, AccordionContent }
| apps/www/registry/default/ui/accordion.tsx | 0 | https://github.com/shadcn-ui/ui/commit/4b200ebf5973602ec017294bbdaaee59cd632d0f | [
0.0005015676142647862,
0.00024236092576757073,
0.0001732850359985605,
0.00019211390463169664,
0.00011708254896802828
] |
{
"id": 7,
"code_window": [
"export default function TypographyLarge() {\n",
" return (\n",
" <div className=\"text-lg font-semibold\">Are you sure absolutely sure?</div>\n",
" )\n",
"}"
],
"labels": [
"keep",
"replace",
"replace",
"replace",
"keep"
],
"after_edit": [
" return <div className=\"text-lg font-semibold\">Are you absolutely sure?</div>\n"
],
"file_path": "apps/www/registry/new-york/example/typography-large.tsx",
"type": "replace",
"edit_start_line_idx": 1
} | "use client"
import { zodResolver } from "@hookform/resolvers/zod"
import { useForm } from "react-hook-form"
import * as z from "zod"
import { Button } from "@/registry/default/ui/button"
import {
Form,
FormControl,
FormField,
FormItem,
FormLabel,
FormMessage,
} from "@/registry/default/ui/form"
import { RadioGroup, RadioGroupItem } from "@/registry/default/ui/radio-group"
import { toast } from "@/registry/default/ui/use-toast"
const FormSchema = z.object({
type: z.enum(["all", "mentions", "none"], {
required_error: "You need to select a notification type.",
}),
})
export default function RadioGroupForm() {
const form = useForm<z.infer<typeof FormSchema>>({
resolver: zodResolver(FormSchema),
})
function onSubmit(data: z.infer<typeof FormSchema>) {
toast({
title: "You submitted the following values:",
description: (
<pre className="mt-2 w-[340px] rounded-md bg-slate-950 p-4">
<code className="text-white">{JSON.stringify(data, null, 2)}</code>
</pre>
),
})
}
return (
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)} className="w-2/3 space-y-6">
<FormField
control={form.control}
name="type"
render={({ field }) => (
<FormItem className="space-y-3">
<FormLabel>Notify me about...</FormLabel>
<FormControl>
<RadioGroup
onValueChange={field.onChange}
defaultValue={field.value}
className="flex flex-col space-y-1"
>
<FormItem className="flex items-center space-x-3 space-y-0">
<FormControl>
<RadioGroupItem value="all" />
</FormControl>
<FormLabel className="font-normal">
All new messages
</FormLabel>
</FormItem>
<FormItem className="flex items-center space-x-3 space-y-0">
<FormControl>
<RadioGroupItem value="mentions" />
</FormControl>
<FormLabel className="font-normal">
Direct messages and mentions
</FormLabel>
</FormItem>
<FormItem className="flex items-center space-x-3 space-y-0">
<FormControl>
<RadioGroupItem value="none" />
</FormControl>
<FormLabel className="font-normal">Nothing</FormLabel>
</FormItem>
</RadioGroup>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<Button type="submit">Submit</Button>
</form>
</Form>
)
}
| apps/www/registry/default/example/radio-group-form.tsx | 0 | https://github.com/shadcn-ui/ui/commit/4b200ebf5973602ec017294bbdaaee59cd632d0f | [
0.00017843133537098765,
0.00016848908853717148,
0.00016212988703045994,
0.00016807674546726048,
0.000004991893092665123
] |
{
"id": 7,
"code_window": [
"export default function TypographyLarge() {\n",
" return (\n",
" <div className=\"text-lg font-semibold\">Are you sure absolutely sure?</div>\n",
" )\n",
"}"
],
"labels": [
"keep",
"replace",
"replace",
"replace",
"keep"
],
"after_edit": [
" return <div className=\"text-lg font-semibold\">Are you absolutely sure?</div>\n"
],
"file_path": "apps/www/registry/new-york/example/typography-large.tsx",
"type": "replace",
"edit_start_line_idx": 1
} | {
"name": "popover",
"dependencies": [
"@radix-ui/react-popover"
],
"files": [
{
"name": "popover.tsx",
"content": "\"use client\"\n\nimport * as React from \"react\"\nimport * as PopoverPrimitive from \"@radix-ui/react-popover\"\n\nimport { cn } from \"@/lib/utils\"\n\nconst Popover = PopoverPrimitive.Root\n\nconst PopoverTrigger = PopoverPrimitive.Trigger\n\nconst PopoverContent = React.forwardRef<\n React.ElementRef<typeof PopoverPrimitive.Content>,\n React.ComponentPropsWithoutRef<typeof PopoverPrimitive.Content>\n>(({ className, align = \"center\", sideOffset = 4, ...props }, ref) => (\n <PopoverPrimitive.Portal>\n <PopoverPrimitive.Content\n ref={ref}\n align={align}\n sideOffset={sideOffset}\n className={cn(\n \"z-50 w-72 rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2\",\n className\n )}\n {...props}\n />\n </PopoverPrimitive.Portal>\n))\nPopoverContent.displayName = PopoverPrimitive.Content.displayName\n\nexport { Popover, PopoverTrigger, PopoverContent }\n"
}
],
"type": "components:ui"
} | apps/www/public/registry/styles/default/popover.json | 0 | https://github.com/shadcn-ui/ui/commit/4b200ebf5973602ec017294bbdaaee59cd632d0f | [
0.00023741764016449451,
0.0002049501781584695,
0.00017248271615244448,
0.0002049501781584695,
0.000032467462006025016
] |
{
"id": 0,
"code_window": [
"\n",
"const isObject = val => val != null && typeof val === 'object' && Array.isArray(val) === false;\n",
"const isFunction = val => typeof val === 'function';\n",
"\n",
"// Copied out of parse-package-name\n",
"const RE_SCOPED = /^(@[^/]+\\/[^/@]+)(?:\\/([^@]+))?(?:@([\\s\\S]+))?/;\n",
"const RE_NORMAL = /^([^/@]+)(?:\\/([^@]+))?(?:@([\\s\\S]+))?/;\n",
"function parsePackageName(input) {\n",
" if (typeof input !== 'string') {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"// '@storybook/addon-actions/register' => ( name: '@storybook/addon-actions', path: '/register', version: '' )\n"
],
"file_path": "lib/core/src/server/presets.js",
"type": "add",
"edit_start_line_idx": 9
} | function wrapPreset(basePresets) {
return {
babel: async (config, args) => basePresets.apply('babel', config, args),
webpack: async (config, args) => basePresets.apply('webpack', config, args),
};
}
function mockPreset(name, mockPresetObject) {
jest.mock(name, () => mockPresetObject, { virtual: true });
}
jest.mock('@storybook/node-logger', () => ({
logger: {
info: jest.fn(),
warn: jest.fn(),
error: jest.fn(),
},
}));
jest.mock('./utils/resolve-file', () => ({
resolveFile: name => {
const KNOWN_FILES = [
'@storybook/addon-actions/register',
'@storybook/addon-knobs/register',
'@storybook/addon-docs/preset',
];
if (KNOWN_FILES.includes(name)) {
return name;
}
throw new Error(`Cannot find module '${name}'`);
},
}));
describe('presets', () => {
it('does not throw when there is no preset file', async () => {
const getPresets = require.requireActual('./presets').default;
let presets;
async function testPresets() {
presets = wrapPreset(getPresets());
await presets.webpack();
await presets.babel();
}
await expect(testPresets()).resolves.toBeUndefined();
expect(presets).toBeDefined();
});
it('does not throw when presets are empty', async () => {
const getPresets = require.requireActual('./presets').default;
const presets = wrapPreset(getPresets([]));
async function testPresets() {
await presets.webpack();
await presets.babel();
}
await expect(testPresets()).resolves.toBeUndefined();
});
it('does not throw when preset can not be loaded', async () => {
const getPresets = require.requireActual('./presets').default;
const presets = wrapPreset(getPresets(['preset-foo']));
async function testPresets() {
await presets.webpack();
await presets.babel();
}
await expect(testPresets()).resolves.toBeUndefined();
});
it('loads and applies presets when they are combined in another preset', async () => {
mockPreset('preset-foo', {
foo: exec => exec.concat('foo'),
});
mockPreset('preset-bar', {
foo: exec => exec.concat('bar'),
});
mockPreset('preset-got', [
'preset-dracarys',
{ name: 'preset-valar', options: { custom: 'morghulis' } },
]);
mockPreset('preset-dracarys', {
foo: exec => exec.concat('dracarys'),
});
mockPreset('preset-valar', {
foo: (exec, options) => exec.concat(`valar ${options.custom}`),
});
const getPresets = require.requireActual('./presets').default;
const presets = getPresets(['preset-foo', 'preset-got', 'preset-bar']);
const result = await presets.apply('foo', []);
expect(result).toEqual(['foo', 'dracarys', 'valar morghulis', 'bar']);
});
it('loads and applies presets when they are declared as a string', async () => {
const mockPresetFooExtendWebpack = jest.fn();
const mockPresetBarExtendBabel = jest.fn();
mockPreset('preset-foo', {
webpack: mockPresetFooExtendWebpack,
});
mockPreset('preset-bar', {
babel: mockPresetBarExtendBabel,
});
const getPresets = require.requireActual('./presets').default;
const presets = wrapPreset(getPresets(['preset-foo', 'preset-bar']));
async function testPresets() {
await presets.webpack();
await presets.babel();
}
await expect(testPresets()).resolves.toBeUndefined();
expect(mockPresetFooExtendWebpack).toHaveBeenCalled();
expect(mockPresetBarExtendBabel).toHaveBeenCalled();
});
it('loads and applies presets when they are declared as an object without props', async () => {
const mockPresetFooExtendWebpack = jest.fn();
const mockPresetBarExtendBabel = jest.fn();
mockPreset('preset-foo', {
webpack: mockPresetFooExtendWebpack,
});
mockPreset('preset-bar', {
babel: mockPresetBarExtendBabel,
});
const getPresets = require.requireActual('./presets').default;
const presets = wrapPreset(getPresets([{ name: 'preset-foo' }, { name: 'preset-bar' }]));
async function testPresets() {
await presets.webpack();
await presets.babel();
}
await expect(testPresets()).resolves.toBeUndefined();
expect(mockPresetFooExtendWebpack).toHaveBeenCalled();
expect(mockPresetBarExtendBabel).toHaveBeenCalled();
});
it('loads and applies presets when they are declared as an object with props', async () => {
const mockPresetFooExtendWebpack = jest.fn();
const mockPresetBarExtendBabel = jest.fn();
mockPreset('preset-foo', {
webpack: mockPresetFooExtendWebpack,
});
mockPreset('preset-bar', {
babel: mockPresetBarExtendBabel,
});
const getPresets = require.requireActual('./presets').default;
const presets = wrapPreset(
getPresets([
{ name: 'preset-foo', options: { foo: 1 } },
{ name: 'preset-bar', options: { bar: 'a' } },
])
);
async function testPresets() {
await presets.webpack({});
await presets.babel({});
}
await expect(testPresets()).resolves.toBeUndefined();
expect(mockPresetFooExtendWebpack).toHaveBeenCalledWith(expect.anything(), {
foo: 1,
presetsList: expect.anything(),
});
expect(mockPresetBarExtendBabel).toHaveBeenCalledWith(expect.anything(), {
bar: 'a',
presetsList: expect.anything(),
});
});
it('loads and applies presets when they are declared as a string and as an object', async () => {
const mockPresetFooExtendWebpack = jest.fn();
const mockPresetBarExtendBabel = jest.fn();
mockPreset('preset-foo', {
webpack: mockPresetFooExtendWebpack,
});
mockPreset('preset-bar', {
babel: mockPresetBarExtendBabel,
});
const getPresets = require.requireActual('./presets').default;
const presets = wrapPreset(
getPresets([
'preset-foo',
{
name: 'preset-bar',
options: {
bar: 'a',
},
},
])
);
async function testPresets() {
await presets.webpack({});
await presets.babel({});
}
await expect(testPresets()).resolves.toBeUndefined();
expect(mockPresetFooExtendWebpack).toHaveBeenCalled();
expect(mockPresetBarExtendBabel).toHaveBeenCalledWith(expect.anything(), {
bar: 'a',
presetsList: expect.arrayContaining([
expect.objectContaining({ name: 'preset-foo' }),
expect.objectContaining({ name: 'preset-bar' }),
]),
});
});
it('applies presets in chain', async () => {
const mockPresetFooExtendWebpack = jest.fn(() => ({}));
const mockPresetBarExtendWebpack = jest.fn(() => ({}));
mockPreset('preset-foo', {
webpack: mockPresetFooExtendWebpack,
});
mockPreset('preset-bar', {
webpack: mockPresetBarExtendWebpack,
});
const getPresets = require.requireActual('./presets').default;
const presets = wrapPreset(
getPresets([
'preset-foo',
{
name: 'preset-bar',
options: {
bar: 'a',
presetsList: expect.arrayContaining([
expect.objectContaining({ name: 'preset-foo' }),
expect.objectContaining({ name: 'preset-bar' }),
]),
},
},
])
);
async function testPresets() {
await presets.webpack();
await presets.babel();
}
await expect(testPresets()).resolves.toBeUndefined();
expect(mockPresetFooExtendWebpack).toHaveBeenCalled();
expect(mockPresetBarExtendWebpack).toHaveBeenCalledWith(expect.anything(), {
bar: 'a',
presetsList: expect.arrayContaining([
expect.objectContaining({ name: 'preset-foo' }),
expect.objectContaining({ name: 'preset-bar' }),
]),
});
});
it('allows for presets to export presets array', async () => {
const getPresets = require.requireActual('./presets').default;
const input = {};
const mockPresetBar = jest.fn(() => input);
mockPreset('preset-foo', {
presets: ['preset-bar'],
});
mockPreset('preset-bar', {
bar: mockPresetBar,
});
const presets = getPresets(['preset-foo']);
const output = await presets.apply('bar');
expect(mockPresetBar).toHaveBeenCalledWith(undefined, expect.any(Object));
expect(input).toBe(output);
});
it('allows for presets to export presets fn', async () => {
const getPresets = require.requireActual('./presets').default;
const input = {};
const storybookOptions = { a: 1 };
const presetOptions = { b: 2 };
const mockPresetBar = jest.fn(() => input);
const mockPresetFoo = jest.fn(() => ['preset-bar']);
mockPreset('preset-foo', {
presets: mockPresetFoo,
});
mockPreset('preset-bar', {
bar: mockPresetBar,
});
const presets = getPresets([{ name: 'preset-foo', options: { b: 2 } }], storybookOptions);
const output = await presets.apply('bar');
expect(mockPresetFoo).toHaveBeenCalledWith({ ...storybookOptions, ...presetOptions });
expect(mockPresetBar).toHaveBeenCalledWith(undefined, expect.any(Object));
expect(input).toBe(output);
});
afterEach(() => {
jest.resetModules();
});
});
describe('resolveAddonName', () => {
const { resolveAddonName } = require.requireActual('./presets');
it('should resolve packages with metadata (relative path)', () => {
expect(resolveAddonName('@storybook/addon-docs')).toEqual({
name: '@storybook/addon-docs/preset',
type: 'presets',
});
});
it('should resolve packages with metadata (absolute path)', () => {
expect(resolveAddonName('@storybook/addon-knobs')).toEqual({
name: '@storybook/addon-knobs/register',
type: 'managerEntries',
});
});
it('should resolve packages without metadata', () => {
expect(resolveAddonName('@storybook/preset-create-react-app')).toEqual({
name: '@storybook/preset-create-react-app',
type: 'presets',
});
});
it('should resolve managerEntries', () => {
expect(resolveAddonName('@storybook/addon-actions/register')).toEqual({
name: '@storybook/addon-actions/register',
type: 'managerEntries',
});
});
it('should resolve presets', () => {
expect(resolveAddonName('@storybook/addon-docs/preset')).toEqual({
name: '@storybook/addon-docs/preset',
type: 'presets',
});
});
it('should resolve preset packages', () => {
expect(resolveAddonName('@storybook/addon-essentials')).toEqual({
name: '@storybook/addon-essentials',
type: 'presets',
});
});
it('should error on invalid inputs', () => {
expect(() => resolveAddonName(null)).toThrow();
});
});
describe('splitAddons', () => {
const { splitAddons } = require.requireActual('./presets');
it('should split managerEntries that end in register', () => {
const addons = [
'@storybook/addon-actions/register',
'storybook-addon-readme/register',
'addon-foo/register.js',
];
expect(splitAddons(addons)).toEqual({
managerEntries: addons,
presets: [],
});
});
it('should split preset packages and package entries', () => {
const addons = [
'@storybook/addon-essentials',
'@storybook/addon-docs/presets',
'addon-bar/presets.js',
];
expect(splitAddons(addons)).toEqual({
managerEntries: [],
presets: addons,
});
});
it('should split preset objects', () => {
const addons = [
{ name: '@storybook/addon-essentials' },
{ name: '@storybook/addon-docs/presets', options: { configureJSX: true } },
];
expect(splitAddons(addons)).toEqual({
managerEntries: [],
presets: addons,
});
});
it('should skip invalid objects', () => {
const addons = [1, true, { foo: 'bar' }];
expect(splitAddons(addons)).toEqual({
managerEntries: [],
presets: [],
});
});
});
| lib/core/src/server/presets.test.js | 1 | https://github.com/storybookjs/storybook/commit/064f52c2c3aa3ad5ca3d614052cdb162f74ee580 | [
0.0015230566496029496,
0.0002348666894249618,
0.00016686870367266238,
0.0001694194506853819,
0.0002825943229254335
] |
{
"id": 0,
"code_window": [
"\n",
"const isObject = val => val != null && typeof val === 'object' && Array.isArray(val) === false;\n",
"const isFunction = val => typeof val === 'function';\n",
"\n",
"// Copied out of parse-package-name\n",
"const RE_SCOPED = /^(@[^/]+\\/[^/@]+)(?:\\/([^@]+))?(?:@([\\s\\S]+))?/;\n",
"const RE_NORMAL = /^([^/@]+)(?:\\/([^@]+))?(?:@([\\s\\S]+))?/;\n",
"function parsePackageName(input) {\n",
" if (typeof input !== 'string') {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"// '@storybook/addon-actions/register' => ( name: '@storybook/addon-actions', path: '/register', version: '' )\n"
],
"file_path": "lib/core/src/server/presets.js",
"type": "add",
"edit_start_line_idx": 9
} | // Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`docs-mdx-compiler-plugin docs-only.mdx 1`] = `
"/* @jsx mdx */
import { assertIsFn, AddContext } from '@storybook/addon-docs/blocks';
import { Meta } from '@storybook/addon-docs/blocks';
const makeShortcode = name =>
function MDXDefaultShortcode(props) {
console.warn(
'Component ' +
name +
' was not imported, exported, or provided by MDXProvider as global scope'
);
return <div {...props} />;
};
const layoutProps = {};
const MDXLayout = 'wrapper';
function MDXContent({ components, ...props }) {
return (
<MDXLayout {...layoutProps} {...props} components={components} mdxType=\\"MDXLayout\\">
<Meta title=\\"docs-only\\" mdxType=\\"Meta\\" />
<h1>{\`Documentation only\`}</h1>
<p>
{\`This is a documentation-only MDX file which generates a dummy \`}
<inlineCode parentName=\\"p\\">{\`docsOnly: true\`}</inlineCode>
{\` story.\`}
</p>
</MDXLayout>
);
}
MDXContent.isMDXComponent = true;
export const __page = () => {
throw new Error('Docs-only story');
};
__page.story = { parameters: { docsOnly: true } };
const componentMeta = { title: 'docs-only', includeStories: ['__page'] };
const mdxStoryNameToKey = {};
componentMeta.parameters = componentMeta.parameters || {};
componentMeta.parameters.docs = {
...(componentMeta.parameters.docs || {}),
page: () => (
<AddContext mdxStoryNameToKey={mdxStoryNameToKey} mdxComponentMeta={componentMeta}>
<MDXContent />
</AddContext>
),
};
export default componentMeta;
"
`;
| addons/docs/src/mdx/__testfixtures__/docs-only.output.snapshot | 0 | https://github.com/storybookjs/storybook/commit/064f52c2c3aa3ad5ca3d614052cdb162f74ee580 | [
0.0001755866251187399,
0.00016927318938542157,
0.0001670930505497381,
0.00016808831423986703,
0.00000289959461952094
] |
{
"id": 0,
"code_window": [
"\n",
"const isObject = val => val != null && typeof val === 'object' && Array.isArray(val) === false;\n",
"const isFunction = val => typeof val === 'function';\n",
"\n",
"// Copied out of parse-package-name\n",
"const RE_SCOPED = /^(@[^/]+\\/[^/@]+)(?:\\/([^@]+))?(?:@([\\s\\S]+))?/;\n",
"const RE_NORMAL = /^([^/@]+)(?:\\/([^@]+))?(?:@([\\s\\S]+))?/;\n",
"function parsePackageName(input) {\n",
" if (typeof input !== 'string') {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"// '@storybook/addon-actions/register' => ( name: '@storybook/addon-actions', path: '/register', version: '' )\n"
],
"file_path": "lib/core/src/server/presets.js",
"type": "add",
"edit_start_line_idx": 9
} | SKIP_PREFLIGHT_CHECK=true
NODE_PATH=src | examples/rax-kitchen-sink/.env | 0 | https://github.com/storybookjs/storybook/commit/064f52c2c3aa3ad5ca3d614052cdb162f74ee580 | [
0.00018322763207834214,
0.00018322763207834214,
0.00018322763207834214,
0.00018322763207834214,
0
] |
{
"id": 0,
"code_window": [
"\n",
"const isObject = val => val != null && typeof val === 'object' && Array.isArray(val) === false;\n",
"const isFunction = val => typeof val === 'function';\n",
"\n",
"// Copied out of parse-package-name\n",
"const RE_SCOPED = /^(@[^/]+\\/[^/@]+)(?:\\/([^@]+))?(?:@([\\s\\S]+))?/;\n",
"const RE_NORMAL = /^([^/@]+)(?:\\/([^@]+))?(?:@([\\s\\S]+))?/;\n",
"function parsePackageName(input) {\n",
" if (typeof input !== 'string') {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"// '@storybook/addon-actions/register' => ( name: '@storybook/addon-actions', path: '/register', version: '' )\n"
],
"file_path": "lib/core/src/server/presets.js",
"type": "add",
"edit_start_line_idx": 9
} | import { snapshotWithOptions } from '../test-bodies';
import { Stories2SnapsConverter } from '../Stories2SnapsConverter';
import { StoryshotsOptions } from './StoryshotsOptions';
const ignore = ['**/node_modules/**'];
const defaultStories2SnapsConverter = new Stories2SnapsConverter();
function getIntegrityOptions({ integrityOptions }: StoryshotsOptions) {
if (integrityOptions === false) {
return false;
}
if (typeof integrityOptions !== 'object') {
return false;
}
const ignoreOption: string[] = Array.isArray(integrityOptions.ignore)
? integrityOptions.ignore
: [];
return {
...integrityOptions,
ignore: [...ignore, ...ignoreOption],
absolute: true,
};
}
function ensureOptionsDefaults(options: StoryshotsOptions) {
const {
suite = 'Storyshots',
asyncJest,
storyNameRegex,
storyKindRegex,
renderer,
serializer,
snapshotSerializers,
stories2snapsConverter = defaultStories2SnapsConverter,
test: testMethod = snapshotWithOptions({ renderer, serializer }),
} = options;
const integrityOptions = getIntegrityOptions(options);
return {
asyncJest,
suite,
storyNameRegex,
storyKindRegex,
stories2snapsConverter,
testMethod,
snapshotSerializers,
integrityOptions,
};
}
export default ensureOptionsDefaults;
| addons/storyshots/storyshots-core/src/api/ensureOptionsDefaults.ts | 0 | https://github.com/storybookjs/storybook/commit/064f52c2c3aa3ad5ca3d614052cdb162f74ee580 | [
0.0003653048479463905,
0.00020230480004101992,
0.0001680988643784076,
0.0001689561759121716,
0.00007292848022188991
] |
{
"id": 1,
"code_window": [
" }\n",
"\n",
" return [];\n",
"};\n",
"\n",
"/**\n",
" * Parse an addon into either a managerEntry or a preset. Throw on invalid input.\n",
" *\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"const isLocalFileImport = packageName => /^[./]/.test(packageName);\n",
"\n"
],
"file_path": "lib/core/src/server/presets.js",
"type": "add",
"edit_start_line_idx": 40
} | import dedent from 'ts-dedent';
import { join } from 'path';
import { logger } from '@storybook/node-logger';
import { resolveFile } from './utils/resolve-file';
const isObject = val => val != null && typeof val === 'object' && Array.isArray(val) === false;
const isFunction = val => typeof val === 'function';
// Copied out of parse-package-name
const RE_SCOPED = /^(@[^/]+\/[^/@]+)(?:\/([^@]+))?(?:@([\s\S]+))?/;
const RE_NORMAL = /^([^/@]+)(?:\/([^@]+))?(?:@([\s\S]+))?/;
function parsePackageName(input) {
if (typeof input !== 'string') {
throw new TypeError('Expected a string');
}
const matched = input.charAt(0) === '@' ? input.match(RE_SCOPED) : input.match(RE_NORMAL);
if (!matched) {
throw new Error(`[parse-package-name] "${input}" is not a valid string`);
}
return {
name: matched[1],
path: matched[2] || '',
version: matched[3] || '',
};
}
const resolvePresetFunction = (input, presetOptions, storybookOptions) => {
if (isFunction(input)) {
return input({ ...storybookOptions, ...presetOptions });
}
if (Array.isArray(input)) {
return input;
}
return [];
};
/**
* Parse an addon into either a managerEntry or a preset. Throw on invalid input.
*
* Valid inputs:
* - '@storybook/addon-actions/register'
* => { type: 'managerEntries', item }
*
* - '@storybook/addon-docs/preset'
* => { type: 'presets', item }
*
* - '@storybook/addon-docs'
* => { type: 'presets', item: '@storybook/addon-docs/preset' }
*
* - { name: '@storybook/addon-docs(/preset)?', options: { ... } }
* => { type: 'presets', item: { name: '@storybook/addon-docs/preset', options } }
*/
export const resolveAddonName = name => {
const { path } = parsePackageName(name);
// when user provides full path, we don't need to do anything
if (path) {
return {
name,
// Accept `register`, `register.js`, `require.resolve('foo/register') cases
type: path.match(/register(.js)?$/) ? 'managerEntries' : 'presets',
};
}
try {
return {
name: resolveFile(join(name, 'preset')),
type: 'presets',
};
// eslint-disable-next-line no-empty
} catch (err) {}
try {
return {
name: resolveFile(join(name, 'register')),
type: 'managerEntries',
};
// eslint-disable-next-line no-empty
} catch (err) {}
return { name, type: 'presets' };
};
export const splitAddons = addons => {
return addons.reduce(
(acc, item) => {
try {
if (isObject(item)) {
const { name } = resolveAddonName(item.name);
acc.presets.push({ ...item, name });
} else {
const { name, type } = resolveAddonName(item);
acc[type].push(name);
}
} catch (err) {
logger.error(
`Addon value should end in /register OR it should be a valid preset https://storybook.js.org/docs/presets/introduction/\n${item}`
);
}
return acc;
},
{
managerEntries: [],
presets: [],
}
);
};
function interopRequireDefault(filePath) {
// eslint-disable-next-line global-require,import/no-dynamic-require
const result = require(`${filePath}`);
const isES6DefaultExported =
typeof result === 'object' && result !== null && typeof result.default !== 'undefined';
return isES6DefaultExported ? result.default : result;
}
function loadPreset(input, level, storybookOptions) {
try {
const name = input.name ? input.name : input;
const presetOptions = input.options ? input.options : {};
const contents = interopRequireDefault(name);
if (Array.isArray(contents)) {
const subPresets = contents;
return loadPresets(subPresets, level + 1, storybookOptions);
}
if (isObject(contents)) {
const { addons: addonsInput, presets: presetsInput, ...rest } = contents;
const subPresets = resolvePresetFunction(presetsInput, presetOptions, storybookOptions);
const subAddons = resolvePresetFunction(addonsInput, presetOptions, storybookOptions);
const { managerEntries, presets } = splitAddons(subAddons);
return [
...loadPresets([...subPresets, ...presets], level + 1, storybookOptions),
{ name: `${name}_additionalManagerEntries`, preset: { managerEntries } },
{
name,
preset: rest,
options: presetOptions,
},
];
}
throw new Error(dedent`
${input} is not a valid preset
`);
} catch (e) {
const warning =
level > 0
? ` Failed to load preset: ${JSON.stringify(input)} on level ${level}`
: ` Failed to load preset: ${JSON.stringify(input)}`;
logger.warn(warning);
logger.error(e);
return [];
}
}
function loadPresets(presets, level, storybookOptions) {
if (!presets || !Array.isArray(presets) || !presets.length) {
return [];
}
if (!level) {
logger.info('=> Loading presets');
}
return presets.reduce((acc, preset) => {
const loaded = loadPreset(preset, level, storybookOptions);
return acc.concat(loaded);
}, []);
}
function applyPresets(presets, extension, config, args) {
const presetResult = new Promise(resolve => resolve(config));
if (!presets.length) {
return presetResult;
}
return presets.reduce((accumulationPromise, { preset, options }) => {
const change = preset[extension];
if (!change) {
return accumulationPromise;
}
if (typeof change === 'function') {
const extensionFn = change;
const context = {
extensionFn,
preset,
combinedOptions: { ...args, ...options, presetsList: presets },
};
return accumulationPromise.then(newConfig =>
context.extensionFn.call(context.preset, newConfig, context.combinedOptions)
);
}
return accumulationPromise.then(newConfig => {
if (Array.isArray(newConfig) && Array.isArray(change)) {
return [...newConfig, ...change];
}
if (isObject(newConfig) && isObject(change)) {
return { ...newConfig, ...change };
}
return change;
});
}, presetResult);
}
function getPresets(presets, storybookOptions) {
const loadedPresets = loadPresets(presets, 0, storybookOptions);
return {
apply: async (extension, config, args = {}) =>
applyPresets(loadedPresets, extension, config, args),
};
}
export default getPresets;
| lib/core/src/server/presets.js | 1 | https://github.com/storybookjs/storybook/commit/064f52c2c3aa3ad5ca3d614052cdb162f74ee580 | [
0.00028593471506610513,
0.00019371956295799464,
0.00016659795073792338,
0.0001867410319391638,
0.000027253710868535563
] |
{
"id": 1,
"code_window": [
" }\n",
"\n",
" return [];\n",
"};\n",
"\n",
"/**\n",
" * Parse an addon into either a managerEntry or a preset. Throw on invalid input.\n",
" *\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"const isLocalFileImport = packageName => /^[./]/.test(packageName);\n",
"\n"
],
"file_path": "lib/core/src/server/presets.js",
"type": "add",
"edit_start_line_idx": 40
} | import React, { Component, Fragment } from 'react';
import { styled } from '@storybook/theming';
import { STORY_RENDERED } from '@storybook/core-events';
import { ActionBar, Icons, ScrollArea } from '@storybook/components';
import { AxeResults, Result } from 'axe-core';
import { API } from '@storybook/api';
import { Provider } from 'react-redux';
import { Report } from './Report';
import { Tabs } from './Tabs';
import { EVENTS } from '../constants';
import store, { clearElements } from '../redux-config';
export enum RuleType {
VIOLATION,
PASS,
INCOMPLETION,
}
const Icon = styled(Icons)(
{
height: 12,
width: 12,
marginRight: 4,
},
({ status, theme }: any) =>
status === 'running'
? {
animation: `${theme.animation.rotate360} 1s linear infinite;`,
}
: {}
);
const Passes = styled.span<{}>(({ theme }) => ({
color: theme.color.positive,
}));
const Violations = styled.span<{}>(({ theme }) => ({
color: theme.color.negative,
}));
const Incomplete = styled.span<{}>(({ theme }) => ({
color: theme.color.warning,
}));
const centeredStyle = {
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
height: '100%',
};
const Loader = styled(({ className }) => (
<div className={className}>
<Icon inline icon="sync" status="running" /> Please wait while the accessibility scan is running
...
</div>
))(centeredStyle);
Loader.displayName = 'Loader';
interface A11YPanelNormalState {
status: 'ready' | 'ran' | 'running';
passes: Result[];
violations: Result[];
incomplete: Result[];
}
interface A11YPanelErrorState {
status: 'error';
error: unknown;
}
type A11YPanelState = A11YPanelNormalState | A11YPanelErrorState;
interface A11YPanelProps {
active: boolean;
api: API;
}
export class A11YPanel extends Component<A11YPanelProps, A11YPanelState> {
state: A11YPanelState = {
status: 'ready',
passes: [],
violations: [],
incomplete: [],
};
componentDidMount() {
const { api } = this.props;
api.on(STORY_RENDERED, this.request);
api.on(EVENTS.RESULT, this.onUpdate);
api.on(EVENTS.ERROR, this.onError);
}
componentDidUpdate(prevProps: A11YPanelProps) {
// TODO: might be able to remove this
const { active } = this.props;
if (!prevProps.active && active) {
// removes all elements from the redux map in store from the previous panel
store.dispatch(clearElements());
this.request();
}
}
componentWillUnmount() {
const { api } = this.props;
api.off(STORY_RENDERED, this.request);
api.off(EVENTS.RESULT, this.onUpdate);
api.off(EVENTS.ERROR, this.onError);
}
onUpdate = ({ passes, violations, incomplete }: AxeResults) => {
this.setState(
{
status: 'ran',
passes,
violations,
incomplete,
},
() => {
setTimeout(() => {
const { status } = this.state;
if (status === 'ran') {
this.setState({
status: 'ready',
});
}
}, 900);
}
);
};
onError = (error: unknown) => {
this.setState({
status: 'error',
error,
});
};
request = () => {
const { api, active } = this.props;
if (active) {
this.setState(
{
status: 'running',
},
() => {
api.emit(EVENTS.REQUEST);
// removes all elements from the redux map in store from the previous panel
store.dispatch(clearElements());
}
);
}
};
render() {
const { active } = this.props;
if (!active) return null;
// eslint-disable-next-line react/destructuring-assignment
if (this.state.status === 'error') {
const { error } = this.state;
return (
<div style={centeredStyle}>
The accessibility scan encountered an error.
<br />
{error}
</div>
);
}
const { passes, violations, incomplete, status } = this.state;
let actionTitle;
if (status === 'ready') {
actionTitle = 'Rerun tests';
} else if (status === 'running') {
actionTitle = (
<Fragment>
<Icon inline icon="sync" status={status} /> Running test
</Fragment>
);
} else if (status === 'ran') {
actionTitle = (
<Fragment>
<Icon inline icon="check" /> Tests completed
</Fragment>
);
}
return (
<Fragment>
<Provider store={store}>
{status === 'running' ? (
<Loader />
) : (
<ScrollArea vertical horizontal>
<Tabs
key="tabs"
tabs={[
{
label: <Violations>{violations.length} Violations</Violations>,
panel: (
<Report
items={violations}
type={RuleType.VIOLATION}
empty="No accessibility violations found."
/>
),
items: violations,
type: RuleType.VIOLATION,
},
{
label: <Passes>{passes.length} Passes</Passes>,
panel: (
<Report
items={passes}
type={RuleType.PASS}
empty="No accessibility checks passed."
/>
),
items: passes,
type: RuleType.PASS,
},
{
label: <Incomplete>{incomplete.length} Incomplete</Incomplete>,
panel: (
<Report
items={incomplete}
type={RuleType.INCOMPLETION}
empty="No accessibility checks incomplete."
/>
),
items: incomplete,
type: RuleType.INCOMPLETION,
},
]}
/>
</ScrollArea>
)}
<ActionBar
key="actionbar"
actionItems={[{ title: actionTitle, onClick: this.request }]}
/>
</Provider>
</Fragment>
);
}
}
| addons/a11y/src/components/A11YPanel.tsx | 0 | https://github.com/storybookjs/storybook/commit/064f52c2c3aa3ad5ca3d614052cdb162f74ee580 | [
0.00021647385437972844,
0.00017143685545306653,
0.00016729600611142814,
0.00016929666162468493,
0.000009245834007742815
] |
{
"id": 1,
"code_window": [
" }\n",
"\n",
" return [];\n",
"};\n",
"\n",
"/**\n",
" * Parse an addon into either a managerEntry or a preset. Throw on invalid input.\n",
" *\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"const isLocalFileImport = packageName => /^[./]/.test(packageName);\n",
"\n"
],
"file_path": "lib/core/src/server/presets.js",
"type": "add",
"edit_start_line_idx": 40
} | # Storybook Storysource Addon
This addon is used to show stories source in the addon panel.
[Framework Support](https://github.com/storybookjs/storybook/blob/master/ADDONS_SUPPORT.md)

## Getting Started
First, install the addon
```sh
yarn add @storybook/addon-storysource --dev
```
You can add configuration for this addon by using a preset or by using the addon config with webpack
### Install using preset
Add the following to your `.storybook/main.js` exports:
```js
module.exports = {
addons: ['@storybook/addon-storysource'],
};
```
You can pass configurations into the addon-storysource loader in your `.storybook/main.js` file, e.g.:
```js
module.exports = {
addons: [
{
name: '@storybook/addon-storysource',
options: {
rule: {
// test: [/\.stories\.jsx?$/], This is default
include: [path.resolve(__dirname, '../src')], // You can specify directories
},
loaderOptions: {
prettierConfig: { printWidth: 80, singleQuote: false },
},
},
},
],
};
```
## Loader Options
The loader can be customized with the following options:
### parser
The parser that will be parsing your code to AST (based on [prettier](https://github.com/prettier/prettier/tree/master/src/language-js))
Allowed values:
- `javascript` - default
- `typescript`
- `flow`
Be sure to update the regex test for the webpack rule if utilizing Typescript files.
Usage:
```js
module.exports = function({ config }) {
config.module.rules.push({
test: /\.stories\.tsx?$/,
loaders: [
{
loader: require.resolve('@storybook/source-loader'),
options: { parser: 'typescript' },
},
],
enforce: 'pre',
});
return config;
};
```
### prettierConfig
The prettier configuration that will be used to format the story source in the addon panel.
Defaults:
```js
{
printWidth: 100,
tabWidth: 2,
bracketSpacing: true,
trailingComma: 'es5',
singleQuote: true,
}
```
Usage:
```js
module.exports = function({ config }) {
config.module.rules.push({
test: /\.stories\.jsx?$/,
loaders: [
{
loader: require.resolve('@storybook/source-loader'),
options: {
prettierConfig: {
printWidth: 100,
singleQuote: false,
},
},
},
],
enforce: 'pre',
});
return config;
};
```
### uglyCommentsRegex
The array of regex that is used to remove "ugly" comments.
Defaults:
```js
[/^eslint-.*/, /^global.*/];
```
Usage:
```js
module.exports = function({ config }) {
config.module.rules.push({
test: /\.stories\.jsx?$/,
loaders: [
{
loader: require.resolve('@storybook/source-loader'),
options: {
uglyCommentsRegex: [/^eslint-.*/, /^global.*/],
},
},
],
enforce: 'pre',
});
return config;
};
```
### injectDecorator
Tell storysource whether you need inject decorator. If false, you need to add the decorator by yourself;
Defaults: true
Usage:
```js
module.exports = function({ config }) {
config.module.rules.push({
test: /\.stories\.jsx?$/,
loaders: [
{
loader: require.resolve('@storybook/source-loader'),
options: { injectDecorator: false },
},
],
enforce: 'pre',
});
return config;
};
```
## Theming
Storysource will automatically use the light or dark syntax theme based on your storybook theme. See [Theming Storybook](https://storybook.js.org/docs/configurations/theming/) for more information.

| addons/storysource/README.md | 0 | https://github.com/storybookjs/storybook/commit/064f52c2c3aa3ad5ca3d614052cdb162f74ee580 | [
0.00023890793090686202,
0.000177128313225694,
0.00016628562298137695,
0.000170409373822622,
0.00001605321085662581
] |
{
"id": 1,
"code_window": [
" }\n",
"\n",
" return [];\n",
"};\n",
"\n",
"/**\n",
" * Parse an addon into either a managerEntry or a preset. Throw on invalid input.\n",
" *\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
"const isLocalFileImport = packageName => /^[./]/.test(packageName);\n",
"\n"
],
"file_path": "lib/core/src/server/presets.js",
"type": "add",
"edit_start_line_idx": 40
} | storybook.js.org
| docs/static/CNAME | 0 | https://github.com/storybookjs/storybook/commit/064f52c2c3aa3ad5ca3d614052cdb162f74ee580 | [
0.00016904300719033927,
0.00016904300719033927,
0.00016904300719033927,
0.00016904300719033927,
0
] |
{
"id": 2,
"code_window": [
" * - { name: '@storybook/addon-docs(/preset)?', options: { ... } }\n",
" * => { type: 'presets', item: { name: '@storybook/addon-docs/preset', options } }\n",
" */\n",
"export const resolveAddonName = name => {\n",
" const { path } = parsePackageName(name);\n",
"\n",
" // when user provides full path, we don't need to do anything\n",
" if (path) {\n",
" return {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" let path;\n",
" if (isLocalFileImport(name)) {\n",
" path = name;\n",
" } else {\n",
" ({ path } = parsePackageName(name));\n",
" }\n"
],
"file_path": "lib/core/src/server/presets.js",
"type": "replace",
"edit_start_line_idx": 57
} | import dedent from 'ts-dedent';
import { join } from 'path';
import { logger } from '@storybook/node-logger';
import { resolveFile } from './utils/resolve-file';
const isObject = val => val != null && typeof val === 'object' && Array.isArray(val) === false;
const isFunction = val => typeof val === 'function';
// Copied out of parse-package-name
const RE_SCOPED = /^(@[^/]+\/[^/@]+)(?:\/([^@]+))?(?:@([\s\S]+))?/;
const RE_NORMAL = /^([^/@]+)(?:\/([^@]+))?(?:@([\s\S]+))?/;
function parsePackageName(input) {
if (typeof input !== 'string') {
throw new TypeError('Expected a string');
}
const matched = input.charAt(0) === '@' ? input.match(RE_SCOPED) : input.match(RE_NORMAL);
if (!matched) {
throw new Error(`[parse-package-name] "${input}" is not a valid string`);
}
return {
name: matched[1],
path: matched[2] || '',
version: matched[3] || '',
};
}
const resolvePresetFunction = (input, presetOptions, storybookOptions) => {
if (isFunction(input)) {
return input({ ...storybookOptions, ...presetOptions });
}
if (Array.isArray(input)) {
return input;
}
return [];
};
/**
* Parse an addon into either a managerEntry or a preset. Throw on invalid input.
*
* Valid inputs:
* - '@storybook/addon-actions/register'
* => { type: 'managerEntries', item }
*
* - '@storybook/addon-docs/preset'
* => { type: 'presets', item }
*
* - '@storybook/addon-docs'
* => { type: 'presets', item: '@storybook/addon-docs/preset' }
*
* - { name: '@storybook/addon-docs(/preset)?', options: { ... } }
* => { type: 'presets', item: { name: '@storybook/addon-docs/preset', options } }
*/
export const resolveAddonName = name => {
const { path } = parsePackageName(name);
// when user provides full path, we don't need to do anything
if (path) {
return {
name,
// Accept `register`, `register.js`, `require.resolve('foo/register') cases
type: path.match(/register(.js)?$/) ? 'managerEntries' : 'presets',
};
}
try {
return {
name: resolveFile(join(name, 'preset')),
type: 'presets',
};
// eslint-disable-next-line no-empty
} catch (err) {}
try {
return {
name: resolveFile(join(name, 'register')),
type: 'managerEntries',
};
// eslint-disable-next-line no-empty
} catch (err) {}
return { name, type: 'presets' };
};
export const splitAddons = addons => {
return addons.reduce(
(acc, item) => {
try {
if (isObject(item)) {
const { name } = resolveAddonName(item.name);
acc.presets.push({ ...item, name });
} else {
const { name, type } = resolveAddonName(item);
acc[type].push(name);
}
} catch (err) {
logger.error(
`Addon value should end in /register OR it should be a valid preset https://storybook.js.org/docs/presets/introduction/\n${item}`
);
}
return acc;
},
{
managerEntries: [],
presets: [],
}
);
};
function interopRequireDefault(filePath) {
// eslint-disable-next-line global-require,import/no-dynamic-require
const result = require(`${filePath}`);
const isES6DefaultExported =
typeof result === 'object' && result !== null && typeof result.default !== 'undefined';
return isES6DefaultExported ? result.default : result;
}
function loadPreset(input, level, storybookOptions) {
try {
const name = input.name ? input.name : input;
const presetOptions = input.options ? input.options : {};
const contents = interopRequireDefault(name);
if (Array.isArray(contents)) {
const subPresets = contents;
return loadPresets(subPresets, level + 1, storybookOptions);
}
if (isObject(contents)) {
const { addons: addonsInput, presets: presetsInput, ...rest } = contents;
const subPresets = resolvePresetFunction(presetsInput, presetOptions, storybookOptions);
const subAddons = resolvePresetFunction(addonsInput, presetOptions, storybookOptions);
const { managerEntries, presets } = splitAddons(subAddons);
return [
...loadPresets([...subPresets, ...presets], level + 1, storybookOptions),
{ name: `${name}_additionalManagerEntries`, preset: { managerEntries } },
{
name,
preset: rest,
options: presetOptions,
},
];
}
throw new Error(dedent`
${input} is not a valid preset
`);
} catch (e) {
const warning =
level > 0
? ` Failed to load preset: ${JSON.stringify(input)} on level ${level}`
: ` Failed to load preset: ${JSON.stringify(input)}`;
logger.warn(warning);
logger.error(e);
return [];
}
}
function loadPresets(presets, level, storybookOptions) {
if (!presets || !Array.isArray(presets) || !presets.length) {
return [];
}
if (!level) {
logger.info('=> Loading presets');
}
return presets.reduce((acc, preset) => {
const loaded = loadPreset(preset, level, storybookOptions);
return acc.concat(loaded);
}, []);
}
function applyPresets(presets, extension, config, args) {
const presetResult = new Promise(resolve => resolve(config));
if (!presets.length) {
return presetResult;
}
return presets.reduce((accumulationPromise, { preset, options }) => {
const change = preset[extension];
if (!change) {
return accumulationPromise;
}
if (typeof change === 'function') {
const extensionFn = change;
const context = {
extensionFn,
preset,
combinedOptions: { ...args, ...options, presetsList: presets },
};
return accumulationPromise.then(newConfig =>
context.extensionFn.call(context.preset, newConfig, context.combinedOptions)
);
}
return accumulationPromise.then(newConfig => {
if (Array.isArray(newConfig) && Array.isArray(change)) {
return [...newConfig, ...change];
}
if (isObject(newConfig) && isObject(change)) {
return { ...newConfig, ...change };
}
return change;
});
}, presetResult);
}
function getPresets(presets, storybookOptions) {
const loadedPresets = loadPresets(presets, 0, storybookOptions);
return {
apply: async (extension, config, args = {}) =>
applyPresets(loadedPresets, extension, config, args),
};
}
export default getPresets;
| lib/core/src/server/presets.js | 1 | https://github.com/storybookjs/storybook/commit/064f52c2c3aa3ad5ca3d614052cdb162f74ee580 | [
0.9992222785949707,
0.11928707361221313,
0.00016887964738998562,
0.00038059684447944164,
0.31195569038391113
] |
{
"id": 2,
"code_window": [
" * - { name: '@storybook/addon-docs(/preset)?', options: { ... } }\n",
" * => { type: 'presets', item: { name: '@storybook/addon-docs/preset', options } }\n",
" */\n",
"export const resolveAddonName = name => {\n",
" const { path } = parsePackageName(name);\n",
"\n",
" // when user provides full path, we don't need to do anything\n",
" if (path) {\n",
" return {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" let path;\n",
" if (isLocalFileImport(name)) {\n",
" path = name;\n",
" } else {\n",
" ({ path } = parsePackageName(name));\n",
" }\n"
],
"file_path": "lib/core/src/server/presets.js",
"type": "replace",
"edit_start_line_idx": 57
} | import {
getVersions,
retrievePackageJson,
writePackageJson,
getBabelDependencies,
installDependencies,
copyTemplate,
} from '../../lib/helpers';
export default async (npmOptions, { storyFormat = 'csf' }) => {
const [storybookVersion, linksVersion, actionsVersion, addonsVersion] = await getVersions(
npmOptions,
'@storybook/ember',
'@storybook/addon-links',
'@storybook/addon-actions',
'@storybook/addons'
);
copyTemplate(__dirname, storyFormat);
const packageJson = await retrievePackageJson();
packageJson.dependencies = packageJson.dependencies || {};
packageJson.devDependencies = packageJson.devDependencies || {};
packageJson.scripts = {
...packageJson.scripts,
...{
storybook: 'start-storybook -p 6006 -s dist',
'build-storybook': 'build-storybook -s dist',
},
};
writePackageJson(packageJson);
const babelDependencies = await getBabelDependencies(npmOptions, packageJson);
installDependencies({ ...npmOptions, packageJson }, [
`@storybook/ember@${storybookVersion}`,
`@storybook/addon-actions@${actionsVersion}`,
`@storybook/addon-links@${linksVersion}`,
`@storybook/addons@${addonsVersion}`,
...babelDependencies,
]);
};
| lib/cli/generators/EMBER/index.js | 0 | https://github.com/storybookjs/storybook/commit/064f52c2c3aa3ad5ca3d614052cdb162f74ee580 | [
0.004324236419051886,
0.001010088250041008,
0.00016903318464756012,
0.00018713016470428556,
0.0016571145970374346
] |
{
"id": 2,
"code_window": [
" * - { name: '@storybook/addon-docs(/preset)?', options: { ... } }\n",
" * => { type: 'presets', item: { name: '@storybook/addon-docs/preset', options } }\n",
" */\n",
"export const resolveAddonName = name => {\n",
" const { path } = parsePackageName(name);\n",
"\n",
" // when user provides full path, we don't need to do anything\n",
" if (path) {\n",
" return {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" let path;\n",
" if (isLocalFileImport(name)) {\n",
" path = name;\n",
" } else {\n",
" ({ path } = parsePackageName(name));\n",
" }\n"
],
"file_path": "lib/core/src/server/presets.js",
"type": "replace",
"edit_start_line_idx": 57
} | import {
retrievePackageJson,
getVersionedPackages,
writePackageJson,
getBabelDependencies,
installDependencies,
copyTemplate,
} from '../../lib/helpers';
export default async (npmOptions, { storyFormat = 'csf' }) => {
const packages = [
'@storybook/react',
'@storybook/addon-actions',
'@storybook/addon-links',
'@storybook/addons',
];
if (storyFormat === 'mdx') {
packages.push('@storybook/addon-docs');
}
const versionedPackages = await getVersionedPackages(npmOptions, ...packages);
copyTemplate(__dirname, storyFormat);
const packageJson = await retrievePackageJson();
packageJson.dependencies = packageJson.dependencies || {};
packageJson.devDependencies = packageJson.devDependencies || {};
packageJson.scripts = packageJson.scripts || {};
packageJson.scripts.storybook = 'start-storybook -p 6006';
packageJson.scripts['build-storybook'] = 'build-storybook';
writePackageJson(packageJson);
const babelDependencies = await getBabelDependencies(npmOptions, packageJson);
installDependencies({ ...npmOptions, packageJson }, [...versionedPackages, ...babelDependencies]);
};
| lib/cli/generators/WEBPACK_REACT/index.js | 0 | https://github.com/storybookjs/storybook/commit/064f52c2c3aa3ad5ca3d614052cdb162f74ee580 | [
0.0011986267054453492,
0.0004267391632311046,
0.00016878015594556928,
0.00016977483755908906,
0.00044564990093931556
] |
{
"id": 2,
"code_window": [
" * - { name: '@storybook/addon-docs(/preset)?', options: { ... } }\n",
" * => { type: 'presets', item: { name: '@storybook/addon-docs/preset', options } }\n",
" */\n",
"export const resolveAddonName = name => {\n",
" const { path } = parsePackageName(name);\n",
"\n",
" // when user provides full path, we don't need to do anything\n",
" if (path) {\n",
" return {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" let path;\n",
" if (isLocalFileImport(name)) {\n",
" path = name;\n",
" } else {\n",
" ({ path } = parsePackageName(name));\n",
" }\n"
],
"file_path": "lib/core/src/server/presets.js",
"type": "replace",
"edit_start_line_idx": 57
} | import { storiesOf, moduleMetadata } from '@storybook/angular';
import { withKnobs, text, object } from '@storybook/addon-knobs';
import { action } from '@storybook/addon-actions';
import { ChipsModule } from './chips.module';
import { ChipsGroupComponent } from './chips-group.component';
import { ChipComponent } from './chip.component';
storiesOf('Custom/Feature Module as Context with forRoot', module)
.addDecorator(withKnobs)
.addDecorator(
moduleMetadata({
imports: [ChipsModule.forRoot()],
})
)
.add(
'Component with self and dependencies declared in its feature module',
() => {
const props: { [K in keyof ChipsGroupComponent]?: any } = {
chips: object('Chips', [
{
id: 1,
text: 'Chip 1',
},
{
id: 2,
text: 'Chip 2',
},
]),
removeChipClick: action('Remove chip'),
removeAllChipsClick: action('Remove all chips clicked'),
};
return {
component: ChipsGroupComponent,
props,
};
},
{
notes: `This component includes a child component, a pipe, and a default provider, all which come from
the specified feature module.`,
}
)
.add('Component with default providers', () => {
const props: { [K in keyof ChipComponent]?: any } = {
displayText: text('Display Text', 'My Chip'),
removeClicked: action('Remove icon clicked'),
};
return {
component: ChipComponent,
props,
};
})
.add('Component with overridden provider', () => {
const props: { [K in keyof ChipComponent]?: any } = {
displayText: text('Display Text', 'My Chip'),
removeClicked: action('Remove icon clicked'),
};
return {
component: ChipComponent,
props,
};
});
| examples/angular-cli/src/stories/module-context/module-context-forRoot.stories.ts | 0 | https://github.com/storybookjs/storybook/commit/064f52c2c3aa3ad5ca3d614052cdb162f74ee580 | [
0.00017363748338539153,
0.00017112272325903177,
0.0001673176884651184,
0.00017116549133788794,
0.000002042177811745205
] |
{
"id": 3,
"code_window": [
" it('should split managerEntries that end in register', () => {\n",
" const addons = [\n",
" '@storybook/addon-actions/register',\n",
" 'storybook-addon-readme/register',\n",
" 'addon-foo/register.js',\n",
" ];\n",
" expect(splitAddons(addons)).toEqual({\n",
" managerEntries: addons,\n",
" presets: [],\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" './local-addon-relative/register',\n",
" '/local-addon-absolute/register',\n"
],
"file_path": "lib/core/src/server/presets.test.js",
"type": "add",
"edit_start_line_idx": 391
} | function wrapPreset(basePresets) {
return {
babel: async (config, args) => basePresets.apply('babel', config, args),
webpack: async (config, args) => basePresets.apply('webpack', config, args),
};
}
function mockPreset(name, mockPresetObject) {
jest.mock(name, () => mockPresetObject, { virtual: true });
}
jest.mock('@storybook/node-logger', () => ({
logger: {
info: jest.fn(),
warn: jest.fn(),
error: jest.fn(),
},
}));
jest.mock('./utils/resolve-file', () => ({
resolveFile: name => {
const KNOWN_FILES = [
'@storybook/addon-actions/register',
'@storybook/addon-knobs/register',
'@storybook/addon-docs/preset',
];
if (KNOWN_FILES.includes(name)) {
return name;
}
throw new Error(`Cannot find module '${name}'`);
},
}));
describe('presets', () => {
it('does not throw when there is no preset file', async () => {
const getPresets = require.requireActual('./presets').default;
let presets;
async function testPresets() {
presets = wrapPreset(getPresets());
await presets.webpack();
await presets.babel();
}
await expect(testPresets()).resolves.toBeUndefined();
expect(presets).toBeDefined();
});
it('does not throw when presets are empty', async () => {
const getPresets = require.requireActual('./presets').default;
const presets = wrapPreset(getPresets([]));
async function testPresets() {
await presets.webpack();
await presets.babel();
}
await expect(testPresets()).resolves.toBeUndefined();
});
it('does not throw when preset can not be loaded', async () => {
const getPresets = require.requireActual('./presets').default;
const presets = wrapPreset(getPresets(['preset-foo']));
async function testPresets() {
await presets.webpack();
await presets.babel();
}
await expect(testPresets()).resolves.toBeUndefined();
});
it('loads and applies presets when they are combined in another preset', async () => {
mockPreset('preset-foo', {
foo: exec => exec.concat('foo'),
});
mockPreset('preset-bar', {
foo: exec => exec.concat('bar'),
});
mockPreset('preset-got', [
'preset-dracarys',
{ name: 'preset-valar', options: { custom: 'morghulis' } },
]);
mockPreset('preset-dracarys', {
foo: exec => exec.concat('dracarys'),
});
mockPreset('preset-valar', {
foo: (exec, options) => exec.concat(`valar ${options.custom}`),
});
const getPresets = require.requireActual('./presets').default;
const presets = getPresets(['preset-foo', 'preset-got', 'preset-bar']);
const result = await presets.apply('foo', []);
expect(result).toEqual(['foo', 'dracarys', 'valar morghulis', 'bar']);
});
it('loads and applies presets when they are declared as a string', async () => {
const mockPresetFooExtendWebpack = jest.fn();
const mockPresetBarExtendBabel = jest.fn();
mockPreset('preset-foo', {
webpack: mockPresetFooExtendWebpack,
});
mockPreset('preset-bar', {
babel: mockPresetBarExtendBabel,
});
const getPresets = require.requireActual('./presets').default;
const presets = wrapPreset(getPresets(['preset-foo', 'preset-bar']));
async function testPresets() {
await presets.webpack();
await presets.babel();
}
await expect(testPresets()).resolves.toBeUndefined();
expect(mockPresetFooExtendWebpack).toHaveBeenCalled();
expect(mockPresetBarExtendBabel).toHaveBeenCalled();
});
it('loads and applies presets when they are declared as an object without props', async () => {
const mockPresetFooExtendWebpack = jest.fn();
const mockPresetBarExtendBabel = jest.fn();
mockPreset('preset-foo', {
webpack: mockPresetFooExtendWebpack,
});
mockPreset('preset-bar', {
babel: mockPresetBarExtendBabel,
});
const getPresets = require.requireActual('./presets').default;
const presets = wrapPreset(getPresets([{ name: 'preset-foo' }, { name: 'preset-bar' }]));
async function testPresets() {
await presets.webpack();
await presets.babel();
}
await expect(testPresets()).resolves.toBeUndefined();
expect(mockPresetFooExtendWebpack).toHaveBeenCalled();
expect(mockPresetBarExtendBabel).toHaveBeenCalled();
});
it('loads and applies presets when they are declared as an object with props', async () => {
const mockPresetFooExtendWebpack = jest.fn();
const mockPresetBarExtendBabel = jest.fn();
mockPreset('preset-foo', {
webpack: mockPresetFooExtendWebpack,
});
mockPreset('preset-bar', {
babel: mockPresetBarExtendBabel,
});
const getPresets = require.requireActual('./presets').default;
const presets = wrapPreset(
getPresets([
{ name: 'preset-foo', options: { foo: 1 } },
{ name: 'preset-bar', options: { bar: 'a' } },
])
);
async function testPresets() {
await presets.webpack({});
await presets.babel({});
}
await expect(testPresets()).resolves.toBeUndefined();
expect(mockPresetFooExtendWebpack).toHaveBeenCalledWith(expect.anything(), {
foo: 1,
presetsList: expect.anything(),
});
expect(mockPresetBarExtendBabel).toHaveBeenCalledWith(expect.anything(), {
bar: 'a',
presetsList: expect.anything(),
});
});
it('loads and applies presets when they are declared as a string and as an object', async () => {
const mockPresetFooExtendWebpack = jest.fn();
const mockPresetBarExtendBabel = jest.fn();
mockPreset('preset-foo', {
webpack: mockPresetFooExtendWebpack,
});
mockPreset('preset-bar', {
babel: mockPresetBarExtendBabel,
});
const getPresets = require.requireActual('./presets').default;
const presets = wrapPreset(
getPresets([
'preset-foo',
{
name: 'preset-bar',
options: {
bar: 'a',
},
},
])
);
async function testPresets() {
await presets.webpack({});
await presets.babel({});
}
await expect(testPresets()).resolves.toBeUndefined();
expect(mockPresetFooExtendWebpack).toHaveBeenCalled();
expect(mockPresetBarExtendBabel).toHaveBeenCalledWith(expect.anything(), {
bar: 'a',
presetsList: expect.arrayContaining([
expect.objectContaining({ name: 'preset-foo' }),
expect.objectContaining({ name: 'preset-bar' }),
]),
});
});
it('applies presets in chain', async () => {
const mockPresetFooExtendWebpack = jest.fn(() => ({}));
const mockPresetBarExtendWebpack = jest.fn(() => ({}));
mockPreset('preset-foo', {
webpack: mockPresetFooExtendWebpack,
});
mockPreset('preset-bar', {
webpack: mockPresetBarExtendWebpack,
});
const getPresets = require.requireActual('./presets').default;
const presets = wrapPreset(
getPresets([
'preset-foo',
{
name: 'preset-bar',
options: {
bar: 'a',
presetsList: expect.arrayContaining([
expect.objectContaining({ name: 'preset-foo' }),
expect.objectContaining({ name: 'preset-bar' }),
]),
},
},
])
);
async function testPresets() {
await presets.webpack();
await presets.babel();
}
await expect(testPresets()).resolves.toBeUndefined();
expect(mockPresetFooExtendWebpack).toHaveBeenCalled();
expect(mockPresetBarExtendWebpack).toHaveBeenCalledWith(expect.anything(), {
bar: 'a',
presetsList: expect.arrayContaining([
expect.objectContaining({ name: 'preset-foo' }),
expect.objectContaining({ name: 'preset-bar' }),
]),
});
});
it('allows for presets to export presets array', async () => {
const getPresets = require.requireActual('./presets').default;
const input = {};
const mockPresetBar = jest.fn(() => input);
mockPreset('preset-foo', {
presets: ['preset-bar'],
});
mockPreset('preset-bar', {
bar: mockPresetBar,
});
const presets = getPresets(['preset-foo']);
const output = await presets.apply('bar');
expect(mockPresetBar).toHaveBeenCalledWith(undefined, expect.any(Object));
expect(input).toBe(output);
});
it('allows for presets to export presets fn', async () => {
const getPresets = require.requireActual('./presets').default;
const input = {};
const storybookOptions = { a: 1 };
const presetOptions = { b: 2 };
const mockPresetBar = jest.fn(() => input);
const mockPresetFoo = jest.fn(() => ['preset-bar']);
mockPreset('preset-foo', {
presets: mockPresetFoo,
});
mockPreset('preset-bar', {
bar: mockPresetBar,
});
const presets = getPresets([{ name: 'preset-foo', options: { b: 2 } }], storybookOptions);
const output = await presets.apply('bar');
expect(mockPresetFoo).toHaveBeenCalledWith({ ...storybookOptions, ...presetOptions });
expect(mockPresetBar).toHaveBeenCalledWith(undefined, expect.any(Object));
expect(input).toBe(output);
});
afterEach(() => {
jest.resetModules();
});
});
describe('resolveAddonName', () => {
const { resolveAddonName } = require.requireActual('./presets');
it('should resolve packages with metadata (relative path)', () => {
expect(resolveAddonName('@storybook/addon-docs')).toEqual({
name: '@storybook/addon-docs/preset',
type: 'presets',
});
});
it('should resolve packages with metadata (absolute path)', () => {
expect(resolveAddonName('@storybook/addon-knobs')).toEqual({
name: '@storybook/addon-knobs/register',
type: 'managerEntries',
});
});
it('should resolve packages without metadata', () => {
expect(resolveAddonName('@storybook/preset-create-react-app')).toEqual({
name: '@storybook/preset-create-react-app',
type: 'presets',
});
});
it('should resolve managerEntries', () => {
expect(resolveAddonName('@storybook/addon-actions/register')).toEqual({
name: '@storybook/addon-actions/register',
type: 'managerEntries',
});
});
it('should resolve presets', () => {
expect(resolveAddonName('@storybook/addon-docs/preset')).toEqual({
name: '@storybook/addon-docs/preset',
type: 'presets',
});
});
it('should resolve preset packages', () => {
expect(resolveAddonName('@storybook/addon-essentials')).toEqual({
name: '@storybook/addon-essentials',
type: 'presets',
});
});
it('should error on invalid inputs', () => {
expect(() => resolveAddonName(null)).toThrow();
});
});
describe('splitAddons', () => {
const { splitAddons } = require.requireActual('./presets');
it('should split managerEntries that end in register', () => {
const addons = [
'@storybook/addon-actions/register',
'storybook-addon-readme/register',
'addon-foo/register.js',
];
expect(splitAddons(addons)).toEqual({
managerEntries: addons,
presets: [],
});
});
it('should split preset packages and package entries', () => {
const addons = [
'@storybook/addon-essentials',
'@storybook/addon-docs/presets',
'addon-bar/presets.js',
];
expect(splitAddons(addons)).toEqual({
managerEntries: [],
presets: addons,
});
});
it('should split preset objects', () => {
const addons = [
{ name: '@storybook/addon-essentials' },
{ name: '@storybook/addon-docs/presets', options: { configureJSX: true } },
];
expect(splitAddons(addons)).toEqual({
managerEntries: [],
presets: addons,
});
});
it('should skip invalid objects', () => {
const addons = [1, true, { foo: 'bar' }];
expect(splitAddons(addons)).toEqual({
managerEntries: [],
presets: [],
});
});
});
| lib/core/src/server/presets.test.js | 1 | https://github.com/storybookjs/storybook/commit/064f52c2c3aa3ad5ca3d614052cdb162f74ee580 | [
0.9970877766609192,
0.0884566381573677,
0.00016386482457164675,
0.0011686728103086352,
0.2700074315071106
] |
{
"id": 3,
"code_window": [
" it('should split managerEntries that end in register', () => {\n",
" const addons = [\n",
" '@storybook/addon-actions/register',\n",
" 'storybook-addon-readme/register',\n",
" 'addon-foo/register.js',\n",
" ];\n",
" expect(splitAddons(addons)).toEqual({\n",
" managerEntries: addons,\n",
" presets: [],\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" './local-addon-relative/register',\n",
" '/local-addon-absolute/register',\n"
],
"file_path": "lib/core/src/server/presets.test.js",
"type": "add",
"edit_start_line_idx": 391
} | {
"extends": "../../tsconfig.json",
"compilerOptions": {
"rootDir": "./src",
"types": ["webpack-env"]
},
"include": [
"src/**/*"
],
"exclude": [
"src/__tests__/**/*"
]
}
| addons/centered/tsconfig.json | 0 | https://github.com/storybookjs/storybook/commit/064f52c2c3aa3ad5ca3d614052cdb162f74ee580 | [
0.0001749340444803238,
0.0001748381764627993,
0.00017474232299719006,
0.0001748381764627993,
9.586074156686664e-8
] |
{
"id": 3,
"code_window": [
" it('should split managerEntries that end in register', () => {\n",
" const addons = [\n",
" '@storybook/addon-actions/register',\n",
" 'storybook-addon-readme/register',\n",
" 'addon-foo/register.js',\n",
" ];\n",
" expect(splitAddons(addons)).toEqual({\n",
" managerEntries: addons,\n",
" presets: [],\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" './local-addon-relative/register',\n",
" '/local-addon-absolute/register',\n"
],
"file_path": "lib/core/src/server/presets.test.js",
"type": "add",
"edit_start_line_idx": 391
} | import React from 'react';
import { Typeset } from './Typeset';
export default {
title: 'Docs/Typeset',
component: Typeset,
};
const fontSizes = ['12px', '14px', '16px', '20px', '24px', '32px', '40px', '48px'];
const fontWeight = 900;
const fontFamily = 'monospace';
export const withFontSizes = () => <Typeset fontSizes={fontSizes} />;
export const withFontWeight = () => <Typeset fontSizes={fontSizes} fontWeight={fontWeight} />;
export const withFontFamily = () => <Typeset fontSizes={fontSizes} fontFamily={fontFamily} />;
export const withWeightText = () => (
<Typeset fontSizes={fontSizes} fontWeight={fontWeight} sampleText="Heading" />
);
| lib/components/src/blocks/Typeset.stories.tsx | 0 | https://github.com/storybookjs/storybook/commit/064f52c2c3aa3ad5ca3d614052cdb162f74ee580 | [
0.00017938048404175788,
0.00017905302229337394,
0.00017872556054499,
0.00017905302229337394,
3.2746174838393927e-7
] |
{
"id": 3,
"code_window": [
" it('should split managerEntries that end in register', () => {\n",
" const addons = [\n",
" '@storybook/addon-actions/register',\n",
" 'storybook-addon-readme/register',\n",
" 'addon-foo/register.js',\n",
" ];\n",
" expect(splitAddons(addons)).toEqual({\n",
" managerEntries: addons,\n",
" presets: [],\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" './local-addon-relative/register',\n",
" '/local-addon-absolute/register',\n"
],
"file_path": "lib/core/src/server/presets.test.js",
"type": "add",
"edit_start_line_idx": 391
} | import packageJson from '../../package.json';
export default {
packageJson,
framework: 'rax',
frameworkPresets: [require.resolve('./framework-preset-rax.js')],
};
| app/rax/src/server/options.js | 0 | https://github.com/storybookjs/storybook/commit/064f52c2c3aa3ad5ca3d614052cdb162f74ee580 | [
0.0001720756699796766,
0.0001720756699796766,
0.0001720756699796766,
0.0001720756699796766,
0
] |
{
"id": 4,
"code_window": [
" const addons = [\n",
" '@storybook/addon-essentials',\n",
" '@storybook/addon-docs/presets',\n",
" 'addon-bar/presets.js',\n",
" ];\n",
" expect(splitAddons(addons)).toEqual({\n",
" managerEntries: [],\n",
" presets: addons,\n",
" });\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" './local-addon-relative/presets',\n",
" '/local-addon-absolute/presets',\n"
],
"file_path": "lib/core/src/server/presets.test.js",
"type": "add",
"edit_start_line_idx": 403
} | import dedent from 'ts-dedent';
import { join } from 'path';
import { logger } from '@storybook/node-logger';
import { resolveFile } from './utils/resolve-file';
const isObject = val => val != null && typeof val === 'object' && Array.isArray(val) === false;
const isFunction = val => typeof val === 'function';
// Copied out of parse-package-name
const RE_SCOPED = /^(@[^/]+\/[^/@]+)(?:\/([^@]+))?(?:@([\s\S]+))?/;
const RE_NORMAL = /^([^/@]+)(?:\/([^@]+))?(?:@([\s\S]+))?/;
function parsePackageName(input) {
if (typeof input !== 'string') {
throw new TypeError('Expected a string');
}
const matched = input.charAt(0) === '@' ? input.match(RE_SCOPED) : input.match(RE_NORMAL);
if (!matched) {
throw new Error(`[parse-package-name] "${input}" is not a valid string`);
}
return {
name: matched[1],
path: matched[2] || '',
version: matched[3] || '',
};
}
const resolvePresetFunction = (input, presetOptions, storybookOptions) => {
if (isFunction(input)) {
return input({ ...storybookOptions, ...presetOptions });
}
if (Array.isArray(input)) {
return input;
}
return [];
};
/**
* Parse an addon into either a managerEntry or a preset. Throw on invalid input.
*
* Valid inputs:
* - '@storybook/addon-actions/register'
* => { type: 'managerEntries', item }
*
* - '@storybook/addon-docs/preset'
* => { type: 'presets', item }
*
* - '@storybook/addon-docs'
* => { type: 'presets', item: '@storybook/addon-docs/preset' }
*
* - { name: '@storybook/addon-docs(/preset)?', options: { ... } }
* => { type: 'presets', item: { name: '@storybook/addon-docs/preset', options } }
*/
export const resolveAddonName = name => {
const { path } = parsePackageName(name);
// when user provides full path, we don't need to do anything
if (path) {
return {
name,
// Accept `register`, `register.js`, `require.resolve('foo/register') cases
type: path.match(/register(.js)?$/) ? 'managerEntries' : 'presets',
};
}
try {
return {
name: resolveFile(join(name, 'preset')),
type: 'presets',
};
// eslint-disable-next-line no-empty
} catch (err) {}
try {
return {
name: resolveFile(join(name, 'register')),
type: 'managerEntries',
};
// eslint-disable-next-line no-empty
} catch (err) {}
return { name, type: 'presets' };
};
export const splitAddons = addons => {
return addons.reduce(
(acc, item) => {
try {
if (isObject(item)) {
const { name } = resolveAddonName(item.name);
acc.presets.push({ ...item, name });
} else {
const { name, type } = resolveAddonName(item);
acc[type].push(name);
}
} catch (err) {
logger.error(
`Addon value should end in /register OR it should be a valid preset https://storybook.js.org/docs/presets/introduction/\n${item}`
);
}
return acc;
},
{
managerEntries: [],
presets: [],
}
);
};
function interopRequireDefault(filePath) {
// eslint-disable-next-line global-require,import/no-dynamic-require
const result = require(`${filePath}`);
const isES6DefaultExported =
typeof result === 'object' && result !== null && typeof result.default !== 'undefined';
return isES6DefaultExported ? result.default : result;
}
function loadPreset(input, level, storybookOptions) {
try {
const name = input.name ? input.name : input;
const presetOptions = input.options ? input.options : {};
const contents = interopRequireDefault(name);
if (Array.isArray(contents)) {
const subPresets = contents;
return loadPresets(subPresets, level + 1, storybookOptions);
}
if (isObject(contents)) {
const { addons: addonsInput, presets: presetsInput, ...rest } = contents;
const subPresets = resolvePresetFunction(presetsInput, presetOptions, storybookOptions);
const subAddons = resolvePresetFunction(addonsInput, presetOptions, storybookOptions);
const { managerEntries, presets } = splitAddons(subAddons);
return [
...loadPresets([...subPresets, ...presets], level + 1, storybookOptions),
{ name: `${name}_additionalManagerEntries`, preset: { managerEntries } },
{
name,
preset: rest,
options: presetOptions,
},
];
}
throw new Error(dedent`
${input} is not a valid preset
`);
} catch (e) {
const warning =
level > 0
? ` Failed to load preset: ${JSON.stringify(input)} on level ${level}`
: ` Failed to load preset: ${JSON.stringify(input)}`;
logger.warn(warning);
logger.error(e);
return [];
}
}
function loadPresets(presets, level, storybookOptions) {
if (!presets || !Array.isArray(presets) || !presets.length) {
return [];
}
if (!level) {
logger.info('=> Loading presets');
}
return presets.reduce((acc, preset) => {
const loaded = loadPreset(preset, level, storybookOptions);
return acc.concat(loaded);
}, []);
}
function applyPresets(presets, extension, config, args) {
const presetResult = new Promise(resolve => resolve(config));
if (!presets.length) {
return presetResult;
}
return presets.reduce((accumulationPromise, { preset, options }) => {
const change = preset[extension];
if (!change) {
return accumulationPromise;
}
if (typeof change === 'function') {
const extensionFn = change;
const context = {
extensionFn,
preset,
combinedOptions: { ...args, ...options, presetsList: presets },
};
return accumulationPromise.then(newConfig =>
context.extensionFn.call(context.preset, newConfig, context.combinedOptions)
);
}
return accumulationPromise.then(newConfig => {
if (Array.isArray(newConfig) && Array.isArray(change)) {
return [...newConfig, ...change];
}
if (isObject(newConfig) && isObject(change)) {
return { ...newConfig, ...change };
}
return change;
});
}, presetResult);
}
function getPresets(presets, storybookOptions) {
const loadedPresets = loadPresets(presets, 0, storybookOptions);
return {
apply: async (extension, config, args = {}) =>
applyPresets(loadedPresets, extension, config, args),
};
}
export default getPresets;
| lib/core/src/server/presets.js | 1 | https://github.com/storybookjs/storybook/commit/064f52c2c3aa3ad5ca3d614052cdb162f74ee580 | [
0.013189910911023617,
0.0012783919228240848,
0.00016513597802259028,
0.00026724417693912983,
0.0027040683198720217
] |
{
"id": 4,
"code_window": [
" const addons = [\n",
" '@storybook/addon-essentials',\n",
" '@storybook/addon-docs/presets',\n",
" 'addon-bar/presets.js',\n",
" ];\n",
" expect(splitAddons(addons)).toEqual({\n",
" managerEntries: [],\n",
" presets: addons,\n",
" });\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" './local-addon-relative/presets',\n",
" '/local-addon-absolute/presets',\n"
],
"file_path": "lib/core/src/server/presets.test.js",
"type": "add",
"edit_start_line_idx": 403
} | import { buildStatic } from '@storybook/core/server';
import options from './options';
buildStatic(options);
| app/svelte/src/server/build.ts | 0 | https://github.com/storybookjs/storybook/commit/064f52c2c3aa3ad5ca3d614052cdb162f74ee580 | [
0.00017049357120413333,
0.00017049357120413333,
0.00017049357120413333,
0.00017049357120413333,
0
] |
{
"id": 4,
"code_window": [
" const addons = [\n",
" '@storybook/addon-essentials',\n",
" '@storybook/addon-docs/presets',\n",
" 'addon-bar/presets.js',\n",
" ];\n",
" expect(splitAddons(addons)).toEqual({\n",
" managerEntries: [],\n",
" presets: addons,\n",
" });\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" './local-addon-relative/presets',\n",
" '/local-addon-absolute/presets',\n"
],
"file_path": "lib/core/src/server/presets.test.js",
"type": "add",
"edit_start_line_idx": 403
} | module.exports = require('../dist/frameworks/common/index');
| addons/docs/vue/index.js | 0 | https://github.com/storybookjs/storybook/commit/064f52c2c3aa3ad5ca3d614052cdb162f74ee580 | [
0.00017342866340186447,
0.00017342866340186447,
0.00017342866340186447,
0.00017342866340186447,
0
] |
{
"id": 4,
"code_window": [
" const addons = [\n",
" '@storybook/addon-essentials',\n",
" '@storybook/addon-docs/presets',\n",
" 'addon-bar/presets.js',\n",
" ];\n",
" expect(splitAddons(addons)).toEqual({\n",
" managerEntries: [],\n",
" presets: addons,\n",
" });\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" './local-addon-relative/presets',\n",
" '/local-addon-absolute/presets',\n"
],
"file_path": "lib/core/src/server/presets.test.js",
"type": "add",
"edit_start_line_idx": 403
} | import React, { Component } from 'react';
import PropTypes from 'prop-types';
export default class DelayedRender extends Component {
static propTypes = {
children: PropTypes.node.isRequired,
};
state = {
show: false,
};
componentDidMount() {
this.showTO = setTimeout(() => {
this.setState({
show: true,
});
}, 1000);
}
componentWillUnmount() {
clearTimeout(this.showTO);
}
render() {
const { show } = this.state;
const { children } = this.props;
return show ? children : <div />;
}
}
| examples/official-storybook/components/DelayedRender.js | 0 | https://github.com/storybookjs/storybook/commit/064f52c2c3aa3ad5ca3d614052cdb162f74ee580 | [
0.00017909743473865092,
0.0001780987367965281,
0.00017760740593075752,
0.00017784508236218244,
5.865887260370073e-7
] |
{
"id": 0,
"code_window": [
" const response = new Response(this._client, request, redirectStatus, redirectHeaders, fromDiskCache, fromServiceWorker, securityDetails);\n",
" request._response = response;\n",
" request._redirectChain.push(request);\n",
" this._requestIdToRequest.delete(request._requestId);\n",
" this._interceptionIdToRequest.delete(request._interceptionId);\n",
" this._attemptedAuthentications.delete(request._interceptionId);\n",
" this.emit(NetworkManager.Events.Response, response);\n",
" this.emit(NetworkManager.Events.RequestFinished, request);\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" response._bodyLoadedPromiseFulfill.call(null, new Error('Response body is unavailable for redirect responses'));\n"
],
"file_path": "lib/NetworkManager.js",
"type": "add",
"edit_start_line_idx": 193
} | /**
* Copyright 2017 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
const EventEmitter = require('events');
const {helper, debugError} = require('./helper');
const Multimap = require('./Multimap');
class NetworkManager extends EventEmitter {
/**
* @param {!Puppeteer.CDPSession} client
* @param {!Puppeteer.FrameManager} frameManager
*/
constructor(client, frameManager) {
super();
this._client = client;
this._frameManager = frameManager;
/** @type {!Map<string, !Request>} */
this._requestIdToRequest = new Map();
/** @type {!Map<string, !Request>} */
this._interceptionIdToRequest = new Map();
/** @type {!Object<string, string>} */
this._extraHTTPHeaders = {};
this._offline = false;
/** @type {?{username: string, password: string}} */
this._credentials = null;
/** @type {!Set<string>} */
this._attemptedAuthentications = new Set();
this._userRequestInterceptionEnabled = false;
this._protocolRequestInterceptionEnabled = false;
/** @type {!Multimap} */
this._requestHashToRequestIds = new Multimap();
/** @type {!Multimap} */
this._requestHashToInterceptionIds = new Multimap();
this._client.on('Network.requestWillBeSent', this._onRequestWillBeSent.bind(this));
this._client.on('Network.requestIntercepted', this._onRequestIntercepted.bind(this));
this._client.on('Network.requestServedFromCache', this._onRequestServedFromCache.bind(this));
this._client.on('Network.responseReceived', this._onResponseReceived.bind(this));
this._client.on('Network.loadingFinished', this._onLoadingFinished.bind(this));
this._client.on('Network.loadingFailed', this._onLoadingFailed.bind(this));
}
/**
* @param {?{username: string, password: string}} credentials
*/
async authenticate(credentials) {
this._credentials = credentials;
await this._updateProtocolRequestInterception();
}
/**
* @param {!Object<string, string>} extraHTTPHeaders
*/
async setExtraHTTPHeaders(extraHTTPHeaders) {
this._extraHTTPHeaders = {};
for (const key of Object.keys(extraHTTPHeaders)) {
const value = extraHTTPHeaders[key];
console.assert(helper.isString(value), `Expected value of header "${key}" to be String, but "${typeof value}" is found.`);
this._extraHTTPHeaders[key.toLowerCase()] = value;
}
await this._client.send('Network.setExtraHTTPHeaders', { headers: this._extraHTTPHeaders });
}
/**
* @return {!Object<string, string>}
*/
extraHTTPHeaders() {
return Object.assign({}, this._extraHTTPHeaders);
}
/**
* @param {boolean} value
*/
async setOfflineMode(value) {
if (this._offline === value)
return;
this._offline = value;
await this._client.send('Network.emulateNetworkConditions', {
offline: this._offline,
// values of 0 remove any active throttling. crbug.com/456324#c9
latency: 0,
downloadThroughput: -1,
uploadThroughput: -1
});
}
/**
* @param {string} userAgent
*/
async setUserAgent(userAgent) {
await this._client.send('Network.setUserAgentOverride', { userAgent });
}
/**
* @param {boolean} value
*/
async setRequestInterception(value) {
this._userRequestInterceptionEnabled = value;
await this._updateProtocolRequestInterception();
}
async _updateProtocolRequestInterception() {
const enabled = this._userRequestInterceptionEnabled || !!this._credentials;
if (enabled === this._protocolRequestInterceptionEnabled)
return;
this._protocolRequestInterceptionEnabled = enabled;
const patterns = enabled ? [{urlPattern: '*'}] : [];
await Promise.all([
this._client.send('Network.setCacheDisabled', {cacheDisabled: enabled}),
this._client.send('Network.setRequestInterception', {patterns})
]);
}
/**
* @param {!Protocol.Network.requestInterceptedPayload} event
*/
_onRequestIntercepted(event) {
if (event.authChallenge) {
/** @type {"Default"|"CancelAuth"|"ProvideCredentials"} */
let response = 'Default';
if (this._attemptedAuthentications.has(event.interceptionId)) {
response = 'CancelAuth';
} else if (this._credentials) {
response = 'ProvideCredentials';
this._attemptedAuthentications.add(event.interceptionId);
}
const {username, password} = this._credentials || {username: undefined, password: undefined};
this._client.send('Network.continueInterceptedRequest', {
interceptionId: event.interceptionId,
authChallengeResponse: { response, username, password }
}).catch(debugError);
return;
}
if (!this._userRequestInterceptionEnabled && this._protocolRequestInterceptionEnabled) {
this._client.send('Network.continueInterceptedRequest', {
interceptionId: event.interceptionId
}).catch(debugError);
}
if (event.redirectUrl) {
const request = this._interceptionIdToRequest.get(event.interceptionId);
if (request) {
this._handleRequestRedirect(request, event.responseStatusCode, event.responseHeaders, false /* fromDiskCache */, false /* fromServiceWorker */, null /* securityDetails */);
this._handleRequestStart(request._requestId, event.interceptionId, event.redirectUrl, event.resourceType, event.request, event.frameId, request._redirectChain);
}
return;
}
const requestHash = generateRequestHash(event.request);
const requestId = this._requestHashToRequestIds.firstValue(requestHash);
if (requestId) {
this._requestHashToRequestIds.delete(requestHash, requestId);
this._handleRequestStart(requestId, event.interceptionId, event.request.url, event.resourceType, event.request, event.frameId, []);
} else {
this._requestHashToInterceptionIds.set(requestHash, event.interceptionId);
this._handleRequestStart(null, event.interceptionId, event.request.url, event.resourceType, event.request, event.frameId, []);
}
}
/**
* @param {!Protocol.Network.requestServedFromCachePayload} event
*/
_onRequestServedFromCache(event) {
const request = this._requestIdToRequest.get(event.requestId);
if (request)
request._fromMemoryCache = true;
}
/**
* @param {!Request} request
* @param {number} redirectStatus
* @param {!Object} redirectHeaders
* @param {boolean} fromDiskCache
* @param {boolean} fromServiceWorker
* @param {?Object} securityDetails
*/
_handleRequestRedirect(request, redirectStatus, redirectHeaders, fromDiskCache, fromServiceWorker, securityDetails) {
const response = new Response(this._client, request, redirectStatus, redirectHeaders, fromDiskCache, fromServiceWorker, securityDetails);
request._response = response;
request._redirectChain.push(request);
this._requestIdToRequest.delete(request._requestId);
this._interceptionIdToRequest.delete(request._interceptionId);
this._attemptedAuthentications.delete(request._interceptionId);
this.emit(NetworkManager.Events.Response, response);
this.emit(NetworkManager.Events.RequestFinished, request);
}
/**
* @param {?string} requestId
* @param {?string} interceptionId
* @param {string} url
* @param {string} resourceType
* @param {!Protocol.Network.Request} requestPayload
* @param {?string} frameId
* @param {!Array<!Request>} redirectChain
*/
_handleRequestStart(requestId, interceptionId, url, resourceType, requestPayload, frameId, redirectChain) {
let frame = null;
if (frameId)
frame = this._frameManager.frame(frameId);
const request = new Request(this._client, requestId, interceptionId, this._userRequestInterceptionEnabled, url, resourceType, requestPayload, frame, redirectChain);
if (requestId)
this._requestIdToRequest.set(requestId, request);
if (interceptionId)
this._interceptionIdToRequest.set(interceptionId, request);
this.emit(NetworkManager.Events.Request, request);
}
/**
* @param {!Protocol.Network.requestWillBeSentPayload} event
*/
_onRequestWillBeSent(event) {
if (this._protocolRequestInterceptionEnabled) {
// All redirects are handled in requestIntercepted.
if (event.redirectResponse)
return;
const requestHash = generateRequestHash(event.request);
const interceptionId = this._requestHashToInterceptionIds.firstValue(requestHash);
const request = interceptionId ? this._interceptionIdToRequest.get(interceptionId) : null;
if (request) {
request._requestId = event.requestId;
this._requestIdToRequest.set(event.requestId, request);
this._requestHashToInterceptionIds.delete(requestHash, interceptionId);
} else {
this._requestHashToRequestIds.set(requestHash, event.requestId);
}
return;
}
let redirectChain = [];
if (event.redirectResponse) {
const request = this._requestIdToRequest.get(event.requestId);
// If we connect late to the target, we could have missed the requestWillBeSent event.
if (request) {
this._handleRequestRedirect(request, event.redirectResponse.status, event.redirectResponse.headers, event.redirectResponse.fromDiskCache, event.redirectResponse.fromServiceWorker, event.redirectResponse.securityDetails);
redirectChain = request._redirectChain;
}
}
this._handleRequestStart(event.requestId, null, event.request.url, event.type, event.request, event.frameId, redirectChain);
}
/**
* @param {!Protocol.Network.responseReceivedPayload} event
*/
_onResponseReceived(event) {
const request = this._requestIdToRequest.get(event.requestId);
// FileUpload sends a response without a matching request.
if (!request)
return;
const response = new Response(this._client, request, event.response.status, event.response.headers,
event.response.fromDiskCache, event.response.fromServiceWorker, event.response.securityDetails);
request._response = response;
this.emit(NetworkManager.Events.Response, response);
}
/**
* @param {!Protocol.Network.loadingFinishedPayload} event
*/
_onLoadingFinished(event) {
const request = this._requestIdToRequest.get(event.requestId);
// For certain requestIds we never receive requestWillBeSent event.
// @see https://crbug.com/750469
if (!request)
return;
request._completePromiseFulfill.call(null);
this._requestIdToRequest.delete(request._requestId);
this._interceptionIdToRequest.delete(request._interceptionId);
this._attemptedAuthentications.delete(request._interceptionId);
this.emit(NetworkManager.Events.RequestFinished, request);
}
/**
* @param {!Protocol.Network.loadingFailedPayload} event
*/
_onLoadingFailed(event) {
const request = this._requestIdToRequest.get(event.requestId);
// For certain requestIds we never receive requestWillBeSent event.
// @see https://crbug.com/750469
if (!request)
return;
request._failureText = event.errorText;
request._completePromiseFulfill.call(null);
this._requestIdToRequest.delete(request._requestId);
this._interceptionIdToRequest.delete(request._interceptionId);
this._attemptedAuthentications.delete(request._interceptionId);
this.emit(NetworkManager.Events.RequestFailed, request);
}
}
class Request {
/**
* @param {!Puppeteer.CDPSession} client
* @param {?string} requestId
* @param {string} interceptionId
* @param {boolean} allowInterception
* @param {string} url
* @param {string} resourceType
* @param {!Protocol.Network.Request} payload
* @param {?Puppeteer.Frame} frame
* @param {!Array<!Request>} redirectChain
*/
constructor(client, requestId, interceptionId, allowInterception, url, resourceType, payload, frame, redirectChain) {
this._client = client;
this._requestId = requestId;
this._interceptionId = interceptionId;
this._allowInterception = allowInterception;
this._interceptionHandled = false;
this._response = null;
this._failureText = null;
this._completePromise = new Promise(fulfill => {
this._completePromiseFulfill = fulfill;
});
this._url = url;
this._resourceType = resourceType.toLowerCase();
this._method = payload.method;
this._postData = payload.postData;
this._headers = {};
this._frame = frame;
this._redirectChain = redirectChain;
for (const key of Object.keys(payload.headers))
this._headers[key.toLowerCase()] = payload.headers[key];
this._fromMemoryCache = false;
}
/**
* @return {string}
*/
url() {
return this._url;
}
/**
* @return {string}
*/
resourceType() {
return this._resourceType;
}
/**
* @return {string}
*/
method() {
return this._method;
}
/**
* @return {string}
*/
postData() {
return this._postData;
}
/**
* @return {!Object}
*/
headers() {
return this._headers;
}
/**
* @return {?Response}
*/
response() {
return this._response;
}
/**
* @return {?Puppeteer.Frame}
*/
frame() {
return this._frame;
}
/**
* @return {!Array<!Request>}
*/
redirectChain() {
return this._redirectChain.slice();
}
/**
* @return {?{errorText: string}}
*/
failure() {
if (!this._failureText)
return null;
return {
errorText: this._failureText
};
}
/**
* @param {!Object=} overrides
*/
async continue(overrides = {}) {
console.assert(this._allowInterception, 'Request Interception is not enabled!');
console.assert(!this._interceptionHandled, 'Request is already handled!');
this._interceptionHandled = true;
await this._client.send('Network.continueInterceptedRequest', {
interceptionId: this._interceptionId,
url: overrides.url,
method: overrides.method,
postData: overrides.postData,
headers: overrides.headers,
}).catch(error => {
// In certain cases, protocol will return error if the request was already canceled
// or the page was closed. We should tolerate these errors.
debugError(error);
});
}
/**
* @param {!{status: number, headers: Object, contentType: string, body: (string|Buffer)}} response
*/
async respond(response) {
// Mocking responses for dataURL requests is not currently supported.
if (this._url.startsWith('data:'))
return;
console.assert(this._allowInterception, 'Request Interception is not enabled!');
console.assert(!this._interceptionHandled, 'Request is already handled!');
this._interceptionHandled = true;
const responseBody = response.body && helper.isString(response.body) ? Buffer.from(/** @type {string} */(response.body)) : /** @type {?Buffer} */(response.body || null);
const responseHeaders = {};
if (response.headers) {
for (const header of Object.keys(response.headers))
responseHeaders[header.toLowerCase()] = response.headers[header];
}
if (response.contentType)
responseHeaders['content-type'] = response.contentType;
if (responseBody && !('content-length' in responseHeaders)) {
// @ts-ignore
responseHeaders['content-length'] = Buffer.byteLength(responseBody);
}
const statusCode = response.status || 200;
const statusText = statusTexts[statusCode] || '';
const statusLine = `HTTP/1.1 ${statusCode} ${statusText}`;
const CRLF = '\r\n';
let text = statusLine + CRLF;
for (const header of Object.keys(responseHeaders))
text += header + ': ' + responseHeaders[header] + CRLF;
text += CRLF;
let responseBuffer = Buffer.from(text, 'utf8');
if (responseBody)
responseBuffer = Buffer.concat([responseBuffer, responseBody]);
await this._client.send('Network.continueInterceptedRequest', {
interceptionId: this._interceptionId,
rawResponse: responseBuffer.toString('base64')
}).catch(error => {
// In certain cases, protocol will return error if the request was already canceled
// or the page was closed. We should tolerate these errors.
debugError(error);
});
}
/**
* @param {string=} errorCode
*/
async abort(errorCode = 'failed') {
const errorReason = errorReasons[errorCode];
console.assert(errorReason, 'Unknown error code: ' + errorCode);
console.assert(this._allowInterception, 'Request Interception is not enabled!');
console.assert(!this._interceptionHandled, 'Request is already handled!');
this._interceptionHandled = true;
await this._client.send('Network.continueInterceptedRequest', {
interceptionId: this._interceptionId,
errorReason
}).catch(error => {
// In certain cases, protocol will return error if the request was already canceled
// or the page was closed. We should tolerate these errors.
debugError(error);
});
}
}
const errorReasons = {
'aborted': 'Aborted',
'accessdenied': 'AccessDenied',
'addressunreachable': 'AddressUnreachable',
'connectionaborted': 'ConnectionAborted',
'connectionclosed': 'ConnectionClosed',
'connectionfailed': 'ConnectionFailed',
'connectionrefused': 'ConnectionRefused',
'connectionreset': 'ConnectionReset',
'internetdisconnected': 'InternetDisconnected',
'namenotresolved': 'NameNotResolved',
'timedout': 'TimedOut',
'failed': 'Failed',
};
helper.tracePublicAPI(Request);
class Response {
/**
* @param {!Puppeteer.CDPSession} client
* @param {!Request} request
* @param {number} status
* @param {!Object} headers
* @param {boolean} fromDiskCache
* @param {boolean} fromServiceWorker
* @param {?Object} securityDetails
*/
constructor(client, request, status, headers, fromDiskCache, fromServiceWorker, securityDetails) {
this._client = client;
this._request = request;
this._contentPromise = null;
this._status = status;
this._url = request.url();
this._fromDiskCache = fromDiskCache;
this._fromServiceWorker = fromServiceWorker;
this._headers = {};
for (const key of Object.keys(headers))
this._headers[key.toLowerCase()] = headers[key];
this._securityDetails = null;
if (securityDetails) {
this._securityDetails = new SecurityDetails(
securityDetails['subjectName'],
securityDetails['issuer'],
securityDetails['validFrom'],
securityDetails['validTo'],
securityDetails['protocol']);
}
}
/**
* @return {string}
*/
url() {
return this._url;
}
/**
* @return {boolean}
*/
ok() {
return this._status === 0 || (this._status >= 200 && this._status <= 299);
}
/**
* @return {number}
*/
status() {
return this._status;
}
/**
* @return {!Object}
*/
headers() {
return this._headers;
}
/**
* @return {?SecurityDetails}
*/
securityDetails() {
return this._securityDetails;
}
/**
* @return {!Promise<!Buffer>}
*/
buffer() {
if (!this._contentPromise) {
this._contentPromise = this._request._completePromise.then(async() => {
const response = await this._client.send('Network.getResponseBody', {
requestId: this._request._requestId
});
return Buffer.from(response.body, response.base64Encoded ? 'base64' : 'utf8');
});
}
return this._contentPromise;
}
/**
* @return {!Promise<string>}
*/
async text() {
const content = await this.buffer();
return content.toString('utf8');
}
/**
* @return {!Promise<!Object>}
*/
async json() {
const content = await this.text();
return JSON.parse(content);
}
/**
* @return {!Request}
*/
request() {
return this._request;
}
/**
* @return {boolean}
*/
fromCache() {
return this._fromDiskCache || this._request._fromMemoryCache;
}
/**
* @return {boolean}
*/
fromServiceWorker() {
return this._fromServiceWorker;
}
}
helper.tracePublicAPI(Response);
/**
* @param {!Protocol.Network.Request} request
* @return {string}
*/
function generateRequestHash(request) {
let normalizedURL = request.url;
try {
// Decoding is necessary to normalize URLs. @see crbug.com/759388
// The method will throw if the URL is malformed. In this case,
// consider URL to be normalized as-is.
normalizedURL = decodeURI(request.url);
} catch (e) {
}
const hash = {
url: normalizedURL,
method: request.method,
postData: request.postData,
headers: {},
};
if (!normalizedURL.startsWith('data:')) {
const headers = Object.keys(request.headers);
headers.sort();
for (let header of headers) {
const headerValue = request.headers[header];
header = header.toLowerCase();
if (header === 'accept' || header === 'referer' || header === 'x-devtools-emulate-network-conditions-client-id')
continue;
hash.headers[header] = headerValue;
}
}
return JSON.stringify(hash);
}
class SecurityDetails {
/**
* @param {string} subjectName
* @param {string} issuer
* @param {number} validFrom
* @param {number} validTo
* @param {string} protocol
*/
constructor(subjectName, issuer, validFrom, validTo, protocol) {
this._subjectName = subjectName;
this._issuer = issuer;
this._validFrom = validFrom;
this._validTo = validTo;
this._protocol = protocol;
}
/**
* @return {string}
*/
subjectName() {
return this._subjectName;
}
/**
* @return {string}
*/
issuer() {
return this._issuer;
}
/**
* @return {number}
*/
validFrom() {
return this._validFrom;
}
/**
* @return {number}
*/
validTo() {
return this._validTo;
}
/**
* @return {string}
*/
protocol() {
return this._protocol;
}
}
NetworkManager.Events = {
Request: 'request',
Response: 'response',
RequestFailed: 'requestfailed',
RequestFinished: 'requestfinished',
};
const statusTexts = {
'100': 'Continue',
'101': 'Switching Protocols',
'102': 'Processing',
'200': 'OK',
'201': 'Created',
'202': 'Accepted',
'203': 'Non-Authoritative Information',
'204': 'No Content',
'206': 'Partial Content',
'207': 'Multi-Status',
'208': 'Already Reported',
'209': 'IM Used',
'300': 'Multiple Choices',
'301': 'Moved Permanently',
'302': 'Found',
'303': 'See Other',
'304': 'Not Modified',
'305': 'Use Proxy',
'306': 'Switch Proxy',
'307': 'Temporary Redirect',
'308': 'Permanent Redirect',
'400': 'Bad Request',
'401': 'Unauthorized',
'402': 'Payment Required',
'403': 'Forbidden',
'404': 'Not Found',
'405': 'Method Not Allowed',
'406': 'Not Acceptable',
'407': 'Proxy Authentication Required',
'408': 'Request Timeout',
'409': 'Conflict',
'410': 'Gone',
'411': 'Length Required',
'412': 'Precondition Failed',
'413': 'Payload Too Large',
'414': 'URI Too Long',
'415': 'Unsupported Media Type',
'416': 'Range Not Satisfiable',
'417': 'Expectation Failed',
'418': 'I\'m a teapot',
'421': 'Misdirected Request',
'422': 'Unprocessable Entity',
'423': 'Locked',
'424': 'Failed Dependency',
'426': 'Upgrade Required',
'428': 'Precondition Required',
'429': 'Too Many Requests',
'431': 'Request Header Fields Too Large',
'451': 'Unavailable For Legal Reasons',
'500': 'Internal Server Error',
'501': 'Not Implemented',
'502': 'Bad Gateway',
'503': 'Service Unavailable',
'504': 'Gateway Timeout',
'505': 'HTTP Version Not Supported',
'506': 'Variant Also Negotiates',
'507': 'Insufficient Storage',
'508': 'Loop Detected',
'510': 'Not Extended',
'511': 'Network Authentication Required',
};
module.exports = {Request, Response, NetworkManager};
| lib/NetworkManager.js | 1 | https://github.com/puppeteer/puppeteer/commit/f8cba455ba5d1bc82721e89fda037e86213b02cb | [
0.9986171722412109,
0.014413176104426384,
0.00016500172205269337,
0.00023990467889234424,
0.11079971492290497
] |
{
"id": 0,
"code_window": [
" const response = new Response(this._client, request, redirectStatus, redirectHeaders, fromDiskCache, fromServiceWorker, securityDetails);\n",
" request._response = response;\n",
" request._redirectChain.push(request);\n",
" this._requestIdToRequest.delete(request._requestId);\n",
" this._interceptionIdToRequest.delete(request._interceptionId);\n",
" this._attemptedAuthentications.delete(request._interceptionId);\n",
" this.emit(NetworkManager.Events.Response, response);\n",
" this.emit(NetworkManager.Events.RequestFinished, request);\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" response._bodyLoadedPromiseFulfill.call(null, new Error('Response body is unavailable for redirect responses'));\n"
],
"file_path": "lib/NetworkManager.js",
"type": "add",
"edit_start_line_idx": 193
} | /**
* Copyright 2017 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
const puppeteer = require('puppeteer');
const devices = require('puppeteer/DeviceDescriptors');
(async() => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.emulate(devices['iPhone 6']);
await page.goto('https://www.nytimes.com/');
await page.screenshot({path: 'full.png', fullPage: true});
await browser.close();
})();
| examples/screenshot-fullpage.js | 0 | https://github.com/puppeteer/puppeteer/commit/f8cba455ba5d1bc82721e89fda037e86213b02cb | [
0.00017642404418438673,
0.00017489663150627166,
0.00017392265726812184,
0.00017434325127396733,
0.0000010935941645584535
] |
{
"id": 0,
"code_window": [
" const response = new Response(this._client, request, redirectStatus, redirectHeaders, fromDiskCache, fromServiceWorker, securityDetails);\n",
" request._response = response;\n",
" request._redirectChain.push(request);\n",
" this._requestIdToRequest.delete(request._requestId);\n",
" this._interceptionIdToRequest.delete(request._interceptionId);\n",
" this._attemptedAuthentications.delete(request._interceptionId);\n",
" this.emit(NetworkManager.Events.Response, response);\n",
" this.emit(NetworkManager.Events.RequestFinished, request);\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" response._bodyLoadedPromiseFulfill.call(null, new Error('Response body is unavailable for redirect responses'));\n"
],
"file_path": "lib/NetworkManager.js",
"type": "add",
"edit_start_line_idx": 193
} | /**
* Copyright 2017 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @fileoverview Search developers.google.com/web for articles tagged
* "Headless Chrome" and scrape results from the results page.
*/
'use strict';
const puppeteer = require('puppeteer');
(async() => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.goto('https://developers.google.com/web/');
// Type into search box.
await page.type('#searchbox input', 'Headless Chrome');
// Wait for suggest overlay to appear and click "show all results".
const allResultsSelector = '.devsite-suggest-all-results';
await page.waitForSelector(allResultsSelector);
await page.click(allResultsSelector);
// Wait for the results page to load and display the results.
const resultsSelector = '.gsc-results .gsc-thumbnail-inside a.gs-title';
await page.waitForSelector(resultsSelector);
// Extract the results from the page.
const links = await page.evaluate(resultsSelector => {
const anchors = Array.from(document.querySelectorAll(resultsSelector));
return anchors.map(anchor => {
const title = anchor.textContent.split('|')[0].trim();
return `${title} - ${anchor.href}`;
});
}, resultsSelector);
console.log(links.join('\n'));
await browser.close();
})();
| examples/search.js | 0 | https://github.com/puppeteer/puppeteer/commit/f8cba455ba5d1bc82721e89fda037e86213b02cb | [
0.00017696402210276574,
0.00017502829723525792,
0.0001720648433547467,
0.0001751676172716543,
0.0000016485608966831933
] |
{
"id": 0,
"code_window": [
" const response = new Response(this._client, request, redirectStatus, redirectHeaders, fromDiskCache, fromServiceWorker, securityDetails);\n",
" request._response = response;\n",
" request._redirectChain.push(request);\n",
" this._requestIdToRequest.delete(request._requestId);\n",
" this._interceptionIdToRequest.delete(request._interceptionId);\n",
" this._attemptedAuthentications.delete(request._interceptionId);\n",
" this.emit(NetworkManager.Events.Response, response);\n",
" this.emit(NetworkManager.Events.RequestFinished, request);\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" response._bodyLoadedPromiseFulfill.call(null, new Error('Response body is unavailable for redirect responses'));\n"
],
"file_path": "lib/NetworkManager.js",
"type": "add",
"edit_start_line_idx": 193
} | <style>
@charset "utf-8";
@namespace svg url(http://www.w3.org/2000/svg);
@font-face {
font-family: "Example Font";
src: url("./Dosis-Regular.ttf");
}
#fluffy {
border: 1px solid black;
z-index: 1;
/* -webkit-disabled-property: rgb(1, 2, 3) */
-lol-cats: "dogs" /* non-existing property */
}
@media (min-width: 1px) {
span {
-webkit-border-radius: 10px;
font-family: "Example Font";
animation: 1s identifier;
}
}
</style>
<div id="fluffy">woof!</div>
<span>fancy text</span>
| test/assets/csscoverage/involved.html | 0 | https://github.com/puppeteer/puppeteer/commit/f8cba455ba5d1bc82721e89fda037e86213b02cb | [
0.00017486883734818548,
0.00017229588411282748,
0.0001704170135781169,
0.0001716018159640953,
0.0000018825489860319067
] |
{
"id": 1,
"code_window": [
" // @see https://crbug.com/750469\n",
" if (!request)\n",
" return;\n",
" request._completePromiseFulfill.call(null);\n",
" this._requestIdToRequest.delete(request._requestId);\n",
" this._interceptionIdToRequest.delete(request._interceptionId);\n",
" this._attemptedAuthentications.delete(request._interceptionId);\n",
" this.emit(NetworkManager.Events.RequestFinished, request);\n",
" }\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" request.response()._bodyLoadedPromiseFulfill.call(null);\n"
],
"file_path": "lib/NetworkManager.js",
"type": "replace",
"edit_start_line_idx": 276
} | /**
* Copyright 2017 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
const EventEmitter = require('events');
const {helper, debugError} = require('./helper');
const Multimap = require('./Multimap');
class NetworkManager extends EventEmitter {
/**
* @param {!Puppeteer.CDPSession} client
* @param {!Puppeteer.FrameManager} frameManager
*/
constructor(client, frameManager) {
super();
this._client = client;
this._frameManager = frameManager;
/** @type {!Map<string, !Request>} */
this._requestIdToRequest = new Map();
/** @type {!Map<string, !Request>} */
this._interceptionIdToRequest = new Map();
/** @type {!Object<string, string>} */
this._extraHTTPHeaders = {};
this._offline = false;
/** @type {?{username: string, password: string}} */
this._credentials = null;
/** @type {!Set<string>} */
this._attemptedAuthentications = new Set();
this._userRequestInterceptionEnabled = false;
this._protocolRequestInterceptionEnabled = false;
/** @type {!Multimap} */
this._requestHashToRequestIds = new Multimap();
/** @type {!Multimap} */
this._requestHashToInterceptionIds = new Multimap();
this._client.on('Network.requestWillBeSent', this._onRequestWillBeSent.bind(this));
this._client.on('Network.requestIntercepted', this._onRequestIntercepted.bind(this));
this._client.on('Network.requestServedFromCache', this._onRequestServedFromCache.bind(this));
this._client.on('Network.responseReceived', this._onResponseReceived.bind(this));
this._client.on('Network.loadingFinished', this._onLoadingFinished.bind(this));
this._client.on('Network.loadingFailed', this._onLoadingFailed.bind(this));
}
/**
* @param {?{username: string, password: string}} credentials
*/
async authenticate(credentials) {
this._credentials = credentials;
await this._updateProtocolRequestInterception();
}
/**
* @param {!Object<string, string>} extraHTTPHeaders
*/
async setExtraHTTPHeaders(extraHTTPHeaders) {
this._extraHTTPHeaders = {};
for (const key of Object.keys(extraHTTPHeaders)) {
const value = extraHTTPHeaders[key];
console.assert(helper.isString(value), `Expected value of header "${key}" to be String, but "${typeof value}" is found.`);
this._extraHTTPHeaders[key.toLowerCase()] = value;
}
await this._client.send('Network.setExtraHTTPHeaders', { headers: this._extraHTTPHeaders });
}
/**
* @return {!Object<string, string>}
*/
extraHTTPHeaders() {
return Object.assign({}, this._extraHTTPHeaders);
}
/**
* @param {boolean} value
*/
async setOfflineMode(value) {
if (this._offline === value)
return;
this._offline = value;
await this._client.send('Network.emulateNetworkConditions', {
offline: this._offline,
// values of 0 remove any active throttling. crbug.com/456324#c9
latency: 0,
downloadThroughput: -1,
uploadThroughput: -1
});
}
/**
* @param {string} userAgent
*/
async setUserAgent(userAgent) {
await this._client.send('Network.setUserAgentOverride', { userAgent });
}
/**
* @param {boolean} value
*/
async setRequestInterception(value) {
this._userRequestInterceptionEnabled = value;
await this._updateProtocolRequestInterception();
}
async _updateProtocolRequestInterception() {
const enabled = this._userRequestInterceptionEnabled || !!this._credentials;
if (enabled === this._protocolRequestInterceptionEnabled)
return;
this._protocolRequestInterceptionEnabled = enabled;
const patterns = enabled ? [{urlPattern: '*'}] : [];
await Promise.all([
this._client.send('Network.setCacheDisabled', {cacheDisabled: enabled}),
this._client.send('Network.setRequestInterception', {patterns})
]);
}
/**
* @param {!Protocol.Network.requestInterceptedPayload} event
*/
_onRequestIntercepted(event) {
if (event.authChallenge) {
/** @type {"Default"|"CancelAuth"|"ProvideCredentials"} */
let response = 'Default';
if (this._attemptedAuthentications.has(event.interceptionId)) {
response = 'CancelAuth';
} else if (this._credentials) {
response = 'ProvideCredentials';
this._attemptedAuthentications.add(event.interceptionId);
}
const {username, password} = this._credentials || {username: undefined, password: undefined};
this._client.send('Network.continueInterceptedRequest', {
interceptionId: event.interceptionId,
authChallengeResponse: { response, username, password }
}).catch(debugError);
return;
}
if (!this._userRequestInterceptionEnabled && this._protocolRequestInterceptionEnabled) {
this._client.send('Network.continueInterceptedRequest', {
interceptionId: event.interceptionId
}).catch(debugError);
}
if (event.redirectUrl) {
const request = this._interceptionIdToRequest.get(event.interceptionId);
if (request) {
this._handleRequestRedirect(request, event.responseStatusCode, event.responseHeaders, false /* fromDiskCache */, false /* fromServiceWorker */, null /* securityDetails */);
this._handleRequestStart(request._requestId, event.interceptionId, event.redirectUrl, event.resourceType, event.request, event.frameId, request._redirectChain);
}
return;
}
const requestHash = generateRequestHash(event.request);
const requestId = this._requestHashToRequestIds.firstValue(requestHash);
if (requestId) {
this._requestHashToRequestIds.delete(requestHash, requestId);
this._handleRequestStart(requestId, event.interceptionId, event.request.url, event.resourceType, event.request, event.frameId, []);
} else {
this._requestHashToInterceptionIds.set(requestHash, event.interceptionId);
this._handleRequestStart(null, event.interceptionId, event.request.url, event.resourceType, event.request, event.frameId, []);
}
}
/**
* @param {!Protocol.Network.requestServedFromCachePayload} event
*/
_onRequestServedFromCache(event) {
const request = this._requestIdToRequest.get(event.requestId);
if (request)
request._fromMemoryCache = true;
}
/**
* @param {!Request} request
* @param {number} redirectStatus
* @param {!Object} redirectHeaders
* @param {boolean} fromDiskCache
* @param {boolean} fromServiceWorker
* @param {?Object} securityDetails
*/
_handleRequestRedirect(request, redirectStatus, redirectHeaders, fromDiskCache, fromServiceWorker, securityDetails) {
const response = new Response(this._client, request, redirectStatus, redirectHeaders, fromDiskCache, fromServiceWorker, securityDetails);
request._response = response;
request._redirectChain.push(request);
this._requestIdToRequest.delete(request._requestId);
this._interceptionIdToRequest.delete(request._interceptionId);
this._attemptedAuthentications.delete(request._interceptionId);
this.emit(NetworkManager.Events.Response, response);
this.emit(NetworkManager.Events.RequestFinished, request);
}
/**
* @param {?string} requestId
* @param {?string} interceptionId
* @param {string} url
* @param {string} resourceType
* @param {!Protocol.Network.Request} requestPayload
* @param {?string} frameId
* @param {!Array<!Request>} redirectChain
*/
_handleRequestStart(requestId, interceptionId, url, resourceType, requestPayload, frameId, redirectChain) {
let frame = null;
if (frameId)
frame = this._frameManager.frame(frameId);
const request = new Request(this._client, requestId, interceptionId, this._userRequestInterceptionEnabled, url, resourceType, requestPayload, frame, redirectChain);
if (requestId)
this._requestIdToRequest.set(requestId, request);
if (interceptionId)
this._interceptionIdToRequest.set(interceptionId, request);
this.emit(NetworkManager.Events.Request, request);
}
/**
* @param {!Protocol.Network.requestWillBeSentPayload} event
*/
_onRequestWillBeSent(event) {
if (this._protocolRequestInterceptionEnabled) {
// All redirects are handled in requestIntercepted.
if (event.redirectResponse)
return;
const requestHash = generateRequestHash(event.request);
const interceptionId = this._requestHashToInterceptionIds.firstValue(requestHash);
const request = interceptionId ? this._interceptionIdToRequest.get(interceptionId) : null;
if (request) {
request._requestId = event.requestId;
this._requestIdToRequest.set(event.requestId, request);
this._requestHashToInterceptionIds.delete(requestHash, interceptionId);
} else {
this._requestHashToRequestIds.set(requestHash, event.requestId);
}
return;
}
let redirectChain = [];
if (event.redirectResponse) {
const request = this._requestIdToRequest.get(event.requestId);
// If we connect late to the target, we could have missed the requestWillBeSent event.
if (request) {
this._handleRequestRedirect(request, event.redirectResponse.status, event.redirectResponse.headers, event.redirectResponse.fromDiskCache, event.redirectResponse.fromServiceWorker, event.redirectResponse.securityDetails);
redirectChain = request._redirectChain;
}
}
this._handleRequestStart(event.requestId, null, event.request.url, event.type, event.request, event.frameId, redirectChain);
}
/**
* @param {!Protocol.Network.responseReceivedPayload} event
*/
_onResponseReceived(event) {
const request = this._requestIdToRequest.get(event.requestId);
// FileUpload sends a response without a matching request.
if (!request)
return;
const response = new Response(this._client, request, event.response.status, event.response.headers,
event.response.fromDiskCache, event.response.fromServiceWorker, event.response.securityDetails);
request._response = response;
this.emit(NetworkManager.Events.Response, response);
}
/**
* @param {!Protocol.Network.loadingFinishedPayload} event
*/
_onLoadingFinished(event) {
const request = this._requestIdToRequest.get(event.requestId);
// For certain requestIds we never receive requestWillBeSent event.
// @see https://crbug.com/750469
if (!request)
return;
request._completePromiseFulfill.call(null);
this._requestIdToRequest.delete(request._requestId);
this._interceptionIdToRequest.delete(request._interceptionId);
this._attemptedAuthentications.delete(request._interceptionId);
this.emit(NetworkManager.Events.RequestFinished, request);
}
/**
* @param {!Protocol.Network.loadingFailedPayload} event
*/
_onLoadingFailed(event) {
const request = this._requestIdToRequest.get(event.requestId);
// For certain requestIds we never receive requestWillBeSent event.
// @see https://crbug.com/750469
if (!request)
return;
request._failureText = event.errorText;
request._completePromiseFulfill.call(null);
this._requestIdToRequest.delete(request._requestId);
this._interceptionIdToRequest.delete(request._interceptionId);
this._attemptedAuthentications.delete(request._interceptionId);
this.emit(NetworkManager.Events.RequestFailed, request);
}
}
class Request {
/**
* @param {!Puppeteer.CDPSession} client
* @param {?string} requestId
* @param {string} interceptionId
* @param {boolean} allowInterception
* @param {string} url
* @param {string} resourceType
* @param {!Protocol.Network.Request} payload
* @param {?Puppeteer.Frame} frame
* @param {!Array<!Request>} redirectChain
*/
constructor(client, requestId, interceptionId, allowInterception, url, resourceType, payload, frame, redirectChain) {
this._client = client;
this._requestId = requestId;
this._interceptionId = interceptionId;
this._allowInterception = allowInterception;
this._interceptionHandled = false;
this._response = null;
this._failureText = null;
this._completePromise = new Promise(fulfill => {
this._completePromiseFulfill = fulfill;
});
this._url = url;
this._resourceType = resourceType.toLowerCase();
this._method = payload.method;
this._postData = payload.postData;
this._headers = {};
this._frame = frame;
this._redirectChain = redirectChain;
for (const key of Object.keys(payload.headers))
this._headers[key.toLowerCase()] = payload.headers[key];
this._fromMemoryCache = false;
}
/**
* @return {string}
*/
url() {
return this._url;
}
/**
* @return {string}
*/
resourceType() {
return this._resourceType;
}
/**
* @return {string}
*/
method() {
return this._method;
}
/**
* @return {string}
*/
postData() {
return this._postData;
}
/**
* @return {!Object}
*/
headers() {
return this._headers;
}
/**
* @return {?Response}
*/
response() {
return this._response;
}
/**
* @return {?Puppeteer.Frame}
*/
frame() {
return this._frame;
}
/**
* @return {!Array<!Request>}
*/
redirectChain() {
return this._redirectChain.slice();
}
/**
* @return {?{errorText: string}}
*/
failure() {
if (!this._failureText)
return null;
return {
errorText: this._failureText
};
}
/**
* @param {!Object=} overrides
*/
async continue(overrides = {}) {
console.assert(this._allowInterception, 'Request Interception is not enabled!');
console.assert(!this._interceptionHandled, 'Request is already handled!');
this._interceptionHandled = true;
await this._client.send('Network.continueInterceptedRequest', {
interceptionId: this._interceptionId,
url: overrides.url,
method: overrides.method,
postData: overrides.postData,
headers: overrides.headers,
}).catch(error => {
// In certain cases, protocol will return error if the request was already canceled
// or the page was closed. We should tolerate these errors.
debugError(error);
});
}
/**
* @param {!{status: number, headers: Object, contentType: string, body: (string|Buffer)}} response
*/
async respond(response) {
// Mocking responses for dataURL requests is not currently supported.
if (this._url.startsWith('data:'))
return;
console.assert(this._allowInterception, 'Request Interception is not enabled!');
console.assert(!this._interceptionHandled, 'Request is already handled!');
this._interceptionHandled = true;
const responseBody = response.body && helper.isString(response.body) ? Buffer.from(/** @type {string} */(response.body)) : /** @type {?Buffer} */(response.body || null);
const responseHeaders = {};
if (response.headers) {
for (const header of Object.keys(response.headers))
responseHeaders[header.toLowerCase()] = response.headers[header];
}
if (response.contentType)
responseHeaders['content-type'] = response.contentType;
if (responseBody && !('content-length' in responseHeaders)) {
// @ts-ignore
responseHeaders['content-length'] = Buffer.byteLength(responseBody);
}
const statusCode = response.status || 200;
const statusText = statusTexts[statusCode] || '';
const statusLine = `HTTP/1.1 ${statusCode} ${statusText}`;
const CRLF = '\r\n';
let text = statusLine + CRLF;
for (const header of Object.keys(responseHeaders))
text += header + ': ' + responseHeaders[header] + CRLF;
text += CRLF;
let responseBuffer = Buffer.from(text, 'utf8');
if (responseBody)
responseBuffer = Buffer.concat([responseBuffer, responseBody]);
await this._client.send('Network.continueInterceptedRequest', {
interceptionId: this._interceptionId,
rawResponse: responseBuffer.toString('base64')
}).catch(error => {
// In certain cases, protocol will return error if the request was already canceled
// or the page was closed. We should tolerate these errors.
debugError(error);
});
}
/**
* @param {string=} errorCode
*/
async abort(errorCode = 'failed') {
const errorReason = errorReasons[errorCode];
console.assert(errorReason, 'Unknown error code: ' + errorCode);
console.assert(this._allowInterception, 'Request Interception is not enabled!');
console.assert(!this._interceptionHandled, 'Request is already handled!');
this._interceptionHandled = true;
await this._client.send('Network.continueInterceptedRequest', {
interceptionId: this._interceptionId,
errorReason
}).catch(error => {
// In certain cases, protocol will return error if the request was already canceled
// or the page was closed. We should tolerate these errors.
debugError(error);
});
}
}
const errorReasons = {
'aborted': 'Aborted',
'accessdenied': 'AccessDenied',
'addressunreachable': 'AddressUnreachable',
'connectionaborted': 'ConnectionAborted',
'connectionclosed': 'ConnectionClosed',
'connectionfailed': 'ConnectionFailed',
'connectionrefused': 'ConnectionRefused',
'connectionreset': 'ConnectionReset',
'internetdisconnected': 'InternetDisconnected',
'namenotresolved': 'NameNotResolved',
'timedout': 'TimedOut',
'failed': 'Failed',
};
helper.tracePublicAPI(Request);
class Response {
/**
* @param {!Puppeteer.CDPSession} client
* @param {!Request} request
* @param {number} status
* @param {!Object} headers
* @param {boolean} fromDiskCache
* @param {boolean} fromServiceWorker
* @param {?Object} securityDetails
*/
constructor(client, request, status, headers, fromDiskCache, fromServiceWorker, securityDetails) {
this._client = client;
this._request = request;
this._contentPromise = null;
this._status = status;
this._url = request.url();
this._fromDiskCache = fromDiskCache;
this._fromServiceWorker = fromServiceWorker;
this._headers = {};
for (const key of Object.keys(headers))
this._headers[key.toLowerCase()] = headers[key];
this._securityDetails = null;
if (securityDetails) {
this._securityDetails = new SecurityDetails(
securityDetails['subjectName'],
securityDetails['issuer'],
securityDetails['validFrom'],
securityDetails['validTo'],
securityDetails['protocol']);
}
}
/**
* @return {string}
*/
url() {
return this._url;
}
/**
* @return {boolean}
*/
ok() {
return this._status === 0 || (this._status >= 200 && this._status <= 299);
}
/**
* @return {number}
*/
status() {
return this._status;
}
/**
* @return {!Object}
*/
headers() {
return this._headers;
}
/**
* @return {?SecurityDetails}
*/
securityDetails() {
return this._securityDetails;
}
/**
* @return {!Promise<!Buffer>}
*/
buffer() {
if (!this._contentPromise) {
this._contentPromise = this._request._completePromise.then(async() => {
const response = await this._client.send('Network.getResponseBody', {
requestId: this._request._requestId
});
return Buffer.from(response.body, response.base64Encoded ? 'base64' : 'utf8');
});
}
return this._contentPromise;
}
/**
* @return {!Promise<string>}
*/
async text() {
const content = await this.buffer();
return content.toString('utf8');
}
/**
* @return {!Promise<!Object>}
*/
async json() {
const content = await this.text();
return JSON.parse(content);
}
/**
* @return {!Request}
*/
request() {
return this._request;
}
/**
* @return {boolean}
*/
fromCache() {
return this._fromDiskCache || this._request._fromMemoryCache;
}
/**
* @return {boolean}
*/
fromServiceWorker() {
return this._fromServiceWorker;
}
}
helper.tracePublicAPI(Response);
/**
* @param {!Protocol.Network.Request} request
* @return {string}
*/
function generateRequestHash(request) {
let normalizedURL = request.url;
try {
// Decoding is necessary to normalize URLs. @see crbug.com/759388
// The method will throw if the URL is malformed. In this case,
// consider URL to be normalized as-is.
normalizedURL = decodeURI(request.url);
} catch (e) {
}
const hash = {
url: normalizedURL,
method: request.method,
postData: request.postData,
headers: {},
};
if (!normalizedURL.startsWith('data:')) {
const headers = Object.keys(request.headers);
headers.sort();
for (let header of headers) {
const headerValue = request.headers[header];
header = header.toLowerCase();
if (header === 'accept' || header === 'referer' || header === 'x-devtools-emulate-network-conditions-client-id')
continue;
hash.headers[header] = headerValue;
}
}
return JSON.stringify(hash);
}
class SecurityDetails {
/**
* @param {string} subjectName
* @param {string} issuer
* @param {number} validFrom
* @param {number} validTo
* @param {string} protocol
*/
constructor(subjectName, issuer, validFrom, validTo, protocol) {
this._subjectName = subjectName;
this._issuer = issuer;
this._validFrom = validFrom;
this._validTo = validTo;
this._protocol = protocol;
}
/**
* @return {string}
*/
subjectName() {
return this._subjectName;
}
/**
* @return {string}
*/
issuer() {
return this._issuer;
}
/**
* @return {number}
*/
validFrom() {
return this._validFrom;
}
/**
* @return {number}
*/
validTo() {
return this._validTo;
}
/**
* @return {string}
*/
protocol() {
return this._protocol;
}
}
NetworkManager.Events = {
Request: 'request',
Response: 'response',
RequestFailed: 'requestfailed',
RequestFinished: 'requestfinished',
};
const statusTexts = {
'100': 'Continue',
'101': 'Switching Protocols',
'102': 'Processing',
'200': 'OK',
'201': 'Created',
'202': 'Accepted',
'203': 'Non-Authoritative Information',
'204': 'No Content',
'206': 'Partial Content',
'207': 'Multi-Status',
'208': 'Already Reported',
'209': 'IM Used',
'300': 'Multiple Choices',
'301': 'Moved Permanently',
'302': 'Found',
'303': 'See Other',
'304': 'Not Modified',
'305': 'Use Proxy',
'306': 'Switch Proxy',
'307': 'Temporary Redirect',
'308': 'Permanent Redirect',
'400': 'Bad Request',
'401': 'Unauthorized',
'402': 'Payment Required',
'403': 'Forbidden',
'404': 'Not Found',
'405': 'Method Not Allowed',
'406': 'Not Acceptable',
'407': 'Proxy Authentication Required',
'408': 'Request Timeout',
'409': 'Conflict',
'410': 'Gone',
'411': 'Length Required',
'412': 'Precondition Failed',
'413': 'Payload Too Large',
'414': 'URI Too Long',
'415': 'Unsupported Media Type',
'416': 'Range Not Satisfiable',
'417': 'Expectation Failed',
'418': 'I\'m a teapot',
'421': 'Misdirected Request',
'422': 'Unprocessable Entity',
'423': 'Locked',
'424': 'Failed Dependency',
'426': 'Upgrade Required',
'428': 'Precondition Required',
'429': 'Too Many Requests',
'431': 'Request Header Fields Too Large',
'451': 'Unavailable For Legal Reasons',
'500': 'Internal Server Error',
'501': 'Not Implemented',
'502': 'Bad Gateway',
'503': 'Service Unavailable',
'504': 'Gateway Timeout',
'505': 'HTTP Version Not Supported',
'506': 'Variant Also Negotiates',
'507': 'Insufficient Storage',
'508': 'Loop Detected',
'510': 'Not Extended',
'511': 'Network Authentication Required',
};
module.exports = {Request, Response, NetworkManager};
| lib/NetworkManager.js | 1 | https://github.com/puppeteer/puppeteer/commit/f8cba455ba5d1bc82721e89fda037e86213b02cb | [
0.9957365989685059,
0.01694440469145775,
0.0001624235592316836,
0.00017690216191112995,
0.11226196587085724
] |
{
"id": 1,
"code_window": [
" // @see https://crbug.com/750469\n",
" if (!request)\n",
" return;\n",
" request._completePromiseFulfill.call(null);\n",
" this._requestIdToRequest.delete(request._requestId);\n",
" this._interceptionIdToRequest.delete(request._interceptionId);\n",
" this._attemptedAuthentications.delete(request._interceptionId);\n",
" this.emit(NetworkManager.Events.RequestFinished, request);\n",
" }\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" request.response()._bodyLoadedPromiseFulfill.call(null);\n"
],
"file_path": "lib/NetworkManager.js",
"type": "replace",
"edit_start_line_idx": 276
} | /**
* Copyright 2017 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
const path = require('path');
const fs = require('fs');
const Diff = require('text-diff');
const mime = require('mime');
const PNG = require('pngjs').PNG;
const pixelmatch = require('pixelmatch');
module.exports = {compare};
const GoldenComparators = {
'image/png': compareImages,
'text/plain': compareText
};
/**
* @param {?Object} actualBuffer
* @param {!Buffer} expectedBuffer
* @return {?{diff: (!Object:undefined), errorMessage: (string|undefined)}}
*/
function compareImages(actualBuffer, expectedBuffer) {
if (!actualBuffer || !(actualBuffer instanceof Buffer))
return { errorMessage: 'Actual result should be Buffer.' };
const actual = PNG.sync.read(actualBuffer);
const expected = PNG.sync.read(expectedBuffer);
if (expected.width !== actual.width || expected.height !== actual.height) {
return {
errorMessage: `Sizes differ: expected image ${expected.width}px X ${expected.height}px, but got ${actual.width}px X ${actual.height}px. `
};
}
const diff = new PNG({width: expected.width, height: expected.height});
const count = pixelmatch(expected.data, actual.data, diff.data, expected.width, expected.height, {threshold: 0.1});
return count > 0 ? { diff: PNG.sync.write(diff) } : null;
}
/**
* @param {?Object} actual
* @param {!Buffer} expectedBuffer
* @return {?{diff: (!Object:undefined), errorMessage: (string|undefined)}}
*/
function compareText(actual, expectedBuffer) {
if (typeof actual !== 'string')
return { errorMessage: 'Actual result should be string' };
const expected = expectedBuffer.toString('utf-8');
if (expected === actual)
return null;
const diff = new Diff();
const result = diff.main(expected, actual);
diff.cleanupSemantic(result);
let html = diff.prettyHtml(result);
const diffStylePath = path.join(__dirname, 'diffstyle.css');
html = `<link rel="stylesheet" href="file://${diffStylePath}">` + html;
return {
diff: html,
diffExtension: '.html'
};
}
/**
* @param {?Object} actual
* @param {string} goldenName
* @return {!{pass: boolean, message: (undefined|string)}}
*/
function compare(goldenPath, outputPath, actual, goldenName) {
goldenPath = path.normalize(goldenPath);
outputPath = path.normalize(outputPath);
const expectedPath = path.join(goldenPath, goldenName);
const actualPath = path.join(outputPath, goldenName);
const messageSuffix = 'Output is saved in "' + path.basename(outputPath + '" directory');
if (!fs.existsSync(expectedPath)) {
ensureOutputDir();
fs.writeFileSync(actualPath, actual);
return {
pass: false,
message: goldenName + ' is missing in golden results. ' + messageSuffix
};
}
const expected = fs.readFileSync(expectedPath);
const comparator = GoldenComparators[mime.lookup(goldenName)];
if (!comparator) {
return {
pass: false,
message: 'Failed to find comparator with type ' + mime.lookup(goldenName) + ': ' + goldenName
};
}
const result = comparator(actual, expected);
if (!result)
return { pass: true };
ensureOutputDir();
if (goldenPath === outputPath) {
fs.writeFileSync(addSuffix(actualPath, '-actual'), actual);
} else {
fs.writeFileSync(actualPath, actual);
// Copy expected to the output/ folder for convenience.
fs.writeFileSync(addSuffix(actualPath, '-expected'), expected);
}
if (result.diff) {
const diffPath = addSuffix(actualPath, '-diff', result.diffExtension);
fs.writeFileSync(diffPath, result.diff);
}
let message = goldenName + ' mismatch!';
if (result.errorMessage)
message += ' ' + result.errorMessage;
return {
pass: false,
message: message + ' ' + messageSuffix
};
function ensureOutputDir() {
if (!fs.existsSync(outputPath))
fs.mkdirSync(outputPath);
}
}
/**
* @param {string} filePath
* @param {string} suffix
* @param {string=} customExtension
* @return {string}
*/
function addSuffix(filePath, suffix, customExtension) {
const dirname = path.dirname(filePath);
const ext = path.extname(filePath);
const name = path.basename(filePath, ext);
return path.join(dirname, name + suffix + (customExtension || ext));
}
| test/golden-utils.js | 0 | https://github.com/puppeteer/puppeteer/commit/f8cba455ba5d1bc82721e89fda037e86213b02cb | [
0.0001780428137863055,
0.0001764582993928343,
0.0001737090351525694,
0.00017660818411968648,
0.0000011314515404592385
] |
{
"id": 1,
"code_window": [
" // @see https://crbug.com/750469\n",
" if (!request)\n",
" return;\n",
" request._completePromiseFulfill.call(null);\n",
" this._requestIdToRequest.delete(request._requestId);\n",
" this._interceptionIdToRequest.delete(request._interceptionId);\n",
" this._attemptedAuthentications.delete(request._interceptionId);\n",
" this.emit(NetworkManager.Events.RequestFinished, request);\n",
" }\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" request.response()._bodyLoadedPromiseFulfill.call(null);\n"
],
"file_path": "lib/NetworkManager.js",
"type": "replace",
"edit_start_line_idx": 276
} | Copyright (c) 2011, Edgar Tolentino and Pablo Impallari (www.impallari.com|[email protected]),
Copyright (c) 2011, Igino Marini. (www.ikern.com|[email protected]),
with Reserved Font Names "Dosis".
This Font Software is licensed under the SIL Open Font License, Version 1.1.
This license is copied below, and is also available with a FAQ at:
http://scripts.sil.org/OFL
-----------------------------------------------------------
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
-----------------------------------------------------------
PREAMBLE
The goals of the Open Font License (OFL) are to stimulate worldwide
development of collaborative font projects, to support the font creation
efforts of academic and linguistic communities, and to provide a free and
open framework in which fonts may be shared and improved in partnership
with others.
The OFL allows the licensed fonts to be used, studied, modified and
redistributed freely as long as they are not sold by themselves. The
fonts, including any derivative works, can be bundled, embedded,
redistributed and/or sold with any software provided that any reserved
names are not used by derivative works. The fonts and derivatives,
however, cannot be released under any other type of license. The
requirement for fonts to remain under this license does not apply
to any document created using the fonts or their derivatives.
DEFINITIONS
"Font Software" refers to the set of files released by the Copyright
Holder(s) under this license and clearly marked as such. This may
include source files, build scripts and documentation.
"Reserved Font Name" refers to any names specified as such after the
copyright statement(s).
"Original Version" refers to the collection of Font Software components as
distributed by the Copyright Holder(s).
"Modified Version" refers to any derivative made by adding to, deleting,
or substituting -- in part or in whole -- any of the components of the
Original Version, by changing formats or by porting the Font Software to a
new environment.
"Author" refers to any designer, engineer, programmer, technical
writer or other person who contributed to the Font Software.
PERMISSION & CONDITIONS
Permission is hereby granted, free of charge, to any person obtaining
a copy of the Font Software, to use, study, copy, merge, embed, modify,
redistribute, and sell modified and unmodified copies of the Font
Software, subject to the following conditions:
1) Neither the Font Software nor any of its individual components,
in Original or Modified Versions, may be sold by itself.
2) Original or Modified Versions of the Font Software may be bundled,
redistributed and/or sold with any software, provided that each copy
contains the above copyright notice and this license. These can be
included either as stand-alone text files, human-readable headers or
in the appropriate machine-readable metadata fields within text or
binary files as long as those fields can be easily viewed by the user.
3) No Modified Version of the Font Software may use the Reserved Font
Name(s) unless explicit written permission is granted by the corresponding
Copyright Holder. This restriction only applies to the primary font name as
presented to the users.
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
Software shall not be used to promote, endorse or advertise any
Modified Version, except to acknowledge the contribution(s) of the
Copyright Holder(s) and the Author(s) or with their explicit written
permission.
5) The Font Software, modified or unmodified, in part or in whole,
must be distributed entirely under this license, and must not be
distributed under any other license. The requirement for fonts to
remain under this license does not apply to any document created
using the Font Software.
TERMINATION
This license becomes null and void if any of the above conditions are
not met.
DISCLAIMER
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
OTHER DEALINGS IN THE FONT SOFTWARE.
| test/assets/csscoverage/OFL.txt | 0 | https://github.com/puppeteer/puppeteer/commit/f8cba455ba5d1bc82721e89fda037e86213b02cb | [
0.00017634144751355052,
0.0001716620899969712,
0.00016025306831579655,
0.0001732579548843205,
0.0000050217058742418885
] |
{
"id": 1,
"code_window": [
" // @see https://crbug.com/750469\n",
" if (!request)\n",
" return;\n",
" request._completePromiseFulfill.call(null);\n",
" this._requestIdToRequest.delete(request._requestId);\n",
" this._interceptionIdToRequest.delete(request._interceptionId);\n",
" this._attemptedAuthentications.delete(request._interceptionId);\n",
" this.emit(NetworkManager.Events.RequestFinished, request);\n",
" }\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" request.response()._bodyLoadedPromiseFulfill.call(null);\n"
],
"file_path": "lib/NetworkManager.js",
"type": "replace",
"edit_start_line_idx": 276
} | /**
* Copyright 2018 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
module.exports.addTests = function({testRunner, expect}) {
const {describe, xdescribe, fdescribe} = testRunner;
const {it, fit, xit} = testRunner;
const {beforeAll, beforeEach, afterAll, afterEach} = testRunner;
describe('JSHandle.getProperty', function() {
it('should work', async({page, server}) => {
const aHandle = await page.evaluateHandle(() => ({
one: 1,
two: 2,
three: 3
}));
const twoHandle = await aHandle.getProperty('two');
expect(await twoHandle.jsonValue()).toEqual(2);
});
});
describe('JSHandle.jsonValue', function() {
it('should work', async({page, server}) => {
const aHandle = await page.evaluateHandle(() => ({foo: 'bar'}));
const json = await aHandle.jsonValue();
expect(json).toEqual({foo: 'bar'});
});
it('should not work with dates', async({page, server}) => {
const dateHandle = await page.evaluateHandle(() => new Date('2017-09-26T00:00:00.000Z'));
const json = await dateHandle.jsonValue();
expect(json).toEqual({});
});
it('should throw for circular objects', async({page, server}) => {
const windowHandle = await page.evaluateHandle('window');
let error = null;
await windowHandle.jsonValue().catch(e => error = e);
expect(error.message).toContain('Object reference chain is too long');
});
});
describe('JSHandle.getProperties', function() {
it('should work', async({page, server}) => {
const aHandle = await page.evaluateHandle(() => ({
foo: 'bar'
}));
const properties = await aHandle.getProperties();
const foo = properties.get('foo');
expect(foo).toBeTruthy();
expect(await foo.jsonValue()).toBe('bar');
});
it('should return even non-own properties', async({page, server}) => {
const aHandle = await page.evaluateHandle(() => {
class A {
constructor() {
this.a = '1';
}
}
class B extends A {
constructor() {
super();
this.b = '2';
}
}
return new B();
});
const properties = await aHandle.getProperties();
expect(await properties.get('a').jsonValue()).toBe('1');
expect(await properties.get('b').jsonValue()).toBe('2');
});
});
describe('JSHandle.asElement', function() {
it('should work', async({page, server}) => {
const aHandle = await page.evaluateHandle(() => document.body);
const element = aHandle.asElement();
expect(element).toBeTruthy();
});
it('should return null for non-elements', async({page, server}) => {
const aHandle = await page.evaluateHandle(() => 2);
const element = aHandle.asElement();
expect(element).toBeFalsy();
});
it('should return ElementHandle for TextNodes', async({page, server}) => {
await page.setContent('<div>ee!</div>');
const aHandle = await page.evaluateHandle(() => document.querySelector('div').firstChild);
const element = aHandle.asElement();
expect(element).toBeTruthy();
expect(await page.evaluate(e => e.nodeType === HTMLElement.TEXT_NODE, element));
});
});
describe('JSHandle.toString', function() {
it('should work for primitives', async({page, server}) => {
const numberHandle = await page.evaluateHandle(() => 2);
expect(numberHandle.toString()).toBe('JSHandle:2');
const stringHandle = await page.evaluateHandle(() => 'a');
expect(stringHandle.toString()).toBe('JSHandle:a');
});
it('should work for complicated objects', async({page, server}) => {
const aHandle = await page.evaluateHandle(() => window);
expect(aHandle.toString()).toBe('JSHandle@object');
});
});
};
| test/jshandle.spec.js | 0 | https://github.com/puppeteer/puppeteer/commit/f8cba455ba5d1bc82721e89fda037e86213b02cb | [
0.00017631826631259173,
0.00017431187734473497,
0.0001708269992377609,
0.0001747555797919631,
0.0000014849942999717314
] |
{
"id": 2,
"code_window": [
" // For certain requestIds we never receive requestWillBeSent event.\n",
" // @see https://crbug.com/750469\n",
" if (!request)\n",
" return;\n",
" request._failureText = event.errorText;\n",
" request._completePromiseFulfill.call(null);\n",
" this._requestIdToRequest.delete(request._requestId);\n",
" this._interceptionIdToRequest.delete(request._interceptionId);\n",
" this._attemptedAuthentications.delete(request._interceptionId);\n",
" this.emit(NetworkManager.Events.RequestFailed, request);\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" const response = request.response();\n",
" if (response)\n",
" response._bodyLoadedPromiseFulfill.call(null);\n"
],
"file_path": "lib/NetworkManager.js",
"type": "replace",
"edit_start_line_idx": 293
} | /**
* Copyright 2018 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
const {waitEvent} = require('./utils');
module.exports.addTests = function({testRunner, expect}) {
const {describe, xdescribe, fdescribe} = testRunner;
const {it, fit, xit} = testRunner;
const {beforeAll, beforeEach, afterAll, afterEach} = testRunner;
describe('Network Events', function() {
it('Page.Events.Request', async({page, server}) => {
const requests = [];
page.on('request', request => requests.push(request));
await page.goto(server.EMPTY_PAGE);
expect(requests.length).toBe(1);
expect(requests[0].url()).toBe(server.EMPTY_PAGE);
expect(requests[0].resourceType()).toBe('document');
expect(requests[0].method()).toBe('GET');
expect(requests[0].response()).toBeTruthy();
expect(requests[0].frame() === page.mainFrame()).toBe(true);
expect(requests[0].frame().url()).toBe(server.EMPTY_PAGE);
});
it('Page.Events.Request should report post data', async({page, server}) => {
await page.goto(server.EMPTY_PAGE);
server.setRoute('/post', (req, res) => res.end());
let request = null;
page.on('request', r => request = r);
await page.evaluate(() => fetch('./post', { method: 'POST', body: JSON.stringify({foo: 'bar'})}));
expect(request).toBeTruthy();
expect(request.postData()).toBe('{"foo":"bar"}');
});
it('Page.Events.Response', async({page, server}) => {
const responses = [];
page.on('response', response => responses.push(response));
await page.goto(server.EMPTY_PAGE);
expect(responses.length).toBe(1);
expect(responses[0].url()).toBe(server.EMPTY_PAGE);
expect(responses[0].status()).toBe(200);
expect(responses[0].ok()).toBe(true);
expect(responses[0].fromCache()).toBe(false);
expect(responses[0].fromServiceWorker()).toBe(false);
expect(responses[0].request()).toBeTruthy();
});
it('Response.fromCache()', async({page, server}) => {
const responses = new Map();
page.on('response', r => responses.set(r.url().split('/').pop(), r));
// Load and re-load to make sure it's cached.
await page.goto(server.PREFIX + '/cached/one-style.html');
await page.reload();
expect(responses.size).toBe(2);
expect(responses.get('one-style.html').status()).toBe(304);
expect(responses.get('one-style.html').fromCache()).toBe(false);
expect(responses.get('one-style.css').status()).toBe(200);
expect(responses.get('one-style.css').fromCache()).toBe(true);
});
it('Response.fromServiceWorker', async({page, server}) => {
const responses = new Map();
page.on('response', r => responses.set(r.url().split('/').pop(), r));
// Load and re-load to make sure serviceworker is installed and running.
await page.goto(server.PREFIX + '/serviceworkers/fetch/sw.html', {waitUntil: 'networkidle2'});
await page.evaluate(async() => await window.activationPromise);
await page.reload();
expect(responses.size).toBe(2);
expect(responses.get('sw.html').status()).toBe(200);
expect(responses.get('sw.html').fromServiceWorker()).toBe(true);
expect(responses.get('style.css').status()).toBe(200);
expect(responses.get('style.css').fromServiceWorker()).toBe(true);
});
it('Page.Events.Response should provide body', async({page, server}) => {
let response = null;
page.on('response', r => response = r);
await page.goto(server.PREFIX + '/simple.json');
expect(response).toBeTruthy();
expect(await response.text()).toBe('{"foo": "bar"}\n');
expect(await response.json()).toEqual({foo: 'bar'});
});
it('Page.Events.Response should not report body unless request is finished', async({page, server}) => {
await page.goto(server.EMPTY_PAGE);
// Setup server to trap request.
let serverResponse = null;
server.setRoute('/get', (req, res) => {
serverResponse = res;
res.write('hello ');
});
// Setup page to trap response.
let pageResponse = null;
let requestFinished = false;
page.on('response', r => pageResponse = r);
page.on('requestfinished', () => requestFinished = true);
// send request and wait for server response
await Promise.all([
page.evaluate(() => fetch('./get', { method: 'GET'})),
waitEvent(page, 'response')
]);
expect(serverResponse).toBeTruthy();
expect(pageResponse).toBeTruthy();
expect(pageResponse.status()).toBe(200);
expect(requestFinished).toBe(false);
const responseText = pageResponse.text();
// Write part of the response and wait for it to be flushed.
await new Promise(x => serverResponse.write('wor', x));
// Finish response.
await new Promise(x => serverResponse.end('ld!', x));
expect(await responseText).toBe('hello world!');
});
it('Page.Events.RequestFailed', async({page, server}) => {
await page.setRequestInterception(true);
page.on('request', request => {
if (request.url().endsWith('css'))
request.abort();
else
request.continue();
});
const failedRequests = [];
page.on('requestfailed', request => failedRequests.push(request));
await page.goto(server.PREFIX + '/one-style.html');
expect(failedRequests.length).toBe(1);
expect(failedRequests[0].url()).toContain('one-style.css');
expect(failedRequests[0].response()).toBe(null);
expect(failedRequests[0].resourceType()).toBe('stylesheet');
expect(failedRequests[0].failure().errorText).toBe('net::ERR_FAILED');
expect(failedRequests[0].frame()).toBeTruthy();
});
it('Page.Events.RequestFinished', async({page, server}) => {
const requests = [];
page.on('requestfinished', request => requests.push(request));
await page.goto(server.EMPTY_PAGE);
expect(requests.length).toBe(1);
expect(requests[0].url()).toBe(server.EMPTY_PAGE);
expect(requests[0].response()).toBeTruthy();
expect(requests[0].frame() === page.mainFrame()).toBe(true);
expect(requests[0].frame().url()).toBe(server.EMPTY_PAGE);
});
it('should fire events in proper order', async({page, server}) => {
const events = [];
page.on('request', request => events.push('request'));
page.on('response', response => events.push('response'));
page.on('requestfinished', request => events.push('requestfinished'));
await page.goto(server.EMPTY_PAGE);
expect(events).toEqual(['request', 'response', 'requestfinished']);
});
it('should support redirects', async({page, server}) => {
const events = [];
page.on('request', request => events.push(`${request.method()} ${request.url()}`));
page.on('response', response => events.push(`${response.status()} ${response.url()}`));
page.on('requestfinished', request => events.push(`DONE ${request.url()}`));
page.on('requestfailed', request => events.push(`FAIL ${request.url()}`));
server.setRedirect('/foo.html', '/empty.html');
const FOO_URL = server.PREFIX + '/foo.html';
const response = await page.goto(FOO_URL);
expect(events).toEqual([
`GET ${FOO_URL}`,
`302 ${FOO_URL}`,
`DONE ${FOO_URL}`,
`GET ${server.EMPTY_PAGE}`,
`200 ${server.EMPTY_PAGE}`,
`DONE ${server.EMPTY_PAGE}`
]);
// Check redirect chain
const redirectChain = response.request().redirectChain();
expect(redirectChain.length).toBe(1);
expect(redirectChain[0].url()).toContain('/foo.html');
});
});
};
| test/network.spec.js | 1 | https://github.com/puppeteer/puppeteer/commit/f8cba455ba5d1bc82721e89fda037e86213b02cb | [
0.0009582274942658842,
0.00022725238522980362,
0.00016497733304277062,
0.00017399480566382408,
0.0001752608804963529
] |
{
"id": 2,
"code_window": [
" // For certain requestIds we never receive requestWillBeSent event.\n",
" // @see https://crbug.com/750469\n",
" if (!request)\n",
" return;\n",
" request._failureText = event.errorText;\n",
" request._completePromiseFulfill.call(null);\n",
" this._requestIdToRequest.delete(request._requestId);\n",
" this._interceptionIdToRequest.delete(request._interceptionId);\n",
" this._attemptedAuthentications.delete(request._interceptionId);\n",
" this.emit(NetworkManager.Events.RequestFailed, request);\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" const response = request.response();\n",
" if (response)\n",
" response._bodyLoadedPromiseFulfill.call(null);\n"
],
"file_path": "lib/NetworkManager.js",
"type": "replace",
"edit_start_line_idx": 293
} | /**
* Copyright 2017 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
const {helper} = require('./helper');
const Launcher = require('./Launcher');
const BrowserFetcher = require('./BrowserFetcher');
module.exports = class {
/**
* @param {!Object=} options
* @return {!Promise<!Puppeteer.Browser>}
*/
static launch(options) {
return Launcher.launch(options);
}
/**
* @param {{browserWSEndpoint: string, ignoreHTTPSErrors: boolean}} options
* @return {!Promise<!Puppeteer.Browser>}
*/
static connect(options) {
return Launcher.connect(options);
}
/**
* @return {string}
*/
static executablePath() {
return Launcher.executablePath();
}
/**
* @return {!Array<string>}
*/
static defaultArgs() {
return Launcher.defaultArgs();
}
/**
* @param {!Object=} options
* @return {!BrowserFetcher}
*/
static createBrowserFetcher(options) {
return new BrowserFetcher(options);
}
};
helper.tracePublicAPI(module.exports, 'Puppeteer');
| lib/Puppeteer.js | 0 | https://github.com/puppeteer/puppeteer/commit/f8cba455ba5d1bc82721e89fda037e86213b02cb | [
0.00017684881458990276,
0.00017374359595123678,
0.00016816843708511442,
0.00017419335199519992,
0.0000026312918635085225
] |
{
"id": 2,
"code_window": [
" // For certain requestIds we never receive requestWillBeSent event.\n",
" // @see https://crbug.com/750469\n",
" if (!request)\n",
" return;\n",
" request._failureText = event.errorText;\n",
" request._completePromiseFulfill.call(null);\n",
" this._requestIdToRequest.delete(request._requestId);\n",
" this._interceptionIdToRequest.delete(request._interceptionId);\n",
" this._attemptedAuthentications.delete(request._interceptionId);\n",
" this.emit(NetworkManager.Events.RequestFailed, request);\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" const response = request.response();\n",
" if (response)\n",
" response._bodyLoadedPromiseFulfill.call(null);\n"
],
"file_path": "lib/NetworkManager.js",
"type": "replace",
"edit_start_line_idx": 293
} | FROM microsoft/windowsservercore:1709
SHELL ["powershell", "-Command", "$ErrorActionPreference = 'Stop'; $ProgressPreference = 'SilentlyContinue';"]
ENV NODE_VERSION 7.10.1
RUN netsh interface ipv4 set subinterface 'vEthernet (Ethernet)' mtu=1460 store=persistent
RUN Invoke-WebRequest $('https://nodejs.org/dist/v{0}/node-v{0}-win-x64.zip' -f $env:NODE_VERSION) -OutFile 'node.zip' -UseBasicParsing ; \
Expand-Archive node.zip -DestinationPath C:\ ; \
Rename-Item -Path $('C:\node-v{0}-win-x64' -f $env:NODE_VERSION) -NewName 'C:\nodejs'
SHELL ["cmd", "/S", "/C"]
RUN setx /m PATH "%PATH%;C:\nodejs"
| .ci/node7/Dockerfile.windows | 0 | https://github.com/puppeteer/puppeteer/commit/f8cba455ba5d1bc82721e89fda037e86213b02cb | [
0.0001707195333437994,
0.000168410042533651,
0.00016610055172350258,
0.000168410042533651,
0.000002309490810148418
] |
{
"id": 2,
"code_window": [
" // For certain requestIds we never receive requestWillBeSent event.\n",
" // @see https://crbug.com/750469\n",
" if (!request)\n",
" return;\n",
" request._failureText = event.errorText;\n",
" request._completePromiseFulfill.call(null);\n",
" this._requestIdToRequest.delete(request._requestId);\n",
" this._interceptionIdToRequest.delete(request._interceptionId);\n",
" this._attemptedAuthentications.delete(request._interceptionId);\n",
" this.emit(NetworkManager.Events.RequestFailed, request);\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" const response = request.response();\n",
" if (response)\n",
" response._bodyLoadedPromiseFulfill.call(null);\n"
],
"file_path": "lib/NetworkManager.js",
"type": "replace",
"edit_start_line_idx": 293
} | {
"classes": [
{
"name": "Foo",
"members": [
{
"name": "frame",
"type": "event",
"hasReturn": false,
"async": false,
"args": []
},
{
"name": "$",
"type": "method",
"hasReturn": true,
"async": false,
"args": [
"selector"
]
},
{
"name": "url",
"type": "property",
"hasReturn": false,
"async": false,
"args": []
}
]
}
]
} | utils/doclint/check_public_api/test/md-builder-common/result.txt | 0 | https://github.com/puppeteer/puppeteer/commit/f8cba455ba5d1bc82721e89fda037e86213b02cb | [
0.00017396794282831252,
0.00017173966625705361,
0.00016995826445054263,
0.00017151626525446773,
0.0000014406939499167493
] |
{
"id": 3,
"code_window": [
" this._interceptionId = interceptionId;\n",
" this._allowInterception = allowInterception;\n",
" this._interceptionHandled = false;\n",
" this._response = null;\n",
" this._failureText = null;\n",
" this._completePromise = new Promise(fulfill => {\n",
" this._completePromiseFulfill = fulfill;\n",
" });\n",
"\n",
" this._url = url;\n",
" this._resourceType = resourceType.toLowerCase();\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "lib/NetworkManager.js",
"type": "replace",
"edit_start_line_idx": 321
} | /**
* Copyright 2018 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
const {waitEvent} = require('./utils');
module.exports.addTests = function({testRunner, expect}) {
const {describe, xdescribe, fdescribe} = testRunner;
const {it, fit, xit} = testRunner;
const {beforeAll, beforeEach, afterAll, afterEach} = testRunner;
describe('Network Events', function() {
it('Page.Events.Request', async({page, server}) => {
const requests = [];
page.on('request', request => requests.push(request));
await page.goto(server.EMPTY_PAGE);
expect(requests.length).toBe(1);
expect(requests[0].url()).toBe(server.EMPTY_PAGE);
expect(requests[0].resourceType()).toBe('document');
expect(requests[0].method()).toBe('GET');
expect(requests[0].response()).toBeTruthy();
expect(requests[0].frame() === page.mainFrame()).toBe(true);
expect(requests[0].frame().url()).toBe(server.EMPTY_PAGE);
});
it('Page.Events.Request should report post data', async({page, server}) => {
await page.goto(server.EMPTY_PAGE);
server.setRoute('/post', (req, res) => res.end());
let request = null;
page.on('request', r => request = r);
await page.evaluate(() => fetch('./post', { method: 'POST', body: JSON.stringify({foo: 'bar'})}));
expect(request).toBeTruthy();
expect(request.postData()).toBe('{"foo":"bar"}');
});
it('Page.Events.Response', async({page, server}) => {
const responses = [];
page.on('response', response => responses.push(response));
await page.goto(server.EMPTY_PAGE);
expect(responses.length).toBe(1);
expect(responses[0].url()).toBe(server.EMPTY_PAGE);
expect(responses[0].status()).toBe(200);
expect(responses[0].ok()).toBe(true);
expect(responses[0].fromCache()).toBe(false);
expect(responses[0].fromServiceWorker()).toBe(false);
expect(responses[0].request()).toBeTruthy();
});
it('Response.fromCache()', async({page, server}) => {
const responses = new Map();
page.on('response', r => responses.set(r.url().split('/').pop(), r));
// Load and re-load to make sure it's cached.
await page.goto(server.PREFIX + '/cached/one-style.html');
await page.reload();
expect(responses.size).toBe(2);
expect(responses.get('one-style.html').status()).toBe(304);
expect(responses.get('one-style.html').fromCache()).toBe(false);
expect(responses.get('one-style.css').status()).toBe(200);
expect(responses.get('one-style.css').fromCache()).toBe(true);
});
it('Response.fromServiceWorker', async({page, server}) => {
const responses = new Map();
page.on('response', r => responses.set(r.url().split('/').pop(), r));
// Load and re-load to make sure serviceworker is installed and running.
await page.goto(server.PREFIX + '/serviceworkers/fetch/sw.html', {waitUntil: 'networkidle2'});
await page.evaluate(async() => await window.activationPromise);
await page.reload();
expect(responses.size).toBe(2);
expect(responses.get('sw.html').status()).toBe(200);
expect(responses.get('sw.html').fromServiceWorker()).toBe(true);
expect(responses.get('style.css').status()).toBe(200);
expect(responses.get('style.css').fromServiceWorker()).toBe(true);
});
it('Page.Events.Response should provide body', async({page, server}) => {
let response = null;
page.on('response', r => response = r);
await page.goto(server.PREFIX + '/simple.json');
expect(response).toBeTruthy();
expect(await response.text()).toBe('{"foo": "bar"}\n');
expect(await response.json()).toEqual({foo: 'bar'});
});
it('Page.Events.Response should not report body unless request is finished', async({page, server}) => {
await page.goto(server.EMPTY_PAGE);
// Setup server to trap request.
let serverResponse = null;
server.setRoute('/get', (req, res) => {
serverResponse = res;
res.write('hello ');
});
// Setup page to trap response.
let pageResponse = null;
let requestFinished = false;
page.on('response', r => pageResponse = r);
page.on('requestfinished', () => requestFinished = true);
// send request and wait for server response
await Promise.all([
page.evaluate(() => fetch('./get', { method: 'GET'})),
waitEvent(page, 'response')
]);
expect(serverResponse).toBeTruthy();
expect(pageResponse).toBeTruthy();
expect(pageResponse.status()).toBe(200);
expect(requestFinished).toBe(false);
const responseText = pageResponse.text();
// Write part of the response and wait for it to be flushed.
await new Promise(x => serverResponse.write('wor', x));
// Finish response.
await new Promise(x => serverResponse.end('ld!', x));
expect(await responseText).toBe('hello world!');
});
it('Page.Events.RequestFailed', async({page, server}) => {
await page.setRequestInterception(true);
page.on('request', request => {
if (request.url().endsWith('css'))
request.abort();
else
request.continue();
});
const failedRequests = [];
page.on('requestfailed', request => failedRequests.push(request));
await page.goto(server.PREFIX + '/one-style.html');
expect(failedRequests.length).toBe(1);
expect(failedRequests[0].url()).toContain('one-style.css');
expect(failedRequests[0].response()).toBe(null);
expect(failedRequests[0].resourceType()).toBe('stylesheet');
expect(failedRequests[0].failure().errorText).toBe('net::ERR_FAILED');
expect(failedRequests[0].frame()).toBeTruthy();
});
it('Page.Events.RequestFinished', async({page, server}) => {
const requests = [];
page.on('requestfinished', request => requests.push(request));
await page.goto(server.EMPTY_PAGE);
expect(requests.length).toBe(1);
expect(requests[0].url()).toBe(server.EMPTY_PAGE);
expect(requests[0].response()).toBeTruthy();
expect(requests[0].frame() === page.mainFrame()).toBe(true);
expect(requests[0].frame().url()).toBe(server.EMPTY_PAGE);
});
it('should fire events in proper order', async({page, server}) => {
const events = [];
page.on('request', request => events.push('request'));
page.on('response', response => events.push('response'));
page.on('requestfinished', request => events.push('requestfinished'));
await page.goto(server.EMPTY_PAGE);
expect(events).toEqual(['request', 'response', 'requestfinished']);
});
it('should support redirects', async({page, server}) => {
const events = [];
page.on('request', request => events.push(`${request.method()} ${request.url()}`));
page.on('response', response => events.push(`${response.status()} ${response.url()}`));
page.on('requestfinished', request => events.push(`DONE ${request.url()}`));
page.on('requestfailed', request => events.push(`FAIL ${request.url()}`));
server.setRedirect('/foo.html', '/empty.html');
const FOO_URL = server.PREFIX + '/foo.html';
const response = await page.goto(FOO_URL);
expect(events).toEqual([
`GET ${FOO_URL}`,
`302 ${FOO_URL}`,
`DONE ${FOO_URL}`,
`GET ${server.EMPTY_PAGE}`,
`200 ${server.EMPTY_PAGE}`,
`DONE ${server.EMPTY_PAGE}`
]);
// Check redirect chain
const redirectChain = response.request().redirectChain();
expect(redirectChain.length).toBe(1);
expect(redirectChain[0].url()).toContain('/foo.html');
});
});
};
| test/network.spec.js | 1 | https://github.com/puppeteer/puppeteer/commit/f8cba455ba5d1bc82721e89fda037e86213b02cb | [
0.00019856418657582253,
0.00017200644651893526,
0.00016338103159796447,
0.0001705794275039807,
0.000006953081083338475
] |
{
"id": 3,
"code_window": [
" this._interceptionId = interceptionId;\n",
" this._allowInterception = allowInterception;\n",
" this._interceptionHandled = false;\n",
" this._response = null;\n",
" this._failureText = null;\n",
" this._completePromise = new Promise(fulfill => {\n",
" this._completePromiseFulfill = fulfill;\n",
" });\n",
"\n",
" this._url = url;\n",
" this._resourceType = resourceType.toLowerCase();\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "lib/NetworkManager.js",
"type": "replace",
"edit_start_line_idx": 321
} | /**
* Copyright 2017 Google Inc., PhantomJS Authors All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
const puppeteer = require('puppeteer');
(async() => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.setRequestInterception(true);
page.on('request', request => {
if (request.resourceType() === 'image')
request.abort();
else
request.continue();
});
await page.goto('https://news.google.com/news/');
await page.screenshot({path: 'news.png', fullPage: true});
await browser.close();
})();
| examples/block-images.js | 0 | https://github.com/puppeteer/puppeteer/commit/f8cba455ba5d1bc82721e89fda037e86213b02cb | [
0.00017460026720073074,
0.0001722087326925248,
0.00016568451246712357,
0.00017427510465495288,
0.0000037693614558520494
] |
{
"id": 3,
"code_window": [
" this._interceptionId = interceptionId;\n",
" this._allowInterception = allowInterception;\n",
" this._interceptionHandled = false;\n",
" this._response = null;\n",
" this._failureText = null;\n",
" this._completePromise = new Promise(fulfill => {\n",
" this._completePromiseFulfill = fulfill;\n",
" });\n",
"\n",
" this._url = url;\n",
" this._resourceType = resourceType.toLowerCase();\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "lib/NetworkManager.js",
"type": "replace",
"edit_start_line_idx": 321
} | <link rel='stylesheet' href='./one-style.css'>
<div>hello, world!</div>
| test/assets/one-style.html | 0 | https://github.com/puppeteer/puppeteer/commit/f8cba455ba5d1bc82721e89fda037e86213b02cb | [
0.00017123013094533235,
0.00017123013094533235,
0.00017123013094533235,
0.00017123013094533235,
0
] |
{
"id": 3,
"code_window": [
" this._interceptionId = interceptionId;\n",
" this._allowInterception = allowInterception;\n",
" this._interceptionHandled = false;\n",
" this._response = null;\n",
" this._failureText = null;\n",
" this._completePromise = new Promise(fulfill => {\n",
" this._completePromiseFulfill = fulfill;\n",
" });\n",
"\n",
" this._url = url;\n",
" this._resourceType = resourceType.toLowerCase();\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "lib/NetworkManager.js",
"type": "replace",
"edit_start_line_idx": 321
} | /**
* Copyright 2017 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
const markdownToc = require('markdown-toc');
const Message = require('./Message');
/**
* @param {!Array<!Source>} sources
* @return {!Array<!Message>}
*/
module.exports = function(sources) {
const warnings = [];
for (const source of sources) {
const newText = markdownToc.insert(source.text());
if (source.setText(newText))
warnings.push('Regenerated table-of-contexts: ' + source.projectPath());
}
return warnings.map(warning => Message.warning(warning));
};
| utils/doclint/toc.js | 0 | https://github.com/puppeteer/puppeteer/commit/f8cba455ba5d1bc82721e89fda037e86213b02cb | [
0.0001760848972480744,
0.00017429869330953807,
0.0001716253609629348,
0.00017474225023761392,
0.0000016427158016085741
] |
{
"id": 4,
"code_window": [
" this._request = request;\n",
" this._contentPromise = null;\n",
"\n",
" this._status = status;\n",
" this._url = request.url();\n",
" this._fromDiskCache = fromDiskCache;\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" this._bodyLoadedPromise = new Promise(fulfill => {\n",
" this._bodyLoadedPromiseFulfill = fulfill;\n",
" });\n",
"\n"
],
"file_path": "lib/NetworkManager.js",
"type": "add",
"edit_start_line_idx": 525
} | /**
* Copyright 2017 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
const EventEmitter = require('events');
const {helper, debugError} = require('./helper');
const Multimap = require('./Multimap');
class NetworkManager extends EventEmitter {
/**
* @param {!Puppeteer.CDPSession} client
* @param {!Puppeteer.FrameManager} frameManager
*/
constructor(client, frameManager) {
super();
this._client = client;
this._frameManager = frameManager;
/** @type {!Map<string, !Request>} */
this._requestIdToRequest = new Map();
/** @type {!Map<string, !Request>} */
this._interceptionIdToRequest = new Map();
/** @type {!Object<string, string>} */
this._extraHTTPHeaders = {};
this._offline = false;
/** @type {?{username: string, password: string}} */
this._credentials = null;
/** @type {!Set<string>} */
this._attemptedAuthentications = new Set();
this._userRequestInterceptionEnabled = false;
this._protocolRequestInterceptionEnabled = false;
/** @type {!Multimap} */
this._requestHashToRequestIds = new Multimap();
/** @type {!Multimap} */
this._requestHashToInterceptionIds = new Multimap();
this._client.on('Network.requestWillBeSent', this._onRequestWillBeSent.bind(this));
this._client.on('Network.requestIntercepted', this._onRequestIntercepted.bind(this));
this._client.on('Network.requestServedFromCache', this._onRequestServedFromCache.bind(this));
this._client.on('Network.responseReceived', this._onResponseReceived.bind(this));
this._client.on('Network.loadingFinished', this._onLoadingFinished.bind(this));
this._client.on('Network.loadingFailed', this._onLoadingFailed.bind(this));
}
/**
* @param {?{username: string, password: string}} credentials
*/
async authenticate(credentials) {
this._credentials = credentials;
await this._updateProtocolRequestInterception();
}
/**
* @param {!Object<string, string>} extraHTTPHeaders
*/
async setExtraHTTPHeaders(extraHTTPHeaders) {
this._extraHTTPHeaders = {};
for (const key of Object.keys(extraHTTPHeaders)) {
const value = extraHTTPHeaders[key];
console.assert(helper.isString(value), `Expected value of header "${key}" to be String, but "${typeof value}" is found.`);
this._extraHTTPHeaders[key.toLowerCase()] = value;
}
await this._client.send('Network.setExtraHTTPHeaders', { headers: this._extraHTTPHeaders });
}
/**
* @return {!Object<string, string>}
*/
extraHTTPHeaders() {
return Object.assign({}, this._extraHTTPHeaders);
}
/**
* @param {boolean} value
*/
async setOfflineMode(value) {
if (this._offline === value)
return;
this._offline = value;
await this._client.send('Network.emulateNetworkConditions', {
offline: this._offline,
// values of 0 remove any active throttling. crbug.com/456324#c9
latency: 0,
downloadThroughput: -1,
uploadThroughput: -1
});
}
/**
* @param {string} userAgent
*/
async setUserAgent(userAgent) {
await this._client.send('Network.setUserAgentOverride', { userAgent });
}
/**
* @param {boolean} value
*/
async setRequestInterception(value) {
this._userRequestInterceptionEnabled = value;
await this._updateProtocolRequestInterception();
}
async _updateProtocolRequestInterception() {
const enabled = this._userRequestInterceptionEnabled || !!this._credentials;
if (enabled === this._protocolRequestInterceptionEnabled)
return;
this._protocolRequestInterceptionEnabled = enabled;
const patterns = enabled ? [{urlPattern: '*'}] : [];
await Promise.all([
this._client.send('Network.setCacheDisabled', {cacheDisabled: enabled}),
this._client.send('Network.setRequestInterception', {patterns})
]);
}
/**
* @param {!Protocol.Network.requestInterceptedPayload} event
*/
_onRequestIntercepted(event) {
if (event.authChallenge) {
/** @type {"Default"|"CancelAuth"|"ProvideCredentials"} */
let response = 'Default';
if (this._attemptedAuthentications.has(event.interceptionId)) {
response = 'CancelAuth';
} else if (this._credentials) {
response = 'ProvideCredentials';
this._attemptedAuthentications.add(event.interceptionId);
}
const {username, password} = this._credentials || {username: undefined, password: undefined};
this._client.send('Network.continueInterceptedRequest', {
interceptionId: event.interceptionId,
authChallengeResponse: { response, username, password }
}).catch(debugError);
return;
}
if (!this._userRequestInterceptionEnabled && this._protocolRequestInterceptionEnabled) {
this._client.send('Network.continueInterceptedRequest', {
interceptionId: event.interceptionId
}).catch(debugError);
}
if (event.redirectUrl) {
const request = this._interceptionIdToRequest.get(event.interceptionId);
if (request) {
this._handleRequestRedirect(request, event.responseStatusCode, event.responseHeaders, false /* fromDiskCache */, false /* fromServiceWorker */, null /* securityDetails */);
this._handleRequestStart(request._requestId, event.interceptionId, event.redirectUrl, event.resourceType, event.request, event.frameId, request._redirectChain);
}
return;
}
const requestHash = generateRequestHash(event.request);
const requestId = this._requestHashToRequestIds.firstValue(requestHash);
if (requestId) {
this._requestHashToRequestIds.delete(requestHash, requestId);
this._handleRequestStart(requestId, event.interceptionId, event.request.url, event.resourceType, event.request, event.frameId, []);
} else {
this._requestHashToInterceptionIds.set(requestHash, event.interceptionId);
this._handleRequestStart(null, event.interceptionId, event.request.url, event.resourceType, event.request, event.frameId, []);
}
}
/**
* @param {!Protocol.Network.requestServedFromCachePayload} event
*/
_onRequestServedFromCache(event) {
const request = this._requestIdToRequest.get(event.requestId);
if (request)
request._fromMemoryCache = true;
}
/**
* @param {!Request} request
* @param {number} redirectStatus
* @param {!Object} redirectHeaders
* @param {boolean} fromDiskCache
* @param {boolean} fromServiceWorker
* @param {?Object} securityDetails
*/
_handleRequestRedirect(request, redirectStatus, redirectHeaders, fromDiskCache, fromServiceWorker, securityDetails) {
const response = new Response(this._client, request, redirectStatus, redirectHeaders, fromDiskCache, fromServiceWorker, securityDetails);
request._response = response;
request._redirectChain.push(request);
this._requestIdToRequest.delete(request._requestId);
this._interceptionIdToRequest.delete(request._interceptionId);
this._attemptedAuthentications.delete(request._interceptionId);
this.emit(NetworkManager.Events.Response, response);
this.emit(NetworkManager.Events.RequestFinished, request);
}
/**
* @param {?string} requestId
* @param {?string} interceptionId
* @param {string} url
* @param {string} resourceType
* @param {!Protocol.Network.Request} requestPayload
* @param {?string} frameId
* @param {!Array<!Request>} redirectChain
*/
_handleRequestStart(requestId, interceptionId, url, resourceType, requestPayload, frameId, redirectChain) {
let frame = null;
if (frameId)
frame = this._frameManager.frame(frameId);
const request = new Request(this._client, requestId, interceptionId, this._userRequestInterceptionEnabled, url, resourceType, requestPayload, frame, redirectChain);
if (requestId)
this._requestIdToRequest.set(requestId, request);
if (interceptionId)
this._interceptionIdToRequest.set(interceptionId, request);
this.emit(NetworkManager.Events.Request, request);
}
/**
* @param {!Protocol.Network.requestWillBeSentPayload} event
*/
_onRequestWillBeSent(event) {
if (this._protocolRequestInterceptionEnabled) {
// All redirects are handled in requestIntercepted.
if (event.redirectResponse)
return;
const requestHash = generateRequestHash(event.request);
const interceptionId = this._requestHashToInterceptionIds.firstValue(requestHash);
const request = interceptionId ? this._interceptionIdToRequest.get(interceptionId) : null;
if (request) {
request._requestId = event.requestId;
this._requestIdToRequest.set(event.requestId, request);
this._requestHashToInterceptionIds.delete(requestHash, interceptionId);
} else {
this._requestHashToRequestIds.set(requestHash, event.requestId);
}
return;
}
let redirectChain = [];
if (event.redirectResponse) {
const request = this._requestIdToRequest.get(event.requestId);
// If we connect late to the target, we could have missed the requestWillBeSent event.
if (request) {
this._handleRequestRedirect(request, event.redirectResponse.status, event.redirectResponse.headers, event.redirectResponse.fromDiskCache, event.redirectResponse.fromServiceWorker, event.redirectResponse.securityDetails);
redirectChain = request._redirectChain;
}
}
this._handleRequestStart(event.requestId, null, event.request.url, event.type, event.request, event.frameId, redirectChain);
}
/**
* @param {!Protocol.Network.responseReceivedPayload} event
*/
_onResponseReceived(event) {
const request = this._requestIdToRequest.get(event.requestId);
// FileUpload sends a response without a matching request.
if (!request)
return;
const response = new Response(this._client, request, event.response.status, event.response.headers,
event.response.fromDiskCache, event.response.fromServiceWorker, event.response.securityDetails);
request._response = response;
this.emit(NetworkManager.Events.Response, response);
}
/**
* @param {!Protocol.Network.loadingFinishedPayload} event
*/
_onLoadingFinished(event) {
const request = this._requestIdToRequest.get(event.requestId);
// For certain requestIds we never receive requestWillBeSent event.
// @see https://crbug.com/750469
if (!request)
return;
request._completePromiseFulfill.call(null);
this._requestIdToRequest.delete(request._requestId);
this._interceptionIdToRequest.delete(request._interceptionId);
this._attemptedAuthentications.delete(request._interceptionId);
this.emit(NetworkManager.Events.RequestFinished, request);
}
/**
* @param {!Protocol.Network.loadingFailedPayload} event
*/
_onLoadingFailed(event) {
const request = this._requestIdToRequest.get(event.requestId);
// For certain requestIds we never receive requestWillBeSent event.
// @see https://crbug.com/750469
if (!request)
return;
request._failureText = event.errorText;
request._completePromiseFulfill.call(null);
this._requestIdToRequest.delete(request._requestId);
this._interceptionIdToRequest.delete(request._interceptionId);
this._attemptedAuthentications.delete(request._interceptionId);
this.emit(NetworkManager.Events.RequestFailed, request);
}
}
class Request {
/**
* @param {!Puppeteer.CDPSession} client
* @param {?string} requestId
* @param {string} interceptionId
* @param {boolean} allowInterception
* @param {string} url
* @param {string} resourceType
* @param {!Protocol.Network.Request} payload
* @param {?Puppeteer.Frame} frame
* @param {!Array<!Request>} redirectChain
*/
constructor(client, requestId, interceptionId, allowInterception, url, resourceType, payload, frame, redirectChain) {
this._client = client;
this._requestId = requestId;
this._interceptionId = interceptionId;
this._allowInterception = allowInterception;
this._interceptionHandled = false;
this._response = null;
this._failureText = null;
this._completePromise = new Promise(fulfill => {
this._completePromiseFulfill = fulfill;
});
this._url = url;
this._resourceType = resourceType.toLowerCase();
this._method = payload.method;
this._postData = payload.postData;
this._headers = {};
this._frame = frame;
this._redirectChain = redirectChain;
for (const key of Object.keys(payload.headers))
this._headers[key.toLowerCase()] = payload.headers[key];
this._fromMemoryCache = false;
}
/**
* @return {string}
*/
url() {
return this._url;
}
/**
* @return {string}
*/
resourceType() {
return this._resourceType;
}
/**
* @return {string}
*/
method() {
return this._method;
}
/**
* @return {string}
*/
postData() {
return this._postData;
}
/**
* @return {!Object}
*/
headers() {
return this._headers;
}
/**
* @return {?Response}
*/
response() {
return this._response;
}
/**
* @return {?Puppeteer.Frame}
*/
frame() {
return this._frame;
}
/**
* @return {!Array<!Request>}
*/
redirectChain() {
return this._redirectChain.slice();
}
/**
* @return {?{errorText: string}}
*/
failure() {
if (!this._failureText)
return null;
return {
errorText: this._failureText
};
}
/**
* @param {!Object=} overrides
*/
async continue(overrides = {}) {
console.assert(this._allowInterception, 'Request Interception is not enabled!');
console.assert(!this._interceptionHandled, 'Request is already handled!');
this._interceptionHandled = true;
await this._client.send('Network.continueInterceptedRequest', {
interceptionId: this._interceptionId,
url: overrides.url,
method: overrides.method,
postData: overrides.postData,
headers: overrides.headers,
}).catch(error => {
// In certain cases, protocol will return error if the request was already canceled
// or the page was closed. We should tolerate these errors.
debugError(error);
});
}
/**
* @param {!{status: number, headers: Object, contentType: string, body: (string|Buffer)}} response
*/
async respond(response) {
// Mocking responses for dataURL requests is not currently supported.
if (this._url.startsWith('data:'))
return;
console.assert(this._allowInterception, 'Request Interception is not enabled!');
console.assert(!this._interceptionHandled, 'Request is already handled!');
this._interceptionHandled = true;
const responseBody = response.body && helper.isString(response.body) ? Buffer.from(/** @type {string} */(response.body)) : /** @type {?Buffer} */(response.body || null);
const responseHeaders = {};
if (response.headers) {
for (const header of Object.keys(response.headers))
responseHeaders[header.toLowerCase()] = response.headers[header];
}
if (response.contentType)
responseHeaders['content-type'] = response.contentType;
if (responseBody && !('content-length' in responseHeaders)) {
// @ts-ignore
responseHeaders['content-length'] = Buffer.byteLength(responseBody);
}
const statusCode = response.status || 200;
const statusText = statusTexts[statusCode] || '';
const statusLine = `HTTP/1.1 ${statusCode} ${statusText}`;
const CRLF = '\r\n';
let text = statusLine + CRLF;
for (const header of Object.keys(responseHeaders))
text += header + ': ' + responseHeaders[header] + CRLF;
text += CRLF;
let responseBuffer = Buffer.from(text, 'utf8');
if (responseBody)
responseBuffer = Buffer.concat([responseBuffer, responseBody]);
await this._client.send('Network.continueInterceptedRequest', {
interceptionId: this._interceptionId,
rawResponse: responseBuffer.toString('base64')
}).catch(error => {
// In certain cases, protocol will return error if the request was already canceled
// or the page was closed. We should tolerate these errors.
debugError(error);
});
}
/**
* @param {string=} errorCode
*/
async abort(errorCode = 'failed') {
const errorReason = errorReasons[errorCode];
console.assert(errorReason, 'Unknown error code: ' + errorCode);
console.assert(this._allowInterception, 'Request Interception is not enabled!');
console.assert(!this._interceptionHandled, 'Request is already handled!');
this._interceptionHandled = true;
await this._client.send('Network.continueInterceptedRequest', {
interceptionId: this._interceptionId,
errorReason
}).catch(error => {
// In certain cases, protocol will return error if the request was already canceled
// or the page was closed. We should tolerate these errors.
debugError(error);
});
}
}
const errorReasons = {
'aborted': 'Aborted',
'accessdenied': 'AccessDenied',
'addressunreachable': 'AddressUnreachable',
'connectionaborted': 'ConnectionAborted',
'connectionclosed': 'ConnectionClosed',
'connectionfailed': 'ConnectionFailed',
'connectionrefused': 'ConnectionRefused',
'connectionreset': 'ConnectionReset',
'internetdisconnected': 'InternetDisconnected',
'namenotresolved': 'NameNotResolved',
'timedout': 'TimedOut',
'failed': 'Failed',
};
helper.tracePublicAPI(Request);
class Response {
/**
* @param {!Puppeteer.CDPSession} client
* @param {!Request} request
* @param {number} status
* @param {!Object} headers
* @param {boolean} fromDiskCache
* @param {boolean} fromServiceWorker
* @param {?Object} securityDetails
*/
constructor(client, request, status, headers, fromDiskCache, fromServiceWorker, securityDetails) {
this._client = client;
this._request = request;
this._contentPromise = null;
this._status = status;
this._url = request.url();
this._fromDiskCache = fromDiskCache;
this._fromServiceWorker = fromServiceWorker;
this._headers = {};
for (const key of Object.keys(headers))
this._headers[key.toLowerCase()] = headers[key];
this._securityDetails = null;
if (securityDetails) {
this._securityDetails = new SecurityDetails(
securityDetails['subjectName'],
securityDetails['issuer'],
securityDetails['validFrom'],
securityDetails['validTo'],
securityDetails['protocol']);
}
}
/**
* @return {string}
*/
url() {
return this._url;
}
/**
* @return {boolean}
*/
ok() {
return this._status === 0 || (this._status >= 200 && this._status <= 299);
}
/**
* @return {number}
*/
status() {
return this._status;
}
/**
* @return {!Object}
*/
headers() {
return this._headers;
}
/**
* @return {?SecurityDetails}
*/
securityDetails() {
return this._securityDetails;
}
/**
* @return {!Promise<!Buffer>}
*/
buffer() {
if (!this._contentPromise) {
this._contentPromise = this._request._completePromise.then(async() => {
const response = await this._client.send('Network.getResponseBody', {
requestId: this._request._requestId
});
return Buffer.from(response.body, response.base64Encoded ? 'base64' : 'utf8');
});
}
return this._contentPromise;
}
/**
* @return {!Promise<string>}
*/
async text() {
const content = await this.buffer();
return content.toString('utf8');
}
/**
* @return {!Promise<!Object>}
*/
async json() {
const content = await this.text();
return JSON.parse(content);
}
/**
* @return {!Request}
*/
request() {
return this._request;
}
/**
* @return {boolean}
*/
fromCache() {
return this._fromDiskCache || this._request._fromMemoryCache;
}
/**
* @return {boolean}
*/
fromServiceWorker() {
return this._fromServiceWorker;
}
}
helper.tracePublicAPI(Response);
/**
* @param {!Protocol.Network.Request} request
* @return {string}
*/
function generateRequestHash(request) {
let normalizedURL = request.url;
try {
// Decoding is necessary to normalize URLs. @see crbug.com/759388
// The method will throw if the URL is malformed. In this case,
// consider URL to be normalized as-is.
normalizedURL = decodeURI(request.url);
} catch (e) {
}
const hash = {
url: normalizedURL,
method: request.method,
postData: request.postData,
headers: {},
};
if (!normalizedURL.startsWith('data:')) {
const headers = Object.keys(request.headers);
headers.sort();
for (let header of headers) {
const headerValue = request.headers[header];
header = header.toLowerCase();
if (header === 'accept' || header === 'referer' || header === 'x-devtools-emulate-network-conditions-client-id')
continue;
hash.headers[header] = headerValue;
}
}
return JSON.stringify(hash);
}
class SecurityDetails {
/**
* @param {string} subjectName
* @param {string} issuer
* @param {number} validFrom
* @param {number} validTo
* @param {string} protocol
*/
constructor(subjectName, issuer, validFrom, validTo, protocol) {
this._subjectName = subjectName;
this._issuer = issuer;
this._validFrom = validFrom;
this._validTo = validTo;
this._protocol = protocol;
}
/**
* @return {string}
*/
subjectName() {
return this._subjectName;
}
/**
* @return {string}
*/
issuer() {
return this._issuer;
}
/**
* @return {number}
*/
validFrom() {
return this._validFrom;
}
/**
* @return {number}
*/
validTo() {
return this._validTo;
}
/**
* @return {string}
*/
protocol() {
return this._protocol;
}
}
NetworkManager.Events = {
Request: 'request',
Response: 'response',
RequestFailed: 'requestfailed',
RequestFinished: 'requestfinished',
};
const statusTexts = {
'100': 'Continue',
'101': 'Switching Protocols',
'102': 'Processing',
'200': 'OK',
'201': 'Created',
'202': 'Accepted',
'203': 'Non-Authoritative Information',
'204': 'No Content',
'206': 'Partial Content',
'207': 'Multi-Status',
'208': 'Already Reported',
'209': 'IM Used',
'300': 'Multiple Choices',
'301': 'Moved Permanently',
'302': 'Found',
'303': 'See Other',
'304': 'Not Modified',
'305': 'Use Proxy',
'306': 'Switch Proxy',
'307': 'Temporary Redirect',
'308': 'Permanent Redirect',
'400': 'Bad Request',
'401': 'Unauthorized',
'402': 'Payment Required',
'403': 'Forbidden',
'404': 'Not Found',
'405': 'Method Not Allowed',
'406': 'Not Acceptable',
'407': 'Proxy Authentication Required',
'408': 'Request Timeout',
'409': 'Conflict',
'410': 'Gone',
'411': 'Length Required',
'412': 'Precondition Failed',
'413': 'Payload Too Large',
'414': 'URI Too Long',
'415': 'Unsupported Media Type',
'416': 'Range Not Satisfiable',
'417': 'Expectation Failed',
'418': 'I\'m a teapot',
'421': 'Misdirected Request',
'422': 'Unprocessable Entity',
'423': 'Locked',
'424': 'Failed Dependency',
'426': 'Upgrade Required',
'428': 'Precondition Required',
'429': 'Too Many Requests',
'431': 'Request Header Fields Too Large',
'451': 'Unavailable For Legal Reasons',
'500': 'Internal Server Error',
'501': 'Not Implemented',
'502': 'Bad Gateway',
'503': 'Service Unavailable',
'504': 'Gateway Timeout',
'505': 'HTTP Version Not Supported',
'506': 'Variant Also Negotiates',
'507': 'Insufficient Storage',
'508': 'Loop Detected',
'510': 'Not Extended',
'511': 'Network Authentication Required',
};
module.exports = {Request, Response, NetworkManager};
| lib/NetworkManager.js | 1 | https://github.com/puppeteer/puppeteer/commit/f8cba455ba5d1bc82721e89fda037e86213b02cb | [
0.9946388602256775,
0.04942692816257477,
0.00016444538778159767,
0.0001774140982888639,
0.18483707308769226
] |
{
"id": 4,
"code_window": [
" this._request = request;\n",
" this._contentPromise = null;\n",
"\n",
" this._status = status;\n",
" this._url = request.url();\n",
" this._fromDiskCache = fromDiskCache;\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" this._bodyLoadedPromise = new Promise(fulfill => {\n",
" this._bodyLoadedPromiseFulfill = fulfill;\n",
" });\n",
"\n"
],
"file_path": "lib/NetworkManager.js",
"type": "add",
"edit_start_line_idx": 525
} | /**
* Copyright 2017 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
const {TestRunner, Reporter, Matchers} = require('..');
const runner = new TestRunner();
const reporter = new Reporter(runner);
const {expect} = new Matchers();
const {describe, xdescribe, fdescribe} = runner;
const {it, fit, xit} = runner;
const {beforeAll, beforeEach, afterAll, afterEach} = runner;
describe('testsuite', () => {
beforeAll(() => {
expect(false).toBeTruthy();
});
it('test', async () => {
});
});
runner.run();
| utils/testrunner/examples/hookfail.js | 0 | https://github.com/puppeteer/puppeteer/commit/f8cba455ba5d1bc82721e89fda037e86213b02cb | [
0.00017771936836652458,
0.00017614421085454524,
0.00017434540495742112,
0.00017625604232307523,
0.0000013798525060337852
] |
{
"id": 4,
"code_window": [
" this._request = request;\n",
" this._contentPromise = null;\n",
"\n",
" this._status = status;\n",
" this._url = request.url();\n",
" this._fromDiskCache = fromDiskCache;\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" this._bodyLoadedPromise = new Promise(fulfill => {\n",
" this._bodyLoadedPromiseFulfill = fulfill;\n",
" });\n",
"\n"
],
"file_path": "lib/NetworkManager.js",
"type": "add",
"edit_start_line_idx": 525
} | /**
* Copyright 2017 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
const fs = require('fs');
const path = require('path');
module.exports.addTests = function({testRunner, expect}) {
const {describe, xdescribe, fdescribe} = testRunner;
const {it, fit, xit} = testRunner;
const {beforeAll, beforeEach, afterAll, afterEach} = testRunner;
describe('Tracing', function() {
beforeEach(function(state) {
state.outputFile = path.join(__dirname, 'assets', `trace-${state.parallelIndex}.json`);
});
afterEach(function(state) {
fs.unlinkSync(state.outputFile);
state.outputFile = null;
});
it('should output a trace', async({page, server, outputFile}) => {
await page.tracing.start({screenshots: true, path: outputFile});
await page.goto(server.PREFIX + '/grid.html');
await page.tracing.stop();
expect(fs.existsSync(outputFile)).toBe(true);
});
it('should run with custom categories if provided', async({page, outputFile}) => {
await page.tracing.start({path: outputFile, categories: ['disabled-by-default-v8.cpu_profiler.hires']});
await page.tracing.stop();
const traceJson = JSON.parse(fs.readFileSync(outputFile));
expect(traceJson.metadata['trace-config']).toContain('disabled-by-default-v8.cpu_profiler.hires');
});
it('should throw if tracing on two pages', async({page, server, browser, outputFile}) => {
await page.tracing.start({path: outputFile});
const newPage = await browser.newPage();
let error = null;
await newPage.tracing.start({path: outputFile}).catch(e => error = e);
await newPage.close();
expect(error).toBeTruthy();
await page.tracing.stop();
});
});
};
| test/tracing.spec.js | 0 | https://github.com/puppeteer/puppeteer/commit/f8cba455ba5d1bc82721e89fda037e86213b02cb | [
0.00017738027963787317,
0.00017542084970045835,
0.00017315850709564984,
0.00017529813339933753,
0.0000012901631407657987
] |
{
"id": 4,
"code_window": [
" this._request = request;\n",
" this._contentPromise = null;\n",
"\n",
" this._status = status;\n",
" this._url = request.url();\n",
" this._fromDiskCache = fromDiskCache;\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" this._bodyLoadedPromise = new Promise(fulfill => {\n",
" this._bodyLoadedPromiseFulfill = fulfill;\n",
" });\n",
"\n"
],
"file_path": "lib/NetworkManager.js",
"type": "add",
"edit_start_line_idx": 525
} | /**
* Copyright 2017 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
const fs = require('fs');
const EventEmitter = require('events');
const mime = require('mime');
const {NetworkManager} = require('./NetworkManager');
const NavigatorWatcher = require('./NavigatorWatcher');
const Dialog = require('./Dialog');
const EmulationManager = require('./EmulationManager');
const {FrameManager} = require('./FrameManager');
const {Keyboard, Mouse, Touchscreen} = require('./Input');
const Tracing = require('./Tracing');
const {helper, debugError} = require('./helper');
const {Coverage} = require('./Coverage');
const writeFileAsync = helper.promisify(fs.writeFile);
class Page extends EventEmitter {
/**
* @param {!Puppeteer.CDPSession} client
* @param {!Puppeteer.Target} target
* @param {boolean} ignoreHTTPSErrors
* @param {boolean} setDefaultViewport
* @param {!Puppeteer.TaskQueue} screenshotTaskQueue
* @return {!Promise<!Page>}
*/
static async create(client, target, ignoreHTTPSErrors, setDefaultViewport, screenshotTaskQueue) {
await client.send('Page.enable');
const {frameTree} = await client.send('Page.getFrameTree');
const page = new Page(client, target, frameTree, ignoreHTTPSErrors, screenshotTaskQueue);
await Promise.all([
client.send('Page.setLifecycleEventsEnabled', { enabled: true }),
client.send('Network.enable', {}),
client.send('Runtime.enable', {}),
client.send('Security.enable', {}),
client.send('Performance.enable', {}),
]);
if (ignoreHTTPSErrors)
await client.send('Security.setOverrideCertificateErrors', {override: true});
// Initialize default page size.
if (setDefaultViewport)
await page.setViewport({width: 800, height: 600});
return page;
}
/**
* @param {!Puppeteer.CDPSession} client
* @param {!Puppeteer.Target} target
* @param {!Protocol.Page.FrameTree} frameTree
* @param {boolean} ignoreHTTPSErrors
* @param {!Puppeteer.TaskQueue} screenshotTaskQueue
*/
constructor(client, target, frameTree, ignoreHTTPSErrors, screenshotTaskQueue) {
super();
this._client = client;
this._target = target;
this._keyboard = new Keyboard(client);
this._mouse = new Mouse(client, this._keyboard);
this._touchscreen = new Touchscreen(client, this._keyboard);
this._frameManager = new FrameManager(client, frameTree, this);
this._networkManager = new NetworkManager(client, this._frameManager);
this._emulationManager = new EmulationManager(client);
this._tracing = new Tracing(client);
/** @type {!Map<string, Function>} */
this._pageBindings = new Map();
this._ignoreHTTPSErrors = ignoreHTTPSErrors;
this._coverage = new Coverage(client);
this._defaultNavigationTimeout = 30000;
this._screenshotTaskQueue = screenshotTaskQueue;
this._frameManager.on(FrameManager.Events.FrameAttached, event => this.emit(Page.Events.FrameAttached, event));
this._frameManager.on(FrameManager.Events.FrameDetached, event => this.emit(Page.Events.FrameDetached, event));
this._frameManager.on(FrameManager.Events.FrameNavigated, event => this.emit(Page.Events.FrameNavigated, event));
this._networkManager.on(NetworkManager.Events.Request, event => this.emit(Page.Events.Request, event));
this._networkManager.on(NetworkManager.Events.Response, event => this.emit(Page.Events.Response, event));
this._networkManager.on(NetworkManager.Events.RequestFailed, event => this.emit(Page.Events.RequestFailed, event));
this._networkManager.on(NetworkManager.Events.RequestFinished, event => this.emit(Page.Events.RequestFinished, event));
client.on('Page.domContentEventFired', event => this.emit(Page.Events.DOMContentLoaded));
client.on('Page.loadEventFired', event => this.emit(Page.Events.Load));
client.on('Runtime.consoleAPICalled', event => this._onConsoleAPI(event));
client.on('Page.javascriptDialogOpening', event => this._onDialog(event));
client.on('Runtime.exceptionThrown', exception => this._handleException(exception.exceptionDetails));
client.on('Security.certificateError', event => this._onCertificateError(event));
client.on('Inspector.targetCrashed', event => this._onTargetCrashed());
client.on('Performance.metrics', event => this._emitMetrics(event));
this._target._isClosedPromise.then(() => this.emit(Page.Events.Close));
}
/**
* @return {!Puppeteer.Target}
*/
target() {
return this._target;
}
_onTargetCrashed() {
this.emit('error', new Error('Page crashed!'));
}
/**
* @return {!Puppeteer.Frame}
*/
mainFrame() {
return this._frameManager.mainFrame();
}
/**
* @return {!Keyboard}
*/
get keyboard() {
return this._keyboard;
}
/**
* @return {!Touchscreen}
*/
get touchscreen() {
return this._touchscreen;
}
/**
* @return {!Coverage}
*/
get coverage() {
return this._coverage;
}
/**
* @return {!Tracing}
*/
get tracing() {
return this._tracing;
}
/**
* @return {!Array<Puppeteer.Frame>}
*/
frames() {
return this._frameManager.frames();
}
/**
* @param {boolean} value
*/
async setRequestInterception(value) {
return this._networkManager.setRequestInterception(value);
}
/**
* @param {boolean} enabled
*/
setOfflineMode(enabled) {
return this._networkManager.setOfflineMode(enabled);
}
/**
* @param {number} timeout
*/
setDefaultNavigationTimeout(timeout) {
this._defaultNavigationTimeout = timeout;
}
/**
* @param {!Protocol.Security.certificateErrorPayload} event
*/
_onCertificateError(event) {
if (!this._ignoreHTTPSErrors)
return;
this._client.send('Security.handleCertificateError', {
eventId: event.eventId,
action: 'continue'
}).catch(debugError);
}
/**
* @param {string} selector
* @return {!Promise<?Puppeteer.ElementHandle>}
*/
async $(selector) {
return this.mainFrame().$(selector);
}
/**
* @param {function()|string} pageFunction
* @param {!Array<*>} args
* @return {!Promise<!Puppeteer.JSHandle>}
*/
async evaluateHandle(pageFunction, ...args) {
const context = await this.mainFrame().executionContext();
return context.evaluateHandle(pageFunction, ...args);
}
/**
* @param {!Puppeteer.JSHandle} prototypeHandle
* @return {!Promise<!Puppeteer.JSHandle>}
*/
async queryObjects(prototypeHandle) {
const context = await this.mainFrame().executionContext();
return context.queryObjects(prototypeHandle);
}
/**
* @param {string} selector
* @param {function()|string} pageFunction
* @param {!Array<*>} args
* @return {!Promise<(!Object|undefined)>}
*/
async $eval(selector, pageFunction, ...args) {
return this.mainFrame().$eval(selector, pageFunction, ...args);
}
/**
* @param {string} selector
* @param {Function|string} pageFunction
* @param {!Array<*>} args
* @return {!Promise<(!Object|undefined)>}
*/
async $$eval(selector, pageFunction, ...args) {
return this.mainFrame().$$eval(selector, pageFunction, ...args);
}
/**
* @param {string} selector
* @return {!Promise<!Array<!Puppeteer.ElementHandle>>}
*/
async $$(selector) {
return this.mainFrame().$$(selector);
}
/**
* @param {string} expression
* @return {!Promise<!Array<!Puppeteer.ElementHandle>>}
*/
async $x(expression) {
return this.mainFrame().$x(expression);
}
/**
* @param {!Array<string>} urls
* @return {!Promise<!Array<Network.Cookie>>}
*/
async cookies(...urls) {
return (await this._client.send('Network.getCookies', {
urls: urls.length ? urls : [this.url()]
})).cookies;
}
/**
* @param {Array<Network.CookieParam>} cookies
*/
async deleteCookie(...cookies) {
const pageURL = this.url();
for (const cookie of cookies) {
const item = Object.assign({}, cookie);
if (!cookie.url && pageURL.startsWith('http'))
item.url = pageURL;
await this._client.send('Network.deleteCookies', item);
}
}
/**
* @param {Array<Network.CookieParam>} cookies
*/
async setCookie(...cookies) {
const pageURL = this.url();
const startsWithHTTP = pageURL.startsWith('http');
const items = cookies.map(cookie => {
const item = Object.assign({}, cookie);
if (!item.url && startsWithHTTP)
item.url = pageURL;
console.assert(
item.url !== 'about:blank',
`Blank page can not have cookie "${item.name}"`
);
console.assert(
!String.prototype.startsWith.call(item.url || '', 'data:'),
`Data URL page can not have cookie "${item.name}"`
);
return item;
});
await this.deleteCookie(...items);
if (items.length)
await this._client.send('Network.setCookies', { cookies: items });
}
/**
* @param {Object} options
* @return {!Promise<!Puppeteer.ElementHandle>}
*/
async addScriptTag(options) {
return this.mainFrame().addScriptTag(options);
}
/**
* @param {Object} options
* @return {!Promise<!Puppeteer.ElementHandle>}
*/
async addStyleTag(options) {
return this.mainFrame().addStyleTag(options);
}
/**
* @param {string} name
* @param {function(?)} puppeteerFunction
*/
async exposeFunction(name, puppeteerFunction) {
if (this._pageBindings[name])
throw new Error(`Failed to add page binding with name ${name}: window['${name}'] already exists!`);
this._pageBindings[name] = puppeteerFunction;
const expression = helper.evaluationString(addPageBinding, name);
await this._client.send('Page.addScriptToEvaluateOnNewDocument', {source: expression});
await Promise.all(this.frames().map(frame => frame.evaluate(expression).catch(debugError)));
function addPageBinding(bindingName) {
window[bindingName] = async(...args) => {
const me = window[bindingName];
let callbacks = me['callbacks'];
if (!callbacks) {
callbacks = new Map();
me['callbacks'] = callbacks;
}
const seq = (me['lastSeq'] || 0) + 1;
me['lastSeq'] = seq;
const promise = new Promise(fulfill => callbacks.set(seq, fulfill));
// eslint-disable-next-line no-console
console.debug('driver:page-binding', JSON.stringify({name: bindingName, seq, args}));
return promise;
};
}
}
/**
* @param {?{username: string, password: string}} credentials
*/
async authenticate(credentials) {
return this._networkManager.authenticate(credentials);
}
/**
* @param {!Object<string, string>} headers
*/
async setExtraHTTPHeaders(headers) {
return this._networkManager.setExtraHTTPHeaders(headers);
}
/**
* @param {string} userAgent
*/
async setUserAgent(userAgent) {
return this._networkManager.setUserAgent(userAgent);
}
/**
* @return {!Promise<!Object>}
*/
async metrics() {
const response = await this._client.send('Performance.getMetrics');
return this._buildMetricsObject(response.metrics);
}
/**
* @param {*} event
*/
_emitMetrics(event) {
this.emit(Page.Events.Metrics, {
title: event.title,
metrics: this._buildMetricsObject(event.metrics)
});
}
/**
* @param {?Array<!Protocol.Performance.Metric>} metrics
* @return {!Object}
*/
_buildMetricsObject(metrics) {
const result = {};
for (const metric of metrics || []) {
if (supportedMetrics.has(metric.name))
result[metric.name] = metric.value;
}
return result;
}
/**
* @param {!Protocol.Runtime.ExceptionDetails} exceptionDetails
*/
_handleException(exceptionDetails) {
const message = helper.getExceptionMessage(exceptionDetails);
this.emit(Page.Events.PageError, new Error(message));
}
async _onConsoleAPI(event) {
if (event.type === 'debug' && event.args.length && event.args[0].value === 'driver:page-binding') {
const {name, seq, args} = JSON.parse(event.args[1].value);
const result = await this._pageBindings[name](...args);
const expression = helper.evaluationString(deliverResult, name, seq, result);
this._client.send('Runtime.evaluate', { expression, contextId: event.executionContextId }).catch(debugError);
function deliverResult(name, seq, result) {
window[name]['callbacks'].get(seq)(result);
window[name]['callbacks'].delete(seq);
}
return;
}
if (!this.listenerCount(Page.Events.Console)) {
event.args.map(arg => helper.releaseObject(this._client, arg));
return;
}
const values = event.args.map(arg => this._frameManager.createJSHandle(event.executionContextId, arg));
const textTokens = [];
for (let i = 0; i < event.args.length; ++i) {
const remoteObject = event.args[i];
if (remoteObject.objectId)
textTokens.push(values[i].toString());
else
textTokens.push(helper.valueFromRemoteObject(remoteObject));
}
const message = new ConsoleMessage(event.type, textTokens.join(' '), values);
this.emit(Page.Events.Console, message);
}
_onDialog(event) {
let dialogType = null;
if (event.type === 'alert')
dialogType = Dialog.Type.Alert;
else if (event.type === 'confirm')
dialogType = Dialog.Type.Confirm;
else if (event.type === 'prompt')
dialogType = Dialog.Type.Prompt;
else if (event.type === 'beforeunload')
dialogType = Dialog.Type.BeforeUnload;
console.assert(dialogType, 'Unknown javascript dialog type: ' + event.type);
const dialog = new Dialog(this._client, dialogType, event.message, event.defaultPrompt);
this.emit(Page.Events.Dialog, dialog);
}
/**
* @return {!string}
*/
url() {
return this.mainFrame().url();
}
/**
* @return {!Promise<String>}
*/
async content() {
return await this._frameManager.mainFrame().content();
}
/**
* @param {string} html
*/
async setContent(html) {
await this._frameManager.mainFrame().setContent(html);
}
/**
* @param {string} url
* @param {!Object=} options
* @return {!Promise<?Puppeteer.Response>}
*/
async goto(url, options = {}) {
const referrer = this._networkManager.extraHTTPHeaders()['referer'];
/** @type {Map<string, !Puppeteer.Request>} */
const requests = new Map();
const eventListeners = [
helper.addEventListener(this._networkManager, NetworkManager.Events.Request, request => {
if (!requests.get(request.url()))
requests.set(request.url(), request);
})
];
const mainFrame = this._frameManager.mainFrame();
const timeout = typeof options.timeout === 'number' ? options.timeout : this._defaultNavigationTimeout;
const watcher = new NavigatorWatcher(this._frameManager, mainFrame, timeout, options);
const navigationPromise = watcher.navigationPromise();
let error = await Promise.race([
navigate(this._client, url, referrer),
navigationPromise,
]);
if (!error)
error = await navigationPromise;
watcher.cancel();
helper.removeEventListeners(eventListeners);
if (error)
throw error;
const request = requests.get(this.mainFrame().url());
return request ? request.response() : null;
/**
* @param {!Puppeteer.CDPSession} client
* @param {string} url
* @param {string} referrer
* @return {!Promise<?Error>}
*/
async function navigate(client, url, referrer) {
try {
const response = await client.send('Page.navigate', {url, referrer});
return response.errorText ? new Error(`${response.errorText} at ${url}`) : null;
} catch (error) {
return error;
}
}
}
/**
* @param {!Object=} options
* @return {!Promise<?Puppeteer.Response>}
*/
async reload(options) {
const [response] = await Promise.all([
this.waitForNavigation(options),
this._client.send('Page.reload')
]);
return response;
}
/**
* @param {!Object=} options
* @return {!Promise<!Puppeteer.Response>}
*/
async waitForNavigation(options = {}) {
const mainFrame = this._frameManager.mainFrame();
const timeout = typeof options.timeout === 'number' ? options.timeout : this._defaultNavigationTimeout;
const watcher = new NavigatorWatcher(this._frameManager, mainFrame, timeout, options);
const responses = new Map();
const listener = helper.addEventListener(this._networkManager, NetworkManager.Events.Response, response => responses.set(response.url(), response));
const error = await watcher.navigationPromise();
helper.removeEventListeners([listener]);
if (error)
throw error;
return responses.get(this.mainFrame().url()) || null;
}
/**
* @param {!Object=} options
* @return {!Promise<?Puppeteer.Response>}
*/
async goBack(options) {
return this._go(-1, options);
}
/**
* @param {!Object=} options
* @return {!Promise<?Puppeteer.Response>}
*/
async goForward(options) {
return this._go(+1, options);
}
/**
* @param {!Object=} options
* @return {!Promise<?Puppeteer.Response>}
*/
async _go(delta, options) {
const history = await this._client.send('Page.getNavigationHistory');
const entry = history.entries[history.currentIndex + delta];
if (!entry)
return null;
const [response] = await Promise.all([
this.waitForNavigation(options),
this._client.send('Page.navigateToHistoryEntry', {entryId: entry.id}),
]);
return response;
}
async bringToFront() {
await this._client.send('Page.bringToFront');
}
/**
* @param {!Object} options
*/
async emulate(options) {
return Promise.all([
this.setViewport(options.viewport),
this.setUserAgent(options.userAgent)
]);
}
/**
* @param {boolean} enabled
*/
async setJavaScriptEnabled(enabled) {
await this._client.send('Emulation.setScriptExecutionDisabled', { value: !enabled });
}
/**
* @param {boolean} enabled
*/
async setBypassCSP(enabled) {
await this._client.send('Page.setBypassCSP', { enabled });
}
/**
* @param {?string} mediaType
*/
async emulateMedia(mediaType) {
console.assert(mediaType === 'screen' || mediaType === 'print' || mediaType === null, 'Unsupported media type: ' + mediaType);
await this._client.send('Emulation.setEmulatedMedia', {media: mediaType || ''});
}
/**
* @param {!Page.Viewport} viewport
*/
async setViewport(viewport) {
const needsReload = await this._emulationManager.emulateViewport(viewport);
this._viewport = viewport;
if (needsReload)
await this.reload();
}
/**
* @return {!Page.Viewport}
*/
viewport() {
return this._viewport;
}
/**
* @param {function()|string} pageFunction
* @param {!Array<*>} args
* @return {!Promise<*>}
*/
async evaluate(pageFunction, ...args) {
return this._frameManager.mainFrame().evaluate(pageFunction, ...args);
}
/**
* @param {function()|string} pageFunction
* @param {!Array<*>} args
*/
async evaluateOnNewDocument(pageFunction, ...args) {
const source = helper.evaluationString(pageFunction, ...args);
await this._client.send('Page.addScriptToEvaluateOnNewDocument', { source });
}
/**
* @param {Boolean} enabled
* @returns {!Promise}
*/
async setCacheEnabled(enabled = true) {
await this._client.send('Network.setCacheDisabled', {cacheDisabled: !enabled});
}
/**
* @param {!Object=} options
* @return {!Promise<!Buffer>}
*/
async screenshot(options = {}) {
let screenshotType = null;
// options.type takes precedence over inferring the type from options.path
// because it may be a 0-length file with no extension created beforehand (i.e. as a temp file).
if (options.type) {
console.assert(options.type === 'png' || options.type === 'jpeg', 'Unknown options.type value: ' + options.type);
screenshotType = options.type;
} else if (options.path) {
const mimeType = mime.lookup(options.path);
if (mimeType === 'image/png')
screenshotType = 'png';
else if (mimeType === 'image/jpeg')
screenshotType = 'jpeg';
console.assert(screenshotType, 'Unsupported screenshot mime type: ' + mimeType);
}
if (!screenshotType)
screenshotType = 'png';
if (options.quality) {
console.assert(screenshotType === 'jpeg', 'options.quality is unsupported for the ' + screenshotType + ' screenshots');
console.assert(typeof options.quality === 'number', 'Expected options.quality to be a number but found ' + (typeof options.quality));
console.assert(Number.isInteger(options.quality), 'Expected options.quality to be an integer');
console.assert(options.quality >= 0 && options.quality <= 100, 'Expected options.quality to be between 0 and 100 (inclusive), got ' + options.quality);
}
console.assert(!options.clip || !options.fullPage, 'options.clip and options.fullPage are exclusive');
if (options.clip) {
console.assert(typeof options.clip.x === 'number', 'Expected options.clip.x to be a number but found ' + (typeof options.clip.x));
console.assert(typeof options.clip.y === 'number', 'Expected options.clip.y to be a number but found ' + (typeof options.clip.y));
console.assert(typeof options.clip.width === 'number', 'Expected options.clip.width to be a number but found ' + (typeof options.clip.width));
console.assert(typeof options.clip.height === 'number', 'Expected options.clip.height to be a number but found ' + (typeof options.clip.height));
}
return this._screenshotTaskQueue.postTask(this._screenshotTask.bind(this, screenshotType, options));
}
/**
* @param {"png"|"jpeg"} format
* @param {!Object=} options
* @return {!Promise<!Buffer>}
*/
async _screenshotTask(format, options) {
await this._client.send('Target.activateTarget', {targetId: this._target._targetId});
let clip = options.clip ? Object.assign({}, options['clip']) : undefined;
if (clip)
clip.scale = 1;
if (options.fullPage) {
const metrics = await this._client.send('Page.getLayoutMetrics');
const width = Math.ceil(metrics.contentSize.width);
const height = Math.ceil(metrics.contentSize.height);
// Overwrite clip for full page at all times.
clip = { x: 0, y: 0, width, height, scale: 1 };
const mobile = this._viewport.isMobile || false;
const deviceScaleFactor = this._viewport.deviceScaleFactor || 1;
const landscape = this._viewport.isLandscape || false;
/** @type {!Protocol.Emulation.ScreenOrientation} */
const screenOrientation = landscape ? { angle: 90, type: 'landscapePrimary' } : { angle: 0, type: 'portraitPrimary' };
await this._client.send('Emulation.setDeviceMetricsOverride', { mobile, width, height, deviceScaleFactor, screenOrientation });
}
if (options.omitBackground)
await this._client.send('Emulation.setDefaultBackgroundColorOverride', { color: { r: 0, g: 0, b: 0, a: 0 } });
const result = await this._client.send('Page.captureScreenshot', { format, quality: options.quality, clip });
if (options.omitBackground)
await this._client.send('Emulation.setDefaultBackgroundColorOverride');
if (options.fullPage)
await this.setViewport(this._viewport);
const buffer = new Buffer(result.data, 'base64');
if (options.path)
await writeFileAsync(options.path, buffer);
return buffer;
}
/**
* @param {!Object=} options
* @return {!Promise<!Buffer>}
*/
async pdf(options = {}) {
const scale = options.scale || 1;
const displayHeaderFooter = !!options.displayHeaderFooter;
const headerTemplate = options.headerTemplate || '';
const footerTemplate = options.footerTemplate || '';
const printBackground = !!options.printBackground;
const landscape = !!options.landscape;
const pageRanges = options.pageRanges || '';
let paperWidth = 8.5;
let paperHeight = 11;
if (options.format) {
const format = Page.PaperFormats[options.format.toLowerCase()];
console.assert(format, 'Unknown paper format: ' + options.format);
paperWidth = format.width;
paperHeight = format.height;
} else {
paperWidth = convertPrintParameterToInches(options.width) || paperWidth;
paperHeight = convertPrintParameterToInches(options.height) || paperHeight;
}
const marginOptions = options.margin || {};
const marginTop = convertPrintParameterToInches(marginOptions.top) || 0;
const marginLeft = convertPrintParameterToInches(marginOptions.left) || 0;
const marginBottom = convertPrintParameterToInches(marginOptions.bottom) || 0;
const marginRight = convertPrintParameterToInches(marginOptions.right) || 0;
const result = await this._client.send('Page.printToPDF', {
landscape: landscape,
displayHeaderFooter: displayHeaderFooter,
headerTemplate: headerTemplate,
footerTemplate: footerTemplate,
printBackground: printBackground,
scale: scale,
paperWidth: paperWidth,
paperHeight: paperHeight,
marginTop: marginTop,
marginBottom: marginBottom,
marginLeft: marginLeft,
marginRight: marginRight,
pageRanges: pageRanges
});
const buffer = new Buffer(result.data, 'base64');
if (options.path)
await writeFileAsync(options.path, buffer);
return buffer;
}
/**
* @return {!Promise<string>}
*/
async title() {
return this.mainFrame().title();
}
async close() {
console.assert(!!this._client._connection, 'Protocol error: Connection closed. Most likely the page has been closed.');
await this._client._connection.send('Target.closeTarget', { targetId: this._target._targetId });
await this._target._isClosedPromise;
}
/**
* @return {!Mouse}
*/
get mouse() {
return this._mouse;
}
/**
* @param {string} selector
* @param {!Object=} options
*/
click(selector, options = {}) {
return this.mainFrame().click(selector, options);
}
/**
* @param {string} selector
*/
focus(selector) {
return this.mainFrame().focus(selector);
}
/**
* @param {string} selector
*/
hover(selector) {
return this.mainFrame().hover(selector);
}
/**
* @param {string} selector
* @param {!Array<string>} values
* @return {!Promise<!Array<string>>}
*/
select(selector, ...values) {
return this.mainFrame().select(selector, ...values);
}
/**
* @param {string} selector
*/
tap(selector) {
return this.mainFrame().tap(selector);
}
/**
* @param {string} selector
* @param {string} text
* @param {{delay: (number|undefined)}=} options
*/
type(selector, text, options) {
return this.mainFrame().type(selector, text, options);
}
/**
* @param {(string|number|Function)} selectorOrFunctionOrTimeout
* @param {!Object=} options
* @param {!Array<*>} args
* @return {!Promise}
*/
waitFor(selectorOrFunctionOrTimeout, options = {}, ...args) {
return this.mainFrame().waitFor(selectorOrFunctionOrTimeout, options, ...args);
}
/**
* @param {string} selector
* @param {!Object=} options
* @return {!Promise}
*/
waitForSelector(selector, options = {}) {
return this.mainFrame().waitForSelector(selector, options);
}
/**
* @param {string} xpath
* @param {!Object=} options
* @return {!Promise}
*/
waitForXPath(xpath, options = {}) {
return this.mainFrame().waitForXPath(xpath, options);
}
/**
* @param {function()} pageFunction
* @param {!Object=} options
* @param {!Array<*>} args
* @return {!Promise}
*/
waitForFunction(pageFunction, options = {}, ...args) {
return this.mainFrame().waitForFunction(pageFunction, options, ...args);
}
}
/** @type {!Set<string>} */
const supportedMetrics = new Set([
'Timestamp',
'Documents',
'Frames',
'JSEventListeners',
'Nodes',
'LayoutCount',
'RecalcStyleCount',
'LayoutDuration',
'RecalcStyleDuration',
'ScriptDuration',
'TaskDuration',
'JSHeapUsedSize',
'JSHeapTotalSize',
]);
/** @enum {string} */
Page.PaperFormats = {
letter: {width: 8.5, height: 11},
legal: {width: 8.5, height: 14},
tabloid: {width: 11, height: 17},
ledger: {width: 17, height: 11},
a0: {width: 33.1, height: 46.8 },
a1: {width: 23.4, height: 33.1 },
a2: {width: 16.5, height: 23.4 },
a3: {width: 11.7, height: 16.5 },
a4: {width: 8.27, height: 11.7 },
a5: {width: 5.83, height: 8.27 },
a6: {width: 4.13, height: 5.83 },
};
const unitToPixels = {
'px': 1,
'in': 96,
'cm': 37.8,
'mm': 3.78
};
/**
* @param {(string|number|undefined)} parameter
* @return {(number|undefined)}
*/
function convertPrintParameterToInches(parameter) {
if (typeof parameter === 'undefined')
return undefined;
let pixels;
if (helper.isNumber(parameter)) {
// Treat numbers as pixel values to be aligned with phantom's paperSize.
pixels = /** @type {number} */ (parameter);
} else if (helper.isString(parameter)) {
const text = /** @type {string} */ (parameter);
let unit = text.substring(text.length - 2).toLowerCase();
let valueText = '';
if (unitToPixels.hasOwnProperty(unit)) {
valueText = text.substring(0, text.length - 2);
} else {
// In case of unknown unit try to parse the whole parameter as number of pixels.
// This is consistent with phantom's paperSize behavior.
unit = 'px';
valueText = text;
}
const value = Number(valueText);
console.assert(!isNaN(value), 'Failed to parse parameter value: ' + text);
pixels = value * unitToPixels[unit];
} else {
throw new Error('page.pdf() Cannot handle parameter type: ' + (typeof parameter));
}
return pixels / 96;
}
Page.Events = {
Close: 'close',
Console: 'console',
Dialog: 'dialog',
DOMContentLoaded: 'domcontentloaded',
Error: 'error',
// Can't use just 'error' due to node.js special treatment of error events.
// @see https://nodejs.org/api/events.html#events_error_events
PageError: 'pageerror',
Request: 'request',
Response: 'response',
RequestFailed: 'requestfailed',
RequestFinished: 'requestfinished',
FrameAttached: 'frameattached',
FrameDetached: 'framedetached',
FrameNavigated: 'framenavigated',
Load: 'load',
Metrics: 'metrics',
};
/**
* @typedef {Object} Page.Viewport
* @property {number} width
* @property {number} height
* @property {number=} deviceScaleFactor
* @property {boolean=} isMobile
* @property {boolean=} isLandscape
* @property {boolean=} hasTouch
*/
/**
* @typedef {Object} Network.Cookie
* @property {string} name
* @property {string} value
* @property {string} domain
* @property {string} path
* @property {number} expires
* @property {number} size
* @property {boolean} httpOnly
* @property {boolean} secure
* @property {boolean} session
* @property {("Strict"|"Lax")=} sameSite
*/
/**
* @typedef {Object} Network.CookieParam
* @property {string} name
* @property {string} value
* @property {string=} url
* @property {string=} domain
* @property {string=} path
* @property {number=} expires
* @property {boolean=} httpOnly
* @property {boolean=} secure
* @property {("Strict"|"Lax")=} sameSite
*/
class ConsoleMessage {
/**
* @param {string} type
* @param {string} text
* @param {!Array<*>} args
*/
constructor(type, text, args) {
this._type = type;
this._text = text;
this._args = args;
}
/**
* @return {string}
*/
type() {
return this._type;
}
/**
* @return {string}
*/
text() {
return this._text;
}
/**
* @return {!Array<string>}
*/
args() {
return this._args;
}
}
module.exports = Page;
helper.tracePublicAPI(Page);
| lib/Page.js | 0 | https://github.com/puppeteer/puppeteer/commit/f8cba455ba5d1bc82721e89fda037e86213b02cb | [
0.0037300523836165667,
0.00023600032727699727,
0.0001647151366341859,
0.00017159403068944812,
0.00040858774445950985
] |
{
"id": 5,
"code_window": [
" /**\n",
" * @return {!Promise<!Buffer>}\n",
" */\n",
" buffer() {\n",
" if (!this._contentPromise) {\n",
" this._contentPromise = this._request._completePromise.then(async() => {\n",
" const response = await this._client.send('Network.getResponseBody', {\n",
" requestId: this._request._requestId\n",
" });\n",
" return Buffer.from(response.body, response.base64Encoded ? 'base64' : 'utf8');\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" this._contentPromise = this._bodyLoadedPromise.then(async error => {\n",
" if (error)\n",
" throw error;\n"
],
"file_path": "lib/NetworkManager.js",
"type": "replace",
"edit_start_line_idx": 583
} | /**
* Copyright 2017 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
const EventEmitter = require('events');
const {helper, debugError} = require('./helper');
const Multimap = require('./Multimap');
class NetworkManager extends EventEmitter {
/**
* @param {!Puppeteer.CDPSession} client
* @param {!Puppeteer.FrameManager} frameManager
*/
constructor(client, frameManager) {
super();
this._client = client;
this._frameManager = frameManager;
/** @type {!Map<string, !Request>} */
this._requestIdToRequest = new Map();
/** @type {!Map<string, !Request>} */
this._interceptionIdToRequest = new Map();
/** @type {!Object<string, string>} */
this._extraHTTPHeaders = {};
this._offline = false;
/** @type {?{username: string, password: string}} */
this._credentials = null;
/** @type {!Set<string>} */
this._attemptedAuthentications = new Set();
this._userRequestInterceptionEnabled = false;
this._protocolRequestInterceptionEnabled = false;
/** @type {!Multimap} */
this._requestHashToRequestIds = new Multimap();
/** @type {!Multimap} */
this._requestHashToInterceptionIds = new Multimap();
this._client.on('Network.requestWillBeSent', this._onRequestWillBeSent.bind(this));
this._client.on('Network.requestIntercepted', this._onRequestIntercepted.bind(this));
this._client.on('Network.requestServedFromCache', this._onRequestServedFromCache.bind(this));
this._client.on('Network.responseReceived', this._onResponseReceived.bind(this));
this._client.on('Network.loadingFinished', this._onLoadingFinished.bind(this));
this._client.on('Network.loadingFailed', this._onLoadingFailed.bind(this));
}
/**
* @param {?{username: string, password: string}} credentials
*/
async authenticate(credentials) {
this._credentials = credentials;
await this._updateProtocolRequestInterception();
}
/**
* @param {!Object<string, string>} extraHTTPHeaders
*/
async setExtraHTTPHeaders(extraHTTPHeaders) {
this._extraHTTPHeaders = {};
for (const key of Object.keys(extraHTTPHeaders)) {
const value = extraHTTPHeaders[key];
console.assert(helper.isString(value), `Expected value of header "${key}" to be String, but "${typeof value}" is found.`);
this._extraHTTPHeaders[key.toLowerCase()] = value;
}
await this._client.send('Network.setExtraHTTPHeaders', { headers: this._extraHTTPHeaders });
}
/**
* @return {!Object<string, string>}
*/
extraHTTPHeaders() {
return Object.assign({}, this._extraHTTPHeaders);
}
/**
* @param {boolean} value
*/
async setOfflineMode(value) {
if (this._offline === value)
return;
this._offline = value;
await this._client.send('Network.emulateNetworkConditions', {
offline: this._offline,
// values of 0 remove any active throttling. crbug.com/456324#c9
latency: 0,
downloadThroughput: -1,
uploadThroughput: -1
});
}
/**
* @param {string} userAgent
*/
async setUserAgent(userAgent) {
await this._client.send('Network.setUserAgentOverride', { userAgent });
}
/**
* @param {boolean} value
*/
async setRequestInterception(value) {
this._userRequestInterceptionEnabled = value;
await this._updateProtocolRequestInterception();
}
async _updateProtocolRequestInterception() {
const enabled = this._userRequestInterceptionEnabled || !!this._credentials;
if (enabled === this._protocolRequestInterceptionEnabled)
return;
this._protocolRequestInterceptionEnabled = enabled;
const patterns = enabled ? [{urlPattern: '*'}] : [];
await Promise.all([
this._client.send('Network.setCacheDisabled', {cacheDisabled: enabled}),
this._client.send('Network.setRequestInterception', {patterns})
]);
}
/**
* @param {!Protocol.Network.requestInterceptedPayload} event
*/
_onRequestIntercepted(event) {
if (event.authChallenge) {
/** @type {"Default"|"CancelAuth"|"ProvideCredentials"} */
let response = 'Default';
if (this._attemptedAuthentications.has(event.interceptionId)) {
response = 'CancelAuth';
} else if (this._credentials) {
response = 'ProvideCredentials';
this._attemptedAuthentications.add(event.interceptionId);
}
const {username, password} = this._credentials || {username: undefined, password: undefined};
this._client.send('Network.continueInterceptedRequest', {
interceptionId: event.interceptionId,
authChallengeResponse: { response, username, password }
}).catch(debugError);
return;
}
if (!this._userRequestInterceptionEnabled && this._protocolRequestInterceptionEnabled) {
this._client.send('Network.continueInterceptedRequest', {
interceptionId: event.interceptionId
}).catch(debugError);
}
if (event.redirectUrl) {
const request = this._interceptionIdToRequest.get(event.interceptionId);
if (request) {
this._handleRequestRedirect(request, event.responseStatusCode, event.responseHeaders, false /* fromDiskCache */, false /* fromServiceWorker */, null /* securityDetails */);
this._handleRequestStart(request._requestId, event.interceptionId, event.redirectUrl, event.resourceType, event.request, event.frameId, request._redirectChain);
}
return;
}
const requestHash = generateRequestHash(event.request);
const requestId = this._requestHashToRequestIds.firstValue(requestHash);
if (requestId) {
this._requestHashToRequestIds.delete(requestHash, requestId);
this._handleRequestStart(requestId, event.interceptionId, event.request.url, event.resourceType, event.request, event.frameId, []);
} else {
this._requestHashToInterceptionIds.set(requestHash, event.interceptionId);
this._handleRequestStart(null, event.interceptionId, event.request.url, event.resourceType, event.request, event.frameId, []);
}
}
/**
* @param {!Protocol.Network.requestServedFromCachePayload} event
*/
_onRequestServedFromCache(event) {
const request = this._requestIdToRequest.get(event.requestId);
if (request)
request._fromMemoryCache = true;
}
/**
* @param {!Request} request
* @param {number} redirectStatus
* @param {!Object} redirectHeaders
* @param {boolean} fromDiskCache
* @param {boolean} fromServiceWorker
* @param {?Object} securityDetails
*/
_handleRequestRedirect(request, redirectStatus, redirectHeaders, fromDiskCache, fromServiceWorker, securityDetails) {
const response = new Response(this._client, request, redirectStatus, redirectHeaders, fromDiskCache, fromServiceWorker, securityDetails);
request._response = response;
request._redirectChain.push(request);
this._requestIdToRequest.delete(request._requestId);
this._interceptionIdToRequest.delete(request._interceptionId);
this._attemptedAuthentications.delete(request._interceptionId);
this.emit(NetworkManager.Events.Response, response);
this.emit(NetworkManager.Events.RequestFinished, request);
}
/**
* @param {?string} requestId
* @param {?string} interceptionId
* @param {string} url
* @param {string} resourceType
* @param {!Protocol.Network.Request} requestPayload
* @param {?string} frameId
* @param {!Array<!Request>} redirectChain
*/
_handleRequestStart(requestId, interceptionId, url, resourceType, requestPayload, frameId, redirectChain) {
let frame = null;
if (frameId)
frame = this._frameManager.frame(frameId);
const request = new Request(this._client, requestId, interceptionId, this._userRequestInterceptionEnabled, url, resourceType, requestPayload, frame, redirectChain);
if (requestId)
this._requestIdToRequest.set(requestId, request);
if (interceptionId)
this._interceptionIdToRequest.set(interceptionId, request);
this.emit(NetworkManager.Events.Request, request);
}
/**
* @param {!Protocol.Network.requestWillBeSentPayload} event
*/
_onRequestWillBeSent(event) {
if (this._protocolRequestInterceptionEnabled) {
// All redirects are handled in requestIntercepted.
if (event.redirectResponse)
return;
const requestHash = generateRequestHash(event.request);
const interceptionId = this._requestHashToInterceptionIds.firstValue(requestHash);
const request = interceptionId ? this._interceptionIdToRequest.get(interceptionId) : null;
if (request) {
request._requestId = event.requestId;
this._requestIdToRequest.set(event.requestId, request);
this._requestHashToInterceptionIds.delete(requestHash, interceptionId);
} else {
this._requestHashToRequestIds.set(requestHash, event.requestId);
}
return;
}
let redirectChain = [];
if (event.redirectResponse) {
const request = this._requestIdToRequest.get(event.requestId);
// If we connect late to the target, we could have missed the requestWillBeSent event.
if (request) {
this._handleRequestRedirect(request, event.redirectResponse.status, event.redirectResponse.headers, event.redirectResponse.fromDiskCache, event.redirectResponse.fromServiceWorker, event.redirectResponse.securityDetails);
redirectChain = request._redirectChain;
}
}
this._handleRequestStart(event.requestId, null, event.request.url, event.type, event.request, event.frameId, redirectChain);
}
/**
* @param {!Protocol.Network.responseReceivedPayload} event
*/
_onResponseReceived(event) {
const request = this._requestIdToRequest.get(event.requestId);
// FileUpload sends a response without a matching request.
if (!request)
return;
const response = new Response(this._client, request, event.response.status, event.response.headers,
event.response.fromDiskCache, event.response.fromServiceWorker, event.response.securityDetails);
request._response = response;
this.emit(NetworkManager.Events.Response, response);
}
/**
* @param {!Protocol.Network.loadingFinishedPayload} event
*/
_onLoadingFinished(event) {
const request = this._requestIdToRequest.get(event.requestId);
// For certain requestIds we never receive requestWillBeSent event.
// @see https://crbug.com/750469
if (!request)
return;
request._completePromiseFulfill.call(null);
this._requestIdToRequest.delete(request._requestId);
this._interceptionIdToRequest.delete(request._interceptionId);
this._attemptedAuthentications.delete(request._interceptionId);
this.emit(NetworkManager.Events.RequestFinished, request);
}
/**
* @param {!Protocol.Network.loadingFailedPayload} event
*/
_onLoadingFailed(event) {
const request = this._requestIdToRequest.get(event.requestId);
// For certain requestIds we never receive requestWillBeSent event.
// @see https://crbug.com/750469
if (!request)
return;
request._failureText = event.errorText;
request._completePromiseFulfill.call(null);
this._requestIdToRequest.delete(request._requestId);
this._interceptionIdToRequest.delete(request._interceptionId);
this._attemptedAuthentications.delete(request._interceptionId);
this.emit(NetworkManager.Events.RequestFailed, request);
}
}
class Request {
/**
* @param {!Puppeteer.CDPSession} client
* @param {?string} requestId
* @param {string} interceptionId
* @param {boolean} allowInterception
* @param {string} url
* @param {string} resourceType
* @param {!Protocol.Network.Request} payload
* @param {?Puppeteer.Frame} frame
* @param {!Array<!Request>} redirectChain
*/
constructor(client, requestId, interceptionId, allowInterception, url, resourceType, payload, frame, redirectChain) {
this._client = client;
this._requestId = requestId;
this._interceptionId = interceptionId;
this._allowInterception = allowInterception;
this._interceptionHandled = false;
this._response = null;
this._failureText = null;
this._completePromise = new Promise(fulfill => {
this._completePromiseFulfill = fulfill;
});
this._url = url;
this._resourceType = resourceType.toLowerCase();
this._method = payload.method;
this._postData = payload.postData;
this._headers = {};
this._frame = frame;
this._redirectChain = redirectChain;
for (const key of Object.keys(payload.headers))
this._headers[key.toLowerCase()] = payload.headers[key];
this._fromMemoryCache = false;
}
/**
* @return {string}
*/
url() {
return this._url;
}
/**
* @return {string}
*/
resourceType() {
return this._resourceType;
}
/**
* @return {string}
*/
method() {
return this._method;
}
/**
* @return {string}
*/
postData() {
return this._postData;
}
/**
* @return {!Object}
*/
headers() {
return this._headers;
}
/**
* @return {?Response}
*/
response() {
return this._response;
}
/**
* @return {?Puppeteer.Frame}
*/
frame() {
return this._frame;
}
/**
* @return {!Array<!Request>}
*/
redirectChain() {
return this._redirectChain.slice();
}
/**
* @return {?{errorText: string}}
*/
failure() {
if (!this._failureText)
return null;
return {
errorText: this._failureText
};
}
/**
* @param {!Object=} overrides
*/
async continue(overrides = {}) {
console.assert(this._allowInterception, 'Request Interception is not enabled!');
console.assert(!this._interceptionHandled, 'Request is already handled!');
this._interceptionHandled = true;
await this._client.send('Network.continueInterceptedRequest', {
interceptionId: this._interceptionId,
url: overrides.url,
method: overrides.method,
postData: overrides.postData,
headers: overrides.headers,
}).catch(error => {
// In certain cases, protocol will return error if the request was already canceled
// or the page was closed. We should tolerate these errors.
debugError(error);
});
}
/**
* @param {!{status: number, headers: Object, contentType: string, body: (string|Buffer)}} response
*/
async respond(response) {
// Mocking responses for dataURL requests is not currently supported.
if (this._url.startsWith('data:'))
return;
console.assert(this._allowInterception, 'Request Interception is not enabled!');
console.assert(!this._interceptionHandled, 'Request is already handled!');
this._interceptionHandled = true;
const responseBody = response.body && helper.isString(response.body) ? Buffer.from(/** @type {string} */(response.body)) : /** @type {?Buffer} */(response.body || null);
const responseHeaders = {};
if (response.headers) {
for (const header of Object.keys(response.headers))
responseHeaders[header.toLowerCase()] = response.headers[header];
}
if (response.contentType)
responseHeaders['content-type'] = response.contentType;
if (responseBody && !('content-length' in responseHeaders)) {
// @ts-ignore
responseHeaders['content-length'] = Buffer.byteLength(responseBody);
}
const statusCode = response.status || 200;
const statusText = statusTexts[statusCode] || '';
const statusLine = `HTTP/1.1 ${statusCode} ${statusText}`;
const CRLF = '\r\n';
let text = statusLine + CRLF;
for (const header of Object.keys(responseHeaders))
text += header + ': ' + responseHeaders[header] + CRLF;
text += CRLF;
let responseBuffer = Buffer.from(text, 'utf8');
if (responseBody)
responseBuffer = Buffer.concat([responseBuffer, responseBody]);
await this._client.send('Network.continueInterceptedRequest', {
interceptionId: this._interceptionId,
rawResponse: responseBuffer.toString('base64')
}).catch(error => {
// In certain cases, protocol will return error if the request was already canceled
// or the page was closed. We should tolerate these errors.
debugError(error);
});
}
/**
* @param {string=} errorCode
*/
async abort(errorCode = 'failed') {
const errorReason = errorReasons[errorCode];
console.assert(errorReason, 'Unknown error code: ' + errorCode);
console.assert(this._allowInterception, 'Request Interception is not enabled!');
console.assert(!this._interceptionHandled, 'Request is already handled!');
this._interceptionHandled = true;
await this._client.send('Network.continueInterceptedRequest', {
interceptionId: this._interceptionId,
errorReason
}).catch(error => {
// In certain cases, protocol will return error if the request was already canceled
// or the page was closed. We should tolerate these errors.
debugError(error);
});
}
}
const errorReasons = {
'aborted': 'Aborted',
'accessdenied': 'AccessDenied',
'addressunreachable': 'AddressUnreachable',
'connectionaborted': 'ConnectionAborted',
'connectionclosed': 'ConnectionClosed',
'connectionfailed': 'ConnectionFailed',
'connectionrefused': 'ConnectionRefused',
'connectionreset': 'ConnectionReset',
'internetdisconnected': 'InternetDisconnected',
'namenotresolved': 'NameNotResolved',
'timedout': 'TimedOut',
'failed': 'Failed',
};
helper.tracePublicAPI(Request);
class Response {
/**
* @param {!Puppeteer.CDPSession} client
* @param {!Request} request
* @param {number} status
* @param {!Object} headers
* @param {boolean} fromDiskCache
* @param {boolean} fromServiceWorker
* @param {?Object} securityDetails
*/
constructor(client, request, status, headers, fromDiskCache, fromServiceWorker, securityDetails) {
this._client = client;
this._request = request;
this._contentPromise = null;
this._status = status;
this._url = request.url();
this._fromDiskCache = fromDiskCache;
this._fromServiceWorker = fromServiceWorker;
this._headers = {};
for (const key of Object.keys(headers))
this._headers[key.toLowerCase()] = headers[key];
this._securityDetails = null;
if (securityDetails) {
this._securityDetails = new SecurityDetails(
securityDetails['subjectName'],
securityDetails['issuer'],
securityDetails['validFrom'],
securityDetails['validTo'],
securityDetails['protocol']);
}
}
/**
* @return {string}
*/
url() {
return this._url;
}
/**
* @return {boolean}
*/
ok() {
return this._status === 0 || (this._status >= 200 && this._status <= 299);
}
/**
* @return {number}
*/
status() {
return this._status;
}
/**
* @return {!Object}
*/
headers() {
return this._headers;
}
/**
* @return {?SecurityDetails}
*/
securityDetails() {
return this._securityDetails;
}
/**
* @return {!Promise<!Buffer>}
*/
buffer() {
if (!this._contentPromise) {
this._contentPromise = this._request._completePromise.then(async() => {
const response = await this._client.send('Network.getResponseBody', {
requestId: this._request._requestId
});
return Buffer.from(response.body, response.base64Encoded ? 'base64' : 'utf8');
});
}
return this._contentPromise;
}
/**
* @return {!Promise<string>}
*/
async text() {
const content = await this.buffer();
return content.toString('utf8');
}
/**
* @return {!Promise<!Object>}
*/
async json() {
const content = await this.text();
return JSON.parse(content);
}
/**
* @return {!Request}
*/
request() {
return this._request;
}
/**
* @return {boolean}
*/
fromCache() {
return this._fromDiskCache || this._request._fromMemoryCache;
}
/**
* @return {boolean}
*/
fromServiceWorker() {
return this._fromServiceWorker;
}
}
helper.tracePublicAPI(Response);
/**
* @param {!Protocol.Network.Request} request
* @return {string}
*/
function generateRequestHash(request) {
let normalizedURL = request.url;
try {
// Decoding is necessary to normalize URLs. @see crbug.com/759388
// The method will throw if the URL is malformed. In this case,
// consider URL to be normalized as-is.
normalizedURL = decodeURI(request.url);
} catch (e) {
}
const hash = {
url: normalizedURL,
method: request.method,
postData: request.postData,
headers: {},
};
if (!normalizedURL.startsWith('data:')) {
const headers = Object.keys(request.headers);
headers.sort();
for (let header of headers) {
const headerValue = request.headers[header];
header = header.toLowerCase();
if (header === 'accept' || header === 'referer' || header === 'x-devtools-emulate-network-conditions-client-id')
continue;
hash.headers[header] = headerValue;
}
}
return JSON.stringify(hash);
}
class SecurityDetails {
/**
* @param {string} subjectName
* @param {string} issuer
* @param {number} validFrom
* @param {number} validTo
* @param {string} protocol
*/
constructor(subjectName, issuer, validFrom, validTo, protocol) {
this._subjectName = subjectName;
this._issuer = issuer;
this._validFrom = validFrom;
this._validTo = validTo;
this._protocol = protocol;
}
/**
* @return {string}
*/
subjectName() {
return this._subjectName;
}
/**
* @return {string}
*/
issuer() {
return this._issuer;
}
/**
* @return {number}
*/
validFrom() {
return this._validFrom;
}
/**
* @return {number}
*/
validTo() {
return this._validTo;
}
/**
* @return {string}
*/
protocol() {
return this._protocol;
}
}
NetworkManager.Events = {
Request: 'request',
Response: 'response',
RequestFailed: 'requestfailed',
RequestFinished: 'requestfinished',
};
const statusTexts = {
'100': 'Continue',
'101': 'Switching Protocols',
'102': 'Processing',
'200': 'OK',
'201': 'Created',
'202': 'Accepted',
'203': 'Non-Authoritative Information',
'204': 'No Content',
'206': 'Partial Content',
'207': 'Multi-Status',
'208': 'Already Reported',
'209': 'IM Used',
'300': 'Multiple Choices',
'301': 'Moved Permanently',
'302': 'Found',
'303': 'See Other',
'304': 'Not Modified',
'305': 'Use Proxy',
'306': 'Switch Proxy',
'307': 'Temporary Redirect',
'308': 'Permanent Redirect',
'400': 'Bad Request',
'401': 'Unauthorized',
'402': 'Payment Required',
'403': 'Forbidden',
'404': 'Not Found',
'405': 'Method Not Allowed',
'406': 'Not Acceptable',
'407': 'Proxy Authentication Required',
'408': 'Request Timeout',
'409': 'Conflict',
'410': 'Gone',
'411': 'Length Required',
'412': 'Precondition Failed',
'413': 'Payload Too Large',
'414': 'URI Too Long',
'415': 'Unsupported Media Type',
'416': 'Range Not Satisfiable',
'417': 'Expectation Failed',
'418': 'I\'m a teapot',
'421': 'Misdirected Request',
'422': 'Unprocessable Entity',
'423': 'Locked',
'424': 'Failed Dependency',
'426': 'Upgrade Required',
'428': 'Precondition Required',
'429': 'Too Many Requests',
'431': 'Request Header Fields Too Large',
'451': 'Unavailable For Legal Reasons',
'500': 'Internal Server Error',
'501': 'Not Implemented',
'502': 'Bad Gateway',
'503': 'Service Unavailable',
'504': 'Gateway Timeout',
'505': 'HTTP Version Not Supported',
'506': 'Variant Also Negotiates',
'507': 'Insufficient Storage',
'508': 'Loop Detected',
'510': 'Not Extended',
'511': 'Network Authentication Required',
};
module.exports = {Request, Response, NetworkManager};
| lib/NetworkManager.js | 1 | https://github.com/puppeteer/puppeteer/commit/f8cba455ba5d1bc82721e89fda037e86213b02cb | [
0.9983170032501221,
0.025444358587265015,
0.0001634946238482371,
0.00017207144992426038,
0.15520478785037994
] |
{
"id": 5,
"code_window": [
" /**\n",
" * @return {!Promise<!Buffer>}\n",
" */\n",
" buffer() {\n",
" if (!this._contentPromise) {\n",
" this._contentPromise = this._request._completePromise.then(async() => {\n",
" const response = await this._client.send('Network.getResponseBody', {\n",
" requestId: this._request._requestId\n",
" });\n",
" return Buffer.from(response.body, response.base64Encoded ? 'base64' : 'utf8');\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" this._contentPromise = this._bodyLoadedPromise.then(async error => {\n",
" if (error)\n",
" throw error;\n"
],
"file_path": "lib/NetworkManager.js",
"type": "replace",
"edit_start_line_idx": 583
} | (async() => {
const [, , puppeteerRoot, options] = process.argv;
const browser = await require(puppeteerRoot).launch(JSON.parse(options));
console.log(browser.wsEndpoint());
})();
| test/fixtures/closeme.js | 0 | https://github.com/puppeteer/puppeteer/commit/f8cba455ba5d1bc82721e89fda037e86213b02cb | [
0.00016531761502847075,
0.00016531761502847075,
0.00016531761502847075,
0.00016531761502847075,
0
] |
{
"id": 5,
"code_window": [
" /**\n",
" * @return {!Promise<!Buffer>}\n",
" */\n",
" buffer() {\n",
" if (!this._contentPromise) {\n",
" this._contentPromise = this._request._completePromise.then(async() => {\n",
" const response = await this._client.send('Network.getResponseBody', {\n",
" requestId: this._request._requestId\n",
" });\n",
" return Buffer.from(response.body, response.base64Encoded ? 'base64' : 'utf8');\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" this._contentPromise = this._bodyLoadedPromise.then(async error => {\n",
" if (error)\n",
" throw error;\n"
],
"file_path": "lib/NetworkManager.js",
"type": "replace",
"edit_start_line_idx": 583
} | ### class: Foo
#### event: 'c'
#### event: 'a'
#### foo.aaa()
#### event: 'b'
#### foo.ddd
#### foo.ccc()
#### foo.bbb()
| utils/doclint/check_public_api/test/check-sorting/doc.md | 0 | https://github.com/puppeteer/puppeteer/commit/f8cba455ba5d1bc82721e89fda037e86213b02cb | [
0.00017142845899797976,
0.00017058468074537814,
0.00016974091704469174,
0.00017058468074537814,
8.437709766440094e-7
] |
{
"id": 5,
"code_window": [
" /**\n",
" * @return {!Promise<!Buffer>}\n",
" */\n",
" buffer() {\n",
" if (!this._contentPromise) {\n",
" this._contentPromise = this._request._completePromise.then(async() => {\n",
" const response = await this._client.send('Network.getResponseBody', {\n",
" requestId: this._request._requestId\n",
" });\n",
" return Buffer.from(response.body, response.base64Encoded ? 'base64' : 'utf8');\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" this._contentPromise = this._bodyLoadedPromise.then(async error => {\n",
" if (error)\n",
" throw error;\n"
],
"file_path": "lib/NetworkManager.js",
"type": "replace",
"edit_start_line_idx": 583
} | /**
* Copyright 2017 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
const transformAsyncFunctions = require('../TransformAsyncFunctions');
const {TestRunner, Reporter, Matchers} = require('../../testrunner/');
const runner = new TestRunner();
new Reporter(runner);
const {describe, xdescribe, fdescribe} = runner;
const {it, fit, xit} = runner;
const {beforeAll, beforeEach, afterAll, afterEach} = runner;
const {expect} = new Matchers();
describe('TransformAsyncFunctions', function() {
it('should convert a function expression', function(done) {
const input = `(async function(){ return 123 })()`;
const output = eval(transformAsyncFunctions(input));
expect(output instanceof Promise).toBe(true);
output.then(result => expect(result).toBe(123)).then(done);
});
it('should convert an arrow function', function(done) {
const input = `(async () => 123)()`;
const output = eval(transformAsyncFunctions(input));
expect(output instanceof Promise).toBe(true);
output.then(result => expect(result).toBe(123)).then(done);
});
it('should convert an arrow function with curly braces', function(done) {
const input = `(async () => { return 123 })()`;
const output = eval(transformAsyncFunctions(input));
expect(output instanceof Promise).toBe(true);
output.then(result => expect(result).toBe(123)).then(done);
});
it('should convert a function declaration', function(done) {
const input = `async function f(){ return 123; } f();`;
const output = eval(transformAsyncFunctions(input));
expect(output instanceof Promise).toBe(true);
output.then(result => expect(result).toBe(123)).then(done);
});
it('should convert await', function(done) {
const input = `async function f(){ return 23 + await Promise.resolve(100); } f();`;
const output = eval(transformAsyncFunctions(input));
expect(output instanceof Promise).toBe(true);
output.then(result => expect(result).toBe(123)).then(done);
});
it('should convert method', function(done) {
const input = `class X{async f() { return 123 }} (new X()).f();`;
const output = eval(transformAsyncFunctions(input));
expect(output instanceof Promise).toBe(true);
output.then(result => expect(result).toBe(123)).then(done);
});
it('should pass arguments', function(done) {
const input = `(async function(a, b){ return await a + await b })(Promise.resolve(100), 23)`;
const output = eval(transformAsyncFunctions(input));
expect(output instanceof Promise).toBe(true);
output.then(result => expect(result).toBe(123)).then(done);
});
it('should still work across eval', function(done) {
const input = `var str = (async function(){ return 123; }).toString(); eval('(' + str + ')')();`;
const output = eval(transformAsyncFunctions(input));
expect(output instanceof Promise).toBe(true);
output.then(result => expect(result).toBe(123)).then(done);
});
it('should work with double await', function(done) {
const input = `async function f(){ return 23 + await Promise.resolve(50 + await Promise.resolve(50)); } f();`;
const output = eval(transformAsyncFunctions(input));
expect(output instanceof Promise).toBe(true);
output.then(result => expect(result).toBe(123)).then(done);
});
it('should work paren around arrow function', function(done) {
const input = `(async x => ( 123))()`;
const output = eval(transformAsyncFunctions(input));
expect(output instanceof Promise).toBe(true);
output.then(result => expect(result).toBe(123)).then(done);
});
it('should work async arrow with await', function(done) {
const input = `(async() => await 123)()`;
const output = eval(transformAsyncFunctions(input));
expect(output instanceof Promise).toBe(true);
output.then(result => expect(result).toBe(123)).then(done);
});
});
runner.run();
| utils/node6-transform/test/test.js | 0 | https://github.com/puppeteer/puppeteer/commit/f8cba455ba5d1bc82721e89fda037e86213b02cb | [
0.00017842331726569682,
0.0001731219090288505,
0.0001682481524767354,
0.00017273635603487492,
0.0000027046094146498945
] |
{
"id": 6,
"code_window": [
" expect(response).toBeTruthy();\n",
" expect(await response.text()).toBe('{\"foo\": \"bar\"}\\n');\n",
" expect(await response.json()).toEqual({foo: 'bar'});\n",
" });\n",
" it('Page.Events.Response should not report body unless request is finished', async({page, server}) => {\n",
" await page.goto(server.EMPTY_PAGE);\n",
" // Setup server to trap request.\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" it('Page.Events.Response should throw when requesting body of redirected response', async({page, server}) => {\n",
" server.setRedirect('/foo.html', '/empty.html');\n",
" const response = await page.goto(server.PREFIX + '/foo.html');\n",
" const redirectChain = response.request().redirectChain();\n",
" expect(redirectChain.length).toBe(1);\n",
" const redirected = redirectChain[0].response();\n",
" expect(redirected.status()).toBe(302);\n",
" let error = null;\n",
" await redirected.text().catch(e => error = e);\n",
" expect(error.message).toContain('Response body is unavailable for redirect responses');\n",
" });\n"
],
"file_path": "test/network.spec.js",
"type": "add",
"edit_start_line_idx": 96
} | /**
* Copyright 2017 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
const EventEmitter = require('events');
const {helper, debugError} = require('./helper');
const Multimap = require('./Multimap');
class NetworkManager extends EventEmitter {
/**
* @param {!Puppeteer.CDPSession} client
* @param {!Puppeteer.FrameManager} frameManager
*/
constructor(client, frameManager) {
super();
this._client = client;
this._frameManager = frameManager;
/** @type {!Map<string, !Request>} */
this._requestIdToRequest = new Map();
/** @type {!Map<string, !Request>} */
this._interceptionIdToRequest = new Map();
/** @type {!Object<string, string>} */
this._extraHTTPHeaders = {};
this._offline = false;
/** @type {?{username: string, password: string}} */
this._credentials = null;
/** @type {!Set<string>} */
this._attemptedAuthentications = new Set();
this._userRequestInterceptionEnabled = false;
this._protocolRequestInterceptionEnabled = false;
/** @type {!Multimap} */
this._requestHashToRequestIds = new Multimap();
/** @type {!Multimap} */
this._requestHashToInterceptionIds = new Multimap();
this._client.on('Network.requestWillBeSent', this._onRequestWillBeSent.bind(this));
this._client.on('Network.requestIntercepted', this._onRequestIntercepted.bind(this));
this._client.on('Network.requestServedFromCache', this._onRequestServedFromCache.bind(this));
this._client.on('Network.responseReceived', this._onResponseReceived.bind(this));
this._client.on('Network.loadingFinished', this._onLoadingFinished.bind(this));
this._client.on('Network.loadingFailed', this._onLoadingFailed.bind(this));
}
/**
* @param {?{username: string, password: string}} credentials
*/
async authenticate(credentials) {
this._credentials = credentials;
await this._updateProtocolRequestInterception();
}
/**
* @param {!Object<string, string>} extraHTTPHeaders
*/
async setExtraHTTPHeaders(extraHTTPHeaders) {
this._extraHTTPHeaders = {};
for (const key of Object.keys(extraHTTPHeaders)) {
const value = extraHTTPHeaders[key];
console.assert(helper.isString(value), `Expected value of header "${key}" to be String, but "${typeof value}" is found.`);
this._extraHTTPHeaders[key.toLowerCase()] = value;
}
await this._client.send('Network.setExtraHTTPHeaders', { headers: this._extraHTTPHeaders });
}
/**
* @return {!Object<string, string>}
*/
extraHTTPHeaders() {
return Object.assign({}, this._extraHTTPHeaders);
}
/**
* @param {boolean} value
*/
async setOfflineMode(value) {
if (this._offline === value)
return;
this._offline = value;
await this._client.send('Network.emulateNetworkConditions', {
offline: this._offline,
// values of 0 remove any active throttling. crbug.com/456324#c9
latency: 0,
downloadThroughput: -1,
uploadThroughput: -1
});
}
/**
* @param {string} userAgent
*/
async setUserAgent(userAgent) {
await this._client.send('Network.setUserAgentOverride', { userAgent });
}
/**
* @param {boolean} value
*/
async setRequestInterception(value) {
this._userRequestInterceptionEnabled = value;
await this._updateProtocolRequestInterception();
}
async _updateProtocolRequestInterception() {
const enabled = this._userRequestInterceptionEnabled || !!this._credentials;
if (enabled === this._protocolRequestInterceptionEnabled)
return;
this._protocolRequestInterceptionEnabled = enabled;
const patterns = enabled ? [{urlPattern: '*'}] : [];
await Promise.all([
this._client.send('Network.setCacheDisabled', {cacheDisabled: enabled}),
this._client.send('Network.setRequestInterception', {patterns})
]);
}
/**
* @param {!Protocol.Network.requestInterceptedPayload} event
*/
_onRequestIntercepted(event) {
if (event.authChallenge) {
/** @type {"Default"|"CancelAuth"|"ProvideCredentials"} */
let response = 'Default';
if (this._attemptedAuthentications.has(event.interceptionId)) {
response = 'CancelAuth';
} else if (this._credentials) {
response = 'ProvideCredentials';
this._attemptedAuthentications.add(event.interceptionId);
}
const {username, password} = this._credentials || {username: undefined, password: undefined};
this._client.send('Network.continueInterceptedRequest', {
interceptionId: event.interceptionId,
authChallengeResponse: { response, username, password }
}).catch(debugError);
return;
}
if (!this._userRequestInterceptionEnabled && this._protocolRequestInterceptionEnabled) {
this._client.send('Network.continueInterceptedRequest', {
interceptionId: event.interceptionId
}).catch(debugError);
}
if (event.redirectUrl) {
const request = this._interceptionIdToRequest.get(event.interceptionId);
if (request) {
this._handleRequestRedirect(request, event.responseStatusCode, event.responseHeaders, false /* fromDiskCache */, false /* fromServiceWorker */, null /* securityDetails */);
this._handleRequestStart(request._requestId, event.interceptionId, event.redirectUrl, event.resourceType, event.request, event.frameId, request._redirectChain);
}
return;
}
const requestHash = generateRequestHash(event.request);
const requestId = this._requestHashToRequestIds.firstValue(requestHash);
if (requestId) {
this._requestHashToRequestIds.delete(requestHash, requestId);
this._handleRequestStart(requestId, event.interceptionId, event.request.url, event.resourceType, event.request, event.frameId, []);
} else {
this._requestHashToInterceptionIds.set(requestHash, event.interceptionId);
this._handleRequestStart(null, event.interceptionId, event.request.url, event.resourceType, event.request, event.frameId, []);
}
}
/**
* @param {!Protocol.Network.requestServedFromCachePayload} event
*/
_onRequestServedFromCache(event) {
const request = this._requestIdToRequest.get(event.requestId);
if (request)
request._fromMemoryCache = true;
}
/**
* @param {!Request} request
* @param {number} redirectStatus
* @param {!Object} redirectHeaders
* @param {boolean} fromDiskCache
* @param {boolean} fromServiceWorker
* @param {?Object} securityDetails
*/
_handleRequestRedirect(request, redirectStatus, redirectHeaders, fromDiskCache, fromServiceWorker, securityDetails) {
const response = new Response(this._client, request, redirectStatus, redirectHeaders, fromDiskCache, fromServiceWorker, securityDetails);
request._response = response;
request._redirectChain.push(request);
this._requestIdToRequest.delete(request._requestId);
this._interceptionIdToRequest.delete(request._interceptionId);
this._attemptedAuthentications.delete(request._interceptionId);
this.emit(NetworkManager.Events.Response, response);
this.emit(NetworkManager.Events.RequestFinished, request);
}
/**
* @param {?string} requestId
* @param {?string} interceptionId
* @param {string} url
* @param {string} resourceType
* @param {!Protocol.Network.Request} requestPayload
* @param {?string} frameId
* @param {!Array<!Request>} redirectChain
*/
_handleRequestStart(requestId, interceptionId, url, resourceType, requestPayload, frameId, redirectChain) {
let frame = null;
if (frameId)
frame = this._frameManager.frame(frameId);
const request = new Request(this._client, requestId, interceptionId, this._userRequestInterceptionEnabled, url, resourceType, requestPayload, frame, redirectChain);
if (requestId)
this._requestIdToRequest.set(requestId, request);
if (interceptionId)
this._interceptionIdToRequest.set(interceptionId, request);
this.emit(NetworkManager.Events.Request, request);
}
/**
* @param {!Protocol.Network.requestWillBeSentPayload} event
*/
_onRequestWillBeSent(event) {
if (this._protocolRequestInterceptionEnabled) {
// All redirects are handled in requestIntercepted.
if (event.redirectResponse)
return;
const requestHash = generateRequestHash(event.request);
const interceptionId = this._requestHashToInterceptionIds.firstValue(requestHash);
const request = interceptionId ? this._interceptionIdToRequest.get(interceptionId) : null;
if (request) {
request._requestId = event.requestId;
this._requestIdToRequest.set(event.requestId, request);
this._requestHashToInterceptionIds.delete(requestHash, interceptionId);
} else {
this._requestHashToRequestIds.set(requestHash, event.requestId);
}
return;
}
let redirectChain = [];
if (event.redirectResponse) {
const request = this._requestIdToRequest.get(event.requestId);
// If we connect late to the target, we could have missed the requestWillBeSent event.
if (request) {
this._handleRequestRedirect(request, event.redirectResponse.status, event.redirectResponse.headers, event.redirectResponse.fromDiskCache, event.redirectResponse.fromServiceWorker, event.redirectResponse.securityDetails);
redirectChain = request._redirectChain;
}
}
this._handleRequestStart(event.requestId, null, event.request.url, event.type, event.request, event.frameId, redirectChain);
}
/**
* @param {!Protocol.Network.responseReceivedPayload} event
*/
_onResponseReceived(event) {
const request = this._requestIdToRequest.get(event.requestId);
// FileUpload sends a response without a matching request.
if (!request)
return;
const response = new Response(this._client, request, event.response.status, event.response.headers,
event.response.fromDiskCache, event.response.fromServiceWorker, event.response.securityDetails);
request._response = response;
this.emit(NetworkManager.Events.Response, response);
}
/**
* @param {!Protocol.Network.loadingFinishedPayload} event
*/
_onLoadingFinished(event) {
const request = this._requestIdToRequest.get(event.requestId);
// For certain requestIds we never receive requestWillBeSent event.
// @see https://crbug.com/750469
if (!request)
return;
request._completePromiseFulfill.call(null);
this._requestIdToRequest.delete(request._requestId);
this._interceptionIdToRequest.delete(request._interceptionId);
this._attemptedAuthentications.delete(request._interceptionId);
this.emit(NetworkManager.Events.RequestFinished, request);
}
/**
* @param {!Protocol.Network.loadingFailedPayload} event
*/
_onLoadingFailed(event) {
const request = this._requestIdToRequest.get(event.requestId);
// For certain requestIds we never receive requestWillBeSent event.
// @see https://crbug.com/750469
if (!request)
return;
request._failureText = event.errorText;
request._completePromiseFulfill.call(null);
this._requestIdToRequest.delete(request._requestId);
this._interceptionIdToRequest.delete(request._interceptionId);
this._attemptedAuthentications.delete(request._interceptionId);
this.emit(NetworkManager.Events.RequestFailed, request);
}
}
class Request {
/**
* @param {!Puppeteer.CDPSession} client
* @param {?string} requestId
* @param {string} interceptionId
* @param {boolean} allowInterception
* @param {string} url
* @param {string} resourceType
* @param {!Protocol.Network.Request} payload
* @param {?Puppeteer.Frame} frame
* @param {!Array<!Request>} redirectChain
*/
constructor(client, requestId, interceptionId, allowInterception, url, resourceType, payload, frame, redirectChain) {
this._client = client;
this._requestId = requestId;
this._interceptionId = interceptionId;
this._allowInterception = allowInterception;
this._interceptionHandled = false;
this._response = null;
this._failureText = null;
this._completePromise = new Promise(fulfill => {
this._completePromiseFulfill = fulfill;
});
this._url = url;
this._resourceType = resourceType.toLowerCase();
this._method = payload.method;
this._postData = payload.postData;
this._headers = {};
this._frame = frame;
this._redirectChain = redirectChain;
for (const key of Object.keys(payload.headers))
this._headers[key.toLowerCase()] = payload.headers[key];
this._fromMemoryCache = false;
}
/**
* @return {string}
*/
url() {
return this._url;
}
/**
* @return {string}
*/
resourceType() {
return this._resourceType;
}
/**
* @return {string}
*/
method() {
return this._method;
}
/**
* @return {string}
*/
postData() {
return this._postData;
}
/**
* @return {!Object}
*/
headers() {
return this._headers;
}
/**
* @return {?Response}
*/
response() {
return this._response;
}
/**
* @return {?Puppeteer.Frame}
*/
frame() {
return this._frame;
}
/**
* @return {!Array<!Request>}
*/
redirectChain() {
return this._redirectChain.slice();
}
/**
* @return {?{errorText: string}}
*/
failure() {
if (!this._failureText)
return null;
return {
errorText: this._failureText
};
}
/**
* @param {!Object=} overrides
*/
async continue(overrides = {}) {
console.assert(this._allowInterception, 'Request Interception is not enabled!');
console.assert(!this._interceptionHandled, 'Request is already handled!');
this._interceptionHandled = true;
await this._client.send('Network.continueInterceptedRequest', {
interceptionId: this._interceptionId,
url: overrides.url,
method: overrides.method,
postData: overrides.postData,
headers: overrides.headers,
}).catch(error => {
// In certain cases, protocol will return error if the request was already canceled
// or the page was closed. We should tolerate these errors.
debugError(error);
});
}
/**
* @param {!{status: number, headers: Object, contentType: string, body: (string|Buffer)}} response
*/
async respond(response) {
// Mocking responses for dataURL requests is not currently supported.
if (this._url.startsWith('data:'))
return;
console.assert(this._allowInterception, 'Request Interception is not enabled!');
console.assert(!this._interceptionHandled, 'Request is already handled!');
this._interceptionHandled = true;
const responseBody = response.body && helper.isString(response.body) ? Buffer.from(/** @type {string} */(response.body)) : /** @type {?Buffer} */(response.body || null);
const responseHeaders = {};
if (response.headers) {
for (const header of Object.keys(response.headers))
responseHeaders[header.toLowerCase()] = response.headers[header];
}
if (response.contentType)
responseHeaders['content-type'] = response.contentType;
if (responseBody && !('content-length' in responseHeaders)) {
// @ts-ignore
responseHeaders['content-length'] = Buffer.byteLength(responseBody);
}
const statusCode = response.status || 200;
const statusText = statusTexts[statusCode] || '';
const statusLine = `HTTP/1.1 ${statusCode} ${statusText}`;
const CRLF = '\r\n';
let text = statusLine + CRLF;
for (const header of Object.keys(responseHeaders))
text += header + ': ' + responseHeaders[header] + CRLF;
text += CRLF;
let responseBuffer = Buffer.from(text, 'utf8');
if (responseBody)
responseBuffer = Buffer.concat([responseBuffer, responseBody]);
await this._client.send('Network.continueInterceptedRequest', {
interceptionId: this._interceptionId,
rawResponse: responseBuffer.toString('base64')
}).catch(error => {
// In certain cases, protocol will return error if the request was already canceled
// or the page was closed. We should tolerate these errors.
debugError(error);
});
}
/**
* @param {string=} errorCode
*/
async abort(errorCode = 'failed') {
const errorReason = errorReasons[errorCode];
console.assert(errorReason, 'Unknown error code: ' + errorCode);
console.assert(this._allowInterception, 'Request Interception is not enabled!');
console.assert(!this._interceptionHandled, 'Request is already handled!');
this._interceptionHandled = true;
await this._client.send('Network.continueInterceptedRequest', {
interceptionId: this._interceptionId,
errorReason
}).catch(error => {
// In certain cases, protocol will return error if the request was already canceled
// or the page was closed. We should tolerate these errors.
debugError(error);
});
}
}
const errorReasons = {
'aborted': 'Aborted',
'accessdenied': 'AccessDenied',
'addressunreachable': 'AddressUnreachable',
'connectionaborted': 'ConnectionAborted',
'connectionclosed': 'ConnectionClosed',
'connectionfailed': 'ConnectionFailed',
'connectionrefused': 'ConnectionRefused',
'connectionreset': 'ConnectionReset',
'internetdisconnected': 'InternetDisconnected',
'namenotresolved': 'NameNotResolved',
'timedout': 'TimedOut',
'failed': 'Failed',
};
helper.tracePublicAPI(Request);
class Response {
/**
* @param {!Puppeteer.CDPSession} client
* @param {!Request} request
* @param {number} status
* @param {!Object} headers
* @param {boolean} fromDiskCache
* @param {boolean} fromServiceWorker
* @param {?Object} securityDetails
*/
constructor(client, request, status, headers, fromDiskCache, fromServiceWorker, securityDetails) {
this._client = client;
this._request = request;
this._contentPromise = null;
this._status = status;
this._url = request.url();
this._fromDiskCache = fromDiskCache;
this._fromServiceWorker = fromServiceWorker;
this._headers = {};
for (const key of Object.keys(headers))
this._headers[key.toLowerCase()] = headers[key];
this._securityDetails = null;
if (securityDetails) {
this._securityDetails = new SecurityDetails(
securityDetails['subjectName'],
securityDetails['issuer'],
securityDetails['validFrom'],
securityDetails['validTo'],
securityDetails['protocol']);
}
}
/**
* @return {string}
*/
url() {
return this._url;
}
/**
* @return {boolean}
*/
ok() {
return this._status === 0 || (this._status >= 200 && this._status <= 299);
}
/**
* @return {number}
*/
status() {
return this._status;
}
/**
* @return {!Object}
*/
headers() {
return this._headers;
}
/**
* @return {?SecurityDetails}
*/
securityDetails() {
return this._securityDetails;
}
/**
* @return {!Promise<!Buffer>}
*/
buffer() {
if (!this._contentPromise) {
this._contentPromise = this._request._completePromise.then(async() => {
const response = await this._client.send('Network.getResponseBody', {
requestId: this._request._requestId
});
return Buffer.from(response.body, response.base64Encoded ? 'base64' : 'utf8');
});
}
return this._contentPromise;
}
/**
* @return {!Promise<string>}
*/
async text() {
const content = await this.buffer();
return content.toString('utf8');
}
/**
* @return {!Promise<!Object>}
*/
async json() {
const content = await this.text();
return JSON.parse(content);
}
/**
* @return {!Request}
*/
request() {
return this._request;
}
/**
* @return {boolean}
*/
fromCache() {
return this._fromDiskCache || this._request._fromMemoryCache;
}
/**
* @return {boolean}
*/
fromServiceWorker() {
return this._fromServiceWorker;
}
}
helper.tracePublicAPI(Response);
/**
* @param {!Protocol.Network.Request} request
* @return {string}
*/
function generateRequestHash(request) {
let normalizedURL = request.url;
try {
// Decoding is necessary to normalize URLs. @see crbug.com/759388
// The method will throw if the URL is malformed. In this case,
// consider URL to be normalized as-is.
normalizedURL = decodeURI(request.url);
} catch (e) {
}
const hash = {
url: normalizedURL,
method: request.method,
postData: request.postData,
headers: {},
};
if (!normalizedURL.startsWith('data:')) {
const headers = Object.keys(request.headers);
headers.sort();
for (let header of headers) {
const headerValue = request.headers[header];
header = header.toLowerCase();
if (header === 'accept' || header === 'referer' || header === 'x-devtools-emulate-network-conditions-client-id')
continue;
hash.headers[header] = headerValue;
}
}
return JSON.stringify(hash);
}
class SecurityDetails {
/**
* @param {string} subjectName
* @param {string} issuer
* @param {number} validFrom
* @param {number} validTo
* @param {string} protocol
*/
constructor(subjectName, issuer, validFrom, validTo, protocol) {
this._subjectName = subjectName;
this._issuer = issuer;
this._validFrom = validFrom;
this._validTo = validTo;
this._protocol = protocol;
}
/**
* @return {string}
*/
subjectName() {
return this._subjectName;
}
/**
* @return {string}
*/
issuer() {
return this._issuer;
}
/**
* @return {number}
*/
validFrom() {
return this._validFrom;
}
/**
* @return {number}
*/
validTo() {
return this._validTo;
}
/**
* @return {string}
*/
protocol() {
return this._protocol;
}
}
NetworkManager.Events = {
Request: 'request',
Response: 'response',
RequestFailed: 'requestfailed',
RequestFinished: 'requestfinished',
};
const statusTexts = {
'100': 'Continue',
'101': 'Switching Protocols',
'102': 'Processing',
'200': 'OK',
'201': 'Created',
'202': 'Accepted',
'203': 'Non-Authoritative Information',
'204': 'No Content',
'206': 'Partial Content',
'207': 'Multi-Status',
'208': 'Already Reported',
'209': 'IM Used',
'300': 'Multiple Choices',
'301': 'Moved Permanently',
'302': 'Found',
'303': 'See Other',
'304': 'Not Modified',
'305': 'Use Proxy',
'306': 'Switch Proxy',
'307': 'Temporary Redirect',
'308': 'Permanent Redirect',
'400': 'Bad Request',
'401': 'Unauthorized',
'402': 'Payment Required',
'403': 'Forbidden',
'404': 'Not Found',
'405': 'Method Not Allowed',
'406': 'Not Acceptable',
'407': 'Proxy Authentication Required',
'408': 'Request Timeout',
'409': 'Conflict',
'410': 'Gone',
'411': 'Length Required',
'412': 'Precondition Failed',
'413': 'Payload Too Large',
'414': 'URI Too Long',
'415': 'Unsupported Media Type',
'416': 'Range Not Satisfiable',
'417': 'Expectation Failed',
'418': 'I\'m a teapot',
'421': 'Misdirected Request',
'422': 'Unprocessable Entity',
'423': 'Locked',
'424': 'Failed Dependency',
'426': 'Upgrade Required',
'428': 'Precondition Required',
'429': 'Too Many Requests',
'431': 'Request Header Fields Too Large',
'451': 'Unavailable For Legal Reasons',
'500': 'Internal Server Error',
'501': 'Not Implemented',
'502': 'Bad Gateway',
'503': 'Service Unavailable',
'504': 'Gateway Timeout',
'505': 'HTTP Version Not Supported',
'506': 'Variant Also Negotiates',
'507': 'Insufficient Storage',
'508': 'Loop Detected',
'510': 'Not Extended',
'511': 'Network Authentication Required',
};
module.exports = {Request, Response, NetworkManager};
| lib/NetworkManager.js | 1 | https://github.com/puppeteer/puppeteer/commit/f8cba455ba5d1bc82721e89fda037e86213b02cb | [
0.0021731124725192785,
0.00031846866477280855,
0.00016074342420324683,
0.00017077602387871593,
0.00044682068983092904
] |
{
"id": 6,
"code_window": [
" expect(response).toBeTruthy();\n",
" expect(await response.text()).toBe('{\"foo\": \"bar\"}\\n');\n",
" expect(await response.json()).toEqual({foo: 'bar'});\n",
" });\n",
" it('Page.Events.Response should not report body unless request is finished', async({page, server}) => {\n",
" await page.goto(server.EMPTY_PAGE);\n",
" // Setup server to trap request.\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" it('Page.Events.Response should throw when requesting body of redirected response', async({page, server}) => {\n",
" server.setRedirect('/foo.html', '/empty.html');\n",
" const response = await page.goto(server.PREFIX + '/foo.html');\n",
" const redirectChain = response.request().redirectChain();\n",
" expect(redirectChain.length).toBe(1);\n",
" const redirected = redirectChain[0].response();\n",
" expect(redirected.status()).toBe(302);\n",
" let error = null;\n",
" await redirected.text().catch(e => error = e);\n",
" expect(error.message).toContain('Response body is unavailable for redirect responses');\n",
" });\n"
],
"file_path": "test/network.spec.js",
"type": "add",
"edit_start_line_idx": 96
} | /**
* Copyright 2017 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
const fs = require('fs');
const path = require('path');
const removeRecursive = require('rimraf').sync;
const transformAsyncFunctions = require('./TransformAsyncFunctions');
const root = path.join(__dirname, '..', '..');
const dest = path.join(__dirname, '..', '..', 'node6');
if (fs.existsSync(dest))
removeRecursive(dest);
fs.mkdirSync(dest);
fs.mkdirSync(path.join(dest, 'utils'));
copyFolder(path.join(root, 'lib'), path.join(dest, 'lib'));
copyFolder(path.join(root, 'test'), path.join(dest, 'test'));
copyFolder(path.join(root, 'utils'), path.join(dest, 'utils'));
function copyFolder(source, target) {
if (fs.existsSync(target))
removeRecursive(target);
fs.mkdirSync(target);
fs.readdirSync(source).forEach(file => {
const from = path.join(source, file);
const to = path.join(target, file);
if (fs.lstatSync(from).isDirectory())
copyFolder(from, to);
else
copyFile(from, to);
});
}
function copyFile(from, to) {
let text = fs.readFileSync(from);
if (from.endsWith('.js')) {
text = text.toString();
const prefix = text.startsWith('#!') ? text.substring(0, text.indexOf('\n')) : '';
text = prefix + transformAsyncFunctions(text.substring(prefix.length));
}
fs.writeFileSync(to, text);
}
| utils/node6-transform/index.js | 0 | https://github.com/puppeteer/puppeteer/commit/f8cba455ba5d1bc82721e89fda037e86213b02cb | [
0.00017683295300230384,
0.00017497521184850484,
0.00017225591000169516,
0.00017507962184026837,
0.0000015054579307616223
] |
{
"id": 6,
"code_window": [
" expect(response).toBeTruthy();\n",
" expect(await response.text()).toBe('{\"foo\": \"bar\"}\\n');\n",
" expect(await response.json()).toEqual({foo: 'bar'});\n",
" });\n",
" it('Page.Events.Response should not report body unless request is finished', async({page, server}) => {\n",
" await page.goto(server.EMPTY_PAGE);\n",
" // Setup server to trap request.\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" it('Page.Events.Response should throw when requesting body of redirected response', async({page, server}) => {\n",
" server.setRedirect('/foo.html', '/empty.html');\n",
" const response = await page.goto(server.PREFIX + '/foo.html');\n",
" const redirectChain = response.request().redirectChain();\n",
" expect(redirectChain.length).toBe(1);\n",
" const redirected = redirectChain[0].response();\n",
" expect(redirected.status()).toBe(302);\n",
" let error = null;\n",
" await redirected.text().catch(e => error = e);\n",
" expect(error.message).toContain('Response body is unavailable for redirect responses');\n",
" });\n"
],
"file_path": "test/network.spec.js",
"type": "add",
"edit_start_line_idx": 96
} | /**
* Copyright 2017 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
module.exports = class Matchers {
constructor(customMatchers = {}) {
this._matchers = {};
Object.assign(this._matchers, DefaultMatchers);
Object.assign(this._matchers, customMatchers);
this.expect = this.expect.bind(this);
}
addMatcher(name, matcher) {
this._matchers[name] = matcher;
}
expect(value) {
return new Expect(value, this._matchers);
}
};
class Expect {
constructor(value, matchers) {
this.not = {};
this.not.not = this;
for (const matcherName of Object.keys(matchers)) {
const matcher = matchers[matcherName];
this[matcherName] = applyMatcher.bind(null, matcherName, matcher, false, value);
this.not[matcherName] = applyMatcher.bind(null, matcherName, matcher, true, value);
}
function applyMatcher(matcherName, matcher, inverse, value, ...args) {
const result = matcher.call(null, value, ...args);
const message = `expect.${matcherName} failed` + (result.message ? `: ${result.message}` : '');
console.assert(result.pass !== inverse, message);
}
}
}
const DefaultMatchers = {
toBe: function(value, other, message) {
message = message || `${value} == ${other}`;
return { pass: value === other, message };
},
toBeFalsy: function(value, message) {
message = message || `${value}`;
return { pass: !value, message };
},
toBeTruthy: function(value, message) {
message = message || `${value}`;
return { pass: !!value, message };
},
toBeGreaterThan: function(value, other, message) {
message = message || `${value} > ${other}`;
return { pass: value > other, message };
},
toBeGreaterThanOrEqual: function(value, other, message) {
message = message || `${value} >= ${other}`;
return { pass: value >= other, message };
},
toBeLessThan: function(value, other, message) {
message = message || `${value} < ${other}`;
return { pass: value < other, message };
},
toBeLessThanOrEqual: function(value, other, message) {
message = message || `${value} <= ${other}`;
return { pass: value <= other, message };
},
toBeNull: function(value, message) {
message = message || `${value} == null`;
return { pass: value === null, message };
},
toContain: function(value, other, message) {
message = message || `${value} ⊇ ${other}`;
return { pass: value.includes(other), message };
},
toEqual: function(value, other, message) {
const valueJson = stringify(value);
const otherJson = stringify(other);
message = message || `${valueJson} ≈ ${otherJson}`;
return { pass: valueJson === otherJson, message };
},
toBeCloseTo: function(value, other, precision, message) {
return {
pass: Math.abs(value - other) < Math.pow(10, -precision),
message
};
}
};
function stringify(value) {
function stabilize(key, object) {
if (typeof object !== 'object' || object === undefined || object === null)
return object;
const result = {};
for (const key of Object.keys(object).sort())
result[key] = object[key];
return result;
}
return JSON.stringify(stabilize(null, value), stabilize);
}
| utils/testrunner/Matchers.js | 0 | https://github.com/puppeteer/puppeteer/commit/f8cba455ba5d1bc82721e89fda037e86213b02cb | [
0.0010902252979576588,
0.00028528476832434535,
0.00016696308739483356,
0.00017403181118424982,
0.0002746183890849352
] |
{
"id": 6,
"code_window": [
" expect(response).toBeTruthy();\n",
" expect(await response.text()).toBe('{\"foo\": \"bar\"}\\n');\n",
" expect(await response.json()).toEqual({foo: 'bar'});\n",
" });\n",
" it('Page.Events.Response should not report body unless request is finished', async({page, server}) => {\n",
" await page.goto(server.EMPTY_PAGE);\n",
" // Setup server to trap request.\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" it('Page.Events.Response should throw when requesting body of redirected response', async({page, server}) => {\n",
" server.setRedirect('/foo.html', '/empty.html');\n",
" const response = await page.goto(server.PREFIX + '/foo.html');\n",
" const redirectChain = response.request().redirectChain();\n",
" expect(redirectChain.length).toBe(1);\n",
" const redirected = redirectChain[0].response();\n",
" expect(redirected.status()).toBe(302);\n",
" let error = null;\n",
" await redirected.text().catch(e => error = e);\n",
" expect(error.message).toContain('Response body is unavailable for redirect responses');\n",
" });\n"
],
"file_path": "test/network.spec.js",
"type": "add",
"edit_start_line_idx": 96
} | class Other {
}
| utils/doclint/check_public_api/test/diff-classes/other.js | 0 | https://github.com/puppeteer/puppeteer/commit/f8cba455ba5d1bc82721e89fda037e86213b02cb | [
0.0001663747534621507,
0.0001663747534621507,
0.0001663747534621507,
0.0001663747534621507,
0
] |
{
"id": 0,
"code_window": [
"import * as cacheManager from 'cache-manager'\n",
"\n",
"const memoryCache = cacheManager.caching({ store: 'memory', max: 100, ttl: 10/*seconds*/ });\n",
"const ttl = 5;\n",
"\n",
"memoryCache.set('foo', 'bar', { ttl: ttl }, (err) => {\n",
"\n",
" if (err) {\n"
],
"labels": [
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"const memoryCache: cacheManager.Cache = cacheManager.caching({ store: 'memory', max: 100, ttl: 10/*seconds*/ });\n"
],
"file_path": "types/cache-manager/cache-manager-tests.ts",
"type": "replace",
"edit_start_line_idx": 2
} | // Type definitions for cache-manager v1.2.0
// Project: https://github.com/BryanDonovan/node-cache-manager
// Definitions by: Simon Gausmann <https://github.com/GausSim>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
interface CachingConfig {
ttl: number;
}
interface StoreConfig extends CachingConfig {
store: string;
max?: number;
isCacheableValue?: (value: any) => boolean;
}
interface Cache {
set<T>(key: string, value: T, options: CachingConfig, callback?: (error: any) => void): void;
set<T>(key: string, value: T, ttl: number, callback?: (error: any) => void): void;
set<T>(key: string, value: T, options: CachingConfig): Promise<any>;
set<T>(key: string, value: T, ttl: number): Promise<any>;
wrap<T>(key: string, wrapper: (callback: (error: any, result: T) => void) => void, options: CachingConfig, callback: (error: any, result: T) => void): void;
wrap<T>(key: string, wrapper: (callback: (error: any, result: T) => void) => void, callback: (error: any, result: T) => void): void;
wrap<T>(key: string, wrapper: (callback: (error: any, result: T) => void) => any, options: CachingConfig): Promise<any>;
wrap<T>(key: string, wrapper: (callback: (error: any, result: T) => void) => void): Promise<any>;
get<T>(key: string, callback: (error: any, result: T) => void): void;
get<T>(key: string): Promise<any>;
del(key: string, callback: (error: any) => void): void;
del(key: string): Promise<any>;
}
declare namespace cacheManager {
function caching(IConfig: StoreConfig): Cache;
function multiCaching(Caches: Cache[]): Cache;
}
export = cacheManager;
| types/cache-manager/index.d.ts | 1 | https://github.com/DefinitelyTyped/DefinitelyTyped/commit/ca7d069c55f1c9586f588554386bcebdc0071bff | [
0.0028723711147904396,
0.001676870509982109,
0.00017628986097406596,
0.0019086819374933839,
0.0009709541336633265
] |
{
"id": 0,
"code_window": [
"import * as cacheManager from 'cache-manager'\n",
"\n",
"const memoryCache = cacheManager.caching({ store: 'memory', max: 100, ttl: 10/*seconds*/ });\n",
"const ttl = 5;\n",
"\n",
"memoryCache.set('foo', 'bar', { ttl: ttl }, (err) => {\n",
"\n",
" if (err) {\n"
],
"labels": [
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"const memoryCache: cacheManager.Cache = cacheManager.caching({ store: 'memory', max: 100, ttl: 10/*seconds*/ });\n"
],
"file_path": "types/cache-manager/cache-manager-tests.ts",
"type": "replace",
"edit_start_line_idx": 2
} | import * as React from 'react';
import { CSSModule } from '../index';
export type CarouselCaptionProps<T = {}> = React.HTMLProps<HTMLElement> & {
captionHeader?: string;
captionText: string;
cssModule?: CSSModule;
} & T;
declare class CarouselCaption<T = {[key: string]: any}> extends React.Component<CarouselCaptionProps<T>> {}
export default CarouselCaption;
| types/reactstrap/lib/CarouselCaption.d.ts | 0 | https://github.com/DefinitelyTyped/DefinitelyTyped/commit/ca7d069c55f1c9586f588554386bcebdc0071bff | [
0.00017562179709784687,
0.00017416005721315742,
0.00017269830277655274,
0.00017416005721315742,
0.0000014617471606470644
] |
{
"id": 0,
"code_window": [
"import * as cacheManager from 'cache-manager'\n",
"\n",
"const memoryCache = cacheManager.caching({ store: 'memory', max: 100, ttl: 10/*seconds*/ });\n",
"const ttl = 5;\n",
"\n",
"memoryCache.set('foo', 'bar', { ttl: ttl }, (err) => {\n",
"\n",
" if (err) {\n"
],
"labels": [
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"const memoryCache: cacheManager.Cache = cacheManager.caching({ store: 'memory', max: 100, ttl: 10/*seconds*/ });\n"
],
"file_path": "types/cache-manager/cache-manager-tests.ts",
"type": "replace",
"edit_start_line_idx": 2
} | import { find } from "lodash";
export default find;
| types/lodash-es/find.d.ts | 0 | https://github.com/DefinitelyTyped/DefinitelyTyped/commit/ca7d069c55f1c9586f588554386bcebdc0071bff | [
0.0001774095289874822,
0.0001774095289874822,
0.0001774095289874822,
0.0001774095289874822,
0
] |
{
"id": 0,
"code_window": [
"import * as cacheManager from 'cache-manager'\n",
"\n",
"const memoryCache = cacheManager.caching({ store: 'memory', max: 100, ttl: 10/*seconds*/ });\n",
"const ttl = 5;\n",
"\n",
"memoryCache.set('foo', 'bar', { ttl: ttl }, (err) => {\n",
"\n",
" if (err) {\n"
],
"labels": [
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"const memoryCache: cacheManager.Cache = cacheManager.caching({ store: 'memory', max: 100, ttl: 10/*seconds*/ });\n"
],
"file_path": "types/cache-manager/cache-manager-tests.ts",
"type": "replace",
"edit_start_line_idx": 2
} | {
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": false,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"routie-tests.ts"
]
} | types/routie/tsconfig.json | 0 | https://github.com/DefinitelyTyped/DefinitelyTyped/commit/ca7d069c55f1c9586f588554386bcebdc0071bff | [
0.00017642235616222024,
0.00017506165022496134,
0.00017366133397445083,
0.00017510126053821295,
0.00000112753048142622
] |
{
"id": 1,
"code_window": [
"// Project: https://github.com/BryanDonovan/node-cache-manager\n",
"// Definitions by: Simon Gausmann <https://github.com/GausSim>\n",
"// Definitions: https://github.com/borisyankov/DefinitelyTyped\n",
"\n",
"interface CachingConfig {\n",
" ttl: number;\n",
"}\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"export interface CachingConfig {\n"
],
"file_path": "types/cache-manager/index.d.ts",
"type": "replace",
"edit_start_line_idx": 5
} | import * as cacheManager from 'cache-manager'
const memoryCache = cacheManager.caching({ store: 'memory', max: 100, ttl: 10/*seconds*/ });
const ttl = 5;
memoryCache.set('foo', 'bar', { ttl: ttl }, (err) => {
if (err) {
throw err;
}
memoryCache.get('foo', (err, result) => {
// console.log(result);
memoryCache.del('foo', (err) => {
});
});
});
function getUser(id: number, cb: Function) {
cb(null, { id: id, name: 'Bob' });
}
const userId = 123;
const key = 'user_' + userId;
// Note: ttl is optional in wrap()
memoryCache.wrap<{ id: number, name: string }>(key, (cb) => {
getUser(userId, cb);
}, { ttl: ttl }, (err, user) => {
//console.log(user);
// Second time fetches user from memoryCache
memoryCache.wrap<{ id: number, name: string }>(key, (cb) => {
getUser(userId, cb);
}, (err, user) => {
//console.log(user);
});
});
| types/cache-manager/cache-manager-tests.ts | 1 | https://github.com/DefinitelyTyped/DefinitelyTyped/commit/ca7d069c55f1c9586f588554386bcebdc0071bff | [
0.0019640219397842884,
0.0005697213346138597,
0.00017339824989903718,
0.00018225726671516895,
0.0007005121442489326
] |
{
"id": 1,
"code_window": [
"// Project: https://github.com/BryanDonovan/node-cache-manager\n",
"// Definitions by: Simon Gausmann <https://github.com/GausSim>\n",
"// Definitions: https://github.com/borisyankov/DefinitelyTyped\n",
"\n",
"interface CachingConfig {\n",
" ttl: number;\n",
"}\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"export interface CachingConfig {\n"
],
"file_path": "types/cache-manager/index.d.ts",
"type": "replace",
"edit_start_line_idx": 5
} | {
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": false,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"express-partials-tests.ts"
]
} | types/express-partials/tsconfig.json | 0 | https://github.com/DefinitelyTyped/DefinitelyTyped/commit/ca7d069c55f1c9586f588554386bcebdc0071bff | [
0.00017515603394713253,
0.00017320452025160193,
0.00017062172992154956,
0.0001738357823342085,
0.0000019041798395846854
] |
{
"id": 1,
"code_window": [
"// Project: https://github.com/BryanDonovan/node-cache-manager\n",
"// Definitions by: Simon Gausmann <https://github.com/GausSim>\n",
"// Definitions: https://github.com/borisyankov/DefinitelyTyped\n",
"\n",
"interface CachingConfig {\n",
" ttl: number;\n",
"}\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"export interface CachingConfig {\n"
],
"file_path": "types/cache-manager/index.d.ts",
"type": "replace",
"edit_start_line_idx": 5
} | {
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6",
"dom"
],
"noImplicitAny": true,
"noImplicitThis": false,
"strictNullChecks": false,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"arbiter-tests.ts"
]
} | types/arbiter/tsconfig.json | 0 | https://github.com/DefinitelyTyped/DefinitelyTyped/commit/ca7d069c55f1c9586f588554386bcebdc0071bff | [
0.0001757899735821411,
0.00017385355022270232,
0.00017039004887919873,
0.00017538062820676714,
0.00000245476030613645
] |
{
"id": 1,
"code_window": [
"// Project: https://github.com/BryanDonovan/node-cache-manager\n",
"// Definitions by: Simon Gausmann <https://github.com/GausSim>\n",
"// Definitions: https://github.com/borisyankov/DefinitelyTyped\n",
"\n",
"interface CachingConfig {\n",
" ttl: number;\n",
"}\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"export interface CachingConfig {\n"
],
"file_path": "types/cache-manager/index.d.ts",
"type": "replace",
"edit_start_line_idx": 5
} | // Type definitions for non-npm package Google Google+ Domains API v1 1.0
// Project: https://developers.google.com/+/domains/
// Definitions by: Bolisov Alexey <https://github.com/Bolisov>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.3
// IMPORTANT
// This file was generated by https://github.com/Bolisov/google-api-typings-generator. Please do not edit it manually.
// In case of any problems please post issue to https://github.com/Bolisov/google-api-typings-generator
// Generated from: https://www.googleapis.com/discovery/v1/apis/plusDomains/v1/rest
/// <reference types="gapi.client" />
declare namespace gapi.client {
/** Load Google+ Domains API v1 */
function load(name: "plusdomains", version: "v1"): PromiseLike<void>;
function load(name: "plusdomains", version: "v1", callback: () => any): void;
const activities: plusdomains.ActivitiesResource;
const audiences: plusdomains.AudiencesResource;
const circles: plusdomains.CirclesResource;
const comments: plusdomains.CommentsResource;
const media: plusdomains.MediaResource;
const people: plusdomains.PeopleResource;
namespace plusdomains {
interface Acl {
/** Description of the access granted, suitable for display. */
description?: string;
/** Whether access is restricted to the domain. */
domainRestricted?: boolean;
/** The list of access entries. */
items?: PlusDomainsAclentryResource[];
/** Identifies this resource as a collection of access controls. Value: "plus#acl". */
kind?: string;
}
interface Activity {
/** Identifies who has access to see this activity. */
access?: Acl;
/** The person who performed this activity. */
actor?: {
/** Actor info specific to particular clients. */
clientSpecificActorInfo?: {
/** Actor info specific to YouTube clients. */
youtubeActorInfo?: {
/** ID of the YouTube channel owned by the Actor. */
channelId?: string;
};
};
/** The name of the actor, suitable for display. */
displayName?: string;
/** The ID of the actor's Person resource. */
id?: string;
/** The image representation of the actor. */
image?: {
/**
* The URL of the actor's profile photo. To resize the image and crop it to a square, append the query string ?sz=x, where x is the dimension in pixels of
* each side.
*/
url?: string;
};
/** An object representation of the individual components of name. */
name?: {
/** The family name ("last name") of the actor. */
familyName?: string;
/** The given name ("first name") of the actor. */
givenName?: string;
};
/** The link to the actor's Google profile. */
url?: string;
/** Verification status of actor. */
verification?: {
/** Verification for one-time or manual processes. */
adHocVerified?: string;
};
};
/** Street address where this activity occurred. */
address?: string;
/** Additional content added by the person who shared this activity, applicable only when resharing an activity. */
annotation?: string;
/** If this activity is a crosspost from another system, this property specifies the ID of the original activity. */
crosspostSource?: string;
/** ETag of this response for caching purposes. */
etag?: string;
/** Latitude and longitude where this activity occurred. Format is latitude followed by longitude, space separated. */
geocode?: string;
/** The ID of this activity. */
id?: string;
/** Identifies this resource as an activity. Value: "plus#activity". */
kind?: string;
/** The location where this activity occurred. */
location?: Place;
/** The object of this activity. */
object?: {
/**
* If this activity's object is itself another activity, such as when a person reshares an activity, this property specifies the original activity's
* actor.
*/
actor?: {
/** Actor info specific to particular clients. */
clientSpecificActorInfo?: {
/** Actor info specific to YouTube clients. */
youtubeActorInfo?: {
/** ID of the YouTube channel owned by the Actor. */
channelId?: string;
};
};
/** The original actor's name, which is suitable for display. */
displayName?: string;
/** ID of the original actor. */
id?: string;
/** The image representation of the original actor. */
image?: {
/** A URL that points to a thumbnail photo of the original actor. */
url?: string;
};
/** A link to the original actor's Google profile. */
url?: string;
/** Verification status of actor. */
verification?: {
/** Verification for one-time or manual processes. */
adHocVerified?: string;
};
};
/** The media objects attached to this activity. */
attachments?: Array<{
/** If the attachment is an article, this property contains a snippet of text from the article. It can also include descriptions for other types. */
content?: string;
/** The title of the attachment, such as a photo caption or an article title. */
displayName?: string;
/** If the attachment is a video, the embeddable link. */
embed?: {
/** Media type of the link. */
type?: string;
/** URL of the link. */
url?: string;
};
/** The full image URL for photo attachments. */
fullImage?: {
/** The height, in pixels, of the linked resource. */
height?: number;
/** Media type of the link. */
type?: string;
/** URL of the image. */
url?: string;
/** The width, in pixels, of the linked resource. */
width?: number;
};
/** The ID of the attachment. */
id?: string;
/** The preview image for photos or videos. */
image?: {
/** The height, in pixels, of the linked resource. */
height?: number;
/** Media type of the link. */
type?: string;
/** Image URL. */
url?: string;
/** The width, in pixels, of the linked resource. */
width?: number;
};
/**
* The type of media object. Possible values include, but are not limited to, the following values:
* - "photo" - A photo.
* - "album" - A photo album.
* - "video" - A video.
* - "article" - An article, specified by a link.
*/
objectType?: string;
/**
* When previewing, these are the optional thumbnails for the post. When posting an article, choose one by setting the attachment.image.url property. If
* you don't choose one, one will be chosen for you.
*/
previewThumbnails?: Array<{
/** URL of the thumbnail image. */
url?: string;
}>;
/** If the attachment is an album, this property is a list of potential additional thumbnails from the album. */
thumbnails?: Array<{
/** Potential name of the thumbnail. */
description?: string;
/** Image resource. */
image?: {
/** The height, in pixels, of the linked resource. */
height?: number;
/** Media type of the link. */
type?: string;
/** Image url. */
url?: string;
/** The width, in pixels, of the linked resource. */
width?: number;
};
/** URL of the webpage containing the image. */
url?: string;
}>;
/** The link to the attachment, which should be of type text/html. */
url?: string;
}>;
/** The HTML-formatted content, which is suitable for display. */
content?: string;
/** The ID of the object. When resharing an activity, this is the ID of the activity that is being reshared. */
id?: string;
/**
* The type of the object. Possible values include, but are not limited to, the following values:
* - "note" - Textual content.
* - "activity" - A Google+ activity.
*/
objectType?: string;
/**
* The content (text) as provided by the author, which is stored without any HTML formatting. When creating or updating an activity, this value must be
* supplied as plain text in the request.
*/
originalContent?: string;
/** People who +1'd this activity. */
plusoners?: {
/** The URL for the collection of people who +1'd this activity. */
selfLink?: string;
/** Total number of people who +1'd this activity. */
totalItems?: number;
};
/** Comments in reply to this activity. */
replies?: {
/** The URL for the collection of comments in reply to this activity. */
selfLink?: string;
/** Total number of comments on this activity. */
totalItems?: number;
};
/** People who reshared this activity. */
resharers?: {
/** The URL for the collection of resharers. */
selfLink?: string;
/** Total number of people who reshared this activity. */
totalItems?: number;
};
/** Status of the activity as seen by the viewer. */
statusForViewer?: {
/** Whether the viewer can comment on the activity. */
canComment?: boolean;
/** Whether the viewer can +1 the activity. */
canPlusone?: boolean;
/** Whether the viewer can edit or delete the activity. */
canUpdate?: boolean;
/** Whether the viewer has +1'd the activity. */
isPlusOned?: boolean;
/** Whether reshares are disabled for the activity. */
resharingDisabled?: boolean;
};
/** The URL that points to the linked resource. */
url?: string;
};
/** ID of the place where this activity occurred. */
placeId?: string;
/** Name of the place where this activity occurred. */
placeName?: string;
/** The service provider that initially published this activity. */
provider?: {
/** Name of the service provider. */
title?: string;
};
/** The time at which this activity was initially published. Formatted as an RFC 3339 timestamp. */
published?: string;
/** Radius, in meters, of the region where this activity occurred, centered at the latitude and longitude identified in geocode. */
radius?: string;
/** Title of this activity. */
title?: string;
/** The time at which this activity was last updated. Formatted as an RFC 3339 timestamp. */
updated?: string;
/** The link to this activity. */
url?: string;
/**
* This activity's verb, which indicates the action that was performed. Possible values include, but are not limited to, the following values:
* - "post" - Publish content to the stream.
* - "share" - Reshare an activity.
*/
verb?: string;
}
interface ActivityFeed {
/** ETag of this response for caching purposes. */
etag?: string;
/** The ID of this collection of activities. Deprecated. */
id?: string;
/** The activities in this page of results. */
items?: Activity[];
/** Identifies this resource as a collection of activities. Value: "plus#activityFeed". */
kind?: string;
/** Link to the next page of activities. */
nextLink?: string;
/** The continuation token, which is used to page through large result sets. Provide this value in a subsequent request to return the next page of results. */
nextPageToken?: string;
/** Link to this activity resource. */
selfLink?: string;
/** The title of this collection of activities, which is a truncated portion of the content. */
title?: string;
/** The time at which this collection of activities was last updated. Formatted as an RFC 3339 timestamp. */
updated?: string;
}
interface Audience {
/** ETag of this response for caching purposes. */
etag?: string;
/** The access control list entry. */
item?: PlusDomainsAclentryResource;
/** Identifies this resource as an audience. Value: "plus#audience". */
kind?: string;
/** The number of people in this circle. This only applies if entity_type is CIRCLE. */
memberCount?: number;
/**
* The circle members' visibility as chosen by the owner of the circle. This only applies for items with "item.type" equals "circle". Possible values are:
*
* - "public" - Members are visible to the public.
* - "limited" - Members are visible to a limited audience.
* - "private" - Members are visible to the owner only.
*/
visibility?: string;
}
interface AudiencesFeed {
/** ETag of this response for caching purposes. */
etag?: string;
/** The audiences in this result. */
items?: Audience[];
/** Identifies this resource as a collection of audiences. Value: "plus#audienceFeed". */
kind?: string;
/** The continuation token, which is used to page through large result sets. Provide this value in a subsequent request to return the next page of results. */
nextPageToken?: string;
/** The total number of ACL entries. The number of entries in this response may be smaller due to paging. */
totalItems?: number;
}
interface Circle {
/** The description of this circle. */
description?: string;
/** The circle name. */
displayName?: string;
/** ETag of this response for caching purposes. */
etag?: string;
/** The ID of the circle. */
id?: string;
/** Identifies this resource as a circle. Value: "plus#circle". */
kind?: string;
/** The people in this circle. */
people?: {
/** The total number of people in this circle. */
totalItems?: number;
};
/** Link to this circle resource */
selfLink?: string;
}
interface CircleFeed {
/** ETag of this response for caching purposes. */
etag?: string;
/** The circles in this page of results. */
items?: Circle[];
/** Identifies this resource as a collection of circles. Value: "plus#circleFeed". */
kind?: string;
/** Link to the next page of circles. */
nextLink?: string;
/** The continuation token, which is used to page through large result sets. Provide this value in a subsequent request to return the next page of results. */
nextPageToken?: string;
/** Link to this page of circles. */
selfLink?: string;
/** The title of this list of resources. */
title?: string;
/** The total number of circles. The number of circles in this response may be smaller due to paging. */
totalItems?: number;
}
interface Comment {
/** The person who posted this comment. */
actor?: {
/** Actor info specific to particular clients. */
clientSpecificActorInfo?: {
/** Actor info specific to YouTube clients. */
youtubeActorInfo?: {
/** ID of the YouTube channel owned by the Actor. */
channelId?: string;
};
};
/** The name of this actor, suitable for display. */
displayName?: string;
/** The ID of the actor. */
id?: string;
/** The image representation of this actor. */
image?: {
/**
* The URL of the actor's profile photo. To resize the image and crop it to a square, append the query string ?sz=x, where x is the dimension in pixels of
* each side.
*/
url?: string;
};
/** A link to the Person resource for this actor. */
url?: string;
/** Verification status of actor. */
verification?: {
/** Verification for one-time or manual processes. */
adHocVerified?: string;
};
};
/** ETag of this response for caching purposes. */
etag?: string;
/** The ID of this comment. */
id?: string;
/** The activity this comment replied to. */
inReplyTo?: Array<{
/** The ID of the activity. */
id?: string;
/** The URL of the activity. */
url?: string;
}>;
/** Identifies this resource as a comment. Value: "plus#comment". */
kind?: string;
/** The object of this comment. */
object?: {
/** The HTML-formatted content, suitable for display. */
content?: string;
/**
* The object type of this comment. Possible values are:
* - "comment" - A comment in reply to an activity.
*/
objectType?: string;
/**
* The content (text) as provided by the author, stored without any HTML formatting. When creating or updating a comment, this value must be supplied as
* plain text in the request.
*/
originalContent?: string;
};
/** People who +1'd this comment. */
plusoners?: {
/** Total number of people who +1'd this comment. */
totalItems?: number;
};
/** The time at which this comment was initially published. Formatted as an RFC 3339 timestamp. */
published?: string;
/** Link to this comment resource. */
selfLink?: string;
/** The time at which this comment was last updated. Formatted as an RFC 3339 timestamp. */
updated?: string;
/**
* This comment's verb, indicating what action was performed. Possible values are:
* - "post" - Publish content to the stream.
*/
verb?: string;
}
interface CommentFeed {
/** ETag of this response for caching purposes. */
etag?: string;
/** The ID of this collection of comments. */
id?: string;
/** The comments in this page of results. */
items?: Comment[];
/** Identifies this resource as a collection of comments. Value: "plus#commentFeed". */
kind?: string;
/** Link to the next page of activities. */
nextLink?: string;
/** The continuation token, which is used to page through large result sets. Provide this value in a subsequent request to return the next page of results. */
nextPageToken?: string;
/** The title of this collection of comments. */
title?: string;
/** The time at which this collection of comments was last updated. Formatted as an RFC 3339 timestamp. */
updated?: string;
}
interface Media {
/** The person who uploaded this media. */
author?: {
/** The author's name. */
displayName?: string;
/** ID of the author. */
id?: string;
/** The author's Google profile image. */
image?: {
/**
* The URL of the author's profile photo. To resize the image and crop it to a square, append the query string ?sz=x, where x is the dimension in pixels
* of each side.
*/
url?: string;
};
/** A link to the author's Google profile. */
url?: string;
};
/** The display name for this media. */
displayName?: string;
/** ETag of this response for caching purposes. */
etag?: string;
/** Exif information of the media item. */
exif?: {
/** The time the media was captured. Formatted as an RFC 3339 timestamp. */
time?: string;
};
/** The height in pixels of the original image. */
height?: number;
/** ID of this media, which is generated by the API. */
id?: string;
/** The type of resource. */
kind?: string;
/** The time at which this media was originally created in UTC. Formatted as an RFC 3339 timestamp that matches this example: 2010-11-25T14:30:27.655Z */
mediaCreatedTime?: string;
/** The URL of this photo or video's still image. */
mediaUrl?: string;
/** The time at which this media was uploaded. Formatted as an RFC 3339 timestamp. */
published?: string;
/** The size in bytes of this video. */
sizeBytes?: string;
/** The list of video streams for this video. There might be several different streams available for a single video, either Flash or MPEG, of various sizes */
streams?: Videostream[];
/** A description, or caption, for this media. */
summary?: string;
/** The time at which this media was last updated. This includes changes to media metadata. Formatted as an RFC 3339 timestamp. */
updated?: string;
/** The URL for the page that hosts this media. */
url?: string;
/** The duration in milliseconds of this video. */
videoDuration?: string;
/**
* The encoding status of this video. Possible values are:
* - "UPLOADING" - Not all the video bytes have been received.
* - "PENDING" - Video not yet processed.
* - "FAILED" - Video processing failed.
* - "READY" - A single video stream is playable.
* - "FINAL" - All video streams are playable.
*/
videoStatus?: string;
/** The width in pixels of the original image. */
width?: number;
}
interface PeopleFeed {
/** ETag of this response for caching purposes. */
etag?: string;
/**
* The people in this page of results. Each item includes the id, displayName, image, and url for the person. To retrieve additional profile data, see the
* people.get method.
*/
items?: Person[];
/** Identifies this resource as a collection of people. Value: "plus#peopleFeed". */
kind?: string;
/** The continuation token, which is used to page through large result sets. Provide this value in a subsequent request to return the next page of results. */
nextPageToken?: string;
/** Link to this resource. */
selfLink?: string;
/** The title of this collection of people. */
title?: string;
/**
* The total number of people available in this list. The number of people in a response might be smaller due to paging. This might not be set for all
* collections.
*/
totalItems?: number;
}
interface Person {
/** A short biography for this person. */
aboutMe?: string;
/** The person's date of birth, represented as YYYY-MM-DD. */
birthday?: string;
/** The "bragging rights" line of this person. */
braggingRights?: string;
/** For followers who are visible, the number of people who have added this person or page to a circle. */
circledByCount?: number;
/** The cover photo content. */
cover?: {
/** Extra information about the cover photo. */
coverInfo?: {
/** The difference between the left position of the cover image and the actual displayed cover image. Only valid for banner layout. */
leftImageOffset?: number;
/** The difference between the top position of the cover image and the actual displayed cover image. Only valid for banner layout. */
topImageOffset?: number;
};
/** The person's primary cover image. */
coverPhoto?: {
/** The height of the image. */
height?: number;
/** The URL of the image. */
url?: string;
/** The width of the image. */
width?: number;
};
/**
* The layout of the cover art. Possible values include, but are not limited to, the following values:
* - "banner" - One large image banner.
*/
layout?: string;
};
/** (this field is not currently used) */
currentLocation?: string;
/** The name of this person, which is suitable for display. */
displayName?: string;
/**
* The hosted domain name for the user's Google Apps account. For instance, example.com. The plus.profile.emails.read or email scope is needed to get this
* domain name.
*/
domain?: string;
/**
* A list of email addresses that this person has, including their Google account email address, and the public verified email addresses on their Google+
* profile. The plus.profile.emails.read scope is needed to retrieve these email addresses, or the email scope can be used to retrieve just the Google
* account email address.
*/
emails?: Array<{
/**
* The type of address. Possible values include, but are not limited to, the following values:
* - "account" - Google account email address.
* - "home" - Home email address.
* - "work" - Work email address.
* - "other" - Other.
*/
type?: string;
/** The email address. */
value?: string;
}>;
/** ETag of this response for caching purposes. */
etag?: string;
/**
* The person's gender. Possible values include, but are not limited to, the following values:
* - "male" - Male gender.
* - "female" - Female gender.
* - "other" - Other.
*/
gender?: string;
/** The ID of this person. */
id?: string;
/** The representation of the person's profile photo. */
image?: {
/** Whether the person's profile photo is the default one */
isDefault?: boolean;
/**
* The URL of the person's profile photo. To resize the image and crop it to a square, append the query string ?sz=x, where x is the dimension in pixels
* of each side.
*/
url?: string;
};
/** Whether this user has signed up for Google+. */
isPlusUser?: boolean;
/** Identifies this resource as a person. Value: "plus#person". */
kind?: string;
/** An object representation of the individual components of a person's name. */
name?: {
/** The family name (last name) of this person. */
familyName?: string;
/** The full name of this person, including middle names, suffixes, etc. */
formatted?: string;
/** The given name (first name) of this person. */
givenName?: string;
/** The honorific prefixes (such as "Dr." or "Mrs.") for this person. */
honorificPrefix?: string;
/** The honorific suffixes (such as "Jr.") for this person. */
honorificSuffix?: string;
/** The middle name of this person. */
middleName?: string;
};
/** The nickname of this person. */
nickname?: string;
/**
* Type of person within Google+. Possible values include, but are not limited to, the following values:
* - "person" - represents an actual person.
* - "page" - represents a page.
*/
objectType?: string;
/** The occupation of this person. */
occupation?: string;
/** A list of current or past organizations with which this person is associated. */
organizations?: Array<{
/** The department within the organization. Deprecated. */
department?: string;
/** A short description of the person's role in this organization. Deprecated. */
description?: string;
/** The date that the person left this organization. */
endDate?: string;
/** The location of this organization. Deprecated. */
location?: string;
/** The name of the organization. */
name?: string;
/** If "true", indicates this organization is the person's primary one, which is typically interpreted as the current one. */
primary?: boolean;
/** The date that the person joined this organization. */
startDate?: string;
/** The person's job title or role within the organization. */
title?: string;
/**
* The type of organization. Possible values include, but are not limited to, the following values:
* - "work" - Work.
* - "school" - School.
*/
type?: string;
}>;
/** A list of places where this person has lived. */
placesLived?: Array<{
/** If "true", this place of residence is this person's primary residence. */
primary?: boolean;
/** A place where this person has lived. For example: "Seattle, WA", "Near Toronto". */
value?: string;
}>;
/** If a Google+ Page, the number of people who have +1'd this page. */
plusOneCount?: number;
/**
* The person's relationship status. Possible values include, but are not limited to, the following values:
* - "single" - Person is single.
* - "in_a_relationship" - Person is in a relationship.
* - "engaged" - Person is engaged.
* - "married" - Person is married.
* - "its_complicated" - The relationship is complicated.
* - "open_relationship" - Person is in an open relationship.
* - "widowed" - Person is widowed.
* - "in_domestic_partnership" - Person is in a domestic partnership.
* - "in_civil_union" - Person is in a civil union.
*/
relationshipStatus?: string;
/** The person's skills. */
skills?: string;
/** The brief description (tagline) of this person. */
tagline?: string;
/** The URL of this person's profile. */
url?: string;
/** A list of URLs for this person. */
urls?: Array<{
/** The label of the URL. */
label?: string;
/**
* The type of URL. Possible values include, but are not limited to, the following values:
* - "otherProfile" - URL for another profile.
* - "contributor" - URL to a site for which this person is a contributor.
* - "website" - URL for this Google+ Page's primary website.
* - "other" - Other URL.
*/
type?: string;
/** The URL value. */
value?: string;
}>;
/** Whether the person or Google+ Page has been verified. */
verified?: boolean;
}
interface Place {
/** The physical address of the place. */
address?: {
/** The formatted address for display. */
formatted?: string;
};
/** The display name of the place. */
displayName?: string;
/** The id of the place. */
id?: string;
/** Identifies this resource as a place. Value: "plus#place". */
kind?: string;
/** The position of the place. */
position?: {
/** The latitude of this position. */
latitude?: number;
/** The longitude of this position. */
longitude?: number;
};
}
interface PlusDomainsAclentryResource {
/** A descriptive name for this entry. Suitable for display. */
displayName?: string;
/** The ID of the entry. For entries of type "person" or "circle", this is the ID of the resource. For other types, this property is not set. */
id?: string;
/**
* The type of entry describing to whom access is granted. Possible values are:
* - "person" - Access to an individual.
* - "circle" - Access to members of a circle.
* - "myCircles" - Access to members of all the person's circles.
* - "extendedCircles" - Access to members of all the person's circles, plus all of the people in their circles.
* - "domain" - Access to members of the person's Google Apps domain.
* - "public" - Access to anyone on the web.
*/
type?: string;
}
interface Videostream {
/** The height, in pixels, of the video resource. */
height?: number;
/** MIME type of the video stream. */
type?: string;
/** URL of the video stream. */
url?: string;
/** The width, in pixels, of the video resource. */
width?: number;
}
interface ActivitiesResource {
/** Get an activity. */
get(request: {
/** The ID of the activity to get. */
activityId: string;
/** Data format for the response. */
alt?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/**
* Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* Overrides userIp if both are provided.
*/
quotaUser?: string;
/** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */
userIp?: string;
}): Request<Activity>;
/** Create a new activity for the authenticated user. */
insert(request: {
/** Data format for the response. */
alt?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/**
* If "true", extract the potential media attachments for a URL. The response will include all possible attachments for a URL, including video, photos,
* and articles based on the content of the page.
*/
preview?: boolean;
/**
* Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* Overrides userIp if both are provided.
*/
quotaUser?: string;
/** The ID of the user to create the activity on behalf of. Its value should be "me", to indicate the authenticated user. */
userId: string;
/** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */
userIp?: string;
}): Request<Activity>;
/** List all of the activities in the specified collection for a particular user. */
list(request: {
/** Data format for the response. */
alt?: string;
/** The collection of activities to list. */
collection: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/**
* The maximum number of activities to include in the response, which is used for paging. For any response, the actual number returned might be less than
* the specified maxResults.
*/
maxResults?: number;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/**
* The continuation token, which is used to page through large result sets. To get the next page of results, set this parameter to the value of
* "nextPageToken" from the previous response.
*/
pageToken?: string;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/**
* Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* Overrides userIp if both are provided.
*/
quotaUser?: string;
/** The ID of the user to get activities for. The special value "me" can be used to indicate the authenticated user. */
userId: string;
/** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */
userIp?: string;
}): Request<ActivityFeed>;
}
interface AudiencesResource {
/** List all of the audiences to which a user can share. */
list(request: {
/** Data format for the response. */
alt?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/**
* The maximum number of circles to include in the response, which is used for paging. For any response, the actual number returned might be less than the
* specified maxResults.
*/
maxResults?: number;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/**
* The continuation token, which is used to page through large result sets. To get the next page of results, set this parameter to the value of
* "nextPageToken" from the previous response.
*/
pageToken?: string;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/**
* Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* Overrides userIp if both are provided.
*/
quotaUser?: string;
/** The ID of the user to get audiences for. The special value "me" can be used to indicate the authenticated user. */
userId: string;
/** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */
userIp?: string;
}): Request<AudiencesFeed>;
}
interface CirclesResource {
/** Add a person to a circle. Google+ limits certain circle operations, including the number of circle adds. Learn More. */
addPeople(request: {
/** Data format for the response. */
alt?: string;
/** The ID of the circle to add the person to. */
circleId: string;
/** Email of the people to add to the circle. Optional, can be repeated. */
email?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/**
* Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* Overrides userIp if both are provided.
*/
quotaUser?: string;
/** IDs of the people to add to the circle. Optional, can be repeated. */
userId?: string;
/** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */
userIp?: string;
}): Request<Circle>;
/** Get a circle. */
get(request: {
/** Data format for the response. */
alt?: string;
/** The ID of the circle to get. */
circleId: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/**
* Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* Overrides userIp if both are provided.
*/
quotaUser?: string;
/** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */
userIp?: string;
}): Request<Circle>;
/** Create a new circle for the authenticated user. */
insert(request: {
/** Data format for the response. */
alt?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/**
* Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* Overrides userIp if both are provided.
*/
quotaUser?: string;
/** The ID of the user to create the circle on behalf of. The value "me" can be used to indicate the authenticated user. */
userId: string;
/** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */
userIp?: string;
}): Request<Circle>;
/** List all of the circles for a user. */
list(request: {
/** Data format for the response. */
alt?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/**
* The maximum number of circles to include in the response, which is used for paging. For any response, the actual number returned might be less than the
* specified maxResults.
*/
maxResults?: number;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/**
* The continuation token, which is used to page through large result sets. To get the next page of results, set this parameter to the value of
* "nextPageToken" from the previous response.
*/
pageToken?: string;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/**
* Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* Overrides userIp if both are provided.
*/
quotaUser?: string;
/** The ID of the user to get circles for. The special value "me" can be used to indicate the authenticated user. */
userId: string;
/** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */
userIp?: string;
}): Request<CircleFeed>;
/** Update a circle's description. This method supports patch semantics. */
patch(request: {
/** Data format for the response. */
alt?: string;
/** The ID of the circle to update. */
circleId: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/**
* Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* Overrides userIp if both are provided.
*/
quotaUser?: string;
/** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */
userIp?: string;
}): Request<Circle>;
/** Delete a circle. */
remove(request: {
/** Data format for the response. */
alt?: string;
/** The ID of the circle to delete. */
circleId: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/**
* Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* Overrides userIp if both are provided.
*/
quotaUser?: string;
/** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */
userIp?: string;
}): Request<void>;
/** Remove a person from a circle. */
removePeople(request: {
/** Data format for the response. */
alt?: string;
/** The ID of the circle to remove the person from. */
circleId: string;
/** Email of the people to add to the circle. Optional, can be repeated. */
email?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/**
* Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* Overrides userIp if both are provided.
*/
quotaUser?: string;
/** IDs of the people to remove from the circle. Optional, can be repeated. */
userId?: string;
/** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */
userIp?: string;
}): Request<void>;
/** Update a circle's description. */
update(request: {
/** Data format for the response. */
alt?: string;
/** The ID of the circle to update. */
circleId: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/**
* Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* Overrides userIp if both are provided.
*/
quotaUser?: string;
/** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */
userIp?: string;
}): Request<Circle>;
}
interface CommentsResource {
/** Get a comment. */
get(request: {
/** Data format for the response. */
alt?: string;
/** The ID of the comment to get. */
commentId: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/**
* Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* Overrides userIp if both are provided.
*/
quotaUser?: string;
/** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */
userIp?: string;
}): Request<Comment>;
/** Create a new comment in reply to an activity. */
insert(request: {
/** The ID of the activity to reply to. */
activityId: string;
/** Data format for the response. */
alt?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/**
* Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* Overrides userIp if both are provided.
*/
quotaUser?: string;
/** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */
userIp?: string;
}): Request<Comment>;
/** List all of the comments for an activity. */
list(request: {
/** The ID of the activity to get comments for. */
activityId: string;
/** Data format for the response. */
alt?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/**
* The maximum number of comments to include in the response, which is used for paging. For any response, the actual number returned might be less than
* the specified maxResults.
*/
maxResults?: number;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/**
* The continuation token, which is used to page through large result sets. To get the next page of results, set this parameter to the value of
* "nextPageToken" from the previous response.
*/
pageToken?: string;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/**
* Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* Overrides userIp if both are provided.
*/
quotaUser?: string;
/** The order in which to sort the list of comments. */
sortOrder?: string;
/** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */
userIp?: string;
}): Request<CommentFeed>;
}
interface MediaResource {
/**
* Add a new media item to an album. The current upload size limitations are 36MB for a photo and 1GB for a video. Uploads do not count against quota if
* photos are less than 2048 pixels on their longest side or videos are less than 15 minutes in length.
*/
insert(request: {
/** Data format for the response. */
alt?: string;
collection: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/**
* Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* Overrides userIp if both are provided.
*/
quotaUser?: string;
/** The ID of the user to create the activity on behalf of. */
userId: string;
/** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */
userIp?: string;
}): Request<Media>;
}
interface PeopleResource {
/** Get a person's profile. */
get(request: {
/** Data format for the response. */
alt?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/**
* Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* Overrides userIp if both are provided.
*/
quotaUser?: string;
/** The ID of the person to get the profile for. The special value "me" can be used to indicate the authenticated user. */
userId: string;
/** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */
userIp?: string;
}): Request<Person>;
/** List all of the people in the specified collection. */
list(request: {
/** Data format for the response. */
alt?: string;
/** The collection of people to list. */
collection: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/**
* The maximum number of people to include in the response, which is used for paging. For any response, the actual number returned might be less than the
* specified maxResults.
*/
maxResults?: number;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** The order to return people in. */
orderBy?: string;
/**
* The continuation token, which is used to page through large result sets. To get the next page of results, set this parameter to the value of
* "nextPageToken" from the previous response.
*/
pageToken?: string;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/**
* Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* Overrides userIp if both are provided.
*/
quotaUser?: string;
/** Get the collection of people for the person identified. Use "me" to indicate the authenticated user. */
userId: string;
/** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */
userIp?: string;
}): Request<PeopleFeed>;
/** List all of the people in the specified collection for a particular activity. */
listByActivity(request: {
/** The ID of the activity to get the list of people for. */
activityId: string;
/** Data format for the response. */
alt?: string;
/** The collection of people to list. */
collection: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/**
* The maximum number of people to include in the response, which is used for paging. For any response, the actual number returned might be less than the
* specified maxResults.
*/
maxResults?: number;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/**
* The continuation token, which is used to page through large result sets. To get the next page of results, set this parameter to the value of
* "nextPageToken" from the previous response.
*/
pageToken?: string;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/**
* Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* Overrides userIp if both are provided.
*/
quotaUser?: string;
/** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */
userIp?: string;
}): Request<PeopleFeed>;
/** List all of the people who are members of a circle. */
listByCircle(request: {
/** Data format for the response. */
alt?: string;
/** The ID of the circle to get the members of. */
circleId: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/**
* The maximum number of people to include in the response, which is used for paging. For any response, the actual number returned might be less than the
* specified maxResults.
*/
maxResults?: number;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/**
* The continuation token, which is used to page through large result sets. To get the next page of results, set this parameter to the value of
* "nextPageToken" from the previous response.
*/
pageToken?: string;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/**
* Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* Overrides userIp if both are provided.
*/
quotaUser?: string;
/** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */
userIp?: string;
}): Request<PeopleFeed>;
}
}
}
| types/gapi.client.plusdomains/index.d.ts | 0 | https://github.com/DefinitelyTyped/DefinitelyTyped/commit/ca7d069c55f1c9586f588554386bcebdc0071bff | [
0.002216031076386571,
0.00025757410912774503,
0.000165572389960289,
0.00017404691607225686,
0.00028648177976720035
] |
{
"id": 2,
"code_window": [
" ttl: number;\n",
"}\n",
"\n",
"interface StoreConfig extends CachingConfig {\n",
" store: string;\n",
" max?: number;\n",
" isCacheableValue?: (value: any) => boolean;\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"export interface StoreConfig extends CachingConfig {\n"
],
"file_path": "types/cache-manager/index.d.ts",
"type": "replace",
"edit_start_line_idx": 9
} | // Type definitions for cache-manager v1.2.0
// Project: https://github.com/BryanDonovan/node-cache-manager
// Definitions by: Simon Gausmann <https://github.com/GausSim>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
interface CachingConfig {
ttl: number;
}
interface StoreConfig extends CachingConfig {
store: string;
max?: number;
isCacheableValue?: (value: any) => boolean;
}
interface Cache {
set<T>(key: string, value: T, options: CachingConfig, callback?: (error: any) => void): void;
set<T>(key: string, value: T, ttl: number, callback?: (error: any) => void): void;
set<T>(key: string, value: T, options: CachingConfig): Promise<any>;
set<T>(key: string, value: T, ttl: number): Promise<any>;
wrap<T>(key: string, wrapper: (callback: (error: any, result: T) => void) => void, options: CachingConfig, callback: (error: any, result: T) => void): void;
wrap<T>(key: string, wrapper: (callback: (error: any, result: T) => void) => void, callback: (error: any, result: T) => void): void;
wrap<T>(key: string, wrapper: (callback: (error: any, result: T) => void) => any, options: CachingConfig): Promise<any>;
wrap<T>(key: string, wrapper: (callback: (error: any, result: T) => void) => void): Promise<any>;
get<T>(key: string, callback: (error: any, result: T) => void): void;
get<T>(key: string): Promise<any>;
del(key: string, callback: (error: any) => void): void;
del(key: string): Promise<any>;
}
declare namespace cacheManager {
function caching(IConfig: StoreConfig): Cache;
function multiCaching(Caches: Cache[]): Cache;
}
export = cacheManager;
| types/cache-manager/index.d.ts | 1 | https://github.com/DefinitelyTyped/DefinitelyTyped/commit/ca7d069c55f1c9586f588554386bcebdc0071bff | [
0.999247670173645,
0.44630369544029236,
0.0004687633190769702,
0.23595373332500458,
0.45475339889526367
] |
{
"id": 2,
"code_window": [
" ttl: number;\n",
"}\n",
"\n",
"interface StoreConfig extends CachingConfig {\n",
" store: string;\n",
" max?: number;\n",
" isCacheableValue?: (value: any) => boolean;\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"export interface StoreConfig extends CachingConfig {\n"
],
"file_path": "types/cache-manager/index.d.ts",
"type": "replace",
"edit_start_line_idx": 9
} | {
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6",
"dom"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"jsx": "react",
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"react-recaptcha-tests.tsx"
]
} | types/react-recaptcha/tsconfig.json | 0 | https://github.com/DefinitelyTyped/DefinitelyTyped/commit/ca7d069c55f1c9586f588554386bcebdc0071bff | [
0.00017071497859433293,
0.00016900012269616127,
0.00016701547428965569,
0.00016926994430832565,
0.0000015223188256641151
] |
{
"id": 2,
"code_window": [
" ttl: number;\n",
"}\n",
"\n",
"interface StoreConfig extends CachingConfig {\n",
" store: string;\n",
" max?: number;\n",
" isCacheableValue?: (value: any) => boolean;\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"export interface StoreConfig extends CachingConfig {\n"
],
"file_path": "types/cache-manager/index.d.ts",
"type": "replace",
"edit_start_line_idx": 9
} | import { toPlainObject } from "./index";
export = toPlainObject;
| types/lodash/toPlainObject.d.ts | 0 | https://github.com/DefinitelyTyped/DefinitelyTyped/commit/ca7d069c55f1c9586f588554386bcebdc0071bff | [
0.00017414636386092752,
0.00017414636386092752,
0.00017414636386092752,
0.00017414636386092752,
0
] |
{
"id": 2,
"code_window": [
" ttl: number;\n",
"}\n",
"\n",
"interface StoreConfig extends CachingConfig {\n",
" store: string;\n",
" max?: number;\n",
" isCacheableValue?: (value: any) => boolean;\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"export interface StoreConfig extends CachingConfig {\n"
],
"file_path": "types/cache-manager/index.d.ts",
"type": "replace",
"edit_start_line_idx": 9
} | { "extends": "dtslint/dt.json" }
| types/http-context/tslint.json | 0 | https://github.com/DefinitelyTyped/DefinitelyTyped/commit/ca7d069c55f1c9586f588554386bcebdc0071bff | [
0.00017157186812255532,
0.00017157186812255532,
0.00017157186812255532,
0.00017157186812255532,
0
] |
{
"id": 3,
"code_window": [
" isCacheableValue?: (value: any) => boolean;\n",
"}\n",
"\n",
"interface Cache {\n",
" set<T>(key: string, value: T, options: CachingConfig, callback?: (error: any) => void): void;\n",
" set<T>(key: string, value: T, ttl: number, callback?: (error: any) => void): void;\n",
" set<T>(key: string, value: T, options: CachingConfig): Promise<any>;\n",
" set<T>(key: string, value: T, ttl: number): Promise<any>;\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"export interface Cache {\n"
],
"file_path": "types/cache-manager/index.d.ts",
"type": "replace",
"edit_start_line_idx": 15
} | import * as cacheManager from 'cache-manager'
const memoryCache = cacheManager.caching({ store: 'memory', max: 100, ttl: 10/*seconds*/ });
const ttl = 5;
memoryCache.set('foo', 'bar', { ttl: ttl }, (err) => {
if (err) {
throw err;
}
memoryCache.get('foo', (err, result) => {
// console.log(result);
memoryCache.del('foo', (err) => {
});
});
});
function getUser(id: number, cb: Function) {
cb(null, { id: id, name: 'Bob' });
}
const userId = 123;
const key = 'user_' + userId;
// Note: ttl is optional in wrap()
memoryCache.wrap<{ id: number, name: string }>(key, (cb) => {
getUser(userId, cb);
}, { ttl: ttl }, (err, user) => {
//console.log(user);
// Second time fetches user from memoryCache
memoryCache.wrap<{ id: number, name: string }>(key, (cb) => {
getUser(userId, cb);
}, (err, user) => {
//console.log(user);
});
});
| types/cache-manager/cache-manager-tests.ts | 1 | https://github.com/DefinitelyTyped/DefinitelyTyped/commit/ca7d069c55f1c9586f588554386bcebdc0071bff | [
0.5623855590820312,
0.11289529502391815,
0.00016989345022011548,
0.00023027145653031766,
0.2247457057237625
] |
{
"id": 3,
"code_window": [
" isCacheableValue?: (value: any) => boolean;\n",
"}\n",
"\n",
"interface Cache {\n",
" set<T>(key: string, value: T, options: CachingConfig, callback?: (error: any) => void): void;\n",
" set<T>(key: string, value: T, ttl: number, callback?: (error: any) => void): void;\n",
" set<T>(key: string, value: T, options: CachingConfig): Promise<any>;\n",
" set<T>(key: string, value: T, ttl: number): Promise<any>;\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"export interface Cache {\n"
],
"file_path": "types/cache-manager/index.d.ts",
"type": "replace",
"edit_start_line_idx": 15
} | import { of } from '../index';
export default of;
| types/ramda/src/of.d.ts | 0 | https://github.com/DefinitelyTyped/DefinitelyTyped/commit/ca7d069c55f1c9586f588554386bcebdc0071bff | [
0.00017594375822227448,
0.00017594375822227448,
0.00017594375822227448,
0.00017594375822227448,
0
] |
{
"id": 3,
"code_window": [
" isCacheableValue?: (value: any) => boolean;\n",
"}\n",
"\n",
"interface Cache {\n",
" set<T>(key: string, value: T, options: CachingConfig, callback?: (error: any) => void): void;\n",
" set<T>(key: string, value: T, ttl: number, callback?: (error: any) => void): void;\n",
" set<T>(key: string, value: T, options: CachingConfig): Promise<any>;\n",
" set<T>(key: string, value: T, ttl: number): Promise<any>;\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"export interface Cache {\n"
],
"file_path": "types/cache-manager/index.d.ts",
"type": "replace",
"edit_start_line_idx": 15
} | {
"compilerOptions": {
"module": "commonjs",
"lib": ["es6"],
"jsx": "react-native",
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": ["../"],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": ["index.d.ts", "react-native-platform-touchable-tests.tsx"]
}
| types/react-native-platform-touchable/tsconfig.json | 0 | https://github.com/DefinitelyTyped/DefinitelyTyped/commit/ca7d069c55f1c9586f588554386bcebdc0071bff | [
0.00017227216449100524,
0.00017195384134538472,
0.00017163550364784896,
0.00017195384134538472,
3.1833042157813907e-7
] |
{
"id": 3,
"code_window": [
" isCacheableValue?: (value: any) => boolean;\n",
"}\n",
"\n",
"interface Cache {\n",
" set<T>(key: string, value: T, options: CachingConfig, callback?: (error: any) => void): void;\n",
" set<T>(key: string, value: T, ttl: number, callback?: (error: any) => void): void;\n",
" set<T>(key: string, value: T, options: CachingConfig): Promise<any>;\n",
" set<T>(key: string, value: T, ttl: number): Promise<any>;\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"export interface Cache {\n"
],
"file_path": "types/cache-manager/index.d.ts",
"type": "replace",
"edit_start_line_idx": 15
} | {
"extends": "dtslint/dt.json",
"rules": {
"callable-types": false,
"interface-name": false,
"no-declare-current-package": false,
"no-unnecessary-generics": false,
"only-arrow-functions": false
}
}
| types/angular-mocks/tslint.json | 0 | https://github.com/DefinitelyTyped/DefinitelyTyped/commit/ca7d069c55f1c9586f588554386bcebdc0071bff | [
0.00017299891624134034,
0.0001718810381134972,
0.00017076315998565406,
0.0001718810381134972,
0.0000011178781278431416
] |
{
"id": 4,
"code_window": [
" del(key: string): Promise<any>;\n",
"}\n",
"\n",
"\n",
"\n",
"declare namespace cacheManager {\n",
" function caching(IConfig: StoreConfig): Cache;\n",
" function multiCaching(Caches: Cache[]): Cache;\n",
"}\n",
"\n",
"export = cacheManager;\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace"
],
"after_edit": [
"export function caching(IConfig: StoreConfig): Cache;\n",
"export function multiCaching(Caches: Cache[]): Cache;"
],
"file_path": "types/cache-manager/index.d.ts",
"type": "replace",
"edit_start_line_idx": 33
} | // Type definitions for cache-manager v1.2.0
// Project: https://github.com/BryanDonovan/node-cache-manager
// Definitions by: Simon Gausmann <https://github.com/GausSim>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
interface CachingConfig {
ttl: number;
}
interface StoreConfig extends CachingConfig {
store: string;
max?: number;
isCacheableValue?: (value: any) => boolean;
}
interface Cache {
set<T>(key: string, value: T, options: CachingConfig, callback?: (error: any) => void): void;
set<T>(key: string, value: T, ttl: number, callback?: (error: any) => void): void;
set<T>(key: string, value: T, options: CachingConfig): Promise<any>;
set<T>(key: string, value: T, ttl: number): Promise<any>;
wrap<T>(key: string, wrapper: (callback: (error: any, result: T) => void) => void, options: CachingConfig, callback: (error: any, result: T) => void): void;
wrap<T>(key: string, wrapper: (callback: (error: any, result: T) => void) => void, callback: (error: any, result: T) => void): void;
wrap<T>(key: string, wrapper: (callback: (error: any, result: T) => void) => any, options: CachingConfig): Promise<any>;
wrap<T>(key: string, wrapper: (callback: (error: any, result: T) => void) => void): Promise<any>;
get<T>(key: string, callback: (error: any, result: T) => void): void;
get<T>(key: string): Promise<any>;
del(key: string, callback: (error: any) => void): void;
del(key: string): Promise<any>;
}
declare namespace cacheManager {
function caching(IConfig: StoreConfig): Cache;
function multiCaching(Caches: Cache[]): Cache;
}
export = cacheManager;
| types/cache-manager/index.d.ts | 1 | https://github.com/DefinitelyTyped/DefinitelyTyped/commit/ca7d069c55f1c9586f588554386bcebdc0071bff | [
0.9969674944877625,
0.40208664536476135,
0.0015661147190257907,
0.013276503421366215,
0.4857257902622223
] |
{
"id": 4,
"code_window": [
" del(key: string): Promise<any>;\n",
"}\n",
"\n",
"\n",
"\n",
"declare namespace cacheManager {\n",
" function caching(IConfig: StoreConfig): Cache;\n",
" function multiCaching(Caches: Cache[]): Cache;\n",
"}\n",
"\n",
"export = cacheManager;\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace"
],
"after_edit": [
"export function caching(IConfig: StoreConfig): Cache;\n",
"export function multiCaching(Caches: Cache[]): Cache;"
],
"file_path": "types/cache-manager/index.d.ts",
"type": "replace",
"edit_start_line_idx": 33
} | import Consul = require("consul");
let ConsulStatic: Consul.ConsulStatic;
let AclStatic: Consul.AclStatic = ConsulStatic.Acl;
let AgentStatic: Consul.AgentStatic = ConsulStatic.Agent;
let AgentCheckStatic: Consul.Agent.CheckStatic = ConsulStatic.Agent.Check;
let AgentServiceStatic: Consul.Agent.ServiceStatic = ConsulStatic.Agent.Service;
let CatalogStatic: Consul.CatalogStatic = ConsulStatic.Catalog;
let CatalogNodeStatic: Consul.Catalog.NodeStatic = ConsulStatic.Catalog.Node;
let CatalogServiceStatic: Consul.Catalog.ServiceStatic = ConsulStatic.Catalog.Service;
let EventStatic: Consul.EventStatic = ConsulStatic.Event;
let HealthStatic: Consul.HealthStatic = ConsulStatic.Health;
let KvStatic: Consul.KvStatic = ConsulStatic.Kv;
let LockStatic: Consul.LockStatic = ConsulStatic.Lock;
let SessionStatic: Consul.SessionStatic = ConsulStatic.Session;
let StatusStatic: Consul.StatusStatic = ConsulStatic.Status;
let WatchStatic: Consul.WatchStatic = ConsulStatic.Watch;
let consul: Consul.Consul;
consul = Consul();
consul = new Consul();
// Consul.Acl
{
let acl: Consul.Acl = consul.acl;
acl = new AclStatic(consul);
consul = acl.consul;
{
let opts: Consul.Acl.CreateOptions;
let callback: Consul.Callback<any>;
let result: Consul.Thenable<any>;
acl.create<any>(opts, callback);
acl.create<any>(callback);
result = acl.create<any>(opts);
result = acl.create<any>();
}
{
let opts: Consul.Acl.UpdateOptions;
let callback: Consul.Callback<any>;
let result: Consul.Thenable<any>;
acl.update<any>(opts, callback);
result = acl.update<any>(opts);
}
{
let id: string;
let opts: Consul.Acl.DestroyOptions;
let callback: Consul.Callback<any>;
let result: Consul.Thenable<any>;
acl.destroy<any>(id, callback);
acl.destroy<any>(opts, callback);
result = acl.destroy<any>(id);
result = acl.destroy<any>(opts);
}
{
let id: string;
let opts: Consul.Acl.InfoOptions;
let callback: Consul.Callback<any>;
let result: Consul.Thenable<any>;
acl.info<any>(id, callback);
acl.info<any>(opts, callback);
result = acl.info<any>(id);
result = acl.info<any>(opts);
acl.get<any>(id, callback);
acl.get<any>(opts, callback);
result = acl.get<any>(id);
result = acl.get<any>(opts);
}
{
let id: string;
let opts: Consul.Acl.CloneOptions;
let callback: Consul.Callback<any>;
let result: Consul.Thenable<any>;
acl.clone<any>(id, callback);
acl.clone<any>(opts, callback);
result = acl.clone<any>(id);
result = acl.clone<any>(opts);
}
{
let opts: Consul.Acl.ListOptions;
let callback: Consul.Callback<any>;
let result: Consul.Thenable<any>;
acl.list<any>(opts, callback);
acl.list<any>(callback);
result = acl.list<any>(opts);
result = acl.list<any>();
}
}
// Consul.Agent
{
let agent: Consul.Agent = consul.agent;
agent = new AgentStatic(consul);
consul = agent.consul;
{
let opts: Consul.Agent.ChecksOptions;
let callback: Consul.Callback<any>;
let result: Consul.Thenable<any>;
agent.checks<any>(opts, callback);
agent.checks<any>(callback);
result = agent.checks<any>(opts);
result = agent.checks<any>();
}
{
let opts: Consul.Agent.ServicesOptions;
let callback: Consul.Callback<any>;
let result: Consul.Thenable<any>;
agent.services<any>(opts, callback);
agent.services<any>(callback);
result = agent.services<any>(opts);
result = agent.services<any>();
}
{
let opts: Consul.Agent.MembersOptions;
let callback: Consul.Callback<any>;
let result: Consul.Thenable<any>;
agent.members<any>(opts, callback);
agent.members<any>(callback);
result = agent.members<any>(opts);
result = agent.members<any>();
}
{
let opts: Consul.Agent.SelfOptions;
let callback: Consul.Callback<any>;
let result: Consul.Thenable<any>;
agent.self<any>(opts, callback);
agent.self<any>(callback);
result = agent.self<any>(opts);
result = agent.self<any>();
}
{
let enable: boolean;
let opts: Consul.Agent.MaintenanceOptions;
let callback: Consul.Callback<any>;
let result: Consul.Thenable<any>;
agent.maintenance<any>(enable, callback);
agent.maintenance<any>(opts, callback);
result = agent.maintenance<any>(enable);
result = agent.maintenance<any>(opts);
}
{
let address: string;
let opts: Consul.Agent.JoinOptions;
let callback: Consul.Callback<any>;
let result: Consul.Thenable<any>;
agent.join<any>(address, callback);
agent.join<any>(opts, callback);
result = agent.join<any>(address);
result = agent.join<any>(opts);
}
{
let node: string;
let opts: Consul.Agent.ForceLeaveOptions;
let callback: Consul.Callback<any>;
let result: Consul.Thenable<any>;
agent.forceLeave<any>(node, callback);
agent.forceLeave<any>(opts, callback);
result = agent.forceLeave<any>(node);
result = agent.forceLeave<any>(opts);
}
// Consul.Agent.Check
{
let check: Consul.Agent.Check = consul.agent.check;
check = new AgentCheckStatic(consul);
consul = check.consul;
{
let id: string;
let opts: Consul.Agent.Check.ListOptions;
let callback: Consul.Callback<any>;
let result: Consul.Thenable<any>;
check.list<any>(opts, callback);
check.list<any>(callback);
result = check.list<any>(opts);
result = check.list<any>();
}
{
let opts: Consul.Agent.Check.RegisterOptions;
let callback: Consul.Callback<any>;
let result: Consul.Thenable<any>;
check.register<any>(opts, callback);
result = check.register<any>(opts);
}
{
let id: string;
let opts: Consul.Agent.Check.DeregisterOptions;
let callback: Consul.Callback<any>;
let result: Consul.Thenable<any>;
check.deregister<any>(id, callback);
check.deregister<any>(opts, callback);
result = check.deregister<any>(id);
result = check.deregister<any>(opts);
}
{
let id: string;
let opts: Consul.Agent.Check.PassOptions;
let callback: Consul.Callback<any>;
let result: Consul.Thenable<any>;
check.pass<any>(id, callback);
check.pass<any>(opts, callback);
result = check.pass<any>(id);
result = check.pass<any>(opts);
}
{
let id: string;
let opts: Consul.Agent.Check.WarnOptions;
let callback: Consul.Callback<any>;
let result: Consul.Thenable<any>;
check.warn<any>(id, callback);
check.warn<any>(opts, callback);
result = check.warn<any>(id);
result = check.warn<any>(opts);
}
{
let id: string;
let opts: Consul.Agent.Check.WarnOptions;
let callback: Consul.Callback<any>;
let result: Consul.Thenable<any>;
check.fail<any>(id, callback);
check.fail<any>(opts, callback);
result = check.fail<any>(id);
result = check.fail<any>(opts);
}
}
// Consul.Agent.Service
{
let service: Consul.Agent.Service = consul.agent.service;
service = new AgentServiceStatic(consul);
consul = service.consul;
{
let opts: Consul.Agent.Service.ListOptions;
let callback: Consul.Callback<any>;
let result: Consul.Thenable<any>;
service.list<any>(opts, callback);
service.list<any>(callback);
result = service.list<any>(opts);
result = service.list<any>();
}
{
let id: string;
let opts: Consul.Agent.Service.RegisterOptions;
let callback: Consul.Callback<any>;
let result: Consul.Thenable<any>;
service.register<any>(id, callback);
service.register<any>(opts, callback);
result = service.register<any>(id);
result = service.register<any>(opts);
}
{
let id: string;
let opts: Consul.Agent.Service.DeregisterOptions;
let callback: Consul.Callback<any>;
let result: Consul.Thenable<any>;
service.deregister<any>(id, callback);
service.deregister<any>(opts, callback);
result = service.deregister<any>(id);
result = service.deregister<any>(opts);
}
{
let opts: Consul.Agent.Service.MaintenanceOptions;
let callback: Consul.Callback<any>;
let result: Consul.Thenable<any>;
service.maintenance<any>(opts, callback);
result = service.maintenance<any>(opts);
}
}
}
// Consul.Catalog
{
let catalog: Consul.Catalog = consul.catalog;
catalog = new CatalogStatic(consul);
consul = catalog.consul;
{
let opts: Consul.Catalog.DatacentersOptions;
let callback: Consul.Callback<any>;
let result: Consul.Thenable<any>;
catalog.datacenters<any>(opts, callback);
catalog.datacenters<any>(callback);
result = catalog.datacenters<any>(opts);
result = catalog.datacenters<any>();
}
{
let dc: string;
let opts: Consul.Catalog.NodesOptions;
let callback: Consul.Callback<any>;
let result: Consul.Thenable<any>;
catalog.nodes<any>(dc, callback);
catalog.nodes<any>(opts, callback);
catalog.nodes<any>(callback);
result = catalog.nodes<any>(dc);
result = catalog.nodes<any>(opts);
result = catalog.nodes<any>();
}
{
let dc: string;
let opts: Consul.Catalog.ServicesOptions;
let callback: Consul.Callback<any>;
let result: Consul.Thenable<any>;
catalog.services<any>(dc, callback);
catalog.services<any>(opts, callback);
catalog.services<any>(callback);
result = catalog.services<any>(dc);
result = catalog.services<any>(opts);
result = catalog.services<any>();
}
// Consul.Catalog.Node
{
let node: Consul.Catalog.Node = consul.catalog.node;
node = new CatalogNodeStatic(consul);
consul = node.consul;
{
let dc: string;
let opts: Consul.Catalog.Node.ListOptions;
let callback: Consul.Callback<any>;
let result: Consul.Thenable<any>;
node.list<any>(dc, callback);
node.list<any>(opts, callback);
node.list<any>(callback);
result = node.list<any>(dc);
result = node.list<any>(opts);
result = node.list<any>();
}
{
let nodeOption: string;
let opts: Consul.Catalog.Node.ServicesOptions;
let callback: Consul.Callback<any>;
let result: Consul.Thenable<any>;
node.services<any>(nodeOption, callback);
node.services<any>(opts, callback);
result = node.services<any>(nodeOption);
result = node.services<any>(opts);
}
}
// Consul.Catalog.Service
{
let service: Consul.Catalog.Service = consul.catalog.service;
service = new CatalogServiceStatic(consul);
consul = service.consul;
{
let dc: string;
let opts: Consul.Catalog.Service.ListOptions;
let callback: Consul.Callback<any>;
let result: Consul.Thenable<any>;
service.list<any>(dc, callback);
service.list<any>(opts, callback);
service.list<any>(callback);
result = service.list<any>(dc);
result = service.list<any>(opts);
result = service.list<any>();
}
{
let serviceOption: string;
let opts: Consul.Catalog.Service.NodesOptions;
let callback: Consul.Callback<any>;
let result: Consul.Thenable<any>;
service.nodes<any>(serviceOption, callback);
service.nodes<any>(opts, callback);
result = service.nodes<any>(serviceOption);
result = service.nodes<any>(opts);
}
}
}
// Consul.Event
{
let event: Consul.Event = consul.event;
event = new EventStatic(consul);
consul = event.consul;
{
let name: string;
let payload: string|Buffer;
let opts: Consul.Event.FireOptions;
let callback: Consul.Callback<any>;
let result: Consul.Thenable<any>;
event.fire<any>(name, payload, callback);
event.fire<any>(name, callback);
event.fire<any>(opts, callback);
result = event.fire<any>(name, payload);
result = event.fire<any>(name);
result = event.fire<any>(opts);
}
{
let name: string;
let opts: Consul.Event.ListOptions;
let callback: Consul.Callback<any>;
let result: Consul.Thenable<any>;
event.list<any>(name, callback);
event.list<any>(opts, callback);
event.list<any>(callback);
result = event.list<any>(name);
result = event.list<any>(opts);
result = event.list<any>();
}
}
// Consul.Health
{
let health: Consul.Health = consul.health;
let name: string;
health = new HealthStatic(consul);
consul = health.consul;
{
let node: string;
let opts: Consul.Health.NodeOptions;
let callback: Consul.Callback<any>;
let result: Consul.Thenable<any>;
health.node<any>(name, callback);
health.node<any>(opts, callback);
result = health.node<any>(name);
result = health.node<any>(opts);
}
{
let service: string;
let opts: Consul.Health.ChecksOptions;
let callback: Consul.Callback<any>;
let result: Consul.Thenable<any>;
health.checks<any>(service, callback);
health.checks<any>(opts, callback);
result = health.checks<any>(service);
result = health.checks<any>(opts);
}
{
let service: string;
let opts: Consul.Health.ServiceOptions;
let callback: Consul.Callback<any>;
let result: Consul.Thenable<any>;
health.service<any>(service, callback);
health.service<any>(opts, callback);
result = health.service<any>(service);
result = health.service<any>(opts);
}
{
let state: string;
let opts: Consul.Health.StateOptions;
let callback: Consul.Callback<any>;
let result: Consul.Thenable<any>;
health.state<any>(state, callback);
health.state<any>(opts, callback);
result = health.state<any>(state);
result = health.state<any>(opts);
}
}
// Consul.Kv
{
let kv: Consul.Kv = consul.kv;
kv = new KvStatic(consul);
consul = kv.consul;
{
let key: string;
let opts: Consul.Kv.GetOptions;
let callback: Consul.Callback<any>;
let result: Consul.Thenable<any>;
kv.get<any>(key, callback);
kv.get<any>(opts, callback);
result = kv.get<any>(key);
result = kv.get<any>(opts);
}
{
let key: string;
let opts: Consul.Kv.KeysOptions;
let callback: Consul.Callback<any>;
let result: Consul.Thenable<any>;
kv.keys<any>(key, callback);
kv.keys<any>(opts, callback);
kv.keys<any>(callback);
result = kv.keys<any>(key);
result = kv.keys<any>(opts);
result = kv.keys<any>();
}
{
let key: string;
let value: string|Buffer;
let opts: Consul.Kv.SetOptions;
let callback: Consul.Callback<any>;
let result: Consul.Thenable<any>;
kv.set<any>(key, value, opts, callback);
kv.set<any>(key, value, callback);
kv.set<any>(opts, callback);
result = kv.set<any>(key, value, opts);
result = kv.set<any>(key, value);
result = kv.set<any>(opts);
}
{
let key: string;
let opts: Consul.Kv.DelOptions;
let callback: Consul.Callback<any>;
let result: Consul.Thenable<any>;
kv.del<any>(key, callback);
kv.del<any>(opts, callback);
result = kv.del<any>(key);
result = kv.del<any>(opts);
kv.delete<any>(key, callback);
kv.delete<any>(opts, callback);
result = kv.delete<any>(key);
result = kv.delete<any>(opts);
}
}
// Consul.Lock
{
let lock: Consul.Lock;
let opts: Consul.Lock.Options;
lock = new LockStatic(consul, opts);
lock = consul.lock(opts);
consul = lock.consul;
lock.acquire();
lock.release();
}
// Consul.Session
{
let session: Consul.Session = consul.session;
session = new SessionStatic(consul);
consul = session.consul;
{
let opts: Consul.Session.CreateOptions;
let callback: Consul.Callback<any>;
let result: Consul.Thenable<any>;
session.create<any>(opts, callback);
session.create<any>(callback);
result = session.create<any>(opts);
result = session.create<any>();
}
{
let id: string;
let opts: Consul.Session.DestroyOptions;
let callback: Consul.Callback<any>;
let result: Consul.Thenable<any>;
session.destroy<any>(id, callback);
session.destroy<any>(opts, callback);
result = session.destroy<any>(id);
result = session.destroy<any>(opts);
}
{
let id: string;
let opts: Consul.Session.InfoOptions;
let callback: Consul.Callback<any>;
let result: Consul.Thenable<any>;
session.info<any>(id, callback);
session.info<any>(opts, callback);
result = session.info<any>(id);
result = session.info<any>(opts);
session.get<any>(id, callback);
session.get<any>(opts, callback);
result = session.get<any>(id);
result = session.get<any>(opts);
}
{
let node: string;
let opts: Consul.Session.NodeOptions;
let callback: Consul.Callback<any>;
let result: Consul.Thenable<any>;
session.node<any>(node, callback);
session.node<any>(opts, callback);
result = session.node<any>(node);
result = session.node<any>(opts);
}
{
let opts: Consul.Session.ListOptions;
let callback: Consul.Callback<any>;
let result: Consul.Thenable<any>;
session.list<any>(opts, callback);
session.list<any>(callback);
result = session.list<any>(opts);
result = session.list<any>();
}
{
let id: string;
let opts: Consul.Session.RenewOptions;
let callback: Consul.Callback<any>;
let result: Consul.Thenable<any>;
session.renew<any>(id, callback);
session.renew<any>(opts, callback);
result = session.renew<any>(id);
result = session.renew<any>(opts);
}
}
// Consul.Status
{
let status: Consul.Status = consul.status;
status = new StatusStatic(consul);
consul = status.consul;
{
let opts: Consul.Status.LeaderOptions;
let callback: Consul.Callback<any>;
let result: Consul.Thenable<any>;
status.leader<any>(opts, callback);
status.leader<any>(callback);
result = status.leader<any>(opts);
result = status.leader<any>();
}
{
let opts: Consul.Status.LeaderOptions;
let callback: Consul.Callback<any>;
let result: Consul.Thenable<any>;
status.peers<any>(opts, callback);
status.peers<any>(callback);
result = status.peers<any>(opts);
result = status.peers<any>();
}
}
// Consul.Watch
{
let watch: Consul.Watch;
let opts: Consul.Watch.Options;
watch = new WatchStatic(consul, opts);
watch = consul.watch(opts);
consul = watch.consul;
watch.isRunning();
watch.updateTime();
watch.end();
}
| types/consul/consul-tests.ts | 0 | https://github.com/DefinitelyTyped/DefinitelyTyped/commit/ca7d069c55f1c9586f588554386bcebdc0071bff | [
0.004143222235143185,
0.0005188549985177815,
0.0001646313030505553,
0.0001705331087578088,
0.0007846742519177496
] |
{
"id": 4,
"code_window": [
" del(key: string): Promise<any>;\n",
"}\n",
"\n",
"\n",
"\n",
"declare namespace cacheManager {\n",
" function caching(IConfig: StoreConfig): Cache;\n",
" function multiCaching(Caches: Cache[]): Cache;\n",
"}\n",
"\n",
"export = cacheManager;\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace"
],
"after_edit": [
"export function caching(IConfig: StoreConfig): Cache;\n",
"export function multiCaching(Caches: Cache[]): Cache;"
],
"file_path": "types/cache-manager/index.d.ts",
"type": "replace",
"edit_start_line_idx": 33
} | import { jdenticon } from "jdenticon";
function testJdenticon() {
if (typeof jdenticon.version !== 'string') {
throw '.version should be of string type.';
}
jdenticon.update('#jdenticon', 'd6d7705392bc7af633328bea8c4c6904', 8);
}
testJdenticon();
| types/jdenticon/jdenticon-tests.ts | 0 | https://github.com/DefinitelyTyped/DefinitelyTyped/commit/ca7d069c55f1c9586f588554386bcebdc0071bff | [
0.00017070650937967002,
0.000170626473845914,
0.00017054642376024276,
0.000170626473845914,
8.004280971363187e-8
] |
{
"id": 4,
"code_window": [
" del(key: string): Promise<any>;\n",
"}\n",
"\n",
"\n",
"\n",
"declare namespace cacheManager {\n",
" function caching(IConfig: StoreConfig): Cache;\n",
" function multiCaching(Caches: Cache[]): Cache;\n",
"}\n",
"\n",
"export = cacheManager;\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace"
],
"after_edit": [
"export function caching(IConfig: StoreConfig): Cache;\n",
"export function multiCaching(Caches: Cache[]): Cache;"
],
"file_path": "types/cache-manager/index.d.ts",
"type": "replace",
"edit_start_line_idx": 33
} | // Type definitions for react-file-input
// Project: https://www.npmjs.com/package/react-file-input
// Definitions by: Dmitry Rogozhny <https://github.com/dmitryrogozhny>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.8
///<reference types="react" />
declare module "react-file-input" {
interface FileInputProps {
name: string;
className: string;
accept: string;
placeholder: string;
disabled?: boolean;
onChange: (event: React.SyntheticEvent<any>) => void;
}
class FileInput extends React.Component<FileInputProps> {
}
export = FileInput;
}
| types/react-file-input/index.d.ts | 0 | https://github.com/DefinitelyTyped/DefinitelyTyped/commit/ca7d069c55f1c9586f588554386bcebdc0071bff | [
0.001239953562617302,
0.0007220941479317844,
0.00016813076217658818,
0.0007581980898976326,
0.0004383139021228999
] |
{
"id": 0,
"code_window": [
"\n",
"/**\n",
" * When spawning VS Code tries to preserve the environment but since it's in\n",
" * the browser, it doesn't work.\n",
" */\n",
"export const preserveEnv = (options?: { env?: NodeJS.ProcessEnv } | null): void => {\n",
"\tif (options && options.env) {\n",
"\t\toptions.env = { ...process.env, ...options.env };\n",
"\t}\n",
"};"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"keep"
],
"after_edit": [
"export const withEnv = <T extends { env?: NodeJS.ProcessEnv }>(options?: T): T | undefined => {\n",
"\treturn options && options.env ? {\n",
"\t\t...options,\n",
"\t\tenv: {\n",
"\t\t\t...process.env, ...options.env,\n",
"\t\t},\n",
"\t} : options;\n"
],
"file_path": "packages/protocol/src/common/util.ts",
"type": "replace",
"edit_start_line_idx": 238
} | import { field, logger } from "@coder/logger";
import { ServerMessage, SharedProcessActive } from "@coder/protocol/src/proto";
import { preserveEnv } from "@coder/protocol";
import { ChildProcess, fork, ForkOptions } from "child_process";
import { randomFillSync } from "crypto";
import * as fs from "fs";
import * as fse from "fs-extra";
import * as os from "os";
import * as path from "path";
import * as WebSocket from "ws";
import { buildDir, cacheHome, dataHome, isCli, serveStatic } from "./constants";
import { createApp } from "./server";
import { forkModule, requireModule } from "./vscode/bootstrapFork";
import { SharedProcess, SharedProcessState } from "./vscode/sharedProcess";
import opn = require("opn");
import * as commander from "commander";
commander.version(process.env.VERSION || "development")
.name("code-server")
.description("Run VS Code on a remote server.")
.option("--cert <value>")
.option("--cert-key <value>")
.option("-e, --extensions-dir <dir>", "Set the root path for extensions.")
.option("-d --user-data-dir <dir>", " Specifies the directory that user data is kept in, useful when running as root.")
.option("--data-dir <value>", "DEPRECATED: Use '--user-data-dir' instead. Customize where user-data is stored.")
.option("-h, --host <value>", "Customize the hostname.", "0.0.0.0")
.option("-o, --open", "Open in the browser on startup.", false)
.option("-p, --port <number>", "Port to bind on.", parseInt(process.env.PORT!, 10) || 8443)
.option("-N, --no-auth", "Start without requiring authentication.", false)
.option("-H, --allow-http", "Allow http connections.", false)
.option("-P, --password <value>", "DEPRECATED: Use the PASSWORD environment variable instead. Specify a password for authentication.")
.option("--disable-telemetry", "Disables ALL telemetry.", false)
.option("--socket <value>", "Listen on a UNIX socket. Host and port will be ignored when set.")
.option("--install-extension <value>", "Install an extension by its ID.")
.option("--bootstrap-fork <name>", "Used for development. Never set.")
.option("--extra-args <args>", "Used for development. Never set.")
.arguments("Specify working directory.")
.parse(process.argv);
Error.stackTraceLimit = Infinity;
if (isCli) {
require("nbin").shimNativeFs(buildDir);
require("nbin").shimNativeFs("/node_modules");
}
// Makes strings or numbers bold in stdout
const bold = (text: string | number): string | number => {
return `\u001B[1m${text}\u001B[0m`;
};
(async (): Promise<void> => {
const args = commander.args;
const options = commander.opts() as {
noAuth: boolean;
readonly allowHttp: boolean;
readonly host: string;
readonly port: number;
readonly disableTelemetry: boolean;
readonly userDataDir?: string;
readonly extensionsDir?: string;
readonly dataDir?: string;
readonly password?: string;
readonly open?: boolean;
readonly cert?: string;
readonly certKey?: string;
readonly socket?: string;
readonly installExtension?: string;
readonly bootstrapFork?: string;
readonly extraArgs?: string;
};
if (options.disableTelemetry) {
process.env.DISABLE_TELEMETRY = "true";
}
// Commander has an exception for `--no` prefixes. Here we'll adjust that.
// tslint:disable-next-line:no-any
const noAuthValue = (commander as any).auth;
options.noAuth = !noAuthValue;
const dataDir = path.resolve(options.userDataDir || options.dataDir || path.join(dataHome, "code-server"));
const extensionsDir = options.extensionsDir ? path.resolve(options.extensionsDir) : path.resolve(dataDir, "extensions");
const workingDir = path.resolve(args[0] || process.cwd());
const dependenciesDir = path.join(os.tmpdir(), "code-server/dependencies");
if (!fs.existsSync(dataDir)) {
const oldDataDir = path.resolve(path.join(os.homedir(), ".code-server"));
if (fs.existsSync(oldDataDir)) {
await fse.move(oldDataDir, dataDir);
logger.info(`Moved data directory from ${oldDataDir} to ${dataDir}`);
}
}
await Promise.all([
fse.mkdirp(cacheHome),
fse.mkdirp(dataDir),
fse.mkdirp(extensionsDir),
fse.mkdirp(workingDir),
fse.mkdirp(dependenciesDir),
]);
const unpackExecutable = (binaryName: string): void => {
const memFile = path.join(isCli ? buildDir! : path.join(__dirname, ".."), "build/dependencies", binaryName);
const diskFile = path.join(dependenciesDir, binaryName);
if (!fse.existsSync(diskFile)) {
fse.writeFileSync(diskFile, fse.readFileSync(memFile));
}
fse.chmodSync(diskFile, "755");
};
unpackExecutable("rg");
// tslint:disable-next-line no-any
(<any>global).RIPGREP_LOCATION = path.join(dependenciesDir, "rg");
const builtInExtensionsDir = path.resolve(buildDir || path.join(__dirname, ".."), "build/extensions");
if (options.bootstrapFork) {
const modulePath = options.bootstrapFork;
if (!modulePath) {
logger.error("No module path specified to fork!");
process.exit(1);
}
process.argv = [
process.argv[0],
process.argv[1],
...(options.extraArgs ? JSON.parse(options.extraArgs) : []),
];
return requireModule(modulePath, builtInExtensionsDir);
}
const logDir = path.join(cacheHome, "code-server/logs", new Date().toISOString().replace(/[-:.TZ]/g, ""));
process.env.VSCODE_LOGS = logDir;
const certPath = options.cert ? path.resolve(options.cert) : undefined;
const certKeyPath = options.certKey ? path.resolve(options.certKey) : undefined;
if (certPath && !certKeyPath) {
logger.error("'--cert-key' flag is required when specifying a certificate!");
process.exit(1);
}
if (!certPath && certKeyPath) {
logger.error("'--cert' flag is required when specifying certificate key!");
process.exit(1);
}
let certData: Buffer | undefined;
let certKeyData: Buffer | undefined;
if (typeof certPath !== "undefined" && typeof certKeyPath !== "undefined") {
try {
certData = fs.readFileSync(certPath);
} catch (ex) {
logger.error(`Failed to read certificate: ${ex.message}`);
process.exit(1);
}
try {
certKeyData = fs.readFileSync(certKeyPath);
} catch (ex) {
logger.error(`Failed to read certificate key: ${ex.message}`);
process.exit(1);
}
}
logger.info(`\u001B[1mcode-server ${process.env.VERSION ? `v${process.env.VERSION}` : "development"}`);
if (options.dataDir) {
logger.warn('"--data-dir" is deprecated. Use "--user-data-dir" instead.');
}
if (options.installExtension) {
let forkOptions = {
env: {
VSCODE_ALLOW_IO: "true"
}
}
preserveEnv(forkOptions);
const fork = forkModule("vs/code/node/cli", [
"--user-data-dir", dataDir,
"--builtin-extensions-dir", builtInExtensionsDir,
"--extensions-dir", extensionsDir,
"--install-extension", options.installExtension,
], forkOptions, dataDir);
fork.stdout.on("data", (d: Buffer) => d.toString().split("\n").forEach((l) => logger.info(l)));
fork.stderr.on("data", (d: Buffer) => d.toString().split("\n").forEach((l) => logger.error(l)));
fork.on("exit", () => process.exit());
return;
}
// TODO: fill in appropriate doc url
logger.info("Additional documentation: http://github.com/codercom/code-server");
logger.info("Initializing", field("data-dir", dataDir), field("extensions-dir", extensionsDir), field("working-dir", workingDir), field("log-dir", logDir));
const sharedProcess = new SharedProcess(dataDir, extensionsDir, builtInExtensionsDir);
const sendSharedProcessReady = (socket: WebSocket): void => {
const active = new SharedProcessActive();
active.setSocketPath(sharedProcess.socketPath);
active.setLogPath(logDir);
const serverMessage = new ServerMessage();
serverMessage.setSharedProcessActive(active);
socket.send(serverMessage.serializeBinary());
};
sharedProcess.onState((event) => {
if (event.state === SharedProcessState.Ready) {
app.wss.clients.forEach((c) => sendSharedProcessReady(c));
}
});
if (options.password) {
logger.warn('"--password" is deprecated. Use the PASSWORD environment variable instead.');
}
let password = options.password || process.env.PASSWORD;
const usingCustomPassword = !!password;
if (!password) {
// Generate a random password with a length of 24.
const buffer = Buffer.alloc(12);
randomFillSync(buffer);
password = buffer.toString("hex");
}
const hasCustomHttps = certData && certKeyData;
const app = await createApp({
allowHttp: options.allowHttp,
bypassAuth: options.noAuth,
registerMiddleware: (app): void => {
// If we're not running from the binary and we aren't serving the static
// pre-built version, use webpack to serve the web files.
if (!isCli && !serveStatic) {
const webpackConfig = require(path.resolve(__dirname, "..", "..", "web", "webpack.config.js"));
const compiler = require("webpack")(webpackConfig);
app.use(require("webpack-dev-middleware")(compiler, {
logger: {
trace: (m: string): void => logger.trace("webpack", field("message", m)),
debug: (m: string): void => logger.debug("webpack", field("message", m)),
info: (m: string): void => logger.info("webpack", field("message", m)),
warn: (m: string): void => logger.warn("webpack", field("message", m)),
error: (m: string): void => logger.error("webpack", field("message", m)),
},
publicPath: webpackConfig.output.publicPath,
stats: webpackConfig.stats,
}));
app.use(require("webpack-hot-middleware")(compiler));
}
},
serverOptions: {
extensionsDirectory: extensionsDir,
builtInExtensionsDirectory: builtInExtensionsDir,
dataDirectory: dataDir,
workingDirectory: workingDir,
cacheDirectory: cacheHome,
fork: (modulePath: string, args?: string[], options?: ForkOptions): ChildProcess => {
if (options && options.env && options.env.AMD_ENTRYPOINT) {
return forkModule(options.env.AMD_ENTRYPOINT, args, options, dataDir);
}
return fork(modulePath, args, options);
},
},
password,
httpsOptions: hasCustomHttps ? {
key: certKeyData,
cert: certData,
} : undefined,
});
logger.info("Starting webserver...", field("host", options.host), field("port", options.port));
if (options.socket) {
app.server.listen(options.socket);
} else {
app.server.listen(options.port, options.host);
}
let clientId = 1;
app.wss.on("connection", (ws, req) => {
const id = clientId++;
if (sharedProcess.state === SharedProcessState.Ready) {
sendSharedProcessReady(ws);
}
logger.info(`WebSocket opened \u001B[0m${req.url}`, field("client", id), field("ip", req.socket.remoteAddress));
ws.on("close", (code) => {
logger.info(`WebSocket closed \u001B[0m${req.url}`, field("client", id), field("code", code));
});
});
app.wss.on("error", (err: NodeJS.ErrnoException) => {
if (err.code === "EADDRINUSE") {
if (options.socket) {
logger.error(`Socket ${bold(options.socket)} is in use. Please specify a different socket.`);
} else {
logger.error(`Port ${bold(options.port)} is in use. Please free up port ${options.port} or specify a different port with the -p flag`);
}
process.exit(1);
}
});
if (!options.certKey && !options.cert) {
logger.warn("No certificate specified. \u001B[1mThis could be insecure.");
// TODO: fill in appropriate doc url
logger.warn("Documentation on securing your setup: https://github.com/codercom/code-server/blob/master/doc/security/ssl.md");
}
if (!options.noAuth && !usingCustomPassword) {
logger.info(" ");
logger.info(`Password:\u001B[1m ${password}`);
} else {
logger.warn("Launched without authentication.");
}
if (options.disableTelemetry) {
logger.info("Telemetry is disabled");
}
const protocol = options.allowHttp ? "http" : "https";
const url = `${protocol}://localhost:${options.port}/`;
logger.info(" ");
logger.info("Started (click the link below to open):");
logger.info(url);
logger.info(" ");
if (options.open) {
try {
await opn(url);
} catch (e) {
logger.warn("Url couldn't be opened automatically.", field("url", url), field("exception", e));
}
}
})().catch((ex) => {
logger.error(ex);
});
| packages/server/src/cli.ts | 1 | https://github.com/coder/code-server/commit/cdb900aca81006b88a92e4f933349a5496b3fd06 | [
0.9991620779037476,
0.060064878314733505,
0.00016835164569783956,
0.0002179793082177639,
0.2347227782011032
] |
{
"id": 0,
"code_window": [
"\n",
"/**\n",
" * When spawning VS Code tries to preserve the environment but since it's in\n",
" * the browser, it doesn't work.\n",
" */\n",
"export const preserveEnv = (options?: { env?: NodeJS.ProcessEnv } | null): void => {\n",
"\tif (options && options.env) {\n",
"\t\toptions.env = { ...process.env, ...options.env };\n",
"\t}\n",
"};"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"keep"
],
"after_edit": [
"export const withEnv = <T extends { env?: NodeJS.ProcessEnv }>(options?: T): T | undefined => {\n",
"\treturn options && options.env ? {\n",
"\t\t...options,\n",
"\t\tenv: {\n",
"\t\t\t...process.env, ...options.env,\n",
"\t\t},\n",
"\t} : options;\n"
],
"file_path": "packages/protocol/src/common/util.ts",
"type": "replace",
"edit_start_line_idx": 238
} | export const gracefulify = (): void => undefined;
export * from "fs";
| packages/vscode/src/fill/graceful-fs.ts | 0 | https://github.com/coder/code-server/commit/cdb900aca81006b88a92e4f933349a5496b3fd06 | [
0.0002029604511335492,
0.0002029604511335492,
0.0002029604511335492,
0.0002029604511335492,
0
] |
{
"id": 0,
"code_window": [
"\n",
"/**\n",
" * When spawning VS Code tries to preserve the environment but since it's in\n",
" * the browser, it doesn't work.\n",
" */\n",
"export const preserveEnv = (options?: { env?: NodeJS.ProcessEnv } | null): void => {\n",
"\tif (options && options.env) {\n",
"\t\toptions.env = { ...process.env, ...options.env };\n",
"\t}\n",
"};"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"keep"
],
"after_edit": [
"export const withEnv = <T extends { env?: NodeJS.ProcessEnv }>(options?: T): T | undefined => {\n",
"\treturn options && options.env ? {\n",
"\t\t...options,\n",
"\t\tenv: {\n",
"\t\t\t...process.env, ...options.env,\n",
"\t\t},\n",
"\t} : options;\n"
],
"file_path": "packages/protocol/src/common/util.ts",
"type": "replace",
"edit_start_line_idx": 238
} | .md-tooltip {
position: relative;
}
.md-tooltip-content {
position: absolute;
bottom: -35px;
left: 50%;
padding: 7px;
transform: translateX(-50%) scale(0);
transition: transform 0.15s cubic-bezier(0, 0, 0.2, 1);
transform-origin: top;
background: rgba(67, 67, 67, 0.97);
color: white;
letter-spacing: 0.3px;
border-radius: 3px;
font-size: 12px;
font-weight: 500;
z-index: 2;
}
.md-tooltip:hover .md-tooltip-content {
transform: translateX(-50%) scale(1);
}
| packages/app/common/src/tooltip.scss | 0 | https://github.com/coder/code-server/commit/cdb900aca81006b88a92e4f933349a5496b3fd06 | [
0.00017850857693701982,
0.00017647950153332204,
0.00017408293206244707,
0.00017684695194475353,
0.0000018253504094900563
] |
{
"id": 0,
"code_window": [
"\n",
"/**\n",
" * When spawning VS Code tries to preserve the environment but since it's in\n",
" * the browser, it doesn't work.\n",
" */\n",
"export const preserveEnv = (options?: { env?: NodeJS.ProcessEnv } | null): void => {\n",
"\tif (options && options.env) {\n",
"\t\toptions.env = { ...process.env, ...options.env };\n",
"\t}\n",
"};"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"keep"
],
"after_edit": [
"export const withEnv = <T extends { env?: NodeJS.ProcessEnv }>(options?: T): T | undefined => {\n",
"\treturn options && options.env ? {\n",
"\t\t...options,\n",
"\t\tenv: {\n",
"\t\t\t...process.env, ...options.env,\n",
"\t\t},\n",
"\t} : options;\n"
],
"file_path": "packages/protocol/src/common/util.ts",
"type": "replace",
"edit_start_line_idx": 238
} | import { URI } from "vs/base/common/uri";
export const getPathFromAmdModule = (_: typeof require, relativePath: string): string => {
if (process.mainModule && process.mainModule.filename) {
const index = process.mainModule.filename.lastIndexOf("/");
return process.mainModule.filename.slice(0, index);
}
return relativePath ? URI.file(relativePath).fsPath : "";
};
| packages/vscode/src/fill/amd.ts | 0 | https://github.com/coder/code-server/commit/cdb900aca81006b88a92e4f933349a5496b3fd06 | [
0.00029632047517225146,
0.00023473288456443697,
0.00017314529395662248,
0.00023473288456443697,
0.00006158759060781449
] |
{
"id": 1,
"code_window": [
"import * as cp from \"child_process\";\n",
"import { ServerProxy } from \"../../common/proxy\";\n",
"import { preserveEnv } from \"../../common/util\";\n",
"import { WritableProxy, ReadableProxy } from \"./stream\";\n",
"\n",
"// tslint:disable completed-docs\n",
"\n",
"export type ForkProvider = (modulePath: string, args?: string[], options?: cp.ForkOptions) => cp.ChildProcess;\n"
],
"labels": [
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { withEnv } from \"../../common/util\";\n"
],
"file_path": "packages/protocol/src/node/modules/child_process.ts",
"type": "replace",
"edit_start_line_idx": 2
} | import { ChildProcess } from "child_process";
import * as os from "os";
import * as path from "path";
import { forkModule } from "./bootstrapFork";
import { StdioIpcHandler } from "../ipc";
import { ParsedArgs } from "vs/platform/environment/common/environment";
import { Emitter } from "@coder/events/src";
import { retry } from "@coder/ide/src/retry";
import { logger, field, Level } from "@coder/logger";
import { preserveEnv } from "@coder/protocol";
export enum SharedProcessState {
Stopped,
Starting,
Ready,
}
export type SharedProcessEvent = {
readonly state: SharedProcessState.Ready | SharedProcessState.Starting;
} | {
readonly state: SharedProcessState.Stopped;
readonly error: string;
};
export class SharedProcess {
public readonly socketPath: string = os.platform() === "win32"
? path.join("\\\\?\\pipe", os.tmpdir(), `.code-server${Math.random().toString()}`)
: path.join(os.tmpdir(), `.code-server${Math.random().toString()}`);
private _state: SharedProcessState = SharedProcessState.Stopped;
private activeProcess: ChildProcess | undefined;
private ipcHandler: StdioIpcHandler | undefined;
private readonly onStateEmitter = new Emitter<SharedProcessEvent>();
public readonly onState = this.onStateEmitter.event;
private readonly logger = logger.named("shared");
private readonly retry = retry.register("Shared process", () => this.connect());
private disposed: boolean = false;
public constructor(
private readonly userDataDir: string,
private readonly extensionsDir: string,
private readonly builtInExtensionsDir: string,
) {
this.retry.run();
}
public get state(): SharedProcessState {
return this._state;
}
/**
* Signal the shared process to terminate.
*/
public dispose(): void {
this.disposed = true;
if (this.ipcHandler) {
this.ipcHandler.send("handshake:goodbye");
}
this.ipcHandler = undefined;
}
/**
* Start and connect to the shared process.
*/
private async connect(): Promise<void> {
this.setState({ state: SharedProcessState.Starting });
const activeProcess = await this.restart();
activeProcess.on("exit", (exitCode) => {
const error = new Error(`Exited with ${exitCode}`);
this.setState({
error: error.message,
state: SharedProcessState.Stopped,
});
if (!this.disposed) {
this.retry.run(error);
}
});
this.setState({ state: SharedProcessState.Ready });
}
/**
* Restart the shared process. Kill existing process if running. Resolve when
* the shared process is ready and reject when it errors or dies before being
* ready.
*/
private async restart(): Promise<ChildProcess> {
if (this.activeProcess && !this.activeProcess.killed) {
this.activeProcess.kill();
}
let forkOptions = {
env: {
VSCODE_ALLOW_IO: "true"
}
}
preserveEnv(forkOptions);
const activeProcess = forkModule("vs/code/electron-browser/sharedProcess/sharedProcessMain", [], forkOptions, this.userDataDir);
this.activeProcess = activeProcess;
await new Promise((resolve, reject): void => {
const doReject = (error: Error | number | null): void => {
if (error === null) {
error = new Error("Exited unexpectedly");
} else if (typeof error === "number") {
error = new Error(`Exited with ${error}`);
}
activeProcess.removeAllListeners();
this.setState({
error: error.message,
state: SharedProcessState.Stopped,
});
reject(error);
};
activeProcess.on("error", doReject);
activeProcess.on("exit", doReject);
activeProcess.stdout.on("data", (data) => {
logger.trace("stdout", field("data", data.toString()));
});
activeProcess.stderr.on("data", (data) => {
// Warn instead of error to prevent panic. It's unlikely stderr here is
// about anything critical to the functioning of the editor.
logger.warn("stderr", field("data", data.toString()));
});
this.ipcHandler = new StdioIpcHandler(activeProcess);
this.ipcHandler.once("handshake:hello", () => {
const data: {
sharedIPCHandle: string;
args: Partial<ParsedArgs>;
logLevel: Level;
} = {
args: {
"builtin-extensions-dir": this.builtInExtensionsDir,
"user-data-dir": this.userDataDir,
"extensions-dir": this.extensionsDir,
},
logLevel: this.logger.level,
sharedIPCHandle: this.socketPath,
};
this.ipcHandler!.send("handshake:hey there", "", data);
});
this.ipcHandler.once("handshake:im ready", () => {
activeProcess.removeListener("error", doReject);
activeProcess.removeListener("exit", doReject);
resolve();
});
});
return activeProcess;
}
/**
* Set the internal shared process state and emit the state event.
*/
private setState(event: SharedProcessEvent): void {
this._state = event.state;
this.onStateEmitter.emit(event);
}
}
| packages/server/src/vscode/sharedProcess.ts | 1 | https://github.com/coder/code-server/commit/cdb900aca81006b88a92e4f933349a5496b3fd06 | [
0.0062582846730947495,
0.0006188685656525195,
0.0001638354588067159,
0.00017217053391505033,
0.0014312482671812177
] |
{
"id": 1,
"code_window": [
"import * as cp from \"child_process\";\n",
"import { ServerProxy } from \"../../common/proxy\";\n",
"import { preserveEnv } from \"../../common/util\";\n",
"import { WritableProxy, ReadableProxy } from \"./stream\";\n",
"\n",
"// tslint:disable completed-docs\n",
"\n",
"export type ForkProvider = (modulePath: string, args?: string[], options?: cp.ForkOptions) => cp.ChildProcess;\n"
],
"labels": [
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { withEnv } from \"../../common/util\";\n"
],
"file_path": "packages/protocol/src/node/modules/child_process.ts",
"type": "replace",
"edit_start_line_idx": 2
} | language: node_js
node_js:
- 10.15.1
services:
- docker
matrix:
include:
- os: linux
dist: trusty
env:
- VSCODE_VERSION="1.33.1" MAJOR_VERSION="1" VERSION="$MAJOR_VERSION.$TRAVIS_BUILD_NUMBER-vsc$VSCODE_VERSION" TARGET="centos"
- os: linux
dist: trusty
env:
- VSCODE_VERSION="1.33.1" MAJOR_VERSION="1" VERSION="$MAJOR_VERSION.$TRAVIS_BUILD_NUMBER-vsc$VSCODE_VERSION" TARGET="alpine"
- os: osx
before_install:
- if [[ "$TRAVIS_OS_NAME" == "linux" ]]; then sudo apt-get install libxkbfile-dev
libsecret-1-dev; fi
- npm install -g [email protected]
script:
- scripts/build.sh
before_deploy:
- echo "$VERSION" "$TRAVIS_COMMIT"
- git config --local user.name "$USER_NAME"
- git config --local user.email "$USER_EMAIL"
- git tag "$VERSION" "$TRAVIS_COMMIT"
- if [[ “$TRAVIS_OS_NAME” == “osx” ]]; then yarn task package $VERSION; fi
deploy:
provider: releases
file_glob: true
draft: true
tag_name: "$VERSION"
target_commitish: "$TRAVIS_COMMIT"
name: "$VERSION"
skip_cleanup: true
api_key:
secure: YL/x24KjYjgYXPcJWk3FV7FGxI79Mh6gBECQEcdlf3fkLEoKFVgzHBoUNWrFPzyR4tgLyWNAgcpD9Lkme1TRWTom7UPjXcwMNyLcLa+uec7ciSAnYD9ntLTpiCuPDD1u0LtRGclSi/EHQ+F8YVq+HZJpXTsJeAmOmihma3GVbGKSZr+BRum+0YZSG4w+o4TOlYzw/4bLWS52MogZcwpjd+hemBbgXLuGU2ziKv2vEKCZFbEeA16II4x1WLI4mutDdCeh7+3aLzGLwDa49NxtsVYNjyNFF75JhCTCNA55e2YMiLz9Uq69IXe/mi5F7xUaFfhIqqLNyKBnKeEOzu3dYnc+8n3LjnQ+00PmkF05nx9kBn3UfV1kwQGh6QbyDmTtBP07rtUMyI14aeQqHjxsaVRdMnwj9Q2DjXRr8UDqESZF0rmK3pHCXS2fBhIzLE8tLVW5Heiba2pQRFMHMZW+KBE97FzcFh7is90Ait3T8enfcd/PWFPYoBejDAdjwxwOkezh5N5ZkYquEfDYuWrFi6zRFCktsruaAcA+xGtTf9oilBBzUqu8Ie+YFWH5me83xakcblJWdaW/D2rLJAJH3m6LFm8lBqyUgDX5t/etob6CpDuYHu5D1J3XINOj/+aLAcadq6qlh70PMZS3zYffUu3JlzaD2amlSHIT8b5YXFc=
file:
- release/*.tar.gz
- release/*.zip
on:
repo: codercom/code-server
branch: master
cache:
yarn: true
timeout: 1000
directories:
- .cache
| .travis.yml | 0 | https://github.com/coder/code-server/commit/cdb900aca81006b88a92e4f933349a5496b3fd06 | [
0.0013041588244959712,
0.0003990159893874079,
0.00016906413657125086,
0.00017358599870931357,
0.0004525768745224923
] |
{
"id": 1,
"code_window": [
"import * as cp from \"child_process\";\n",
"import { ServerProxy } from \"../../common/proxy\";\n",
"import { preserveEnv } from \"../../common/util\";\n",
"import { WritableProxy, ReadableProxy } from \"./stream\";\n",
"\n",
"// tslint:disable completed-docs\n",
"\n",
"export type ForkProvider = (modulePath: string, args?: string[], options?: cp.ForkOptions) => cp.ChildProcess;\n"
],
"labels": [
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { withEnv } from \"../../common/util\";\n"
],
"file_path": "packages/protocol/src/node/modules/child_process.ts",
"type": "replace",
"edit_start_line_idx": 2
} | import { readFile, writeFile } from "fs";
import { mkdirp } from "fs-extra";
import * as path from "path";
import { promisify } from "util";
import { IDisposable } from "@coder/disposable";
import { logger, field } from "@coder/logger";
import { Event } from "vs/base/common/event";
import * as workspaceStorage from "vs/base/node/storage";
import * as globalStorage from "vs/platform/storage/node/storageIpc";
import { IStorageService, WillSaveStateReason } from "vs/platform/storage/common/storage";
import * as paths from "./paths";
import { workbench } from "../workbench";
// tslint:disable completed-docs
class StorageDatabase implements workspaceStorage.IStorageDatabase {
public readonly onDidChangeItemsExternal = Event.None;
private readonly items = new Map<string, string>();
private fetched: boolean = false;
private readonly path: string;
public constructor(path: string) {
this.path = path.replace(/\.vscdb$/, ".json");
logger.debug("Setting up storage", field("path", this.path));
window.addEventListener("unload", () => {
if (!navigator.sendBeacon) {
throw new Error("cannot save state");
}
this.triggerFlush(WillSaveStateReason.SHUTDOWN);
const resourceBaseUrl = location.pathname.replace(/\/$/, "") + "/resource";
navigator.sendBeacon(`${resourceBaseUrl}/${this.path}`, this.content);
});
}
public async getItems(): Promise<Map<string, string>> {
if (this.fetched) {
return this.items;
}
try {
const contents = await promisify(readFile)(this.path, "utf8");
const json = JSON.parse(contents);
Object.keys(json).forEach((key) => {
this.items.set(key, json[key]);
});
} catch (error) {
if (error.code !== "ENOENT") {
throw error;
}
}
this.fetched = true;
return this.items;
}
public updateItems(request: workspaceStorage.IUpdateRequest): Promise<void> {
if (request.insert) {
request.insert.forEach((value, key) => {
if (key === "colorThemeData") {
localStorage.setItem("colorThemeData", value);
}
this.items.set(key, value);
});
}
if (request.delete) {
request.delete.forEach(key => this.items.delete(key));
}
return this.save();
}
public close(): Promise<void> {
return Promise.resolve();
}
public checkIntegrity(): Promise<string> {
return Promise.resolve("ok");
}
private async save(): Promise<void> {
await mkdirp(path.dirname(this.path));
return promisify(writeFile)(this.path, this.content);
}
private triggerFlush(reason: WillSaveStateReason = WillSaveStateReason.NONE): boolean {
// tslint:disable-next-line:no-any
const storageService = workbench.serviceCollection.get<IStorageService>(IStorageService) as any;
if (reason === WillSaveStateReason.SHUTDOWN && storageService.close) {
storageService.close();
return true;
}
if (storageService._onWillSaveState) {
storageService._onWillSaveState.fire({ reason });
return true;
}
return false;
}
private get content(): string {
const json: { [key: string]: string } = {};
this.items.forEach((value, key) => {
json[key] = value;
});
return JSON.stringify(json);
}
}
class GlobalStorageDatabase extends StorageDatabase implements IDisposable {
public constructor() {
super(path.join(paths.getAppDataPath(), "globalStorage", "state.vscdb"));
}
public dispose(): void {
// Nothing to do.
}
}
const workspaceTarget = workspaceStorage as typeof workspaceStorage;
// @ts-ignore TODO: don't ignore it.
workspaceTarget.SQLiteStorageDatabase = StorageDatabase;
const globalTarget = globalStorage as typeof globalStorage;
// @ts-ignore TODO: don't ignore it.
globalTarget.GlobalStorageDatabaseChannelClient = GlobalStorageDatabase;
| packages/vscode/src/fill/storageDatabase.ts | 0 | https://github.com/coder/code-server/commit/cdb900aca81006b88a92e4f933349a5496b3fd06 | [
0.00019550349679775536,
0.00017306987137999386,
0.00016528058040421456,
0.00017151534848380834,
0.0000069794177761650644
] |
{
"id": 1,
"code_window": [
"import * as cp from \"child_process\";\n",
"import { ServerProxy } from \"../../common/proxy\";\n",
"import { preserveEnv } from \"../../common/util\";\n",
"import { WritableProxy, ReadableProxy } from \"./stream\";\n",
"\n",
"// tslint:disable completed-docs\n",
"\n",
"export type ForkProvider = (modulePath: string, args?: string[], options?: cp.ForkOptions) => cp.ChildProcess;\n"
],
"labels": [
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { withEnv } from \"../../common/util\";\n"
],
"file_path": "packages/protocol/src/node/modules/child_process.ts",
"type": "replace",
"edit_start_line_idx": 2
} | const fs = require("fs");
const util = require("util");
// This isn't properly promisified in Jest.
Object.defineProperty(fs.read, util.promisify.custom, {
configurable: true,
value: (...args) => {
return new Promise((resolve, reject) => {
args.push((error, bytesRead, buffer) => {
if (error) {
reject(error);
} else {
resolve({ bytesRead, buffer });
}
});
fs.read(...args);
});
},
});
global.requestAnimationFrame = (cb) => {
setTimeout(cb, 0);
};
// lchmod might not be available. Jest runs graceful-fs which makes this a no-op
// when it doesn't exist but that doesn't seem to always run when running
// multiple tests (or maybe it gets undone after a test).
if (!fs.lchmod) {
fs.lchmod = function (path, mode, cb) {
if (cb) {
process.nextTick(cb);
}
};
fs.lchmodSync = function () {};
}
| scripts/test-setup.js | 0 | https://github.com/coder/code-server/commit/cdb900aca81006b88a92e4f933349a5496b3fd06 | [
0.0001746204070514068,
0.00017198991554323584,
0.00016715360106900334,
0.00017309284885413945,
0.0000028842327992606442
] |
{
"id": 2,
"code_window": [
"\tpublic async exec(\n",
"\t\tcommand: string,\n",
"\t\toptions?: { encoding?: string | null } & cp.ExecOptions | null,\n",
"\t\tcallback?: ((error: cp.ExecException | null, stdin: string | Buffer, stdout: string | Buffer) => void),\n",
"\t): Promise<ChildProcessProxies> {\n",
"\t\tpreserveEnv(options);\n",
"\n",
"\t\treturn this.returnProxies(cp.exec(command, options, callback));\n",
"\t}\n",
"\n",
"\tpublic async fork(modulePath: string, args?: string[], options?: cp.ForkOptions): Promise<ChildProcessProxies> {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\treturn this.returnProxies(cp.exec(command, options && withEnv(options), callback));\n"
],
"file_path": "packages/protocol/src/node/modules/child_process.ts",
"type": "replace",
"edit_start_line_idx": 73
} | import * as cp from "child_process";
import { ServerProxy } from "../../common/proxy";
import { preserveEnv } from "../../common/util";
import { WritableProxy, ReadableProxy } from "./stream";
// tslint:disable completed-docs
export type ForkProvider = (modulePath: string, args?: string[], options?: cp.ForkOptions) => cp.ChildProcess;
export class ChildProcessProxy extends ServerProxy<cp.ChildProcess> {
public constructor(instance: cp.ChildProcess) {
super({
bindEvents: ["close", "disconnect", "error", "exit", "message"],
doneEvents: ["close"],
instance,
});
}
public async kill(signal?: string): Promise<void> {
this.instance.kill(signal);
}
public async disconnect(): Promise<void> {
this.instance.disconnect();
}
public async ref(): Promise<void> {
this.instance.ref();
}
public async unref(): Promise<void> {
this.instance.unref();
}
// tslint:disable-next-line no-any
public async send(message: any): Promise<void> {
return new Promise((resolve, reject): void => {
this.instance.send(message, (error) => {
if (error) {
reject(error);
} else {
resolve();
}
});
});
}
public async getPid(): Promise<number> {
return this.instance.pid;
}
public async dispose(): Promise<void> {
this.instance.kill();
setTimeout(() => this.instance.kill("SIGKILL"), 5000); // Double tap.
await super.dispose();
}
}
export interface ChildProcessProxies {
childProcess: ChildProcessProxy;
stdin?: WritableProxy | null;
stdout?: ReadableProxy | null;
stderr?: ReadableProxy | null;
}
export class ChildProcessModuleProxy {
public constructor(private readonly forkProvider?: ForkProvider) {}
public async exec(
command: string,
options?: { encoding?: string | null } & cp.ExecOptions | null,
callback?: ((error: cp.ExecException | null, stdin: string | Buffer, stdout: string | Buffer) => void),
): Promise<ChildProcessProxies> {
preserveEnv(options);
return this.returnProxies(cp.exec(command, options, callback));
}
public async fork(modulePath: string, args?: string[], options?: cp.ForkOptions): Promise<ChildProcessProxies> {
preserveEnv(options);
return this.returnProxies((this.forkProvider || cp.fork)(modulePath, args, options));
}
public async spawn(command: string, args?: string[], options?: cp.SpawnOptions): Promise<ChildProcessProxies> {
preserveEnv(options);
return this.returnProxies(cp.spawn(command, args, options));
}
private returnProxies(process: cp.ChildProcess): ChildProcessProxies {
return {
childProcess: new ChildProcessProxy(process),
stdin: process.stdin && new WritableProxy(process.stdin),
// Child processes streams appear to immediately flow so we need to bind
// to the data event right away.
stdout: process.stdout && new ReadableProxy(process.stdout, ["data"]),
stderr: process.stderr && new ReadableProxy(process.stderr, ["data"]),
};
}
}
| packages/protocol/src/node/modules/child_process.ts | 1 | https://github.com/coder/code-server/commit/cdb900aca81006b88a92e4f933349a5496b3fd06 | [
0.9982427358627319,
0.18176370859146118,
0.00016393436817452312,
0.0005835670745000243,
0.3838345408439636
] |
{
"id": 2,
"code_window": [
"\tpublic async exec(\n",
"\t\tcommand: string,\n",
"\t\toptions?: { encoding?: string | null } & cp.ExecOptions | null,\n",
"\t\tcallback?: ((error: cp.ExecException | null, stdin: string | Buffer, stdout: string | Buffer) => void),\n",
"\t): Promise<ChildProcessProxies> {\n",
"\t\tpreserveEnv(options);\n",
"\n",
"\t\treturn this.returnProxies(cp.exec(command, options, callback));\n",
"\t}\n",
"\n",
"\tpublic async fork(modulePath: string, args?: string[], options?: cp.ForkOptions): Promise<ChildProcessProxies> {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\treturn this.returnProxies(cp.exec(command, options && withEnv(options), callback));\n"
],
"file_path": "packages/protocol/src/node/modules/child_process.ts",
"type": "replace",
"edit_start_line_idx": 73
} | const fs = require("fs");
const util = require("util");
// This isn't properly promisified in Jest.
Object.defineProperty(fs.read, util.promisify.custom, {
configurable: true,
value: (...args) => {
return new Promise((resolve, reject) => {
args.push((error, bytesRead, buffer) => {
if (error) {
reject(error);
} else {
resolve({ bytesRead, buffer });
}
});
fs.read(...args);
});
},
});
global.requestAnimationFrame = (cb) => {
setTimeout(cb, 0);
};
// lchmod might not be available. Jest runs graceful-fs which makes this a no-op
// when it doesn't exist but that doesn't seem to always run when running
// multiple tests (or maybe it gets undone after a test).
if (!fs.lchmod) {
fs.lchmod = function (path, mode, cb) {
if (cb) {
process.nextTick(cb);
}
};
fs.lchmodSync = function () {};
}
| scripts/test-setup.js | 0 | https://github.com/coder/code-server/commit/cdb900aca81006b88a92e4f933349a5496b3fd06 | [
0.00017505569849163294,
0.0001712124649202451,
0.00016614487685728818,
0.00017182464944198728,
0.000003224725332984235
] |
{
"id": 2,
"code_window": [
"\tpublic async exec(\n",
"\t\tcommand: string,\n",
"\t\toptions?: { encoding?: string | null } & cp.ExecOptions | null,\n",
"\t\tcallback?: ((error: cp.ExecException | null, stdin: string | Buffer, stdout: string | Buffer) => void),\n",
"\t): Promise<ChildProcessProxies> {\n",
"\t\tpreserveEnv(options);\n",
"\n",
"\t\treturn this.returnProxies(cp.exec(command, options, callback));\n",
"\t}\n",
"\n",
"\tpublic async fork(modulePath: string, args?: string[], options?: cp.ForkOptions): Promise<ChildProcessProxies> {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\treturn this.returnProxies(cp.exec(command, options && withEnv(options), callback));\n"
],
"file_path": "packages/protocol/src/node/modules/child_process.ts",
"type": "replace",
"edit_start_line_idx": 73
} | import { Module } from "@coder/protocol";
import { client } from "./client";
export = client.modules[Module.Net];
| packages/ide/src/fill/net.ts | 0 | https://github.com/coder/code-server/commit/cdb900aca81006b88a92e4f933349a5496b3fd06 | [
0.0001761962630553171,
0.0001761962630553171,
0.0001761962630553171,
0.0001761962630553171,
0
] |
{
"id": 2,
"code_window": [
"\tpublic async exec(\n",
"\t\tcommand: string,\n",
"\t\toptions?: { encoding?: string | null } & cp.ExecOptions | null,\n",
"\t\tcallback?: ((error: cp.ExecException | null, stdin: string | Buffer, stdout: string | Buffer) => void),\n",
"\t): Promise<ChildProcessProxies> {\n",
"\t\tpreserveEnv(options);\n",
"\n",
"\t\treturn this.returnProxies(cp.exec(command, options, callback));\n",
"\t}\n",
"\n",
"\tpublic async fork(modulePath: string, args?: string[], options?: cp.ForkOptions): Promise<ChildProcessProxies> {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\treturn this.returnProxies(cp.exec(command, options && withEnv(options), callback));\n"
],
"file_path": "packages/protocol/src/node/modules/child_process.ts",
"type": "replace",
"edit_start_line_idx": 73
} | export * from "./client";
| packages/vscode/src/index.ts | 0 | https://github.com/coder/code-server/commit/cdb900aca81006b88a92e4f933349a5496b3fd06 | [
0.00016903947107493877,
0.00016903947107493877,
0.00016903947107493877,
0.00016903947107493877,
0
] |
{
"id": 3,
"code_window": [
"\t}\n",
"\n",
"\tpublic async fork(modulePath: string, args?: string[], options?: cp.ForkOptions): Promise<ChildProcessProxies> {\n",
"\t\tpreserveEnv(options);\n",
"\n",
"\t\treturn this.returnProxies((this.forkProvider || cp.fork)(modulePath, args, options));\n",
"\t}\n",
"\n",
"\tpublic async spawn(command: string, args?: string[], options?: cp.SpawnOptions): Promise<ChildProcessProxies> {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\treturn this.returnProxies((this.forkProvider || cp.fork)(modulePath, args, withEnv(options)));\n"
],
"file_path": "packages/protocol/src/node/modules/child_process.ts",
"type": "replace",
"edit_start_line_idx": 79
} | /// <reference path="../../../../../lib/vscode/src/typings/node-pty.d.ts" />
import { EventEmitter } from "events";
import * as pty from "node-pty";
import { ServerProxy } from "../../common/proxy";
import { preserveEnv } from "../../common/util";
// tslint:disable completed-docs
/**
* Server-side IPty proxy.
*/
export class NodePtyProcessProxy extends ServerProxy {
public constructor(private readonly process: pty.IPty) {
super({
bindEvents: ["process", "data", "exit"],
doneEvents: ["exit"],
instance: new EventEmitter(),
});
this.process.on("data", (data) => this.instance.emit("data", data));
this.process.on("exit", (exitCode, signal) => this.instance.emit("exit", exitCode, signal));
let name = process.process;
setTimeout(() => { // Need to wait for the caller to listen to the event.
this.instance.emit("process", name);
}, 1);
const timer = setInterval(() => {
if (process.process !== name) {
name = process.process;
this.instance.emit("process", name);
}
}, 200);
this.process.on("exit", () => clearInterval(timer));
}
public async getPid(): Promise<number> {
return this.process.pid;
}
public async getProcess(): Promise<string> {
return this.process.process;
}
public async kill(signal?: string): Promise<void> {
this.process.kill(signal);
}
public async resize(columns: number, rows: number): Promise<void> {
this.process.resize(columns, rows);
}
public async write(data: string): Promise<void> {
this.process.write(data);
}
public async dispose(): Promise<void> {
this.process.kill();
setTimeout(() => this.process.kill("SIGKILL"), 5000); // Double tap.
await super.dispose();
}
}
/**
* Server-side node-pty proxy.
*/
export class NodePtyModuleProxy {
public async spawn(file: string, args: string[] | string, options: pty.IPtyForkOptions): Promise<NodePtyProcessProxy> {
preserveEnv(options);
return new NodePtyProcessProxy(require("node-pty").spawn(file, args, options));
}
}
| packages/protocol/src/node/modules/node-pty.ts | 1 | https://github.com/coder/code-server/commit/cdb900aca81006b88a92e4f933349a5496b3fd06 | [
0.9970890879631042,
0.12566925585269928,
0.0001672824437264353,
0.00017221577581949532,
0.32937386631965637
] |
{
"id": 3,
"code_window": [
"\t}\n",
"\n",
"\tpublic async fork(modulePath: string, args?: string[], options?: cp.ForkOptions): Promise<ChildProcessProxies> {\n",
"\t\tpreserveEnv(options);\n",
"\n",
"\t\treturn this.returnProxies((this.forkProvider || cp.fork)(modulePath, args, options));\n",
"\t}\n",
"\n",
"\tpublic async spawn(command: string, args?: string[], options?: cp.SpawnOptions): Promise<ChildProcessProxies> {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\treturn this.returnProxies((this.forkProvider || cp.fork)(modulePath, args, withEnv(options)));\n"
],
"file_path": "packages/protocol/src/node/modules/child_process.ts",
"type": "replace",
"edit_start_line_idx": 79
} | import { InitData, SharedProcessData } from "@coder/protocol";
class Paths {
private _appData: string | undefined;
private _defaultUserData: string | undefined;
private _socketPath: string | undefined;
private _extensionsDirectory: string | undefined;
private _builtInExtensionsDirectory: string | undefined;
private _workingDirectory: string | undefined;
public get appData(): string {
if (typeof this._appData === "undefined") {
throw new Error("trying to access appData before it has been set");
}
return this._appData;
}
public get defaultUserData(): string {
if (typeof this._defaultUserData === "undefined") {
throw new Error("trying to access defaultUserData before it has been set");
}
return this._defaultUserData;
}
public get socketPath(): string {
if (typeof this._socketPath === "undefined") {
throw new Error("trying to access socketPath before it has been set");
}
return this._socketPath;
}
public get extensionsDirectory(): string {
if (!this._extensionsDirectory) {
throw new Error("trying to access extensions directory before it has been set");
}
return this._extensionsDirectory;
}
public get builtInExtensionsDirectory(): string {
if (!this._builtInExtensionsDirectory) {
throw new Error("trying to access builtin extensions directory before it has been set");
}
return this._builtInExtensionsDirectory;
}
public get workingDirectory(): string {
if (!this._workingDirectory) {
throw new Error("trying to access working directory before it has been set");
}
return this._workingDirectory;
}
public initialize(data: InitData, sharedData: SharedProcessData): void {
process.env.VSCODE_LOGS = sharedData.logPath;
this._appData = data.dataDirectory;
this._defaultUserData = data.dataDirectory;
this._socketPath = sharedData.socketPath;
this._extensionsDirectory = data.extensionsDirectory;
this._builtInExtensionsDirectory = data.builtInExtensionsDirectory;
this._workingDirectory = data.workingDirectory;
}
}
export const _paths = new Paths();
export const getAppDataPath = (): string => _paths.appData;
export const getDefaultUserDataPath = (): string => _paths.defaultUserData;
export const getWorkingDirectory = (): string => _paths.workingDirectory;
export const getExtensionsDirectory = (): string => _paths.extensionsDirectory;
export const getBuiltInExtensionsDirectory = (): string => _paths.builtInExtensionsDirectory;
export const getSocketPath = (): string => _paths.socketPath;
| packages/vscode/src/fill/paths.ts | 0 | https://github.com/coder/code-server/commit/cdb900aca81006b88a92e4f933349a5496b3fd06 | [
0.0005699842004105449,
0.00022140057990327477,
0.00016907315875869244,
0.00017197444685734808,
0.00013176073844078928
] |
{
"id": 3,
"code_window": [
"\t}\n",
"\n",
"\tpublic async fork(modulePath: string, args?: string[], options?: cp.ForkOptions): Promise<ChildProcessProxies> {\n",
"\t\tpreserveEnv(options);\n",
"\n",
"\t\treturn this.returnProxies((this.forkProvider || cp.fork)(modulePath, args, options));\n",
"\t}\n",
"\n",
"\tpublic async spawn(command: string, args?: string[], options?: cp.SpawnOptions): Promise<ChildProcessProxies> {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\treturn this.returnProxies((this.forkProvider || cp.fork)(modulePath, args, withEnv(options)));\n"
],
"file_path": "packages/protocol/src/node/modules/child_process.ts",
"type": "replace",
"edit_start_line_idx": 79
} | import * as ts from "typescript";
import * as Lint from "tslint";
/**
* Rule for disallowing blank lines around the content of blocks.
*/
export class Rule extends Lint.Rules.AbstractRule {
public static BEFORE_FAILURE_STRING = "Blocks must not start with blank lines";
public static AFTER_FAILURE_STRING = "Blocks must not end with blank lines";
/**
* Apply the rule.
*/
public apply(sourceFile: ts.SourceFile): Lint.RuleFailure[] {
return this.applyWithWalker(new NoBlockPaddingWalker(sourceFile, this.getOptions()));
}
}
/**
* Walker for checking block padding.
*/
class NoBlockPaddingWalker extends Lint.RuleWalker {
/**
* Apply this rule to interfaces.
*/
public visitInterfaceDeclaration(node: ts.InterfaceDeclaration): void {
this.visitBlockNode(node);
super.visitInterfaceDeclaration(node);
}
/**
* Apply this rule to classes.
*/
public visitClassDeclaration(node: ts.ClassDeclaration): void {
this.visitBlockNode(node);
super.visitClassDeclaration(node);
}
/**
* Add failures to blank lines surrounding a block's content.
*/
private visitBlockNode(node: ts.ClassDeclaration | ts.InterfaceDeclaration): void {
const sourceFile = node.getSourceFile();
const children = node.getChildren();
const openBraceIndex = children.findIndex((n) => n.kind === ts.SyntaxKind.OpenBraceToken);
if (openBraceIndex !== -1) {
const nextToken = children[openBraceIndex + 1];
if (nextToken) {
const startLine = this.getStartIncludingComments(sourceFile, nextToken);
const openBraceToken = children[openBraceIndex];
if (ts.getLineAndCharacterOfPosition(sourceFile, openBraceToken.getEnd()).line + 1 < startLine) {
this.addFailureAt(openBraceToken.getEnd(), openBraceToken.getEnd(), Rule.BEFORE_FAILURE_STRING);
}
}
}
const closeBraceIndex = children.findIndex((n) => n.kind === ts.SyntaxKind.CloseBraceToken);
if (closeBraceIndex >= 2) {
const previousToken = children[closeBraceIndex - 1];
if (previousToken) {
let endLine = ts.getLineAndCharacterOfPosition(sourceFile, previousToken.getEnd()).line;
const closeBraceToken = children[closeBraceIndex];
if (this.getStartIncludingComments(sourceFile, closeBraceToken) > endLine + 1) {
this.addFailureAt(closeBraceToken.getStart(), closeBraceToken.getStart(), Rule.AFTER_FAILURE_STRING);
}
}
}
}
/**
* getStart() doesn't account for comments while this does.
*/
private getStartIncludingComments(sourceFile: ts.SourceFile, node: ts.Node): number {
// This gets the line the node starts on without counting comments.
let startLine = ts.getLineAndCharacterOfPosition(sourceFile, node.getStart()).line;
// Adjust the start line for the comments.
const comments = ts.getLeadingCommentRanges(sourceFile.text, node.pos) || [];
comments.forEach((c) => {
const commentStartLine = ts.getLineAndCharacterOfPosition(sourceFile, c.pos).line;
if (commentStartLine < startLine) {
startLine = commentStartLine;
}
});
return startLine;
}
}
| rules/src/noBlockPaddingRule.ts | 0 | https://github.com/coder/code-server/commit/cdb900aca81006b88a92e4f933349a5496b3fd06 | [
0.0001892496511572972,
0.00017672375543043017,
0.0001722496672300622,
0.0001756229466991499,
0.000004642269686883083
] |
{
"id": 3,
"code_window": [
"\t}\n",
"\n",
"\tpublic async fork(modulePath: string, args?: string[], options?: cp.ForkOptions): Promise<ChildProcessProxies> {\n",
"\t\tpreserveEnv(options);\n",
"\n",
"\t\treturn this.returnProxies((this.forkProvider || cp.fork)(modulePath, args, options));\n",
"\t}\n",
"\n",
"\tpublic async spawn(command: string, args?: string[], options?: cp.SpawnOptions): Promise<ChildProcessProxies> {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\treturn this.returnProxies((this.forkProvider || cp.fork)(modulePath, args, withEnv(options)));\n"
],
"file_path": "packages/protocol/src/node/modules/child_process.ts",
"type": "replace",
"edit_start_line_idx": 79
} | @import url("https://use.typekit.net/vzk7ygg.css");
html, body {
background-color: #FFFFFF;
min-height: 100%;
}
body {
font-family: 'aktiv-grotesk';
display: flex;
align-items: center;
justify-content: center;
height: calc(100vh - 20px);
margin: 0;
padding: 10px;
--mdc-theme-primary: #AAADA1;
--mdc-theme-secondary: #AAADA1;
&.in-app {
.back {
pointer-events: all;
opacity: 1;
}
}
}
.login {
box-shadow: 0 18px 80px 10px rgba(69, 65, 78, 0.08);
max-width: 328px;
width: 100%;
padding: 40px;
border-radius: 5px;
position: relative;
color: #575962;
.title {
margin-bottom: 0px;
font-size: 12px;
font-weight: 500;
letter-spacing: 1.5px;
line-height: 15px;
margin-bottom: 5px;
margin-top: 0px;
text-align: center;
text-transform: uppercase;
}
.subtitle {
text-align: center;
margin: 0;
font-size: 19px;
font-weight: bold;
line-height: 25px;
margin-bottom: 45px;
}
.mdc-text-field {
width: 100%;
background: none !important;
&::before {
background: none !important;
}
}
.mdc-form-field {
text-align: left;
font-size: 12px;
color: #797E84;
margin-top: 16px;
}
.mdc-button {
border-radius: 24px;
padding-left: 75px;
padding-right: 75px;
padding-top: 15px;
padding-bottom: 15px;
height: 48px;
margin: 0 auto;
display: block;
box-shadow: 0 12px 17px 2px rgba(171,173,163,0.14), 0 5px 22px 4px rgba(171,173,163,0.12), 0 7px 8px -4px rgba(171,173,163,0.2);
margin-top: 40px;
}
}
.mdc-text-field--focused:not(.mdc-text-field--disabled) .mdc-floating-label {
color: var(--mdc-theme-primary);
}
.mdc-floating-label--float-above {
transform: translateY(-70%) scale(0.75);
}
.mdc-text-field:not(.mdc-text-field--disabled):not(.mdc-text-field--outlined):not(.mdc-text-field--textarea) .mdc-text-field__input, .mdc-text-field:not(.mdc-text-field--disabled):not(.mdc-text-field--outlined):not(.mdc-text-field--textarea) .mdc-text-field__input:hover {
border-bottom-color: #EBEDF2;
}
.back {
position: absolute;
top: -50px;
left: -50px;
font-weight: bold;
opacity: 0;
pointer-events: none;
// transition: 500ms opacity ease;
}
#error-display {
box-sizing: border-box;
color: #bb2d0f;
font-size: 14px;
font-weight: 400;
letter-spacing: 0.3px;
line-height: 12px;
padding: 8px;
padding-bottom: 0;
padding-top: 20px;
text-align: center;
}
| packages/app/browser/src/app.scss | 0 | https://github.com/coder/code-server/commit/cdb900aca81006b88a92e4f933349a5496b3fd06 | [
0.0001789753878256306,
0.00017649757501203567,
0.00017425465921405703,
0.00017654385010246187,
0.0000013911034102420672
] |
{
"id": 4,
"code_window": [
"\t}\n",
"\n",
"\tpublic async spawn(command: string, args?: string[], options?: cp.SpawnOptions): Promise<ChildProcessProxies> {\n",
"\t\tpreserveEnv(options);\n",
"\n",
"\t\treturn this.returnProxies(cp.spawn(command, args, options));\n",
"\t}\n",
"\n",
"\tprivate returnProxies(process: cp.ChildProcess): ChildProcessProxies {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\treturn this.returnProxies(cp.spawn(command, args, withEnv(options)));\n"
],
"file_path": "packages/protocol/src/node/modules/child_process.ts",
"type": "replace",
"edit_start_line_idx": 85
} | import * as cp from "child_process";
import { ServerProxy } from "../../common/proxy";
import { preserveEnv } from "../../common/util";
import { WritableProxy, ReadableProxy } from "./stream";
// tslint:disable completed-docs
export type ForkProvider = (modulePath: string, args?: string[], options?: cp.ForkOptions) => cp.ChildProcess;
export class ChildProcessProxy extends ServerProxy<cp.ChildProcess> {
public constructor(instance: cp.ChildProcess) {
super({
bindEvents: ["close", "disconnect", "error", "exit", "message"],
doneEvents: ["close"],
instance,
});
}
public async kill(signal?: string): Promise<void> {
this.instance.kill(signal);
}
public async disconnect(): Promise<void> {
this.instance.disconnect();
}
public async ref(): Promise<void> {
this.instance.ref();
}
public async unref(): Promise<void> {
this.instance.unref();
}
// tslint:disable-next-line no-any
public async send(message: any): Promise<void> {
return new Promise((resolve, reject): void => {
this.instance.send(message, (error) => {
if (error) {
reject(error);
} else {
resolve();
}
});
});
}
public async getPid(): Promise<number> {
return this.instance.pid;
}
public async dispose(): Promise<void> {
this.instance.kill();
setTimeout(() => this.instance.kill("SIGKILL"), 5000); // Double tap.
await super.dispose();
}
}
export interface ChildProcessProxies {
childProcess: ChildProcessProxy;
stdin?: WritableProxy | null;
stdout?: ReadableProxy | null;
stderr?: ReadableProxy | null;
}
export class ChildProcessModuleProxy {
public constructor(private readonly forkProvider?: ForkProvider) {}
public async exec(
command: string,
options?: { encoding?: string | null } & cp.ExecOptions | null,
callback?: ((error: cp.ExecException | null, stdin: string | Buffer, stdout: string | Buffer) => void),
): Promise<ChildProcessProxies> {
preserveEnv(options);
return this.returnProxies(cp.exec(command, options, callback));
}
public async fork(modulePath: string, args?: string[], options?: cp.ForkOptions): Promise<ChildProcessProxies> {
preserveEnv(options);
return this.returnProxies((this.forkProvider || cp.fork)(modulePath, args, options));
}
public async spawn(command: string, args?: string[], options?: cp.SpawnOptions): Promise<ChildProcessProxies> {
preserveEnv(options);
return this.returnProxies(cp.spawn(command, args, options));
}
private returnProxies(process: cp.ChildProcess): ChildProcessProxies {
return {
childProcess: new ChildProcessProxy(process),
stdin: process.stdin && new WritableProxy(process.stdin),
// Child processes streams appear to immediately flow so we need to bind
// to the data event right away.
stdout: process.stdout && new ReadableProxy(process.stdout, ["data"]),
stderr: process.stderr && new ReadableProxy(process.stderr, ["data"]),
};
}
}
| packages/protocol/src/node/modules/child_process.ts | 1 | https://github.com/coder/code-server/commit/cdb900aca81006b88a92e4f933349a5496b3fd06 | [
0.990404486656189,
0.1756589561700821,
0.00016851627151481807,
0.0021255577448755503,
0.3644549548625946
] |
{
"id": 4,
"code_window": [
"\t}\n",
"\n",
"\tpublic async spawn(command: string, args?: string[], options?: cp.SpawnOptions): Promise<ChildProcessProxies> {\n",
"\t\tpreserveEnv(options);\n",
"\n",
"\t\treturn this.returnProxies(cp.spawn(command, args, options));\n",
"\t}\n",
"\n",
"\tprivate returnProxies(process: cp.ChildProcess): ChildProcessProxies {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\treturn this.returnProxies(cp.spawn(command, args, withEnv(options)));\n"
],
"file_path": "packages/protocol/src/node/modules/child_process.ts",
"type": "replace",
"edit_start_line_idx": 85
} | {
"name": "@coder/tunnel",
"main": "src/tunnel.ts"
} | packages/tunnel/package.json | 0 | https://github.com/coder/code-server/commit/cdb900aca81006b88a92e4f933349a5496b3fd06 | [
0.0001731075026327744,
0.0001731075026327744,
0.0001731075026327744,
0.0001731075026327744,
0
] |
{
"id": 4,
"code_window": [
"\t}\n",
"\n",
"\tpublic async spawn(command: string, args?: string[], options?: cp.SpawnOptions): Promise<ChildProcessProxies> {\n",
"\t\tpreserveEnv(options);\n",
"\n",
"\t\treturn this.returnProxies(cp.spawn(command, args, options));\n",
"\t}\n",
"\n",
"\tprivate returnProxies(process: cp.ChildProcess): ChildProcessProxies {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\treturn this.returnProxies(cp.spawn(command, args, withEnv(options)));\n"
],
"file_path": "packages/protocol/src/node/modules/child_process.ts",
"type": "replace",
"edit_start_line_idx": 85
} | import { Emitter } from "@coder/events";
import "./dialog.scss";
export interface IDialogOptions {
message?: string;
detail?: string;
buttons?: string[];
input?: {
value: string;
selection?: {
start: number;
end: number;
};
};
}
export interface IDialogAction {
buttonIndex?: number;
key?: IKey;
}
export enum IKey {
Enter = "Enter",
Escape = "Escape",
}
export class Dialog {
private readonly overlay: HTMLElement;
private cachedActiveElement: HTMLElement | undefined;
private input: HTMLInputElement | undefined;
private errors: HTMLElement;
private buttons: HTMLElement[] | undefined;
private readonly msgBox: HTMLElement;
private actionEmitter = new Emitter<IDialogAction>();
public onAction = this.actionEmitter.event;
public constructor(private readonly options: IDialogOptions) {
this.msgBox = document.createElement("div");
this.msgBox.classList.add("msgbox");
if (this.options.message) {
const messageDiv = document.createElement("div");
messageDiv.classList.add("msg");
messageDiv.innerText = this.options.message;
this.msgBox.appendChild(messageDiv);
}
if (this.options.detail) {
const detailDiv = document.createElement("div");
detailDiv.classList.add("detail");
detailDiv.innerText = this.options.detail;
this.msgBox.appendChild(detailDiv);
}
if (this.options.input) {
this.msgBox.classList.add("input");
this.input = document.createElement("input");
this.input.classList.add("input");
this.input.value = this.options.input.value;
this.input.addEventListener("keydown", (event) => {
if (event.key === IKey.Enter) {
event.preventDefault();
this.actionEmitter.emit({
buttonIndex: undefined,
key: IKey.Enter,
});
}
});
this.msgBox.appendChild(this.input);
}
this.errors = document.createElement("div");
this.errors.classList.add("errors");
if (this.options.buttons && this.options.buttons.length > 0) {
this.buttons = this.options.buttons.map((buttonText, buttonIndex) => {
const button = document.createElement("button");
// TODO: support mnemonics.
button.innerText = buttonText.replace("&&", "");
button.addEventListener("click", () => {
this.actionEmitter.emit({
buttonIndex,
key: undefined,
});
});
return button;
});
const buttonWrapper = document.createElement("div");
buttonWrapper.classList.add("button-wrapper");
this.buttons.forEach((b) => buttonWrapper.appendChild(b));
this.msgBox.appendChild(buttonWrapper);
}
this.overlay = document.createElement("div");
this.overlay.className = "msgbox-overlay";
this.overlay.appendChild(this.msgBox);
setTimeout(() => {
this.overlay.style.opacity = "1";
});
}
/**
* Input value if this dialog has an input.
*/
public get inputValue(): string | undefined {
return this.input ? this.input.value : undefined;
}
/**
* Display or remove an error.
*/
public set error(error: string | undefined) {
while (this.errors.lastChild) {
this.errors.removeChild(this.errors.lastChild);
}
if (error) {
const errorDiv = document.createElement("error");
errorDiv.innerText = error;
this.errors.appendChild(errorDiv);
this.msgBox.appendChild(this.errors);
}
}
/**
* Show the dialog.
*/
public show(): void {
if (!this.cachedActiveElement) {
this.cachedActiveElement = document.activeElement as HTMLElement;
(document.querySelector(".monaco-workbench") || document.body).appendChild(this.overlay);
document.addEventListener("keydown", this.onKeydown);
if (this.input) {
this.input.focus();
if (this.options.input && this.options.input.selection) {
this.input.setSelectionRange(
this.options.input.selection.start,
this.options.input.selection.end,
);
}
} else if (this.buttons) {
this.buttons[0].focus();
}
}
}
/**
* Remove the dialog and clean up.
*/
public hide(): void {
if (this.cachedActiveElement) {
this.overlay.remove();
document.removeEventListener("keydown", this.onKeydown);
this.cachedActiveElement.focus();
this.cachedActiveElement = undefined;
}
}
/**
* Capture escape.
*/
private onKeydown = (event: KeyboardEvent): void => {
if (event.key === "Escape") {
event.preventDefault();
event.stopPropagation();
this.actionEmitter.emit({
buttonIndex: undefined,
key: IKey.Escape,
});
}
}
}
| packages/ide/src/fill/dialog.ts | 0 | https://github.com/coder/code-server/commit/cdb900aca81006b88a92e4f933349a5496b3fd06 | [
0.00018944355542771518,
0.00017267656221520156,
0.00016784148465376347,
0.0001722340239211917,
0.000004803118372365134
] |
{
"id": 4,
"code_window": [
"\t}\n",
"\n",
"\tpublic async spawn(command: string, args?: string[], options?: cp.SpawnOptions): Promise<ChildProcessProxies> {\n",
"\t\tpreserveEnv(options);\n",
"\n",
"\t\treturn this.returnProxies(cp.spawn(command, args, options));\n",
"\t}\n",
"\n",
"\tprivate returnProxies(process: cp.ChildProcess): ChildProcessProxies {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\t\treturn this.returnProxies(cp.spawn(command, args, withEnv(options)));\n"
],
"file_path": "packages/protocol/src/node/modules/child_process.ts",
"type": "replace",
"edit_start_line_idx": 85
} | import * as cp from "child_process";
import {field, Logger, logger, time} from "@coder/logger";
export interface CommandResult {
readonly exitCode: number;
readonly stdout: string;
readonly stderr: string;
}
const execute = (command: string, args: string[] = [], options: cp.SpawnOptions, logger: Logger): Promise<CommandResult> => {
let resolve: (result: CommandResult) => void;
const prom = new Promise<CommandResult>((res): void => {
resolve = res;
});
const stdout: string[] = [];
const stderr: string[] = [];
const complete = (exitCode: number): void => {
resolve({
stderr: stderr.join(""),
stdout: stdout.join(""),
exitCode,
});
};
logger.info(`Executing '${command} ${JSON.stringify(args)}'`, field("options", options));
const proc = cp.spawn(command, args.length > 0 ? args : [], options);
proc.on("close", (code) => {
complete(code);
});
proc.on("exit", (code) => {
complete(code!);
});
proc.stdout.on("data", (d) => {
stdout.push(d.toString());
logger.debug("stdio", field("stdout", d.toString()));
});
proc.stderr.on("data", (d) => {
stderr.push(d.toString());
logger.debug("stdio", field("stderr", d.toString()));
});
return prom;
};
// tslint:disable-next-line no-any
export type TaskFunction = (runner: Runner, ...args: any[]) => void | Promise<void>;
export interface Runner {
cwd: string;
execute(command: string, args?: string[], env?: object): Promise<CommandResult>;
}
export interface Task {
readonly name: string;
readonly func: TaskFunction;
}
const tasks = new Map<string, Task>();
const activated = new Map<string, Promise<void>>();
export const register = (name: string, func: TaskFunction): () => void | Promise<void> => {
if (tasks.has(name)) {
throw new Error(`Task "${name}" already registered`);
}
tasks.set(name, {
name,
func,
});
return (): void | Promise<void> => {
return run(name);
};
};
export const run = (name: string = process.argv[2]): void | Promise<void> => {
const task = tasks.get(name);
if (!task) {
logger.error("Task not found.", field("name", name), field("available", Array.from(tasks.keys())));
return process.exit(1);
}
if (activated.has(name)) {
return activated.get(name);
}
let cwd: string = process.cwd();
const log = logger.named(name);
const timer = time(Number.MAX_SAFE_INTEGER);
let outputTimer: NodeJS.Timer | undefined;
log.info("Starting...");
const prom = task.func({
set cwd(path: string) {
cwd = path;
},
execute(command: string, args: string[] = [], env?: object): Promise<CommandResult> {
const prom = execute(command, args, {
cwd,
env: env as NodeJS.ProcessEnv,
}, log);
return prom.then((result: CommandResult) => {
if (result.exitCode != 0) {
log.error("failed",
field("exitCode", result.exitCode),
field("stdout", result.stdout),
field("stderr", result.stderr)
);
}
return result;
});
},
}, ...process.argv.slice(3));
if (prom) {
activated.set(name, prom);
const doOutput = (): void => {
outputTimer = setTimeout(() => {
log.info("Still running...");
doOutput();
}, 60 * 1000 * 5);
};
doOutput();
prom.then(() => {
if (outputTimer) {
clearTimeout(outputTimer);
}
log.info("Completed!", field("time", timer));
}).catch((ex) => {
activated.delete(name);
log.error(`Failed: ${ex.message}`);
log.error(`Stack: ${ex.stack}`);
return process.exit(1);
});
}
return prom;
};
| packages/runner/src/runner.ts | 0 | https://github.com/coder/code-server/commit/cdb900aca81006b88a92e4f933349a5496b3fd06 | [
0.9981794357299805,
0.07123813778162003,
0.00016527742263861,
0.00017709771054796875,
0.24821488559246063
] |
{
"id": 5,
"code_window": [
"/// <reference path=\"../../../../../lib/vscode/src/typings/node-pty.d.ts\" />\n",
"import { EventEmitter } from \"events\";\n",
"import * as pty from \"node-pty\";\n",
"import { ServerProxy } from \"../../common/proxy\";\n",
"import { preserveEnv } from \"../../common/util\";\n",
"\n",
"// tslint:disable completed-docs\n",
"\n",
"/**\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { withEnv } from \"../../common/util\";\n"
],
"file_path": "packages/protocol/src/node/modules/node-pty.ts",
"type": "replace",
"edit_start_line_idx": 4
} | import { Argument, Module as ProtoModule, WorkingInit } from "../proto";
import { OperatingSystem } from "../common/connection";
import { ClientServerProxy, Module, ServerProxy } from "./proxy";
// tslint:disable no-any
/**
* Return true if we're in a browser environment (including web workers).
*/
export const isBrowserEnvironment = (): boolean => {
return typeof process === "undefined" || typeof process.stdout === "undefined";
};
/**
* Escape a path. This prevents any issues with file names that have quotes,
* spaces, braces, etc.
*/
export const escapePath = (path: string): string => {
return `'${path.replace(/'/g, "'\\''")}'`;
};
export type EventCallback = (event: string, ...args: any[]) => void;
export type IEncodingOptions = {
encoding?: BufferEncoding | null;
flag?: string;
mode?: string;
persistent?: boolean;
recursive?: boolean;
} | BufferEncoding | undefined | null;
export type IEncodingOptionsCallback = IEncodingOptions | ((err: NodeJS.ErrnoException, ...args: any[]) => void);
/**
* Convert an argument to proto.
* If sending a function is possible, provide `storeFunction`.
* If sending a proxy is possible, provide `storeProxy`.
*/
export const argumentToProto = <P = ClientServerProxy | ServerProxy>(
value: any,
storeFunction?: (fn: () => void) => number,
storeProxy?: (proxy: P) => number | Module,
): Argument => {
const convert = (currentValue: any): Argument => {
const message = new Argument();
if (isProxy<P>(currentValue)) {
if (!storeProxy) {
throw new Error("no way to serialize proxy");
}
const arg = new Argument.ProxyValue();
const id = storeProxy(currentValue);
if (typeof id === "string") {
throw new Error("unable to serialize module proxy");
}
arg.setId(id);
message.setProxy(arg);
} else if (currentValue instanceof Error
|| (currentValue && typeof currentValue.message !== "undefined"
&& typeof currentValue.stack !== "undefined")) {
const arg = new Argument.ErrorValue();
arg.setMessage(currentValue.message);
arg.setStack(currentValue.stack);
arg.setCode(currentValue.code);
message.setError(arg);
} else if (currentValue instanceof Uint8Array || currentValue instanceof Buffer) {
const arg = new Argument.BufferValue();
arg.setData(currentValue);
message.setBuffer(arg);
} else if (Array.isArray(currentValue)) {
const arg = new Argument.ArrayValue();
arg.setDataList(currentValue.map(convert));
message.setArray(arg);
} else if (currentValue instanceof Date
|| (currentValue && typeof currentValue.getTime === "function")) {
const arg = new Argument.DateValue();
arg.setDate(currentValue.toString());
message.setDate(arg);
} else if (currentValue !== null && typeof currentValue === "object") {
const arg = new Argument.ObjectValue();
const map = arg.getDataMap();
Object.keys(currentValue).forEach((key) => {
map.set(key, convert(currentValue[key]));
});
message.setObject(arg);
} else if (currentValue === null) {
message.setNull(new Argument.NullValue());
} else {
switch (typeof currentValue) {
case "undefined":
message.setUndefined(new Argument.UndefinedValue());
break;
case "function":
if (!storeFunction) {
throw new Error("no way to serialize function");
}
const arg = new Argument.FunctionValue();
arg.setId(storeFunction(currentValue));
message.setFunction(arg);
break;
case "number":
message.setNumber(currentValue);
break;
case "string":
message.setString(currentValue);
break;
case "boolean":
message.setBoolean(currentValue);
break;
default:
throw new Error(`cannot convert ${typeof currentValue} to proto`);
}
}
return message;
};
return convert(value);
};
/**
* Convert proto to an argument.
* If running a remote callback is supported, provide `runCallback`.
* If using a remote proxy is supported, provide `createProxy`.
*/
export const protoToArgument = (
message?: Argument,
runCallback?: (id: number, args: any[]) => void,
createProxy?: (id: number) => ServerProxy,
): any => {
const convert = (currentMessage: Argument): any => {
switch (currentMessage.getMsgCase()) {
case Argument.MsgCase.ERROR:
const errorMessage = currentMessage.getError()!;
const error = new Error(errorMessage.getMessage());
(error as NodeJS.ErrnoException).code = errorMessage.getCode();
(error as any).originalStack = errorMessage.getStack();
return error;
case Argument.MsgCase.BUFFER:
return Buffer.from(currentMessage.getBuffer()!.getData() as Uint8Array);
case Argument.MsgCase.ARRAY:
return currentMessage.getArray()!.getDataList().map((a) => convert(a));
case Argument.MsgCase.PROXY:
if (!createProxy) {
throw new Error("no way to create proxy");
}
return createProxy(currentMessage.getProxy()!.getId());
case Argument.MsgCase.DATE:
return new Date(currentMessage.getDate()!.getDate());
case Argument.MsgCase.OBJECT:
const obj: { [Key: string]: any } = {};
currentMessage.getObject()!.getDataMap().forEach((argument, key) => {
obj[key] = convert(argument);
});
return obj;
case Argument.MsgCase.UNDEFINED:
return undefined;
case Argument.MsgCase.NULL:
return null;
case Argument.MsgCase.FUNCTION:
if (!runCallback) {
throw new Error("no way to run remote callback");
}
return (...args: any[]): void => {
return runCallback(currentMessage.getFunction()!.getId(), args);
};
case Argument.MsgCase.NUMBER:
return currentMessage.getNumber();
case Argument.MsgCase.STRING:
return currentMessage.getString();
case Argument.MsgCase.BOOLEAN:
return currentMessage.getBoolean();
default:
throw new Error("cannot convert unexpected proto to argument");
}
};
return message && convert(message);
};
export const protoToModule = (protoModule: ProtoModule): Module => {
switch (protoModule) {
case ProtoModule.CHILDPROCESS: return Module.ChildProcess;
case ProtoModule.FS: return Module.Fs;
case ProtoModule.NET: return Module.Net;
case ProtoModule.NODEPTY: return Module.NodePty;
case ProtoModule.SPDLOG: return Module.Spdlog;
case ProtoModule.TRASH: return Module.Trash;
default: throw new Error(`invalid module ${protoModule}`);
}
};
export const moduleToProto = (moduleName: Module): ProtoModule => {
switch (moduleName) {
case Module.ChildProcess: return ProtoModule.CHILDPROCESS;
case Module.Fs: return ProtoModule.FS;
case Module.Net: return ProtoModule.NET;
case Module.NodePty: return ProtoModule.NODEPTY;
case Module.Spdlog: return ProtoModule.SPDLOG;
case Module.Trash: return ProtoModule.TRASH;
default: throw new Error(`invalid module "${moduleName}"`);
}
};
export const protoToOperatingSystem = (protoOp: WorkingInit.OperatingSystem): OperatingSystem => {
switch (protoOp) {
case WorkingInit.OperatingSystem.WINDOWS: return OperatingSystem.Windows;
case WorkingInit.OperatingSystem.LINUX: return OperatingSystem.Linux;
case WorkingInit.OperatingSystem.MAC: return OperatingSystem.Mac;
default: throw new Error(`unsupported operating system ${protoOp}`);
}
};
export const platformToProto = (platform: NodeJS.Platform): WorkingInit.OperatingSystem => {
switch (platform) {
case "win32": return WorkingInit.OperatingSystem.WINDOWS;
case "linux": return WorkingInit.OperatingSystem.LINUX;
case "darwin": return WorkingInit.OperatingSystem.MAC;
default: throw new Error(`unrecognized platform "${platform}"`);
}
};
export const isProxy = <P = ClientServerProxy | ServerProxy>(value: any): value is P => {
return value && typeof value === "object" && typeof value.onEvent === "function";
};
export const isPromise = (value: any): value is Promise<any> => {
return typeof value.then === "function" && typeof value.catch === "function";
};
/**
* When spawning VS Code tries to preserve the environment but since it's in
* the browser, it doesn't work.
*/
export const preserveEnv = (options?: { env?: NodeJS.ProcessEnv } | null): void => {
if (options && options.env) {
options.env = { ...process.env, ...options.env };
}
};
| packages/protocol/src/common/util.ts | 1 | https://github.com/coder/code-server/commit/cdb900aca81006b88a92e4f933349a5496b3fd06 | [
0.005194205325096846,
0.0003917013527825475,
0.00016359926667064428,
0.00017416362243238837,
0.0009814727818593383
] |
{
"id": 5,
"code_window": [
"/// <reference path=\"../../../../../lib/vscode/src/typings/node-pty.d.ts\" />\n",
"import { EventEmitter } from \"events\";\n",
"import * as pty from \"node-pty\";\n",
"import { ServerProxy } from \"../../common/proxy\";\n",
"import { preserveEnv } from \"../../common/util\";\n",
"\n",
"// tslint:disable completed-docs\n",
"\n",
"/**\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { withEnv } from \"../../common/util\";\n"
],
"file_path": "packages/protocol/src/node/modules/node-pty.ts",
"type": "replace",
"edit_start_line_idx": 4
} | import * as cp from "child_process";
import {field, Logger, logger, time} from "@coder/logger";
export interface CommandResult {
readonly exitCode: number;
readonly stdout: string;
readonly stderr: string;
}
const execute = (command: string, args: string[] = [], options: cp.SpawnOptions, logger: Logger): Promise<CommandResult> => {
let resolve: (result: CommandResult) => void;
const prom = new Promise<CommandResult>((res): void => {
resolve = res;
});
const stdout: string[] = [];
const stderr: string[] = [];
const complete = (exitCode: number): void => {
resolve({
stderr: stderr.join(""),
stdout: stdout.join(""),
exitCode,
});
};
logger.info(`Executing '${command} ${JSON.stringify(args)}'`, field("options", options));
const proc = cp.spawn(command, args.length > 0 ? args : [], options);
proc.on("close", (code) => {
complete(code);
});
proc.on("exit", (code) => {
complete(code!);
});
proc.stdout.on("data", (d) => {
stdout.push(d.toString());
logger.debug("stdio", field("stdout", d.toString()));
});
proc.stderr.on("data", (d) => {
stderr.push(d.toString());
logger.debug("stdio", field("stderr", d.toString()));
});
return prom;
};
// tslint:disable-next-line no-any
export type TaskFunction = (runner: Runner, ...args: any[]) => void | Promise<void>;
export interface Runner {
cwd: string;
execute(command: string, args?: string[], env?: object): Promise<CommandResult>;
}
export interface Task {
readonly name: string;
readonly func: TaskFunction;
}
const tasks = new Map<string, Task>();
const activated = new Map<string, Promise<void>>();
export const register = (name: string, func: TaskFunction): () => void | Promise<void> => {
if (tasks.has(name)) {
throw new Error(`Task "${name}" already registered`);
}
tasks.set(name, {
name,
func,
});
return (): void | Promise<void> => {
return run(name);
};
};
export const run = (name: string = process.argv[2]): void | Promise<void> => {
const task = tasks.get(name);
if (!task) {
logger.error("Task not found.", field("name", name), field("available", Array.from(tasks.keys())));
return process.exit(1);
}
if (activated.has(name)) {
return activated.get(name);
}
let cwd: string = process.cwd();
const log = logger.named(name);
const timer = time(Number.MAX_SAFE_INTEGER);
let outputTimer: NodeJS.Timer | undefined;
log.info("Starting...");
const prom = task.func({
set cwd(path: string) {
cwd = path;
},
execute(command: string, args: string[] = [], env?: object): Promise<CommandResult> {
const prom = execute(command, args, {
cwd,
env: env as NodeJS.ProcessEnv,
}, log);
return prom.then((result: CommandResult) => {
if (result.exitCode != 0) {
log.error("failed",
field("exitCode", result.exitCode),
field("stdout", result.stdout),
field("stderr", result.stderr)
);
}
return result;
});
},
}, ...process.argv.slice(3));
if (prom) {
activated.set(name, prom);
const doOutput = (): void => {
outputTimer = setTimeout(() => {
log.info("Still running...");
doOutput();
}, 60 * 1000 * 5);
};
doOutput();
prom.then(() => {
if (outputTimer) {
clearTimeout(outputTimer);
}
log.info("Completed!", field("time", timer));
}).catch((ex) => {
activated.delete(name);
log.error(`Failed: ${ex.message}`);
log.error(`Stack: ${ex.stack}`);
return process.exit(1);
});
}
return prom;
};
| packages/runner/src/runner.ts | 0 | https://github.com/coder/code-server/commit/cdb900aca81006b88a92e4f933349a5496b3fd06 | [
0.0005158991552889347,
0.00019610018352977931,
0.00017042172839865088,
0.00017397059127688408,
0.00008547995093977079
] |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.