diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/.bin/mime b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/.bin/mime deleted file mode 120000 index fbb7ee0eed..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/.bin/mime +++ /dev/null @@ -1 +0,0 @@ -../mime/cli.js \ No newline at end of file diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/long/LICENSE b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/long/LICENSE deleted file mode 100644 index 4b1ad51b2f..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/long/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ - MIT License - - Copyright (c) Microsoft Corporation. All rights reserved. - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in all - copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - SOFTWARE diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/long/README.md b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/long/README.md deleted file mode 100644 index 1136e4f809..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/long/README.md +++ /dev/null @@ -1,16 +0,0 @@ -# Installation -> `npm install --save @types/long` - -# Summary -This package contains type definitions for long.js (https://github.com/dcodeIO/long.js). - -# Details -Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/long. - -### Additional Details - * Last updated: Wed, 22 Jan 2020 19:19:46 GMT - * Dependencies: none - * Global values: `Long` - -# Credits -These definitions were written by Peter Kooijmans (https://github.com/peterkooijmans). diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/long/index.d.ts b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/long/index.d.ts deleted file mode 100644 index 39f8ab508e..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/long/index.d.ts +++ /dev/null @@ -1,389 +0,0 @@ -// Type definitions for long.js 4.0.0 -// Project: https://github.com/dcodeIO/long.js -// Definitions by: Peter Kooijmans -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// Definitions by: Denis Cappellin - -export = Long; -export as namespace Long; - -declare const Long: Long.LongConstructor; -type Long = Long.Long; -declare namespace Long { - interface LongConstructor { - /** - * Constructs a 64 bit two's-complement integer, given its low and high 32 bit values as signed integers. See the from* functions below for more convenient ways of constructing Longs. - */ - new( low: number, high?: number, unsigned?: boolean ): Long; - prototype: Long; - /** - * Maximum unsigned value. - */ - MAX_UNSIGNED_VALUE: Long; - - /** - * Maximum signed value. - */ - MAX_VALUE: Long; - - /** - * Minimum signed value. - */ - MIN_VALUE: Long; - - /** - * Signed negative one. - */ - NEG_ONE: Long; - - /** - * Signed one. - */ - ONE: Long; - - /** - * Unsigned one. - */ - UONE: Long; - - /** - * Unsigned zero. - */ - UZERO: Long; - - /** - * Signed zero - */ - ZERO: Long; - - /** - * Returns a Long representing the 64 bit integer that comes by concatenating the given low and high bits. Each is assumed to use 32 bits. - */ - fromBits( lowBits:number, highBits:number, unsigned?:boolean ): Long; - - /** - * Returns a Long representing the given 32 bit integer value. - */ - fromInt( value: number, unsigned?: boolean ): Long; - - /** - * Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned. - */ - fromNumber( value: number, unsigned?: boolean ): Long; - - /** - * Returns a Long representation of the given string, written using the specified radix. - */ - fromString( str: string, unsigned?: boolean | number, radix?: number ): Long; - - /** - * Creates a Long from its byte representation. - */ - fromBytes( bytes: number[], unsigned?: boolean, le?: boolean ): Long; - - /** - * Creates a Long from its little endian byte representation. - */ - fromBytesLE( bytes: number[], unsigned?: boolean ): Long; - - /** - * Creates a Long from its little endian byte representation. - */ - fromBytesBE( bytes: number[], unsigned?: boolean ): Long; - - /** - * Tests if the specified object is a Long. - */ - isLong( obj: any ): obj is Long; - - /** - * Converts the specified value to a Long. - */ - fromValue( val: Long | number | string | {low: number, high: number, unsigned: boolean} ): Long; - } - interface Long - { - /** - * The high 32 bits as a signed value. - */ - high: number; - - /** - * The low 32 bits as a signed value. - */ - low: number; - - /** - * Whether unsigned or not. - */ - unsigned: boolean; - - /** - * Returns the sum of this and the specified Long. - */ - add( addend: number | Long | string ): Long; - - /** - * Returns the bitwise AND of this Long and the specified. - */ - and( other: Long | number | string ): Long; - - /** - * Compares this Long's value with the specified's. - */ - compare( other: Long | number | string ): number; - - /** - * Compares this Long's value with the specified's. - */ - comp( other: Long | number | string ): number; - - /** - * Returns this Long divided by the specified. - */ - divide( divisor: Long | number | string ): Long; - - /** - * Returns this Long divided by the specified. - */ - div( divisor: Long | number | string ): Long; - - /** - * Tests if this Long's value equals the specified's. - */ - equals( other: Long | number | string ): boolean; - - /** - * Tests if this Long's value equals the specified's. - */ - eq( other: Long | number | string ): boolean; - - /** - * Gets the high 32 bits as a signed integer. - */ - getHighBits(): number; - - /** - * Gets the high 32 bits as an unsigned integer. - */ - getHighBitsUnsigned(): number; - - /** - * Gets the low 32 bits as a signed integer. - */ - getLowBits(): number; - - /** - * Gets the low 32 bits as an unsigned integer. - */ - getLowBitsUnsigned(): number; - - /** - * Gets the number of bits needed to represent the absolute value of this Long. - */ - getNumBitsAbs(): number; - - /** - * Tests if this Long's value is greater than the specified's. - */ - greaterThan( other: Long | number | string ): boolean; - - /** - * Tests if this Long's value is greater than the specified's. - */ - gt( other: Long | number | string ): boolean; - - /** - * Tests if this Long's value is greater than or equal the specified's. - */ - greaterThanOrEqual( other: Long | number | string ): boolean; - - /** - * Tests if this Long's value is greater than or equal the specified's. - */ - gte( other: Long | number | string ): boolean; - - /** - * Tests if this Long's value is even. - */ - isEven(): boolean; - - /** - * Tests if this Long's value is negative. - */ - isNegative(): boolean; - - /** - * Tests if this Long's value is odd. - */ - isOdd(): boolean; - - /** - * Tests if this Long's value is positive. - */ - isPositive(): boolean; - - /** - * Tests if this Long's value equals zero. - */ - isZero(): boolean; - - /** - * Tests if this Long's value is less than the specified's. - */ - lessThan( other: Long | number | string ): boolean; - - /** - * Tests if this Long's value is less than the specified's. - */ - lt( other: Long | number | string ): boolean; - - /** - * Tests if this Long's value is less than or equal the specified's. - */ - lessThanOrEqual( other: Long | number | string ): boolean; - - /** - * Tests if this Long's value is less than or equal the specified's. - */ - lte( other: Long | number | string ): boolean; - - /** - * Returns this Long modulo the specified. - */ - modulo( other: Long | number | string ): Long; - - /** - * Returns this Long modulo the specified. - */ - mod( other: Long | number | string ): Long; - - /** - * Returns the product of this and the specified Long. - */ - multiply( multiplier: Long | number | string ): Long; - - /** - * Returns the product of this and the specified Long. - */ - mul( multiplier: Long | number | string ): Long; - - /** - * Negates this Long's value. - */ - negate(): Long; - - /** - * Negates this Long's value. - */ - neg(): Long; - - /** - * Returns the bitwise NOT of this Long. - */ - not(): Long; - - /** - * Tests if this Long's value differs from the specified's. - */ - notEquals( other: Long | number | string ): boolean; - - /** - * Tests if this Long's value differs from the specified's. - */ - neq( other: Long | number | string ): boolean; - - /** - * Returns the bitwise OR of this Long and the specified. - */ - or( other: Long | number | string ): Long; - - /** - * Returns this Long with bits shifted to the left by the given amount. - */ - shiftLeft( numBits: number | Long ): Long; - - /** - * Returns this Long with bits shifted to the left by the given amount. - */ - shl( numBits: number | Long ): Long; - - /** - * Returns this Long with bits arithmetically shifted to the right by the given amount. - */ - shiftRight( numBits: number | Long ): Long; - - /** - * Returns this Long with bits arithmetically shifted to the right by the given amount. - */ - shr( numBits: number | Long ): Long; - - /** - * Returns this Long with bits logically shifted to the right by the given amount. - */ - shiftRightUnsigned( numBits: number | Long ): Long; - - /** - * Returns this Long with bits logically shifted to the right by the given amount. - */ - shru( numBits: number | Long ): Long; - - /** - * Returns the difference of this and the specified Long. - */ - subtract( subtrahend: number | Long | string ): Long; - - /** - * Returns the difference of this and the specified Long. - */ - sub( subtrahend: number | Long |string ): Long; - - /** - * Converts the Long to a 32 bit integer, assuming it is a 32 bit integer. - */ - toInt(): number; - - /** - * Converts the Long to a the nearest floating-point representation of this value (double, 53 bit mantissa). - */ - toNumber(): number; - - /** - * Converts this Long to its byte representation. - */ - - toBytes( le?: boolean ): number[]; - - /** - * Converts this Long to its little endian byte representation. - */ - - toBytesLE(): number[]; - - /** - * Converts this Long to its big endian byte representation. - */ - - toBytesBE(): number[]; - - /** - * Converts this Long to signed. - */ - toSigned(): Long; - - /** - * Converts the Long to a string written in the specified radix. - */ - toString( radix?: number ): string; - - /** - * Converts this Long to unsigned. - */ - toUnsigned(): Long; - - /** - * Returns the bitwise XOR of this Long and the given one. - */ - xor( other: Long | number | string ): Long; - } -} diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/long/package.json b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/long/package.json deleted file mode 100644 index 5c7b58c464..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/long/package.json +++ /dev/null @@ -1,53 +0,0 @@ -{ - "_from": "@types/long@^4.0.0", - "_id": "@types/long@4.0.1", - "_inBundle": false, - "_integrity": "sha512-5tXH6Bx/kNGd3MgffdmP4dy2Z+G4eaXw0SE81Tq3BNadtnMR5/ySMzX4SLEzHJzSmPNn4HIdpQsBvXMUykr58w==", - "_location": "/@types/long", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "@types/long@^4.0.0", - "name": "@types/long", - "escapedName": "@types%2flong", - "scope": "@types", - "rawSpec": "^4.0.0", - "saveSpec": null, - "fetchSpec": "^4.0.0" - }, - "_requiredBy": [ - "/cassandra-driver" - ], - "_resolved": "https://registry.npmjs.org/@types/long/-/long-4.0.1.tgz", - "_shasum": "459c65fa1867dafe6a8f322c4c51695663cc55e9", - "_spec": "@types/long@^4.0.0", - "_where": "/home/jan/Documents/skweb/node_modules/cassandra-driver", - "bugs": { - "url": "https://github.com/DefinitelyTyped/DefinitelyTyped/issues" - }, - "bundleDependencies": false, - "contributors": [ - { - "name": "Peter Kooijmans", - "url": "https://github.com/peterkooijmans" - } - ], - "dependencies": {}, - "deprecated": false, - "description": "TypeScript definitions for long.js", - "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped#readme", - "license": "MIT", - "main": "", - "name": "@types/long", - "repository": { - "type": "git", - "url": "git+https://github.com/DefinitelyTyped/DefinitelyTyped.git", - "directory": "types/long" - }, - "scripts": {}, - "typeScriptVersion": "2.8", - "types": "index.d.ts", - "typesPublisherContentHash": "5a2ae1424989c49d7303e1f5cc510288bfab1e71e0e2143cdcb9d24ff1c3dc8e", - "version": "4.0.1" -} diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/node/LICENSE b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/node/LICENSE deleted file mode 100644 index 9e841e7a26..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/node/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ - MIT License - - Copyright (c) Microsoft Corporation. - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in all - copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - SOFTWARE diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/node/README.md b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/node/README.md deleted file mode 100644 index a862ce8f8a..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/node/README.md +++ /dev/null @@ -1,16 +0,0 @@ -# Installation -> `npm install --save @types/node` - -# Summary -This package contains type definitions for Node.js (http://nodejs.org/). - -# Details -Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/node. - -### Additional Details - * Last updated: Fri, 16 Oct 2020 18:46:36 GMT - * Dependencies: none - * Global values: `Buffer`, `__dirname`, `__filename`, `clearImmediate`, `clearInterval`, `clearTimeout`, `console`, `exports`, `global`, `module`, `process`, `queueMicrotask`, `require`, `setImmediate`, `setInterval`, `setTimeout` - -# Credits -These definitions were written by [Microsoft TypeScript](https://github.com/Microsoft), [DefinitelyTyped](https://github.com/DefinitelyTyped), [Alberto Schiabel](https://github.com/jkomyno), [Alexander T.](https://github.com/a-tarasyuk), [Alvis HT Tang](https://github.com/alvis), [Andrew Makarov](https://github.com/r3nya), [Benjamin Toueg](https://github.com/btoueg), [Bruno Scheufler](https://github.com/brunoscheufler), [Chigozirim C.](https://github.com/smac89), [David Junger](https://github.com/touffy), [Deividas Bakanas](https://github.com/DeividasBakanas), [Eugene Y. Q. Shen](https://github.com/eyqs), [Flarna](https://github.com/Flarna), [Hannes Magnusson](https://github.com/Hannes-Magnusson-CK), [Hoàng Văn Khải](https://github.com/KSXGitHub), [Huw](https://github.com/hoo29), [Kelvin Jin](https://github.com/kjin), [Klaus Meinhardt](https://github.com/ajafff), [Lishude](https://github.com/islishude), [Mariusz Wiktorczyk](https://github.com/mwiktorczyk), [Mohsen Azimi](https://github.com/mohsen1), [Nicolas Even](https://github.com/n-e), [Nikita Galkin](https://github.com/galkin), [Parambir Singh](https://github.com/parambirs), [Sebastian Silbermann](https://github.com/eps1lon), [Simon Schick](https://github.com/SimonSchick), [Thomas den Hollander](https://github.com/ThomasdenH), [Wilco Bakker](https://github.com/WilcoBakker), [wwwy3y3](https://github.com/wwwy3y3), [Samuel Ainsworth](https://github.com/samuela), [Kyle Uehlein](https://github.com/kuehlein), [Jordi Oliveras Rovira](https://github.com/j-oliveras), [Thanik Bhongbhibhat](https://github.com/bhongy), [Marcin Kopacz](https://github.com/chyzwar), [Trivikram Kamat](https://github.com/trivikr), [Minh Son Nguyen](https://github.com/nguymin4), [Junxiao Shi](https://github.com/yoursunny), [Ilia Baryshnikov](https://github.com/qwelias), [ExE Boss](https://github.com/ExE-Boss), [Surasak Chaisurin](https://github.com/Ryan-Willpower), [Piotr Błażejewicz](https://github.com/peterblazejewicz), [Anna Henningsen](https://github.com/addaleax), [Jason Kwok](https://github.com/JasonHK), and [Victor Perin](https://github.com/victorperin). diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/node/assert.d.ts b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/node/assert.d.ts deleted file mode 100644 index 3706d99edd..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/node/assert.d.ts +++ /dev/null @@ -1,120 +0,0 @@ -declare module 'assert' { - /** An alias of `assert.ok()`. */ - function assert(value: any, message?: string | Error): asserts value; - namespace assert { - class AssertionError implements Error { - name: string; - message: string; - actual: any; - expected: any; - operator: string; - generatedMessage: boolean; - code: 'ERR_ASSERTION'; - - constructor(options?: { - /** If provided, the error message is set to this value. */ - message?: string; - /** The `actual` property on the error instance. */ - actual?: any; - /** The `expected` property on the error instance. */ - expected?: any; - /** The `operator` property on the error instance. */ - operator?: string; - /** If provided, the generated stack trace omits frames before this function. */ - stackStartFn?: Function; - }); - } - - class CallTracker { - calls(exact?: number): () => void; - calls any>(fn?: Func, exact?: number): Func; - report(): CallTrackerReportInformation[]; - verify(): void; - } - export interface CallTrackerReportInformation { - message: string; - /** The actual number of times the function was called. */ - actual: number; - /** The number of times the function was expected to be called. */ - expected: number; - /** The name of the function that is wrapped. */ - operator: string; - /** A stack trace of the function. */ - stack: object; - } - - type AssertPredicate = RegExp | (new () => object) | ((thrown: any) => boolean) | object | Error; - - function fail(message?: string | Error): never; - /** @deprecated since v10.0.0 - use fail([message]) or other assert functions instead. */ - function fail( - actual: any, - expected: any, - message?: string | Error, - operator?: string, - stackStartFn?: Function, - ): never; - function ok(value: any, message?: string | Error): asserts value; - /** @deprecated since v9.9.0 - use strictEqual() instead. */ - function equal(actual: any, expected: any, message?: string | Error): void; - /** @deprecated since v9.9.0 - use notStrictEqual() instead. */ - function notEqual(actual: any, expected: any, message?: string | Error): void; - /** @deprecated since v9.9.0 - use deepStrictEqual() instead. */ - function deepEqual(actual: any, expected: any, message?: string | Error): void; - /** @deprecated since v9.9.0 - use notDeepStrictEqual() instead. */ - function notDeepEqual(actual: any, expected: any, message?: string | Error): void; - function strictEqual(actual: any, expected: T, message?: string | Error): asserts actual is T; - function notStrictEqual(actual: any, expected: any, message?: string | Error): void; - function deepStrictEqual(actual: any, expected: T, message?: string | Error): asserts actual is T; - function notDeepStrictEqual(actual: any, expected: any, message?: string | Error): void; - - function throws(block: () => any, message?: string | Error): void; - function throws(block: () => any, error: AssertPredicate, message?: string | Error): void; - function doesNotThrow(block: () => any, message?: string | Error): void; - function doesNotThrow(block: () => any, error: RegExp | Function, message?: string | Error): void; - - function ifError(value: any): asserts value is null | undefined; - - function rejects(block: (() => Promise) | Promise, message?: string | Error): Promise; - function rejects( - block: (() => Promise) | Promise, - error: AssertPredicate, - message?: string | Error, - ): Promise; - function doesNotReject(block: (() => Promise) | Promise, message?: string | Error): Promise; - function doesNotReject( - block: (() => Promise) | Promise, - error: RegExp | Function, - message?: string | Error, - ): Promise; - - function match(value: string, regExp: RegExp, message?: string | Error): void; - function doesNotMatch(value: string, regExp: RegExp, message?: string | Error): void; - - const strict: Omit< - typeof assert, - | 'strict' - | 'deepEqual' - | 'notDeepEqual' - | 'equal' - | 'notEqual' - | 'ok' - | 'strictEqual' - | 'deepStrictEqual' - | 'ifError' - > & { - (value: any, message?: string | Error): asserts value; - strict: typeof strict; - deepEqual: typeof deepStrictEqual; - notDeepEqual: typeof notDeepStrictEqual; - equal: typeof strictEqual; - notEqual: typeof notStrictEqual; - ok(value: any, message?: string | Error): asserts value; - strictEqual(actual: any, expected: T, message?: string | Error): asserts actual is T; - deepStrictEqual(actual: any, expected: T, message?: string | Error): asserts actual is T; - ifError(value: any): asserts value is null | undefined; - }; - } - - export = assert; -} diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/node/async_hooks.d.ts b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/node/async_hooks.d.ts deleted file mode 100644 index ab35e5dbc6..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/node/async_hooks.d.ts +++ /dev/null @@ -1,226 +0,0 @@ -/** - * Async Hooks module: https://nodejs.org/api/async_hooks.html - */ -declare module "async_hooks" { - /** - * Returns the asyncId of the current execution context. - */ - function executionAsyncId(): number; - - /** - * The resource representing the current execution. - * Useful to store data within the resource. - * - * Resource objects returned by `executionAsyncResource()` are most often internal - * Node.js handle objects with undocumented APIs. Using any functions or properties - * on the object is likely to crash your application and should be avoided. - * - * Using `executionAsyncResource()` in the top-level execution context will - * return an empty object as there is no handle or request object to use, - * but having an object representing the top-level can be helpful. - */ - function executionAsyncResource(): object; - - /** - * Returns the ID of the resource responsible for calling the callback that is currently being executed. - */ - function triggerAsyncId(): number; - - interface HookCallbacks { - /** - * Called when a class is constructed that has the possibility to emit an asynchronous event. - * @param asyncId a unique ID for the async resource - * @param type the type of the async resource - * @param triggerAsyncId the unique ID of the async resource in whose execution context this async resource was created - * @param resource reference to the resource representing the async operation, needs to be released during destroy - */ - init?(asyncId: number, type: string, triggerAsyncId: number, resource: object): void; - - /** - * When an asynchronous operation is initiated or completes a callback is called to notify the user. - * The before callback is called just before said callback is executed. - * @param asyncId the unique identifier assigned to the resource about to execute the callback. - */ - before?(asyncId: number): void; - - /** - * Called immediately after the callback specified in before is completed. - * @param asyncId the unique identifier assigned to the resource which has executed the callback. - */ - after?(asyncId: number): void; - - /** - * Called when a promise has resolve() called. This may not be in the same execution id - * as the promise itself. - * @param asyncId the unique id for the promise that was resolve()d. - */ - promiseResolve?(asyncId: number): void; - - /** - * Called after the resource corresponding to asyncId is destroyed - * @param asyncId a unique ID for the async resource - */ - destroy?(asyncId: number): void; - } - - interface AsyncHook { - /** - * Enable the callbacks for a given AsyncHook instance. If no callbacks are provided enabling is a noop. - */ - enable(): this; - - /** - * Disable the callbacks for a given AsyncHook instance from the global pool of AsyncHook callbacks to be executed. Once a hook has been disabled it will not be called again until enabled. - */ - disable(): this; - } - - /** - * Registers functions to be called for different lifetime events of each async operation. - * @param options the callbacks to register - * @return an AsyncHooks instance used for disabling and enabling hooks - */ - function createHook(options: HookCallbacks): AsyncHook; - - interface AsyncResourceOptions { - /** - * The ID of the execution context that created this async event. - * Default: `executionAsyncId()` - */ - triggerAsyncId?: number; - - /** - * Disables automatic `emitDestroy` when the object is garbage collected. - * This usually does not need to be set (even if `emitDestroy` is called - * manually), unless the resource's `asyncId` is retrieved and the - * sensitive API's `emitDestroy` is called with it. - * Default: `false` - */ - requireManualDestroy?: boolean; - } - - /** - * The class AsyncResource was designed to be extended by the embedder's async resources. - * Using this users can easily trigger the lifetime events of their own resources. - */ - class AsyncResource { - /** - * AsyncResource() is meant to be extended. Instantiating a - * new AsyncResource() also triggers init. If triggerAsyncId is omitted then - * async_hook.executionAsyncId() is used. - * @param type The type of async event. - * @param triggerAsyncId The ID of the execution context that created - * this async event (default: `executionAsyncId()`), or an - * AsyncResourceOptions object (since 9.3) - */ - constructor(type: string, triggerAsyncId?: number|AsyncResourceOptions); - - /** - * Binds the given function to the current execution context. - * @param fn The function to bind to the current execution context. - * @param type An optional name to associate with the underlying `AsyncResource`. - */ - static bind any>(fn: Func, type?: string): Func & { asyncResource: AsyncResource }; - - /** - * Binds the given function to execute to this `AsyncResource`'s scope. - * @param fn The function to bind to the current `AsyncResource`. - */ - bind any>(fn: Func): Func & { asyncResource: AsyncResource }; - - /** - * Call the provided function with the provided arguments in the - * execution context of the async resource. This will establish the - * context, trigger the AsyncHooks before callbacks, call the function, - * trigger the AsyncHooks after callbacks, and then restore the original - * execution context. - * @param fn The function to call in the execution context of this - * async resource. - * @param thisArg The receiver to be used for the function call. - * @param args Optional arguments to pass to the function. - */ - runInAsyncScope(fn: (this: This, ...args: any[]) => Result, thisArg?: This, ...args: any[]): Result; - - /** - * Call AsyncHooks destroy callbacks. - */ - emitDestroy(): void; - - /** - * @return the unique ID assigned to this AsyncResource instance. - */ - asyncId(): number; - - /** - * @return the trigger ID for this AsyncResource instance. - */ - triggerAsyncId(): number; - } - - /** - * When having multiple instances of `AsyncLocalStorage`, they are independent - * from each other. It is safe to instantiate this class multiple times. - */ - class AsyncLocalStorage { - /** - * This method disables the instance of `AsyncLocalStorage`. All subsequent calls - * to `asyncLocalStorage.getStore()` will return `undefined` until - * `asyncLocalStorage.run()` is called again. - * - * When calling `asyncLocalStorage.disable()`, all current contexts linked to the - * instance will be exited. - * - * Calling `asyncLocalStorage.disable()` is required before the - * `asyncLocalStorage` can be garbage collected. This does not apply to stores - * provided by the `asyncLocalStorage`, as those objects are garbage collected - * along with the corresponding async resources. - * - * This method is to be used when the `asyncLocalStorage` is not in use anymore - * in the current process. - */ - disable(): void; - - /** - * This method returns the current store. If this method is called outside of an - * asynchronous context initialized by calling `asyncLocalStorage.run`, it will - * return `undefined`. - */ - getStore(): T | undefined; - - /** - * This methods runs a function synchronously within a context and return its - * return value. The store is not accessible outside of the callback function or - * the asynchronous operations created within the callback. - * - * Optionally, arguments can be passed to the function. They will be passed to the - * callback function. - * - * I the callback function throws an error, it will be thrown by `run` too. The - * stacktrace will not be impacted by this call and the context will be exited. - */ - // TODO: Apply generic vararg once available - run(store: T, callback: (...args: any[]) => R, ...args: any[]): R; - - /** - * This methods runs a function synchronously outside of a context and return its - * return value. The store is not accessible within the callback function or the - * asynchronous operations created within the callback. - * - * Optionally, arguments can be passed to the function. They will be passed to the - * callback function. - * - * If the callback function throws an error, it will be thrown by `exit` too. The - * stacktrace will not be impacted by this call and the context will be - * re-entered. - */ - // TODO: Apply generic vararg once available - exit(callback: (...args: any[]) => R, ...args: any[]): R; - - /** - * Calling `asyncLocalStorage.enterWith(store)` will transition into the context - * for the remainder of the current synchronous execution and will persist - * through any following asynchronous calls. - */ - enterWith(store: T): void; - } -} diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/node/base.d.ts b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/node/base.d.ts deleted file mode 100644 index dcbc7baa74..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/node/base.d.ts +++ /dev/null @@ -1,20 +0,0 @@ -// NOTE: These definitions support NodeJS and TypeScript 3.7. - -// NOTE: TypeScript version-specific augmentations can be found in the following paths: -// - ~/base.d.ts - Shared definitions common to all TypeScript versions -// - ~/index.d.ts - Definitions specific to TypeScript 2.1 -// - ~/ts3.7/base.d.ts - Definitions specific to TypeScript 3.7 -// - ~/ts3.7/index.d.ts - Definitions specific to TypeScript 3.7 with assert pulled in - -// Reference required types from the default lib: -/// -/// -/// -/// - -// Base definitions for all NodeJS modules that are not specific to any version of TypeScript: -// tslint:disable-next-line:no-bad-reference -/// - -// TypeScript 3.7-specific augmentations: -/// diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/node/buffer.d.ts b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/node/buffer.d.ts deleted file mode 100644 index 76c92cf8d2..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/node/buffer.d.ts +++ /dev/null @@ -1,22 +0,0 @@ -declare module "buffer" { - export const INSPECT_MAX_BYTES: number; - export const kMaxLength: number; - export const kStringMaxLength: number; - export const constants: { - MAX_LENGTH: number; - MAX_STRING_LENGTH: number; - }; - const BuffType: typeof Buffer; - - export type TranscodeEncoding = "ascii" | "utf8" | "utf16le" | "ucs2" | "latin1" | "binary"; - - export function transcode(source: Uint8Array, fromEnc: TranscodeEncoding, toEnc: TranscodeEncoding): Buffer; - - export const SlowBuffer: { - /** @deprecated since v6.0.0, use `Buffer.allocUnsafeSlow()` */ - new(size: number): Buffer; - prototype: Buffer; - }; - - export { BuffType as Buffer }; -} diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/node/child_process.d.ts b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/node/child_process.d.ts deleted file mode 100644 index b53e91e7b4..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/node/child_process.d.ts +++ /dev/null @@ -1,509 +0,0 @@ -declare module "child_process" { - import { BaseEncodingOptions } from 'fs'; - import * as events from "events"; - import * as net from "net"; - import { Writable, Readable, Stream, Pipe } from "stream"; - - type Serializable = string | object | number | boolean; - type SendHandle = net.Socket | net.Server; - - interface ChildProcess extends events.EventEmitter { - stdin: Writable | null; - stdout: Readable | null; - stderr: Readable | null; - readonly channel?: Pipe | null; - readonly stdio: [ - Writable | null, // stdin - Readable | null, // stdout - Readable | null, // stderr - Readable | Writable | null | undefined, // extra - Readable | Writable | null | undefined // extra - ]; - readonly killed: boolean; - readonly pid: number; - readonly connected: boolean; - readonly exitCode: number | null; - readonly signalCode: NodeJS.Signals | null; - readonly spawnargs: string[]; - readonly spawnfile: string; - kill(signal?: NodeJS.Signals | number): boolean; - send(message: Serializable, callback?: (error: Error | null) => void): boolean; - send(message: Serializable, sendHandle?: SendHandle, callback?: (error: Error | null) => void): boolean; - send(message: Serializable, sendHandle?: SendHandle, options?: MessageOptions, callback?: (error: Error | null) => void): boolean; - disconnect(): void; - unref(): void; - ref(): void; - - /** - * events.EventEmitter - * 1. close - * 2. disconnect - * 3. error - * 4. exit - * 5. message - */ - - addListener(event: string, listener: (...args: any[]) => void): this; - addListener(event: "close", listener: (code: number, signal: NodeJS.Signals) => void): this; - addListener(event: "disconnect", listener: () => void): this; - addListener(event: "error", listener: (err: Error) => void): this; - addListener(event: "exit", listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; - addListener(event: "message", listener: (message: Serializable, sendHandle: SendHandle) => void): this; - - emit(event: string | symbol, ...args: any[]): boolean; - emit(event: "close", code: number, signal: NodeJS.Signals): boolean; - emit(event: "disconnect"): boolean; - emit(event: "error", err: Error): boolean; - emit(event: "exit", code: number | null, signal: NodeJS.Signals | null): boolean; - emit(event: "message", message: Serializable, sendHandle: SendHandle): boolean; - - on(event: string, listener: (...args: any[]) => void): this; - on(event: "close", listener: (code: number, signal: NodeJS.Signals) => void): this; - on(event: "disconnect", listener: () => void): this; - on(event: "error", listener: (err: Error) => void): this; - on(event: "exit", listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; - on(event: "message", listener: (message: Serializable, sendHandle: SendHandle) => void): this; - - once(event: string, listener: (...args: any[]) => void): this; - once(event: "close", listener: (code: number, signal: NodeJS.Signals) => void): this; - once(event: "disconnect", listener: () => void): this; - once(event: "error", listener: (err: Error) => void): this; - once(event: "exit", listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; - once(event: "message", listener: (message: Serializable, sendHandle: SendHandle) => void): this; - - prependListener(event: string, listener: (...args: any[]) => void): this; - prependListener(event: "close", listener: (code: number, signal: NodeJS.Signals) => void): this; - prependListener(event: "disconnect", listener: () => void): this; - prependListener(event: "error", listener: (err: Error) => void): this; - prependListener(event: "exit", listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; - prependListener(event: "message", listener: (message: Serializable, sendHandle: SendHandle) => void): this; - - prependOnceListener(event: string, listener: (...args: any[]) => void): this; - prependOnceListener(event: "close", listener: (code: number, signal: NodeJS.Signals) => void): this; - prependOnceListener(event: "disconnect", listener: () => void): this; - prependOnceListener(event: "error", listener: (err: Error) => void): this; - prependOnceListener(event: "exit", listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; - prependOnceListener(event: "message", listener: (message: Serializable, sendHandle: SendHandle) => void): this; - } - - // return this object when stdio option is undefined or not specified - interface ChildProcessWithoutNullStreams extends ChildProcess { - stdin: Writable; - stdout: Readable; - stderr: Readable; - readonly stdio: [ - Writable, // stdin - Readable, // stdout - Readable, // stderr - Readable | Writable | null | undefined, // extra, no modification - Readable | Writable | null | undefined // extra, no modification - ]; - } - - // return this object when stdio option is a tuple of 3 - interface ChildProcessByStdio< - I extends null | Writable, - O extends null | Readable, - E extends null | Readable, - > extends ChildProcess { - stdin: I; - stdout: O; - stderr: E; - readonly stdio: [ - I, - O, - E, - Readable | Writable | null | undefined, // extra, no modification - Readable | Writable | null | undefined // extra, no modification - ]; - } - - interface MessageOptions { - keepOpen?: boolean; - } - - type StdioOptions = "pipe" | "ignore" | "inherit" | Array<("pipe" | "ipc" | "ignore" | "inherit" | Stream | number | null | undefined)>; - - type SerializationType = 'json' | 'advanced'; - - interface MessagingOptions { - /** - * Specify the kind of serialization used for sending messages between processes. - * @default 'json' - */ - serialization?: SerializationType; - } - - interface ProcessEnvOptions { - uid?: number; - gid?: number; - cwd?: string; - env?: NodeJS.ProcessEnv; - } - - interface CommonOptions extends ProcessEnvOptions { - /** - * @default true - */ - windowsHide?: boolean; - /** - * @default 0 - */ - timeout?: number; - } - - interface CommonSpawnOptions extends CommonOptions, MessagingOptions { - argv0?: string; - stdio?: StdioOptions; - shell?: boolean | string; - windowsVerbatimArguments?: boolean; - } - - interface SpawnOptions extends CommonSpawnOptions { - detached?: boolean; - } - - interface SpawnOptionsWithoutStdio extends SpawnOptions { - stdio?: 'pipe' | Array; - } - - type StdioNull = 'inherit' | 'ignore' | Stream; - type StdioPipe = undefined | null | 'pipe'; - - interface SpawnOptionsWithStdioTuple< - Stdin extends StdioNull | StdioPipe, - Stdout extends StdioNull | StdioPipe, - Stderr extends StdioNull | StdioPipe, - > extends SpawnOptions { - stdio: [Stdin, Stdout, Stderr]; - } - - // overloads of spawn without 'args' - function spawn(command: string, options?: SpawnOptionsWithoutStdio): ChildProcessWithoutNullStreams; - - function spawn( - command: string, - options: SpawnOptionsWithStdioTuple, - ): ChildProcessByStdio; - function spawn( - command: string, - options: SpawnOptionsWithStdioTuple, - ): ChildProcessByStdio; - function spawn( - command: string, - options: SpawnOptionsWithStdioTuple, - ): ChildProcessByStdio; - function spawn( - command: string, - options: SpawnOptionsWithStdioTuple, - ): ChildProcessByStdio; - function spawn( - command: string, - options: SpawnOptionsWithStdioTuple, - ): ChildProcessByStdio; - function spawn( - command: string, - options: SpawnOptionsWithStdioTuple, - ): ChildProcessByStdio; - function spawn( - command: string, - options: SpawnOptionsWithStdioTuple, - ): ChildProcessByStdio; - function spawn( - command: string, - options: SpawnOptionsWithStdioTuple, - ): ChildProcessByStdio; - - function spawn(command: string, options: SpawnOptions): ChildProcess; - - // overloads of spawn with 'args' - function spawn(command: string, args?: ReadonlyArray, options?: SpawnOptionsWithoutStdio): ChildProcessWithoutNullStreams; - - function spawn( - command: string, - args: ReadonlyArray, - options: SpawnOptionsWithStdioTuple, - ): ChildProcessByStdio; - function spawn( - command: string, - args: ReadonlyArray, - options: SpawnOptionsWithStdioTuple, - ): ChildProcessByStdio; - function spawn( - command: string, - args: ReadonlyArray, - options: SpawnOptionsWithStdioTuple, - ): ChildProcessByStdio; - function spawn( - command: string, - args: ReadonlyArray, - options: SpawnOptionsWithStdioTuple, - ): ChildProcessByStdio; - function spawn( - command: string, - args: ReadonlyArray, - options: SpawnOptionsWithStdioTuple, - ): ChildProcessByStdio; - function spawn( - command: string, - args: ReadonlyArray, - options: SpawnOptionsWithStdioTuple, - ): ChildProcessByStdio; - function spawn( - command: string, - args: ReadonlyArray, - options: SpawnOptionsWithStdioTuple, - ): ChildProcessByStdio; - function spawn( - command: string, - args: ReadonlyArray, - options: SpawnOptionsWithStdioTuple, - ): ChildProcessByStdio; - - function spawn(command: string, args: ReadonlyArray, options: SpawnOptions): ChildProcess; - - interface ExecOptions extends CommonOptions { - shell?: string; - maxBuffer?: number; - killSignal?: NodeJS.Signals | number; - } - - interface ExecOptionsWithStringEncoding extends ExecOptions { - encoding: BufferEncoding; - } - - interface ExecOptionsWithBufferEncoding extends ExecOptions { - encoding: BufferEncoding | null; // specify `null`. - } - - interface ExecException extends Error { - cmd?: string; - killed?: boolean; - code?: number; - signal?: NodeJS.Signals; - } - - // no `options` definitely means stdout/stderr are `string`. - function exec(command: string, callback?: (error: ExecException | null, stdout: string, stderr: string) => void): ChildProcess; - - // `options` with `"buffer"` or `null` for `encoding` means stdout/stderr are definitely `Buffer`. - function exec(command: string, options: { encoding: "buffer" | null } & ExecOptions, callback?: (error: ExecException | null, stdout: Buffer, stderr: Buffer) => void): ChildProcess; - - // `options` with well known `encoding` means stdout/stderr are definitely `string`. - function exec(command: string, options: { encoding: BufferEncoding } & ExecOptions, callback?: (error: ExecException | null, stdout: string, stderr: string) => void): ChildProcess; - - // `options` with an `encoding` whose type is `string` means stdout/stderr could either be `Buffer` or `string`. - // There is no guarantee the `encoding` is unknown as `string` is a superset of `BufferEncoding`. - function exec( - command: string, - options: { encoding: BufferEncoding } & ExecOptions, - callback?: (error: ExecException | null, stdout: string | Buffer, stderr: string | Buffer) => void, - ): ChildProcess; - - // `options` without an `encoding` means stdout/stderr are definitely `string`. - function exec(command: string, options: ExecOptions, callback?: (error: ExecException | null, stdout: string, stderr: string) => void): ChildProcess; - - // fallback if nothing else matches. Worst case is always `string | Buffer`. - function exec( - command: string, - options: (BaseEncodingOptions & ExecOptions) | undefined | null, - callback?: (error: ExecException | null, stdout: string | Buffer, stderr: string | Buffer) => void, - ): ChildProcess; - - interface PromiseWithChild extends Promise { - child: ChildProcess; - } - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - namespace exec { - function __promisify__(command: string): PromiseWithChild<{ stdout: string, stderr: string }>; - function __promisify__(command: string, options: { encoding: "buffer" | null } & ExecOptions): PromiseWithChild<{ stdout: Buffer, stderr: Buffer }>; - function __promisify__(command: string, options: { encoding: BufferEncoding } & ExecOptions): PromiseWithChild<{ stdout: string, stderr: string }>; - function __promisify__(command: string, options: ExecOptions): PromiseWithChild<{ stdout: string, stderr: string }>; - function __promisify__(command: string, options?: (BaseEncodingOptions & ExecOptions) | null): PromiseWithChild<{ stdout: string | Buffer, stderr: string | Buffer }>; - } - - interface ExecFileOptions extends CommonOptions { - maxBuffer?: number; - killSignal?: NodeJS.Signals | number; - windowsVerbatimArguments?: boolean; - shell?: boolean | string; - } - interface ExecFileOptionsWithStringEncoding extends ExecFileOptions { - encoding: BufferEncoding; - } - interface ExecFileOptionsWithBufferEncoding extends ExecFileOptions { - encoding: 'buffer' | null; - } - interface ExecFileOptionsWithOtherEncoding extends ExecFileOptions { - encoding: BufferEncoding; - } - - function execFile(file: string): ChildProcess; - function execFile(file: string, options: (BaseEncodingOptions & ExecFileOptions) | undefined | null): ChildProcess; - function execFile(file: string, args?: ReadonlyArray | null): ChildProcess; - function execFile(file: string, args: ReadonlyArray | undefined | null, options: (BaseEncodingOptions & ExecFileOptions) | undefined | null): ChildProcess; - - // no `options` definitely means stdout/stderr are `string`. - function execFile(file: string, callback: (error: ExecException | null, stdout: string, stderr: string) => void): ChildProcess; - function execFile(file: string, args: ReadonlyArray | undefined | null, callback: (error: ExecException | null, stdout: string, stderr: string) => void): ChildProcess; - - // `options` with `"buffer"` or `null` for `encoding` means stdout/stderr are definitely `Buffer`. - function execFile(file: string, options: ExecFileOptionsWithBufferEncoding, callback: (error: ExecException | null, stdout: Buffer, stderr: Buffer) => void): ChildProcess; - function execFile( - file: string, - args: ReadonlyArray | undefined | null, - options: ExecFileOptionsWithBufferEncoding, - callback: (error: ExecException | null, stdout: Buffer, stderr: Buffer) => void, - ): ChildProcess; - - // `options` with well known `encoding` means stdout/stderr are definitely `string`. - function execFile(file: string, options: ExecFileOptionsWithStringEncoding, callback: (error: ExecException | null, stdout: string, stderr: string) => void): ChildProcess; - function execFile( - file: string, - args: ReadonlyArray | undefined | null, - options: ExecFileOptionsWithStringEncoding, - callback: (error: ExecException | null, stdout: string, stderr: string) => void, - ): ChildProcess; - - // `options` with an `encoding` whose type is `string` means stdout/stderr could either be `Buffer` or `string`. - // There is no guarantee the `encoding` is unknown as `string` is a superset of `BufferEncoding`. - function execFile( - file: string, - options: ExecFileOptionsWithOtherEncoding, - callback: (error: ExecException | null, stdout: string | Buffer, stderr: string | Buffer) => void, - ): ChildProcess; - function execFile( - file: string, - args: ReadonlyArray | undefined | null, - options: ExecFileOptionsWithOtherEncoding, - callback: (error: ExecException | null, stdout: string | Buffer, stderr: string | Buffer) => void, - ): ChildProcess; - - // `options` without an `encoding` means stdout/stderr are definitely `string`. - function execFile(file: string, options: ExecFileOptions, callback: (error: ExecException | null, stdout: string, stderr: string) => void): ChildProcess; - function execFile( - file: string, - args: ReadonlyArray | undefined | null, - options: ExecFileOptions, - callback: (error: ExecException | null, stdout: string, stderr: string) => void - ): ChildProcess; - - // fallback if nothing else matches. Worst case is always `string | Buffer`. - function execFile( - file: string, - options: (BaseEncodingOptions & ExecFileOptions) | undefined | null, - callback: ((error: ExecException | null, stdout: string | Buffer, stderr: string | Buffer) => void) | undefined | null, - ): ChildProcess; - function execFile( - file: string, - args: ReadonlyArray | undefined | null, - options: (BaseEncodingOptions & ExecFileOptions) | undefined | null, - callback: ((error: ExecException | null, stdout: string | Buffer, stderr: string | Buffer) => void) | undefined | null, - ): ChildProcess; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - namespace execFile { - function __promisify__(file: string): PromiseWithChild<{ stdout: string, stderr: string }>; - function __promisify__(file: string, args: ReadonlyArray | undefined | null): PromiseWithChild<{ stdout: string, stderr: string }>; - function __promisify__(file: string, options: ExecFileOptionsWithBufferEncoding): PromiseWithChild<{ stdout: Buffer, stderr: Buffer }>; - function __promisify__(file: string, args: ReadonlyArray | undefined | null, options: ExecFileOptionsWithBufferEncoding): PromiseWithChild<{ stdout: Buffer, stderr: Buffer }>; - function __promisify__(file: string, options: ExecFileOptionsWithStringEncoding): PromiseWithChild<{ stdout: string, stderr: string }>; - function __promisify__(file: string, args: ReadonlyArray | undefined | null, options: ExecFileOptionsWithStringEncoding): PromiseWithChild<{ stdout: string, stderr: string }>; - function __promisify__(file: string, options: ExecFileOptionsWithOtherEncoding): PromiseWithChild<{ stdout: string | Buffer, stderr: string | Buffer }>; - function __promisify__( - file: string, - args: ReadonlyArray | undefined | null, - options: ExecFileOptionsWithOtherEncoding, - ): PromiseWithChild<{ stdout: string | Buffer, stderr: string | Buffer }>; - function __promisify__(file: string, options: ExecFileOptions): PromiseWithChild<{ stdout: string, stderr: string }>; - function __promisify__(file: string, args: ReadonlyArray | undefined | null, options: ExecFileOptions): PromiseWithChild<{ stdout: string, stderr: string }>; - function __promisify__(file: string, options: (BaseEncodingOptions & ExecFileOptions) | undefined | null): PromiseWithChild<{ stdout: string | Buffer, stderr: string | Buffer }>; - function __promisify__( - file: string, - args: ReadonlyArray | undefined | null, - options: (BaseEncodingOptions & ExecFileOptions) | undefined | null, - ): PromiseWithChild<{ stdout: string | Buffer, stderr: string | Buffer }>; - } - - interface ForkOptions extends ProcessEnvOptions, MessagingOptions { - execPath?: string; - execArgv?: string[]; - silent?: boolean; - stdio?: StdioOptions; - detached?: boolean; - windowsVerbatimArguments?: boolean; - } - function fork(modulePath: string, options?: ForkOptions): ChildProcess; - function fork(modulePath: string, args?: ReadonlyArray, options?: ForkOptions): ChildProcess; - - interface SpawnSyncOptions extends CommonSpawnOptions { - input?: string | NodeJS.ArrayBufferView; - killSignal?: NodeJS.Signals | number; - maxBuffer?: number; - encoding?: BufferEncoding | 'buffer' | null; - } - interface SpawnSyncOptionsWithStringEncoding extends SpawnSyncOptions { - encoding: BufferEncoding; - } - interface SpawnSyncOptionsWithBufferEncoding extends SpawnSyncOptions { - encoding?: 'buffer' | null; - } - interface SpawnSyncReturns { - pid: number; - output: string[]; - stdout: T; - stderr: T; - status: number | null; - signal: NodeJS.Signals | null; - error?: Error; - } - function spawnSync(command: string): SpawnSyncReturns; - function spawnSync(command: string, options?: SpawnSyncOptionsWithStringEncoding): SpawnSyncReturns; - function spawnSync(command: string, options?: SpawnSyncOptionsWithBufferEncoding): SpawnSyncReturns; - function spawnSync(command: string, options?: SpawnSyncOptions): SpawnSyncReturns; - function spawnSync(command: string, args?: ReadonlyArray, options?: SpawnSyncOptionsWithStringEncoding): SpawnSyncReturns; - function spawnSync(command: string, args?: ReadonlyArray, options?: SpawnSyncOptionsWithBufferEncoding): SpawnSyncReturns; - function spawnSync(command: string, args?: ReadonlyArray, options?: SpawnSyncOptions): SpawnSyncReturns; - - interface ExecSyncOptions extends CommonOptions { - input?: string | Uint8Array; - stdio?: StdioOptions; - shell?: string; - killSignal?: NodeJS.Signals | number; - maxBuffer?: number; - encoding?: BufferEncoding | 'buffer' | null; - } - interface ExecSyncOptionsWithStringEncoding extends ExecSyncOptions { - encoding: BufferEncoding; - } - interface ExecSyncOptionsWithBufferEncoding extends ExecSyncOptions { - encoding?: 'buffer' | null; - } - function execSync(command: string): Buffer; - function execSync(command: string, options?: ExecSyncOptionsWithStringEncoding): string; - function execSync(command: string, options?: ExecSyncOptionsWithBufferEncoding): Buffer; - function execSync(command: string, options?: ExecSyncOptions): Buffer; - - interface ExecFileSyncOptions extends CommonOptions { - input?: string | NodeJS.ArrayBufferView; - stdio?: StdioOptions; - killSignal?: NodeJS.Signals | number; - maxBuffer?: number; - encoding?: BufferEncoding; - shell?: boolean | string; - } - interface ExecFileSyncOptionsWithStringEncoding extends ExecFileSyncOptions { - encoding: BufferEncoding; - } - interface ExecFileSyncOptionsWithBufferEncoding extends ExecFileSyncOptions { - encoding: BufferEncoding; // specify `null`. - } - function execFileSync(command: string): Buffer; - function execFileSync(command: string, options?: ExecFileSyncOptionsWithStringEncoding): string; - function execFileSync(command: string, options?: ExecFileSyncOptionsWithBufferEncoding): Buffer; - function execFileSync(command: string, options?: ExecFileSyncOptions): Buffer; - function execFileSync(command: string, args?: ReadonlyArray, options?: ExecFileSyncOptionsWithStringEncoding): string; - function execFileSync(command: string, args?: ReadonlyArray, options?: ExecFileSyncOptionsWithBufferEncoding): Buffer; - function execFileSync(command: string, args?: ReadonlyArray, options?: ExecFileSyncOptions): Buffer; -} diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/node/cluster.d.ts b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/node/cluster.d.ts deleted file mode 100644 index 0ef6c2a052..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/node/cluster.d.ts +++ /dev/null @@ -1,262 +0,0 @@ -declare module "cluster" { - import * as child from "child_process"; - import * as events from "events"; - import * as net from "net"; - - // interfaces - interface ClusterSettings { - execArgv?: string[]; // default: process.execArgv - exec?: string; - args?: string[]; - silent?: boolean; - stdio?: any[]; - uid?: number; - gid?: number; - inspectPort?: number | (() => number); - } - - interface Address { - address: string; - port: number; - addressType: number | "udp4" | "udp6"; // 4, 6, -1, "udp4", "udp6" - } - - class Worker extends events.EventEmitter { - id: number; - process: child.ChildProcess; - send(message: child.Serializable, sendHandle?: child.SendHandle, callback?: (error: Error | null) => void): boolean; - kill(signal?: string): void; - destroy(signal?: string): void; - disconnect(): void; - isConnected(): boolean; - isDead(): boolean; - exitedAfterDisconnect: boolean; - - /** - * events.EventEmitter - * 1. disconnect - * 2. error - * 3. exit - * 4. listening - * 5. message - * 6. online - */ - addListener(event: string, listener: (...args: any[]) => void): this; - addListener(event: "disconnect", listener: () => void): this; - addListener(event: "error", listener: (error: Error) => void): this; - addListener(event: "exit", listener: (code: number, signal: string) => void): this; - addListener(event: "listening", listener: (address: Address) => void): this; - addListener(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. - addListener(event: "online", listener: () => void): this; - - emit(event: string | symbol, ...args: any[]): boolean; - emit(event: "disconnect"): boolean; - emit(event: "error", error: Error): boolean; - emit(event: "exit", code: number, signal: string): boolean; - emit(event: "listening", address: Address): boolean; - emit(event: "message", message: any, handle: net.Socket | net.Server): boolean; - emit(event: "online"): boolean; - - on(event: string, listener: (...args: any[]) => void): this; - on(event: "disconnect", listener: () => void): this; - on(event: "error", listener: (error: Error) => void): this; - on(event: "exit", listener: (code: number, signal: string) => void): this; - on(event: "listening", listener: (address: Address) => void): this; - on(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. - on(event: "online", listener: () => void): this; - - once(event: string, listener: (...args: any[]) => void): this; - once(event: "disconnect", listener: () => void): this; - once(event: "error", listener: (error: Error) => void): this; - once(event: "exit", listener: (code: number, signal: string) => void): this; - once(event: "listening", listener: (address: Address) => void): this; - once(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. - once(event: "online", listener: () => void): this; - - prependListener(event: string, listener: (...args: any[]) => void): this; - prependListener(event: "disconnect", listener: () => void): this; - prependListener(event: "error", listener: (error: Error) => void): this; - prependListener(event: "exit", listener: (code: number, signal: string) => void): this; - prependListener(event: "listening", listener: (address: Address) => void): this; - prependListener(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. - prependListener(event: "online", listener: () => void): this; - - prependOnceListener(event: string, listener: (...args: any[]) => void): this; - prependOnceListener(event: "disconnect", listener: () => void): this; - prependOnceListener(event: "error", listener: (error: Error) => void): this; - prependOnceListener(event: "exit", listener: (code: number, signal: string) => void): this; - prependOnceListener(event: "listening", listener: (address: Address) => void): this; - prependOnceListener(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. - prependOnceListener(event: "online", listener: () => void): this; - } - - interface Cluster extends events.EventEmitter { - Worker: Worker; - disconnect(callback?: () => void): void; - fork(env?: any): Worker; - isMaster: boolean; - isWorker: boolean; - schedulingPolicy: number; - settings: ClusterSettings; - setupMaster(settings?: ClusterSettings): void; - worker?: Worker; - workers?: NodeJS.Dict; - - readonly SCHED_NONE: number; - readonly SCHED_RR: number; - - /** - * events.EventEmitter - * 1. disconnect - * 2. exit - * 3. fork - * 4. listening - * 5. message - * 6. online - * 7. setup - */ - addListener(event: string, listener: (...args: any[]) => void): this; - addListener(event: "disconnect", listener: (worker: Worker) => void): this; - addListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; - addListener(event: "fork", listener: (worker: Worker) => void): this; - addListener(event: "listening", listener: (worker: Worker, address: Address) => void): this; - addListener(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. - addListener(event: "online", listener: (worker: Worker) => void): this; - addListener(event: "setup", listener: (settings: ClusterSettings) => void): this; - - emit(event: string | symbol, ...args: any[]): boolean; - emit(event: "disconnect", worker: Worker): boolean; - emit(event: "exit", worker: Worker, code: number, signal: string): boolean; - emit(event: "fork", worker: Worker): boolean; - emit(event: "listening", worker: Worker, address: Address): boolean; - emit(event: "message", worker: Worker, message: any, handle: net.Socket | net.Server): boolean; - emit(event: "online", worker: Worker): boolean; - emit(event: "setup", settings: ClusterSettings): boolean; - - on(event: string, listener: (...args: any[]) => void): this; - on(event: "disconnect", listener: (worker: Worker) => void): this; - on(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; - on(event: "fork", listener: (worker: Worker) => void): this; - on(event: "listening", listener: (worker: Worker, address: Address) => void): this; - on(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. - on(event: "online", listener: (worker: Worker) => void): this; - on(event: "setup", listener: (settings: ClusterSettings) => void): this; - - once(event: string, listener: (...args: any[]) => void): this; - once(event: "disconnect", listener: (worker: Worker) => void): this; - once(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; - once(event: "fork", listener: (worker: Worker) => void): this; - once(event: "listening", listener: (worker: Worker, address: Address) => void): this; - once(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. - once(event: "online", listener: (worker: Worker) => void): this; - once(event: "setup", listener: (settings: ClusterSettings) => void): this; - - prependListener(event: string, listener: (...args: any[]) => void): this; - prependListener(event: "disconnect", listener: (worker: Worker) => void): this; - prependListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; - prependListener(event: "fork", listener: (worker: Worker) => void): this; - prependListener(event: "listening", listener: (worker: Worker, address: Address) => void): this; - prependListener(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. - prependListener(event: "online", listener: (worker: Worker) => void): this; - prependListener(event: "setup", listener: (settings: ClusterSettings) => void): this; - - prependOnceListener(event: string, listener: (...args: any[]) => void): this; - prependOnceListener(event: "disconnect", listener: (worker: Worker) => void): this; - prependOnceListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; - prependOnceListener(event: "fork", listener: (worker: Worker) => void): this; - prependOnceListener(event: "listening", listener: (worker: Worker, address: Address) => void): this; - // the handle is a net.Socket or net.Server object, or undefined. - prependOnceListener(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; - prependOnceListener(event: "online", listener: (worker: Worker) => void): this; - prependOnceListener(event: "setup", listener: (settings: ClusterSettings) => void): this; - } - - const SCHED_NONE: number; - const SCHED_RR: number; - - function disconnect(callback?: () => void): void; - function fork(env?: any): Worker; - const isMaster: boolean; - const isWorker: boolean; - let schedulingPolicy: number; - const settings: ClusterSettings; - function setupMaster(settings?: ClusterSettings): void; - const worker: Worker; - const workers: NodeJS.Dict; - - /** - * events.EventEmitter - * 1. disconnect - * 2. exit - * 3. fork - * 4. listening - * 5. message - * 6. online - * 7. setup - */ - function addListener(event: string, listener: (...args: any[]) => void): Cluster; - function addListener(event: "disconnect", listener: (worker: Worker) => void): Cluster; - function addListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): Cluster; - function addListener(event: "fork", listener: (worker: Worker) => void): Cluster; - function addListener(event: "listening", listener: (worker: Worker, address: Address) => void): Cluster; - // the handle is a net.Socket or net.Server object, or undefined. - function addListener(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): Cluster; - function addListener(event: "online", listener: (worker: Worker) => void): Cluster; - function addListener(event: "setup", listener: (settings: ClusterSettings) => void): Cluster; - - function emit(event: string | symbol, ...args: any[]): boolean; - function emit(event: "disconnect", worker: Worker): boolean; - function emit(event: "exit", worker: Worker, code: number, signal: string): boolean; - function emit(event: "fork", worker: Worker): boolean; - function emit(event: "listening", worker: Worker, address: Address): boolean; - function emit(event: "message", worker: Worker, message: any, handle: net.Socket | net.Server): boolean; - function emit(event: "online", worker: Worker): boolean; - function emit(event: "setup", settings: ClusterSettings): boolean; - - function on(event: string, listener: (...args: any[]) => void): Cluster; - function on(event: "disconnect", listener: (worker: Worker) => void): Cluster; - function on(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): Cluster; - function on(event: "fork", listener: (worker: Worker) => void): Cluster; - function on(event: "listening", listener: (worker: Worker, address: Address) => void): Cluster; - function on(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): Cluster; // the handle is a net.Socket or net.Server object, or undefined. - function on(event: "online", listener: (worker: Worker) => void): Cluster; - function on(event: "setup", listener: (settings: ClusterSettings) => void): Cluster; - - function once(event: string, listener: (...args: any[]) => void): Cluster; - function once(event: "disconnect", listener: (worker: Worker) => void): Cluster; - function once(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): Cluster; - function once(event: "fork", listener: (worker: Worker) => void): Cluster; - function once(event: "listening", listener: (worker: Worker, address: Address) => void): Cluster; - function once(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): Cluster; // the handle is a net.Socket or net.Server object, or undefined. - function once(event: "online", listener: (worker: Worker) => void): Cluster; - function once(event: "setup", listener: (settings: ClusterSettings) => void): Cluster; - - function removeListener(event: string, listener: (...args: any[]) => void): Cluster; - function removeAllListeners(event?: string): Cluster; - function setMaxListeners(n: number): Cluster; - function getMaxListeners(): number; - function listeners(event: string): Function[]; - function listenerCount(type: string): number; - - function prependListener(event: string, listener: (...args: any[]) => void): Cluster; - function prependListener(event: "disconnect", listener: (worker: Worker) => void): Cluster; - function prependListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): Cluster; - function prependListener(event: "fork", listener: (worker: Worker) => void): Cluster; - function prependListener(event: "listening", listener: (worker: Worker, address: Address) => void): Cluster; - // the handle is a net.Socket or net.Server object, or undefined. - function prependListener(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): Cluster; - function prependListener(event: "online", listener: (worker: Worker) => void): Cluster; - function prependListener(event: "setup", listener: (settings: ClusterSettings) => void): Cluster; - - function prependOnceListener(event: string, listener: (...args: any[]) => void): Cluster; - function prependOnceListener(event: "disconnect", listener: (worker: Worker) => void): Cluster; - function prependOnceListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): Cluster; - function prependOnceListener(event: "fork", listener: (worker: Worker) => void): Cluster; - function prependOnceListener(event: "listening", listener: (worker: Worker, address: Address) => void): Cluster; - // the handle is a net.Socket or net.Server object, or undefined. - function prependOnceListener(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): Cluster; - function prependOnceListener(event: "online", listener: (worker: Worker) => void): Cluster; - function prependOnceListener(event: "setup", listener: (settings: ClusterSettings) => void): Cluster; - - function eventNames(): string[]; -} diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/node/console.d.ts b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/node/console.d.ts deleted file mode 100644 index 178beb45f5..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/node/console.d.ts +++ /dev/null @@ -1,133 +0,0 @@ -declare module "console" { - import { InspectOptions } from 'util'; - - global { - // This needs to be global to avoid TS2403 in case lib.dom.d.ts is present in the same build - interface Console { - Console: NodeJS.ConsoleConstructor; - /** - * A simple assertion test that verifies whether `value` is truthy. - * If it is not, an `AssertionError` is thrown. - * If provided, the error `message` is formatted using `util.format()` and used as the error message. - */ - assert(value: any, message?: string, ...optionalParams: any[]): void; - /** - * When `stdout` is a TTY, calling `console.clear()` will attempt to clear the TTY. - * When `stdout` is not a TTY, this method does nothing. - */ - clear(): void; - /** - * Maintains an internal counter specific to `label` and outputs to `stdout` the number of times `console.count()` has been called with the given `label`. - */ - count(label?: string): void; - /** - * Resets the internal counter specific to `label`. - */ - countReset(label?: string): void; - /** - * The `console.debug()` function is an alias for {@link console.log()}. - */ - debug(message?: any, ...optionalParams: any[]): void; - /** - * Uses {@link util.inspect()} on `obj` and prints the resulting string to `stdout`. - * This function bypasses any custom `inspect()` function defined on `obj`. - */ - dir(obj: any, options?: InspectOptions): void; - /** - * This method calls {@link console.log()} passing it the arguments received. Please note that this method does not produce any XML formatting - */ - dirxml(...data: any[]): void; - /** - * Prints to `stderr` with newline. - */ - error(message?: any, ...optionalParams: any[]): void; - /** - * Increases indentation of subsequent lines by two spaces. - * If one or more `label`s are provided, those are printed first without the additional indentation. - */ - group(...label: any[]): void; - /** - * The `console.groupCollapsed()` function is an alias for {@link console.group()}. - */ - groupCollapsed(...label: any[]): void; - /** - * Decreases indentation of subsequent lines by two spaces. - */ - groupEnd(): void; - /** - * The {@link console.info()} function is an alias for {@link console.log()}. - */ - info(message?: any, ...optionalParams: any[]): void; - /** - * Prints to `stdout` with newline. - */ - log(message?: any, ...optionalParams: any[]): void; - /** - * This method does not display anything unless used in the inspector. - * Prints to `stdout` the array `array` formatted as a table. - */ - table(tabularData: any, properties?: ReadonlyArray): void; - /** - * Starts a timer that can be used to compute the duration of an operation. Timers are identified by a unique `label`. - */ - time(label?: string): void; - /** - * Stops a timer that was previously started by calling {@link console.time()} and prints the result to `stdout`. - */ - timeEnd(label?: string): void; - /** - * For a timer that was previously started by calling {@link console.time()}, prints the elapsed time and other `data` arguments to `stdout`. - */ - timeLog(label?: string, ...data: any[]): void; - /** - * Prints to `stderr` the string 'Trace :', followed by the {@link util.format()} formatted message and stack trace to the current position in the code. - */ - trace(message?: any, ...optionalParams: any[]): void; - /** - * The {@link console.warn()} function is an alias for {@link console.error()}. - */ - warn(message?: any, ...optionalParams: any[]): void; - - // --- Inspector mode only --- - /** - * This method does not display anything unless used in the inspector. - * Starts a JavaScript CPU profile with an optional label. - */ - profile(label?: string): void; - /** - * This method does not display anything unless used in the inspector. - * Stops the current JavaScript CPU profiling session if one has been started and prints the report to the Profiles panel of the inspector. - */ - profileEnd(label?: string): void; - /** - * This method does not display anything unless used in the inspector. - * Adds an event with the label `label` to the Timeline panel of the inspector. - */ - timeStamp(label?: string): void; - } - - var console: Console; - - namespace NodeJS { - interface ConsoleConstructorOptions { - stdout: WritableStream; - stderr?: WritableStream; - ignoreErrors?: boolean; - colorMode?: boolean | 'auto'; - inspectOptions?: InspectOptions; - } - - interface ConsoleConstructor { - prototype: Console; - new(stdout: WritableStream, stderr?: WritableStream, ignoreErrors?: boolean): Console; - new(options: ConsoleConstructorOptions): Console; - } - - interface Global { - console: typeof console; - } - } - } - - export = console; -} diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/node/constants.d.ts b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/node/constants.d.ts deleted file mode 100644 index d124ae66c0..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/node/constants.d.ts +++ /dev/null @@ -1,8 +0,0 @@ -/** @deprecated since v6.3.0 - use constants property exposed by the relevant module instead. */ -declare module "constants" { - import { constants as osConstants, SignalConstants } from 'os'; - import { constants as cryptoConstants } from 'crypto'; - import { constants as fsConstants } from 'fs'; - const exp: typeof osConstants.errno & typeof osConstants.priority & SignalConstants & typeof cryptoConstants & typeof fsConstants; - export = exp; -} diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/node/crypto.d.ts b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/node/crypto.d.ts deleted file mode 100644 index 17660cf52c..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/node/crypto.d.ts +++ /dev/null @@ -1,775 +0,0 @@ -declare module "crypto" { - import * as stream from "stream"; - - interface Certificate { - exportChallenge(spkac: BinaryLike): Buffer; - exportPublicKey(spkac: BinaryLike): Buffer; - verifySpkac(spkac: NodeJS.ArrayBufferView): boolean; - } - const Certificate: { - new(): Certificate; - (): Certificate; - }; - - namespace constants { // https://nodejs.org/dist/latest-v10.x/docs/api/crypto.html#crypto_crypto_constants - const OPENSSL_VERSION_NUMBER: number; - - /** Applies multiple bug workarounds within OpenSSL. See https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_options.html for detail. */ - const SSL_OP_ALL: number; - /** Allows legacy insecure renegotiation between OpenSSL and unpatched clients or servers. See https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_options.html. */ - const SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION: number; - /** Attempts to use the server's preferences instead of the client's when selecting a cipher. See https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_options.html. */ - const SSL_OP_CIPHER_SERVER_PREFERENCE: number; - /** Instructs OpenSSL to use Cisco's "speshul" version of DTLS_BAD_VER. */ - const SSL_OP_CISCO_ANYCONNECT: number; - /** Instructs OpenSSL to turn on cookie exchange. */ - const SSL_OP_COOKIE_EXCHANGE: number; - /** Instructs OpenSSL to add server-hello extension from an early version of the cryptopro draft. */ - const SSL_OP_CRYPTOPRO_TLSEXT_BUG: number; - /** Instructs OpenSSL to disable a SSL 3.0/TLS 1.0 vulnerability workaround added in OpenSSL 0.9.6d. */ - const SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS: number; - /** Instructs OpenSSL to always use the tmp_rsa key when performing RSA operations. */ - const SSL_OP_EPHEMERAL_RSA: number; - /** Allows initial connection to servers that do not support RI. */ - const SSL_OP_LEGACY_SERVER_CONNECT: number; - const SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER: number; - const SSL_OP_MICROSOFT_SESS_ID_BUG: number; - /** Instructs OpenSSL to disable the workaround for a man-in-the-middle protocol-version vulnerability in the SSL 2.0 server implementation. */ - const SSL_OP_MSIE_SSLV2_RSA_PADDING: number; - const SSL_OP_NETSCAPE_CA_DN_BUG: number; - const SSL_OP_NETSCAPE_CHALLENGE_BUG: number; - const SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG: number; - const SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG: number; - /** Instructs OpenSSL to disable support for SSL/TLS compression. */ - const SSL_OP_NO_COMPRESSION: number; - const SSL_OP_NO_QUERY_MTU: number; - /** Instructs OpenSSL to always start a new session when performing renegotiation. */ - const SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION: number; - const SSL_OP_NO_SSLv2: number; - const SSL_OP_NO_SSLv3: number; - const SSL_OP_NO_TICKET: number; - const SSL_OP_NO_TLSv1: number; - const SSL_OP_NO_TLSv1_1: number; - const SSL_OP_NO_TLSv1_2: number; - const SSL_OP_PKCS1_CHECK_1: number; - const SSL_OP_PKCS1_CHECK_2: number; - /** Instructs OpenSSL to always create a new key when using temporary/ephemeral DH parameters. */ - const SSL_OP_SINGLE_DH_USE: number; - /** Instructs OpenSSL to always create a new key when using temporary/ephemeral ECDH parameters. */ - const SSL_OP_SINGLE_ECDH_USE: number; - const SSL_OP_SSLEAY_080_CLIENT_DH_BUG: number; - const SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG: number; - const SSL_OP_TLS_BLOCK_PADDING_BUG: number; - const SSL_OP_TLS_D5_BUG: number; - /** Instructs OpenSSL to disable version rollback attack detection. */ - const SSL_OP_TLS_ROLLBACK_BUG: number; - - const ENGINE_METHOD_RSA: number; - const ENGINE_METHOD_DSA: number; - const ENGINE_METHOD_DH: number; - const ENGINE_METHOD_RAND: number; - const ENGINE_METHOD_EC: number; - const ENGINE_METHOD_CIPHERS: number; - const ENGINE_METHOD_DIGESTS: number; - const ENGINE_METHOD_PKEY_METHS: number; - const ENGINE_METHOD_PKEY_ASN1_METHS: number; - const ENGINE_METHOD_ALL: number; - const ENGINE_METHOD_NONE: number; - - const DH_CHECK_P_NOT_SAFE_PRIME: number; - const DH_CHECK_P_NOT_PRIME: number; - const DH_UNABLE_TO_CHECK_GENERATOR: number; - const DH_NOT_SUITABLE_GENERATOR: number; - - const ALPN_ENABLED: number; - - const RSA_PKCS1_PADDING: number; - const RSA_SSLV23_PADDING: number; - const RSA_NO_PADDING: number; - const RSA_PKCS1_OAEP_PADDING: number; - const RSA_X931_PADDING: number; - const RSA_PKCS1_PSS_PADDING: number; - /** Sets the salt length for RSA_PKCS1_PSS_PADDING to the digest size when signing or verifying. */ - const RSA_PSS_SALTLEN_DIGEST: number; - /** Sets the salt length for RSA_PKCS1_PSS_PADDING to the maximum permissible value when signing data. */ - const RSA_PSS_SALTLEN_MAX_SIGN: number; - /** Causes the salt length for RSA_PKCS1_PSS_PADDING to be determined automatically when verifying a signature. */ - const RSA_PSS_SALTLEN_AUTO: number; - - const POINT_CONVERSION_COMPRESSED: number; - const POINT_CONVERSION_UNCOMPRESSED: number; - const POINT_CONVERSION_HYBRID: number; - - /** Specifies the built-in default cipher list used by Node.js (colon-separated values). */ - const defaultCoreCipherList: string; - /** Specifies the active default cipher list used by the current Node.js process (colon-separated values). */ - const defaultCipherList: string; - } - - interface HashOptions extends stream.TransformOptions { - /** - * For XOF hash functions such as `shake256`, the - * outputLength option can be used to specify the desired output length in bytes. - */ - outputLength?: number; - } - - /** @deprecated since v10.0.0 */ - const fips: boolean; - - function createHash(algorithm: string, options?: HashOptions): Hash; - function createHmac(algorithm: string, key: BinaryLike | KeyObject, options?: stream.TransformOptions): Hmac; - - type Utf8AsciiLatin1Encoding = "utf8" | "ascii" | "latin1"; - type HexBase64Latin1Encoding = "latin1" | "hex" | "base64"; - type Utf8AsciiBinaryEncoding = "utf8" | "ascii" | "binary"; - type HexBase64BinaryEncoding = "binary" | "base64" | "hex"; - type ECDHKeyFormat = "compressed" | "uncompressed" | "hybrid"; - - class Hash extends stream.Transform { - private constructor(); - copy(): Hash; - update(data: BinaryLike): Hash; - update(data: string, input_encoding: Utf8AsciiLatin1Encoding): Hash; - digest(): Buffer; - digest(encoding: HexBase64Latin1Encoding): string; - } - class Hmac extends stream.Transform { - private constructor(); - update(data: BinaryLike): Hmac; - update(data: string, input_encoding: Utf8AsciiLatin1Encoding): Hmac; - digest(): Buffer; - digest(encoding: HexBase64Latin1Encoding): string; - } - - type KeyObjectType = 'secret' | 'public' | 'private'; - - interface KeyExportOptions { - type: 'pkcs1' | 'spki' | 'pkcs8' | 'sec1'; - format: T; - cipher?: string; - passphrase?: string | Buffer; - } - - class KeyObject { - private constructor(); - asymmetricKeyType?: KeyType; - /** - * For asymmetric keys, this property represents the size of the embedded key in - * bytes. This property is `undefined` for symmetric keys. - */ - asymmetricKeySize?: number; - export(options: KeyExportOptions<'pem'>): string | Buffer; - export(options?: KeyExportOptions<'der'>): Buffer; - symmetricKeySize?: number; - type: KeyObjectType; - } - - type CipherCCMTypes = 'aes-128-ccm' | 'aes-192-ccm' | 'aes-256-ccm' | 'chacha20-poly1305'; - type CipherGCMTypes = 'aes-128-gcm' | 'aes-192-gcm' | 'aes-256-gcm'; - - type BinaryLike = string | NodeJS.ArrayBufferView; - - type CipherKey = BinaryLike | KeyObject; - - interface CipherCCMOptions extends stream.TransformOptions { - authTagLength: number; - } - interface CipherGCMOptions extends stream.TransformOptions { - authTagLength?: number; - } - /** @deprecated since v10.0.0 use `createCipheriv()` */ - function createCipher(algorithm: CipherCCMTypes, password: BinaryLike, options: CipherCCMOptions): CipherCCM; - /** @deprecated since v10.0.0 use `createCipheriv()` */ - function createCipher(algorithm: CipherGCMTypes, password: BinaryLike, options?: CipherGCMOptions): CipherGCM; - /** @deprecated since v10.0.0 use `createCipheriv()` */ - function createCipher(algorithm: string, password: BinaryLike, options?: stream.TransformOptions): Cipher; - - function createCipheriv( - algorithm: CipherCCMTypes, - key: CipherKey, - iv: BinaryLike | null, - options: CipherCCMOptions - ): CipherCCM; - function createCipheriv( - algorithm: CipherGCMTypes, - key: CipherKey, - iv: BinaryLike | null, - options?: CipherGCMOptions - ): CipherGCM; - function createCipheriv( - algorithm: string, key: CipherKey, iv: BinaryLike | null, options?: stream.TransformOptions - ): Cipher; - - class Cipher extends stream.Transform { - private constructor(); - update(data: BinaryLike): Buffer; - update(data: string, input_encoding: Utf8AsciiBinaryEncoding): Buffer; - update(data: NodeJS.ArrayBufferView, input_encoding: undefined, output_encoding: HexBase64BinaryEncoding): string; - update(data: string, input_encoding: Utf8AsciiBinaryEncoding | undefined, output_encoding: HexBase64BinaryEncoding): string; - final(): Buffer; - final(output_encoding: BufferEncoding): string; - setAutoPadding(auto_padding?: boolean): this; - // getAuthTag(): Buffer; - // setAAD(buffer: NodeJS.ArrayBufferView): this; - } - interface CipherCCM extends Cipher { - setAAD(buffer: NodeJS.ArrayBufferView, options: { plaintextLength: number }): this; - getAuthTag(): Buffer; - } - interface CipherGCM extends Cipher { - setAAD(buffer: NodeJS.ArrayBufferView, options?: { plaintextLength: number }): this; - getAuthTag(): Buffer; - } - /** @deprecated since v10.0.0 use `createDecipheriv()` */ - function createDecipher(algorithm: CipherCCMTypes, password: BinaryLike, options: CipherCCMOptions): DecipherCCM; - /** @deprecated since v10.0.0 use `createDecipheriv()` */ - function createDecipher(algorithm: CipherGCMTypes, password: BinaryLike, options?: CipherGCMOptions): DecipherGCM; - /** @deprecated since v10.0.0 use `createDecipheriv()` */ - function createDecipher(algorithm: string, password: BinaryLike, options?: stream.TransformOptions): Decipher; - - function createDecipheriv( - algorithm: CipherCCMTypes, - key: CipherKey, - iv: BinaryLike | null, - options: CipherCCMOptions, - ): DecipherCCM; - function createDecipheriv( - algorithm: CipherGCMTypes, - key: CipherKey, - iv: BinaryLike | null, - options?: CipherGCMOptions, - ): DecipherGCM; - function createDecipheriv(algorithm: string, key: CipherKey, iv: BinaryLike | null, options?: stream.TransformOptions): Decipher; - - class Decipher extends stream.Transform { - private constructor(); - update(data: NodeJS.ArrayBufferView): Buffer; - update(data: string, input_encoding: HexBase64BinaryEncoding): Buffer; - update(data: NodeJS.ArrayBufferView, input_encoding: HexBase64BinaryEncoding | undefined, output_encoding: Utf8AsciiBinaryEncoding): string; - update(data: string, input_encoding: HexBase64BinaryEncoding | undefined, output_encoding: Utf8AsciiBinaryEncoding): string; - final(): Buffer; - final(output_encoding: BufferEncoding): string; - setAutoPadding(auto_padding?: boolean): this; - // setAuthTag(tag: NodeJS.ArrayBufferView): this; - // setAAD(buffer: NodeJS.ArrayBufferView): this; - } - interface DecipherCCM extends Decipher { - setAuthTag(buffer: NodeJS.ArrayBufferView): this; - setAAD(buffer: NodeJS.ArrayBufferView, options: { plaintextLength: number }): this; - } - interface DecipherGCM extends Decipher { - setAuthTag(buffer: NodeJS.ArrayBufferView): this; - setAAD(buffer: NodeJS.ArrayBufferView, options?: { plaintextLength: number }): this; - } - - interface PrivateKeyInput { - key: string | Buffer; - format?: KeyFormat; - type?: 'pkcs1' | 'pkcs8' | 'sec1'; - passphrase?: string | Buffer; - } - - interface PublicKeyInput { - key: string | Buffer; - format?: KeyFormat; - type?: 'pkcs1' | 'spki'; - } - - function createPrivateKey(key: PrivateKeyInput | string | Buffer): KeyObject; - function createPublicKey(key: PublicKeyInput | string | Buffer | KeyObject): KeyObject; - function createSecretKey(key: NodeJS.ArrayBufferView): KeyObject; - - function createSign(algorithm: string, options?: stream.WritableOptions): Signer; - - type DSAEncoding = 'der' | 'ieee-p1363'; - - interface SigningOptions { - /** - * @See crypto.constants.RSA_PKCS1_PADDING - */ - padding?: number; - saltLength?: number; - dsaEncoding?: DSAEncoding; - } - - interface SignPrivateKeyInput extends PrivateKeyInput, SigningOptions { - } - interface SignKeyObjectInput extends SigningOptions { - key: KeyObject; - } - interface VerifyPublicKeyInput extends PublicKeyInput, SigningOptions { - } - interface VerifyKeyObjectInput extends SigningOptions { - key: KeyObject; - } - - type KeyLike = string | Buffer | KeyObject; - - class Signer extends stream.Writable { - private constructor(); - - update(data: BinaryLike): Signer; - update(data: string, input_encoding: Utf8AsciiLatin1Encoding): Signer; - sign(private_key: KeyLike | SignKeyObjectInput | SignPrivateKeyInput): Buffer; - sign(private_key: KeyLike | SignKeyObjectInput | SignPrivateKeyInput, output_format: HexBase64Latin1Encoding): string; - } - - function createVerify(algorithm: string, options?: stream.WritableOptions): Verify; - class Verify extends stream.Writable { - private constructor(); - - update(data: BinaryLike): Verify; - update(data: string, input_encoding: Utf8AsciiLatin1Encoding): Verify; - verify(object: KeyLike | VerifyKeyObjectInput | VerifyPublicKeyInput, signature: NodeJS.ArrayBufferView): boolean; - verify(object: KeyLike | VerifyKeyObjectInput | VerifyPublicKeyInput, signature: string, signature_format?: HexBase64Latin1Encoding): boolean; - // https://nodejs.org/api/crypto.html#crypto_verifier_verify_object_signature_signature_format - // The signature field accepts a TypedArray type, but it is only available starting ES2017 - } - function createDiffieHellman(prime_length: number, generator?: number | NodeJS.ArrayBufferView): DiffieHellman; - function createDiffieHellman(prime: NodeJS.ArrayBufferView): DiffieHellman; - function createDiffieHellman(prime: string, prime_encoding: HexBase64Latin1Encoding): DiffieHellman; - function createDiffieHellman(prime: string, prime_encoding: HexBase64Latin1Encoding, generator: number | NodeJS.ArrayBufferView): DiffieHellman; - function createDiffieHellman(prime: string, prime_encoding: HexBase64Latin1Encoding, generator: string, generator_encoding: HexBase64Latin1Encoding): DiffieHellman; - class DiffieHellman { - private constructor(); - generateKeys(): Buffer; - generateKeys(encoding: HexBase64Latin1Encoding): string; - computeSecret(other_public_key: NodeJS.ArrayBufferView): Buffer; - computeSecret(other_public_key: string, input_encoding: HexBase64Latin1Encoding): Buffer; - computeSecret(other_public_key: NodeJS.ArrayBufferView, output_encoding: HexBase64Latin1Encoding): string; - computeSecret(other_public_key: string, input_encoding: HexBase64Latin1Encoding, output_encoding: HexBase64Latin1Encoding): string; - getPrime(): Buffer; - getPrime(encoding: HexBase64Latin1Encoding): string; - getGenerator(): Buffer; - getGenerator(encoding: HexBase64Latin1Encoding): string; - getPublicKey(): Buffer; - getPublicKey(encoding: HexBase64Latin1Encoding): string; - getPrivateKey(): Buffer; - getPrivateKey(encoding: HexBase64Latin1Encoding): string; - setPublicKey(public_key: NodeJS.ArrayBufferView): void; - setPublicKey(public_key: string, encoding: BufferEncoding): void; - setPrivateKey(private_key: NodeJS.ArrayBufferView): void; - setPrivateKey(private_key: string, encoding: BufferEncoding): void; - verifyError: number; - } - function getDiffieHellman(group_name: string): DiffieHellman; - function pbkdf2( - password: BinaryLike, - salt: BinaryLike, - iterations: number, - keylen: number, - digest: string, - callback: (err: Error | null, derivedKey: Buffer) => any, - ): void; - function pbkdf2Sync(password: BinaryLike, salt: BinaryLike, iterations: number, keylen: number, digest: string): Buffer; - - function randomBytes(size: number): Buffer; - function randomBytes(size: number, callback: (err: Error | null, buf: Buffer) => void): void; - function pseudoRandomBytes(size: number): Buffer; - function pseudoRandomBytes(size: number, callback: (err: Error | null, buf: Buffer) => void): void; - - function randomInt(max: number): number; - function randomInt(min: number, max: number): number; - function randomInt(max: number, callback: (err: Error | null, value: number) => void): void; - function randomInt(min: number, max: number, callback: (err: Error | null, value: number) => void): void; - - function randomFillSync(buffer: T, offset?: number, size?: number): T; - function randomFill(buffer: T, callback: (err: Error | null, buf: T) => void): void; - function randomFill(buffer: T, offset: number, callback: (err: Error | null, buf: T) => void): void; - function randomFill(buffer: T, offset: number, size: number, callback: (err: Error | null, buf: T) => void): void; - - interface ScryptOptions { - N?: number; - r?: number; - p?: number; - maxmem?: number; - } - function scrypt( - password: BinaryLike, - salt: BinaryLike, - keylen: number, callback: (err: Error | null, derivedKey: Buffer) => void, - ): void; - function scrypt( - password: BinaryLike, - salt: BinaryLike, - keylen: number, - options: ScryptOptions, - callback: (err: Error | null, derivedKey: Buffer) => void, - ): void; - function scryptSync(password: BinaryLike, salt: BinaryLike, keylen: number, options?: ScryptOptions): Buffer; - - interface RsaPublicKey { - key: KeyLike; - padding?: number; - } - interface RsaPrivateKey { - key: KeyLike; - passphrase?: string; - /** - * @default 'sha1' - */ - oaepHash?: string; - oaepLabel?: NodeJS.TypedArray; - padding?: number; - } - function publicEncrypt(key: RsaPublicKey | RsaPrivateKey | KeyLike, buffer: NodeJS.ArrayBufferView): Buffer; - function publicDecrypt(key: RsaPublicKey | RsaPrivateKey | KeyLike, buffer: NodeJS.ArrayBufferView): Buffer; - function privateDecrypt(private_key: RsaPrivateKey | KeyLike, buffer: NodeJS.ArrayBufferView): Buffer; - function privateEncrypt(private_key: RsaPrivateKey | KeyLike, buffer: NodeJS.ArrayBufferView): Buffer; - function getCiphers(): string[]; - function getCurves(): string[]; - function getFips(): 1 | 0; - function getHashes(): string[]; - class ECDH { - private constructor(); - static convertKey( - key: BinaryLike, - curve: string, - inputEncoding?: HexBase64Latin1Encoding, - outputEncoding?: "latin1" | "hex" | "base64", - format?: "uncompressed" | "compressed" | "hybrid", - ): Buffer | string; - generateKeys(): Buffer; - generateKeys(encoding: HexBase64Latin1Encoding, format?: ECDHKeyFormat): string; - computeSecret(other_public_key: NodeJS.ArrayBufferView): Buffer; - computeSecret(other_public_key: string, input_encoding: HexBase64Latin1Encoding): Buffer; - computeSecret(other_public_key: NodeJS.ArrayBufferView, output_encoding: HexBase64Latin1Encoding): string; - computeSecret(other_public_key: string, input_encoding: HexBase64Latin1Encoding, output_encoding: HexBase64Latin1Encoding): string; - getPrivateKey(): Buffer; - getPrivateKey(encoding: HexBase64Latin1Encoding): string; - getPublicKey(): Buffer; - getPublicKey(encoding: HexBase64Latin1Encoding, format?: ECDHKeyFormat): string; - setPrivateKey(private_key: NodeJS.ArrayBufferView): void; - setPrivateKey(private_key: string, encoding: HexBase64Latin1Encoding): void; - } - function createECDH(curve_name: string): ECDH; - function timingSafeEqual(a: NodeJS.ArrayBufferView, b: NodeJS.ArrayBufferView): boolean; - /** @deprecated since v10.0.0 */ - const DEFAULT_ENCODING: BufferEncoding; - - type KeyType = 'rsa' | 'dsa' | 'ec' | 'ed25519' | 'ed448' | 'x25519' | 'x448'; - type KeyFormat = 'pem' | 'der'; - - interface BasePrivateKeyEncodingOptions { - format: T; - cipher?: string; - passphrase?: string; - } - - interface KeyPairKeyObjectResult { - publicKey: KeyObject; - privateKey: KeyObject; - } - - interface ED25519KeyPairKeyObjectOptions { - /** - * No options. - */ - } - - interface ED448KeyPairKeyObjectOptions { - /** - * No options. - */ - } - - interface X25519KeyPairKeyObjectOptions { - /** - * No options. - */ - } - - interface X448KeyPairKeyObjectOptions { - /** - * No options. - */ - } - - interface ECKeyPairKeyObjectOptions { - /** - * Name of the curve to use. - */ - namedCurve: string; - } - - interface RSAKeyPairKeyObjectOptions { - /** - * Key size in bits - */ - modulusLength: number; - - /** - * @default 0x10001 - */ - publicExponent?: number; - } - - interface DSAKeyPairKeyObjectOptions { - /** - * Key size in bits - */ - modulusLength: number; - - /** - * Size of q in bits - */ - divisorLength: number; - } - - interface RSAKeyPairOptions { - /** - * Key size in bits - */ - modulusLength: number; - /** - * @default 0x10001 - */ - publicExponent?: number; - - publicKeyEncoding: { - type: 'pkcs1' | 'spki'; - format: PubF; - }; - privateKeyEncoding: BasePrivateKeyEncodingOptions & { - type: 'pkcs1' | 'pkcs8'; - }; - } - - interface DSAKeyPairOptions { - /** - * Key size in bits - */ - modulusLength: number; - /** - * Size of q in bits - */ - divisorLength: number; - - publicKeyEncoding: { - type: 'spki'; - format: PubF; - }; - privateKeyEncoding: BasePrivateKeyEncodingOptions & { - type: 'pkcs8'; - }; - } - - interface ECKeyPairOptions { - /** - * Name of the curve to use. - */ - namedCurve: string; - - publicKeyEncoding: { - type: 'pkcs1' | 'spki'; - format: PubF; - }; - privateKeyEncoding: BasePrivateKeyEncodingOptions & { - type: 'sec1' | 'pkcs8'; - }; - } - - interface ED25519KeyPairOptions { - publicKeyEncoding: { - type: 'spki'; - format: PubF; - }; - privateKeyEncoding: BasePrivateKeyEncodingOptions & { - type: 'pkcs8'; - }; - } - - interface ED448KeyPairOptions { - publicKeyEncoding: { - type: 'spki'; - format: PubF; - }; - privateKeyEncoding: BasePrivateKeyEncodingOptions & { - type: 'pkcs8'; - }; - } - - interface X25519KeyPairOptions { - publicKeyEncoding: { - type: 'spki'; - format: PubF; - }; - privateKeyEncoding: BasePrivateKeyEncodingOptions & { - type: 'pkcs8'; - }; - } - - interface X448KeyPairOptions { - publicKeyEncoding: { - type: 'spki'; - format: PubF; - }; - privateKeyEncoding: BasePrivateKeyEncodingOptions & { - type: 'pkcs8'; - }; - } - - interface KeyPairSyncResult { - publicKey: T1; - privateKey: T2; - } - - function generateKeyPairSync(type: 'rsa', options: RSAKeyPairOptions<'pem', 'pem'>): KeyPairSyncResult; - function generateKeyPairSync(type: 'rsa', options: RSAKeyPairOptions<'pem', 'der'>): KeyPairSyncResult; - function generateKeyPairSync(type: 'rsa', options: RSAKeyPairOptions<'der', 'pem'>): KeyPairSyncResult; - function generateKeyPairSync(type: 'rsa', options: RSAKeyPairOptions<'der', 'der'>): KeyPairSyncResult; - function generateKeyPairSync(type: 'rsa', options: RSAKeyPairKeyObjectOptions): KeyPairKeyObjectResult; - - function generateKeyPairSync(type: 'dsa', options: DSAKeyPairOptions<'pem', 'pem'>): KeyPairSyncResult; - function generateKeyPairSync(type: 'dsa', options: DSAKeyPairOptions<'pem', 'der'>): KeyPairSyncResult; - function generateKeyPairSync(type: 'dsa', options: DSAKeyPairOptions<'der', 'pem'>): KeyPairSyncResult; - function generateKeyPairSync(type: 'dsa', options: DSAKeyPairOptions<'der', 'der'>): KeyPairSyncResult; - function generateKeyPairSync(type: 'dsa', options: DSAKeyPairKeyObjectOptions): KeyPairKeyObjectResult; - - function generateKeyPairSync(type: 'ec', options: ECKeyPairOptions<'pem', 'pem'>): KeyPairSyncResult; - function generateKeyPairSync(type: 'ec', options: ECKeyPairOptions<'pem', 'der'>): KeyPairSyncResult; - function generateKeyPairSync(type: 'ec', options: ECKeyPairOptions<'der', 'pem'>): KeyPairSyncResult; - function generateKeyPairSync(type: 'ec', options: ECKeyPairOptions<'der', 'der'>): KeyPairSyncResult; - function generateKeyPairSync(type: 'ec', options: ECKeyPairKeyObjectOptions): KeyPairKeyObjectResult; - - function generateKeyPairSync(type: 'ed25519', options: ED25519KeyPairOptions<'pem', 'pem'>): KeyPairSyncResult; - function generateKeyPairSync(type: 'ed25519', options: ED25519KeyPairOptions<'pem', 'der'>): KeyPairSyncResult; - function generateKeyPairSync(type: 'ed25519', options: ED25519KeyPairOptions<'der', 'pem'>): KeyPairSyncResult; - function generateKeyPairSync(type: 'ed25519', options: ED25519KeyPairOptions<'der', 'der'>): KeyPairSyncResult; - function generateKeyPairSync(type: 'ed25519', options?: ED25519KeyPairKeyObjectOptions): KeyPairKeyObjectResult; - - function generateKeyPairSync(type: 'ed448', options: ED448KeyPairOptions<'pem', 'pem'>): KeyPairSyncResult; - function generateKeyPairSync(type: 'ed448', options: ED448KeyPairOptions<'pem', 'der'>): KeyPairSyncResult; - function generateKeyPairSync(type: 'ed448', options: ED448KeyPairOptions<'der', 'pem'>): KeyPairSyncResult; - function generateKeyPairSync(type: 'ed448', options: ED448KeyPairOptions<'der', 'der'>): KeyPairSyncResult; - function generateKeyPairSync(type: 'ed448', options?: ED448KeyPairKeyObjectOptions): KeyPairKeyObjectResult; - - function generateKeyPairSync(type: 'x25519', options: X25519KeyPairOptions<'pem', 'pem'>): KeyPairSyncResult; - function generateKeyPairSync(type: 'x25519', options: X25519KeyPairOptions<'pem', 'der'>): KeyPairSyncResult; - function generateKeyPairSync(type: 'x25519', options: X25519KeyPairOptions<'der', 'pem'>): KeyPairSyncResult; - function generateKeyPairSync(type: 'x25519', options: X25519KeyPairOptions<'der', 'der'>): KeyPairSyncResult; - function generateKeyPairSync(type: 'x25519', options?: X25519KeyPairKeyObjectOptions): KeyPairKeyObjectResult; - - function generateKeyPairSync(type: 'x448', options: X448KeyPairOptions<'pem', 'pem'>): KeyPairSyncResult; - function generateKeyPairSync(type: 'x448', options: X448KeyPairOptions<'pem', 'der'>): KeyPairSyncResult; - function generateKeyPairSync(type: 'x448', options: X448KeyPairOptions<'der', 'pem'>): KeyPairSyncResult; - function generateKeyPairSync(type: 'x448', options: X448KeyPairOptions<'der', 'der'>): KeyPairSyncResult; - function generateKeyPairSync(type: 'x448', options?: X448KeyPairKeyObjectOptions): KeyPairKeyObjectResult; - - function generateKeyPair(type: 'rsa', options: RSAKeyPairOptions<'pem', 'pem'>, callback: (err: Error | null, publicKey: string, privateKey: string) => void): void; - function generateKeyPair(type: 'rsa', options: RSAKeyPairOptions<'pem', 'der'>, callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void): void; - function generateKeyPair(type: 'rsa', options: RSAKeyPairOptions<'der', 'pem'>, callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void): void; - function generateKeyPair(type: 'rsa', options: RSAKeyPairOptions<'der', 'der'>, callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void): void; - function generateKeyPair(type: 'rsa', options: RSAKeyPairKeyObjectOptions, callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void): void; - - function generateKeyPair(type: 'dsa', options: DSAKeyPairOptions<'pem', 'pem'>, callback: (err: Error | null, publicKey: string, privateKey: string) => void): void; - function generateKeyPair(type: 'dsa', options: DSAKeyPairOptions<'pem', 'der'>, callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void): void; - function generateKeyPair(type: 'dsa', options: DSAKeyPairOptions<'der', 'pem'>, callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void): void; - function generateKeyPair(type: 'dsa', options: DSAKeyPairOptions<'der', 'der'>, callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void): void; - function generateKeyPair(type: 'dsa', options: DSAKeyPairKeyObjectOptions, callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void): void; - - function generateKeyPair(type: 'ec', options: ECKeyPairOptions<'pem', 'pem'>, callback: (err: Error | null, publicKey: string, privateKey: string) => void): void; - function generateKeyPair(type: 'ec', options: ECKeyPairOptions<'pem', 'der'>, callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void): void; - function generateKeyPair(type: 'ec', options: ECKeyPairOptions<'der', 'pem'>, callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void): void; - function generateKeyPair(type: 'ec', options: ECKeyPairOptions<'der', 'der'>, callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void): void; - function generateKeyPair(type: 'ec', options: ECKeyPairKeyObjectOptions, callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void): void; - - function generateKeyPair(type: 'ed25519', options: ED25519KeyPairOptions<'pem', 'pem'>, callback: (err: Error | null, publicKey: string, privateKey: string) => void): void; - function generateKeyPair(type: 'ed25519', options: ED25519KeyPairOptions<'pem', 'der'>, callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void): void; - function generateKeyPair(type: 'ed25519', options: ED25519KeyPairOptions<'der', 'pem'>, callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void): void; - function generateKeyPair(type: 'ed25519', options: ED25519KeyPairOptions<'der', 'der'>, callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void): void; - function generateKeyPair(type: 'ed25519', options: ED25519KeyPairKeyObjectOptions | undefined, callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void): void; - - function generateKeyPair(type: 'ed448', options: ED448KeyPairOptions<'pem', 'pem'>, callback: (err: Error | null, publicKey: string, privateKey: string) => void): void; - function generateKeyPair(type: 'ed448', options: ED448KeyPairOptions<'pem', 'der'>, callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void): void; - function generateKeyPair(type: 'ed448', options: ED448KeyPairOptions<'der', 'pem'>, callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void): void; - function generateKeyPair(type: 'ed448', options: ED448KeyPairOptions<'der', 'der'>, callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void): void; - function generateKeyPair(type: 'ed448', options: ED448KeyPairKeyObjectOptions | undefined, callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void): void; - - function generateKeyPair(type: 'x25519', options: X25519KeyPairOptions<'pem', 'pem'>, callback: (err: Error | null, publicKey: string, privateKey: string) => void): void; - function generateKeyPair(type: 'x25519', options: X25519KeyPairOptions<'pem', 'der'>, callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void): void; - function generateKeyPair(type: 'x25519', options: X25519KeyPairOptions<'der', 'pem'>, callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void): void; - function generateKeyPair(type: 'x25519', options: X25519KeyPairOptions<'der', 'der'>, callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void): void; - function generateKeyPair(type: 'x25519', options: X25519KeyPairKeyObjectOptions | undefined, callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void): void; - - function generateKeyPair(type: 'x448', options: X448KeyPairOptions<'pem', 'pem'>, callback: (err: Error | null, publicKey: string, privateKey: string) => void): void; - function generateKeyPair(type: 'x448', options: X448KeyPairOptions<'pem', 'der'>, callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void): void; - function generateKeyPair(type: 'x448', options: X448KeyPairOptions<'der', 'pem'>, callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void): void; - function generateKeyPair(type: 'x448', options: X448KeyPairOptions<'der', 'der'>, callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void): void; - function generateKeyPair(type: 'x448', options: X448KeyPairKeyObjectOptions | undefined, callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void): void; - - namespace generateKeyPair { - function __promisify__(type: "rsa", options: RSAKeyPairOptions<'pem', 'pem'>): Promise<{ publicKey: string, privateKey: string }>; - function __promisify__(type: "rsa", options: RSAKeyPairOptions<'pem', 'der'>): Promise<{ publicKey: string, privateKey: Buffer }>; - function __promisify__(type: "rsa", options: RSAKeyPairOptions<'der', 'pem'>): Promise<{ publicKey: Buffer, privateKey: string }>; - function __promisify__(type: "rsa", options: RSAKeyPairOptions<'der', 'der'>): Promise<{ publicKey: Buffer, privateKey: Buffer }>; - function __promisify__(type: "rsa", options: RSAKeyPairKeyObjectOptions): Promise; - - function __promisify__(type: "dsa", options: DSAKeyPairOptions<'pem', 'pem'>): Promise<{ publicKey: string, privateKey: string }>; - function __promisify__(type: "dsa", options: DSAKeyPairOptions<'pem', 'der'>): Promise<{ publicKey: string, privateKey: Buffer }>; - function __promisify__(type: "dsa", options: DSAKeyPairOptions<'der', 'pem'>): Promise<{ publicKey: Buffer, privateKey: string }>; - function __promisify__(type: "dsa", options: DSAKeyPairOptions<'der', 'der'>): Promise<{ publicKey: Buffer, privateKey: Buffer }>; - function __promisify__(type: "dsa", options: DSAKeyPairKeyObjectOptions): Promise; - - function __promisify__(type: "ec", options: ECKeyPairOptions<'pem', 'pem'>): Promise<{ publicKey: string, privateKey: string }>; - function __promisify__(type: "ec", options: ECKeyPairOptions<'pem', 'der'>): Promise<{ publicKey: string, privateKey: Buffer }>; - function __promisify__(type: "ec", options: ECKeyPairOptions<'der', 'pem'>): Promise<{ publicKey: Buffer, privateKey: string }>; - function __promisify__(type: "ec", options: ECKeyPairOptions<'der', 'der'>): Promise<{ publicKey: Buffer, privateKey: Buffer }>; - function __promisify__(type: "ec", options: ECKeyPairKeyObjectOptions): Promise; - - function __promisify__(type: "ed25519", options: ED25519KeyPairOptions<'pem', 'pem'>): Promise<{ publicKey: string, privateKey: string }>; - function __promisify__(type: "ed25519", options: ED25519KeyPairOptions<'pem', 'der'>): Promise<{ publicKey: string, privateKey: Buffer }>; - function __promisify__(type: "ed25519", options: ED25519KeyPairOptions<'der', 'pem'>): Promise<{ publicKey: Buffer, privateKey: string }>; - function __promisify__(type: "ed25519", options: ED25519KeyPairOptions<'der', 'der'>): Promise<{ publicKey: Buffer, privateKey: Buffer }>; - function __promisify__(type: "ed25519", options?: ED25519KeyPairKeyObjectOptions): Promise; - - function __promisify__(type: "ed448", options: ED448KeyPairOptions<'pem', 'pem'>): Promise<{ publicKey: string, privateKey: string }>; - function __promisify__(type: "ed448", options: ED448KeyPairOptions<'pem', 'der'>): Promise<{ publicKey: string, privateKey: Buffer }>; - function __promisify__(type: "ed448", options: ED448KeyPairOptions<'der', 'pem'>): Promise<{ publicKey: Buffer, privateKey: string }>; - function __promisify__(type: "ed448", options: ED448KeyPairOptions<'der', 'der'>): Promise<{ publicKey: Buffer, privateKey: Buffer }>; - function __promisify__(type: "ed448", options?: ED448KeyPairKeyObjectOptions): Promise; - - function __promisify__(type: "x25519", options: X25519KeyPairOptions<'pem', 'pem'>): Promise<{ publicKey: string, privateKey: string }>; - function __promisify__(type: "x25519", options: X25519KeyPairOptions<'pem', 'der'>): Promise<{ publicKey: string, privateKey: Buffer }>; - function __promisify__(type: "x25519", options: X25519KeyPairOptions<'der', 'pem'>): Promise<{ publicKey: Buffer, privateKey: string }>; - function __promisify__(type: "x25519", options: X25519KeyPairOptions<'der', 'der'>): Promise<{ publicKey: Buffer, privateKey: Buffer }>; - function __promisify__(type: "x25519", options?: X25519KeyPairKeyObjectOptions): Promise; - - function __promisify__(type: "x448", options: X448KeyPairOptions<'pem', 'pem'>): Promise<{ publicKey: string, privateKey: string }>; - function __promisify__(type: "x448", options: X448KeyPairOptions<'pem', 'der'>): Promise<{ publicKey: string, privateKey: Buffer }>; - function __promisify__(type: "x448", options: X448KeyPairOptions<'der', 'pem'>): Promise<{ publicKey: Buffer, privateKey: string }>; - function __promisify__(type: "x448", options: X448KeyPairOptions<'der', 'der'>): Promise<{ publicKey: Buffer, privateKey: Buffer }>; - function __promisify__(type: "x448", options?: X448KeyPairKeyObjectOptions): Promise; - } - - /** - * Calculates and returns the signature for `data` using the given private key and - * algorithm. If `algorithm` is `null` or `undefined`, then the algorithm is - * dependent upon the key type (especially Ed25519 and Ed448). - * - * If `key` is not a [`KeyObject`][], this function behaves as if `key` had been - * passed to [`crypto.createPrivateKey()`][]. - */ - function sign(algorithm: string | null | undefined, data: NodeJS.ArrayBufferView, key: KeyLike | SignKeyObjectInput | SignPrivateKeyInput): Buffer; - - /** - * Calculates and returns the signature for `data` using the given private key and - * algorithm. If `algorithm` is `null` or `undefined`, then the algorithm is - * dependent upon the key type (especially Ed25519 and Ed448). - * - * If `key` is not a [`KeyObject`][], this function behaves as if `key` had been - * passed to [`crypto.createPublicKey()`][]. - */ - function verify(algorithm: string | null | undefined, data: NodeJS.ArrayBufferView, key: KeyLike | VerifyKeyObjectInput | VerifyPublicKeyInput, signature: NodeJS.ArrayBufferView): boolean; - - /** - * Computes the Diffie-Hellman secret based on a privateKey and a publicKey. - * Both keys must have the same asymmetricKeyType, which must be one of - * 'dh' (for Diffie-Hellman), 'ec' (for ECDH), 'x448', or 'x25519' (for ECDH-ES). - */ - function diffieHellman(options: { - privateKey: KeyObject; - publicKey: KeyObject - }): Buffer; -} diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/node/dgram.d.ts b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/node/dgram.d.ts deleted file mode 100644 index 73f2aa7191..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/node/dgram.d.ts +++ /dev/null @@ -1,141 +0,0 @@ -declare module "dgram" { - import { AddressInfo } from "net"; - import * as dns from "dns"; - import * as events from "events"; - - interface RemoteInfo { - address: string; - family: 'IPv4' | 'IPv6'; - port: number; - size: number; - } - - interface BindOptions { - port?: number; - address?: string; - exclusive?: boolean; - fd?: number; - } - - type SocketType = "udp4" | "udp6"; - - interface SocketOptions { - type: SocketType; - reuseAddr?: boolean; - /** - * @default false - */ - ipv6Only?: boolean; - recvBufferSize?: number; - sendBufferSize?: number; - lookup?: (hostname: string, options: dns.LookupOneOptions, callback: (err: NodeJS.ErrnoException | null, address: string, family: number) => void) => void; - } - - function createSocket(type: SocketType, callback?: (msg: Buffer, rinfo: RemoteInfo) => void): Socket; - function createSocket(options: SocketOptions, callback?: (msg: Buffer, rinfo: RemoteInfo) => void): Socket; - - class Socket extends events.EventEmitter { - addMembership(multicastAddress: string, multicastInterface?: string): void; - address(): AddressInfo; - bind(port?: number, address?: string, callback?: () => void): void; - bind(port?: number, callback?: () => void): void; - bind(callback?: () => void): void; - bind(options: BindOptions, callback?: () => void): void; - close(callback?: () => void): void; - connect(port: number, address?: string, callback?: () => void): void; - connect(port: number, callback: () => void): void; - disconnect(): void; - dropMembership(multicastAddress: string, multicastInterface?: string): void; - getRecvBufferSize(): number; - getSendBufferSize(): number; - ref(): this; - remoteAddress(): AddressInfo; - send(msg: string | Uint8Array | ReadonlyArray, port?: number, address?: string, callback?: (error: Error | null, bytes: number) => void): void; - send(msg: string | Uint8Array | ReadonlyArray, port?: number, callback?: (error: Error | null, bytes: number) => void): void; - send(msg: string | Uint8Array | ReadonlyArray, callback?: (error: Error | null, bytes: number) => void): void; - send(msg: string | Uint8Array, offset: number, length: number, port?: number, address?: string, callback?: (error: Error | null, bytes: number) => void): void; - send(msg: string | Uint8Array, offset: number, length: number, port?: number, callback?: (error: Error | null, bytes: number) => void): void; - send(msg: string | Uint8Array, offset: number, length: number, callback?: (error: Error | null, bytes: number) => void): void; - setBroadcast(flag: boolean): void; - setMulticastInterface(multicastInterface: string): void; - setMulticastLoopback(flag: boolean): void; - setMulticastTTL(ttl: number): void; - setRecvBufferSize(size: number): void; - setSendBufferSize(size: number): void; - setTTL(ttl: number): void; - unref(): this; - /** - * Tells the kernel to join a source-specific multicast channel at the given - * `sourceAddress` and `groupAddress`, using the `multicastInterface` with the - * `IP_ADD_SOURCE_MEMBERSHIP` socket option. - * If the `multicastInterface` argument - * is not specified, the operating system will choose one interface and will add - * membership to it. - * To add membership to every available interface, call - * `socket.addSourceSpecificMembership()` multiple times, once per interface. - */ - addSourceSpecificMembership(sourceAddress: string, groupAddress: string, multicastInterface?: string): void; - - /** - * Instructs the kernel to leave a source-specific multicast channel at the given - * `sourceAddress` and `groupAddress` using the `IP_DROP_SOURCE_MEMBERSHIP` - * socket option. This method is automatically called by the kernel when the - * socket is closed or the process terminates, so most apps will never have - * reason to call this. - * - * If `multicastInterface` is not specified, the operating system will attempt to - * drop membership on all valid interfaces. - */ - dropSourceSpecificMembership(sourceAddress: string, groupAddress: string, multicastInterface?: string): void; - - /** - * events.EventEmitter - * 1. close - * 2. connect - * 3. error - * 4. listening - * 5. message - */ - addListener(event: string, listener: (...args: any[]) => void): this; - addListener(event: "close", listener: () => void): this; - addListener(event: "connect", listener: () => void): this; - addListener(event: "error", listener: (err: Error) => void): this; - addListener(event: "listening", listener: () => void): this; - addListener(event: "message", listener: (msg: Buffer, rinfo: RemoteInfo) => void): this; - - emit(event: string | symbol, ...args: any[]): boolean; - emit(event: "close"): boolean; - emit(event: "connect"): boolean; - emit(event: "error", err: Error): boolean; - emit(event: "listening"): boolean; - emit(event: "message", msg: Buffer, rinfo: RemoteInfo): boolean; - - on(event: string, listener: (...args: any[]) => void): this; - on(event: "close", listener: () => void): this; - on(event: "connect", listener: () => void): this; - on(event: "error", listener: (err: Error) => void): this; - on(event: "listening", listener: () => void): this; - on(event: "message", listener: (msg: Buffer, rinfo: RemoteInfo) => void): this; - - once(event: string, listener: (...args: any[]) => void): this; - once(event: "close", listener: () => void): this; - once(event: "connect", listener: () => void): this; - once(event: "error", listener: (err: Error) => void): this; - once(event: "listening", listener: () => void): this; - once(event: "message", listener: (msg: Buffer, rinfo: RemoteInfo) => void): this; - - prependListener(event: string, listener: (...args: any[]) => void): this; - prependListener(event: "close", listener: () => void): this; - prependListener(event: "connect", listener: () => void): this; - prependListener(event: "error", listener: (err: Error) => void): this; - prependListener(event: "listening", listener: () => void): this; - prependListener(event: "message", listener: (msg: Buffer, rinfo: RemoteInfo) => void): this; - - prependOnceListener(event: string, listener: (...args: any[]) => void): this; - prependOnceListener(event: "close", listener: () => void): this; - prependOnceListener(event: "connect", listener: () => void): this; - prependOnceListener(event: "error", listener: (err: Error) => void): this; - prependOnceListener(event: "listening", listener: () => void): this; - prependOnceListener(event: "message", listener: (msg: Buffer, rinfo: RemoteInfo) => void): this; - } -} diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/node/dns.d.ts b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/node/dns.d.ts deleted file mode 100644 index 8ce8864445..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/node/dns.d.ts +++ /dev/null @@ -1,371 +0,0 @@ -declare module "dns" { - // Supported getaddrinfo flags. - const ADDRCONFIG: number; - const V4MAPPED: number; - /** - * If `dns.V4MAPPED` is specified, return resolved IPv6 addresses as - * well as IPv4 mapped IPv6 addresses. - */ - const ALL: number; - - interface LookupOptions { - family?: number; - hints?: number; - all?: boolean; - verbatim?: boolean; - } - - interface LookupOneOptions extends LookupOptions { - all?: false; - } - - interface LookupAllOptions extends LookupOptions { - all: true; - } - - interface LookupAddress { - address: string; - family: number; - } - - function lookup(hostname: string, family: number, callback: (err: NodeJS.ErrnoException | null, address: string, family: number) => void): void; - function lookup(hostname: string, options: LookupOneOptions, callback: (err: NodeJS.ErrnoException | null, address: string, family: number) => void): void; - function lookup(hostname: string, options: LookupAllOptions, callback: (err: NodeJS.ErrnoException | null, addresses: LookupAddress[]) => void): void; - function lookup(hostname: string, options: LookupOptions, callback: (err: NodeJS.ErrnoException | null, address: string | LookupAddress[], family: number) => void): void; - function lookup(hostname: string, callback: (err: NodeJS.ErrnoException | null, address: string, family: number) => void): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - namespace lookup { - function __promisify__(hostname: string, options: LookupAllOptions): Promise; - function __promisify__(hostname: string, options?: LookupOneOptions | number): Promise; - function __promisify__(hostname: string, options: LookupOptions): Promise; - } - - function lookupService(address: string, port: number, callback: (err: NodeJS.ErrnoException | null, hostname: string, service: string) => void): void; - - namespace lookupService { - function __promisify__(address: string, port: number): Promise<{ hostname: string, service: string }>; - } - - interface ResolveOptions { - ttl: boolean; - } - - interface ResolveWithTtlOptions extends ResolveOptions { - ttl: true; - } - - interface RecordWithTtl { - address: string; - ttl: number; - } - - /** @deprecated Use `AnyARecord` or `AnyAaaaRecord` instead. */ - type AnyRecordWithTtl = AnyARecord | AnyAaaaRecord; - - interface AnyARecord extends RecordWithTtl { - type: "A"; - } - - interface AnyAaaaRecord extends RecordWithTtl { - type: "AAAA"; - } - - interface MxRecord { - priority: number; - exchange: string; - } - - interface AnyMxRecord extends MxRecord { - type: "MX"; - } - - interface NaptrRecord { - flags: string; - service: string; - regexp: string; - replacement: string; - order: number; - preference: number; - } - - interface AnyNaptrRecord extends NaptrRecord { - type: "NAPTR"; - } - - interface SoaRecord { - nsname: string; - hostmaster: string; - serial: number; - refresh: number; - retry: number; - expire: number; - minttl: number; - } - - interface AnySoaRecord extends SoaRecord { - type: "SOA"; - } - - interface SrvRecord { - priority: number; - weight: number; - port: number; - name: string; - } - - interface AnySrvRecord extends SrvRecord { - type: "SRV"; - } - - interface AnyTxtRecord { - type: "TXT"; - entries: string[]; - } - - interface AnyNsRecord { - type: "NS"; - value: string; - } - - interface AnyPtrRecord { - type: "PTR"; - value: string; - } - - interface AnyCnameRecord { - type: "CNAME"; - value: string; - } - - type AnyRecord = AnyARecord | - AnyAaaaRecord | - AnyCnameRecord | - AnyMxRecord | - AnyNaptrRecord | - AnyNsRecord | - AnyPtrRecord | - AnySoaRecord | - AnySrvRecord | - AnyTxtRecord; - - function resolve(hostname: string, callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void): void; - function resolve(hostname: string, rrtype: "A", callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void): void; - function resolve(hostname: string, rrtype: "AAAA", callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void): void; - function resolve(hostname: string, rrtype: "ANY", callback: (err: NodeJS.ErrnoException | null, addresses: AnyRecord[]) => void): void; - function resolve(hostname: string, rrtype: "CNAME", callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void): void; - function resolve(hostname: string, rrtype: "MX", callback: (err: NodeJS.ErrnoException | null, addresses: MxRecord[]) => void): void; - function resolve(hostname: string, rrtype: "NAPTR", callback: (err: NodeJS.ErrnoException | null, addresses: NaptrRecord[]) => void): void; - function resolve(hostname: string, rrtype: "NS", callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void): void; - function resolve(hostname: string, rrtype: "PTR", callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void): void; - function resolve(hostname: string, rrtype: "SOA", callback: (err: NodeJS.ErrnoException | null, addresses: SoaRecord) => void): void; - function resolve(hostname: string, rrtype: "SRV", callback: (err: NodeJS.ErrnoException | null, addresses: SrvRecord[]) => void): void; - function resolve(hostname: string, rrtype: "TXT", callback: (err: NodeJS.ErrnoException | null, addresses: string[][]) => void): void; - function resolve( - hostname: string, - rrtype: string, - callback: (err: NodeJS.ErrnoException | null, addresses: string[] | MxRecord[] | NaptrRecord[] | SoaRecord | SrvRecord[] | string[][] | AnyRecord[]) => void, - ): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - namespace resolve { - function __promisify__(hostname: string, rrtype?: "A" | "AAAA" | "CNAME" | "NS" | "PTR"): Promise; - function __promisify__(hostname: string, rrtype: "ANY"): Promise; - function __promisify__(hostname: string, rrtype: "MX"): Promise; - function __promisify__(hostname: string, rrtype: "NAPTR"): Promise; - function __promisify__(hostname: string, rrtype: "SOA"): Promise; - function __promisify__(hostname: string, rrtype: "SRV"): Promise; - function __promisify__(hostname: string, rrtype: "TXT"): Promise; - function __promisify__(hostname: string, rrtype: string): Promise; - } - - function resolve4(hostname: string, callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void): void; - function resolve4(hostname: string, options: ResolveWithTtlOptions, callback: (err: NodeJS.ErrnoException | null, addresses: RecordWithTtl[]) => void): void; - function resolve4(hostname: string, options: ResolveOptions, callback: (err: NodeJS.ErrnoException | null, addresses: string[] | RecordWithTtl[]) => void): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - namespace resolve4 { - function __promisify__(hostname: string): Promise; - function __promisify__(hostname: string, options: ResolveWithTtlOptions): Promise; - function __promisify__(hostname: string, options?: ResolveOptions): Promise; - } - - function resolve6(hostname: string, callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void): void; - function resolve6(hostname: string, options: ResolveWithTtlOptions, callback: (err: NodeJS.ErrnoException | null, addresses: RecordWithTtl[]) => void): void; - function resolve6(hostname: string, options: ResolveOptions, callback: (err: NodeJS.ErrnoException | null, addresses: string[] | RecordWithTtl[]) => void): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - namespace resolve6 { - function __promisify__(hostname: string): Promise; - function __promisify__(hostname: string, options: ResolveWithTtlOptions): Promise; - function __promisify__(hostname: string, options?: ResolveOptions): Promise; - } - - function resolveCname(hostname: string, callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void): void; - namespace resolveCname { - function __promisify__(hostname: string): Promise; - } - - function resolveMx(hostname: string, callback: (err: NodeJS.ErrnoException | null, addresses: MxRecord[]) => void): void; - namespace resolveMx { - function __promisify__(hostname: string): Promise; - } - - function resolveNaptr(hostname: string, callback: (err: NodeJS.ErrnoException | null, addresses: NaptrRecord[]) => void): void; - namespace resolveNaptr { - function __promisify__(hostname: string): Promise; - } - - function resolveNs(hostname: string, callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void): void; - namespace resolveNs { - function __promisify__(hostname: string): Promise; - } - - function resolvePtr(hostname: string, callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void): void; - namespace resolvePtr { - function __promisify__(hostname: string): Promise; - } - - function resolveSoa(hostname: string, callback: (err: NodeJS.ErrnoException | null, address: SoaRecord) => void): void; - namespace resolveSoa { - function __promisify__(hostname: string): Promise; - } - - function resolveSrv(hostname: string, callback: (err: NodeJS.ErrnoException | null, addresses: SrvRecord[]) => void): void; - namespace resolveSrv { - function __promisify__(hostname: string): Promise; - } - - function resolveTxt(hostname: string, callback: (err: NodeJS.ErrnoException | null, addresses: string[][]) => void): void; - namespace resolveTxt { - function __promisify__(hostname: string): Promise; - } - - function resolveAny(hostname: string, callback: (err: NodeJS.ErrnoException | null, addresses: AnyRecord[]) => void): void; - namespace resolveAny { - function __promisify__(hostname: string): Promise; - } - - function reverse(ip: string, callback: (err: NodeJS.ErrnoException | null, hostnames: string[]) => void): void; - function setServers(servers: ReadonlyArray): void; - function getServers(): string[]; - - // Error codes - const NODATA: string; - const FORMERR: string; - const SERVFAIL: string; - const NOTFOUND: string; - const NOTIMP: string; - const REFUSED: string; - const BADQUERY: string; - const BADNAME: string; - const BADFAMILY: string; - const BADRESP: string; - const CONNREFUSED: string; - const TIMEOUT: string; - const EOF: string; - const FILE: string; - const NOMEM: string; - const DESTRUCTION: string; - const BADSTR: string; - const BADFLAGS: string; - const NONAME: string; - const BADHINTS: string; - const NOTINITIALIZED: string; - const LOADIPHLPAPI: string; - const ADDRGETNETWORKPARAMS: string; - const CANCELLED: string; - - class Resolver { - getServers: typeof getServers; - setServers: typeof setServers; - resolve: typeof resolve; - resolve4: typeof resolve4; - resolve6: typeof resolve6; - resolveAny: typeof resolveAny; - resolveCname: typeof resolveCname; - resolveMx: typeof resolveMx; - resolveNaptr: typeof resolveNaptr; - resolveNs: typeof resolveNs; - resolvePtr: typeof resolvePtr; - resolveSoa: typeof resolveSoa; - resolveSrv: typeof resolveSrv; - resolveTxt: typeof resolveTxt; - reverse: typeof reverse; - cancel(): void; - } - - namespace promises { - function getServers(): string[]; - - function lookup(hostname: string, family: number): Promise; - function lookup(hostname: string, options: LookupOneOptions): Promise; - function lookup(hostname: string, options: LookupAllOptions): Promise; - function lookup(hostname: string, options: LookupOptions): Promise; - function lookup(hostname: string): Promise; - - function lookupService(address: string, port: number): Promise<{ hostname: string, service: string }>; - - function resolve(hostname: string): Promise; - function resolve(hostname: string, rrtype: "A"): Promise; - function resolve(hostname: string, rrtype: "AAAA"): Promise; - function resolve(hostname: string, rrtype: "ANY"): Promise; - function resolve(hostname: string, rrtype: "CNAME"): Promise; - function resolve(hostname: string, rrtype: "MX"): Promise; - function resolve(hostname: string, rrtype: "NAPTR"): Promise; - function resolve(hostname: string, rrtype: "NS"): Promise; - function resolve(hostname: string, rrtype: "PTR"): Promise; - function resolve(hostname: string, rrtype: "SOA"): Promise; - function resolve(hostname: string, rrtype: "SRV"): Promise; - function resolve(hostname: string, rrtype: "TXT"): Promise; - function resolve(hostname: string, rrtype: string): Promise; - - function resolve4(hostname: string): Promise; - function resolve4(hostname: string, options: ResolveWithTtlOptions): Promise; - function resolve4(hostname: string, options: ResolveOptions): Promise; - - function resolve6(hostname: string): Promise; - function resolve6(hostname: string, options: ResolveWithTtlOptions): Promise; - function resolve6(hostname: string, options: ResolveOptions): Promise; - - function resolveAny(hostname: string): Promise; - - function resolveCname(hostname: string): Promise; - - function resolveMx(hostname: string): Promise; - - function resolveNaptr(hostname: string): Promise; - - function resolveNs(hostname: string): Promise; - - function resolvePtr(hostname: string): Promise; - - function resolveSoa(hostname: string): Promise; - - function resolveSrv(hostname: string): Promise; - - function resolveTxt(hostname: string): Promise; - - function reverse(ip: string): Promise; - - function setServers(servers: ReadonlyArray): void; - - class Resolver { - getServers: typeof getServers; - resolve: typeof resolve; - resolve4: typeof resolve4; - resolve6: typeof resolve6; - resolveAny: typeof resolveAny; - resolveCname: typeof resolveCname; - resolveMx: typeof resolveMx; - resolveNaptr: typeof resolveNaptr; - resolveNs: typeof resolveNs; - resolvePtr: typeof resolvePtr; - resolveSoa: typeof resolveSoa; - resolveSrv: typeof resolveSrv; - resolveTxt: typeof resolveTxt; - reverse: typeof reverse; - setServers: typeof setServers; - } - } -} diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/node/domain.d.ts b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/node/domain.d.ts deleted file mode 100644 index 63dcc9b039..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/node/domain.d.ts +++ /dev/null @@ -1,24 +0,0 @@ -declare module "domain" { - import { EventEmitter } from "events"; - - global { - namespace NodeJS { - interface Domain extends EventEmitter { - run(fn: (...args: any[]) => T, ...args: any[]): T; - add(emitter: EventEmitter | Timer): void; - remove(emitter: EventEmitter | Timer): void; - bind(cb: T): T; - intercept(cb: T): T; - } - } - } - - interface Domain extends NodeJS.Domain {} - class Domain extends EventEmitter { - members: Array; - enter(): void; - exit(): void; - } - - function create(): Domain; -} diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/node/events.d.ts b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/node/events.d.ts deleted file mode 100644 index a55b7b5157..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/node/events.d.ts +++ /dev/null @@ -1,83 +0,0 @@ -declare module "events" { - interface EventEmitterOptions { - /** - * Enables automatic capturing of promise rejection. - */ - captureRejections?: boolean; - } - - interface NodeEventTarget { - once(event: string | symbol, listener: (...args: any[]) => void): this; - } - - interface DOMEventTarget { - addEventListener(event: string, listener: (...args: any[]) => void, opts?: { once: boolean }): any; - } - - namespace EventEmitter { - function once(emitter: NodeEventTarget, event: string | symbol): Promise; - function once(emitter: DOMEventTarget, event: string): Promise; - function on(emitter: EventEmitter, event: string): AsyncIterableIterator; - const captureRejectionSymbol: unique symbol; - - /** - * This symbol shall be used to install a listener for only monitoring `'error'` - * events. Listeners installed using this symbol are called before the regular - * `'error'` listeners are called. - * - * Installing a listener using this symbol does not change the behavior once an - * `'error'` event is emitted, therefore the process will still crash if no - * regular `'error'` listener is installed. - */ - const errorMonitor: unique symbol; - /** - * Sets or gets the default captureRejection value for all emitters. - */ - let captureRejections: boolean; - - interface EventEmitter extends NodeJS.EventEmitter { - } - - class EventEmitter { - constructor(options?: EventEmitterOptions); - /** @deprecated since v4.0.0 */ - static listenerCount(emitter: EventEmitter, event: string | symbol): number; - static defaultMaxListeners: number; - /** - * This symbol shall be used to install a listener for only monitoring `'error'` - * events. Listeners installed using this symbol are called before the regular - * `'error'` listeners are called. - * - * Installing a listener using this symbol does not change the behavior once an - * `'error'` event is emitted, therefore the process will still crash if no - * regular `'error'` listener is installed. - */ - static readonly errorMonitor: unique symbol; - } - } - - global { - namespace NodeJS { - interface EventEmitter { - addListener(event: string | symbol, listener: (...args: any[]) => void): this; - on(event: string | symbol, listener: (...args: any[]) => void): this; - once(event: string | symbol, listener: (...args: any[]) => void): this; - removeListener(event: string | symbol, listener: (...args: any[]) => void): this; - off(event: string | symbol, listener: (...args: any[]) => void): this; - removeAllListeners(event?: string | symbol): this; - setMaxListeners(n: number): this; - getMaxListeners(): number; - listeners(event: string | symbol): Function[]; - rawListeners(event: string | symbol): Function[]; - emit(event: string | symbol, ...args: any[]): boolean; - listenerCount(type: string | symbol): number; - // Added in Node 6... - prependListener(event: string | symbol, listener: (...args: any[]) => void): this; - prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; - eventNames(): Array; - } - } - } - - export = EventEmitter; -} diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/node/fs.d.ts b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/node/fs.d.ts deleted file mode 100644 index af95ccb459..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/node/fs.d.ts +++ /dev/null @@ -1,2156 +0,0 @@ -declare module "fs" { - import * as stream from "stream"; - import * as events from "events"; - import { URL } from "url"; - import * as promises from 'fs/promises'; - - export { promises }; - /** - * Valid types for path values in "fs". - */ - export type PathLike = string | Buffer | URL; - - export type NoParamCallback = (err: NodeJS.ErrnoException | null) => void; - - export type BufferEncodingOption = 'buffer' | { encoding: 'buffer' }; - - export interface BaseEncodingOptions { - encoding?: BufferEncoding | null; - } - - export type OpenMode = number | string; - - export type Mode = number | string; - - export interface StatsBase { - isFile(): boolean; - isDirectory(): boolean; - isBlockDevice(): boolean; - isCharacterDevice(): boolean; - isSymbolicLink(): boolean; - isFIFO(): boolean; - isSocket(): boolean; - - dev: T; - ino: T; - mode: T; - nlink: T; - uid: T; - gid: T; - rdev: T; - size: T; - blksize: T; - blocks: T; - atimeMs: T; - mtimeMs: T; - ctimeMs: T; - birthtimeMs: T; - atime: Date; - mtime: Date; - ctime: Date; - birthtime: Date; - } - - export interface Stats extends StatsBase { - } - - export class Stats { - } - - export class Dirent { - isFile(): boolean; - isDirectory(): boolean; - isBlockDevice(): boolean; - isCharacterDevice(): boolean; - isSymbolicLink(): boolean; - isFIFO(): boolean; - isSocket(): boolean; - name: string; - } - - /** - * A class representing a directory stream. - */ - export class Dir { - readonly path: string; - - /** - * Asynchronously iterates over the directory via `readdir(3)` until all entries have been read. - */ - [Symbol.asyncIterator](): AsyncIterableIterator; - - /** - * Asynchronously close the directory's underlying resource handle. - * Subsequent reads will result in errors. - */ - close(): Promise; - close(cb: NoParamCallback): void; - - /** - * Synchronously close the directory's underlying resource handle. - * Subsequent reads will result in errors. - */ - closeSync(): void; - - /** - * Asynchronously read the next directory entry via `readdir(3)` as an `Dirent`. - * After the read is completed, a value is returned that will be resolved with an `Dirent`, or `null` if there are no more directory entries to read. - * Directory entries returned by this function are in no particular order as provided by the operating system's underlying directory mechanisms. - */ - read(): Promise; - read(cb: (err: NodeJS.ErrnoException | null, dirEnt: Dirent | null) => void): void; - - /** - * Synchronously read the next directory entry via `readdir(3)` as a `Dirent`. - * If there are no more directory entries to read, null will be returned. - * Directory entries returned by this function are in no particular order as provided by the operating system's underlying directory mechanisms. - */ - readSync(): Dirent; - } - - export interface FSWatcher extends events.EventEmitter { - close(): void; - - /** - * events.EventEmitter - * 1. change - * 2. error - */ - addListener(event: string, listener: (...args: any[]) => void): this; - addListener(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; - addListener(event: "error", listener: (error: Error) => void): this; - addListener(event: "close", listener: () => void): this; - - on(event: string, listener: (...args: any[]) => void): this; - on(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; - on(event: "error", listener: (error: Error) => void): this; - on(event: "close", listener: () => void): this; - - once(event: string, listener: (...args: any[]) => void): this; - once(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; - once(event: "error", listener: (error: Error) => void): this; - once(event: "close", listener: () => void): this; - - prependListener(event: string, listener: (...args: any[]) => void): this; - prependListener(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; - prependListener(event: "error", listener: (error: Error) => void): this; - prependListener(event: "close", listener: () => void): this; - - prependOnceListener(event: string, listener: (...args: any[]) => void): this; - prependOnceListener(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; - prependOnceListener(event: "error", listener: (error: Error) => void): this; - prependOnceListener(event: "close", listener: () => void): this; - } - - export class ReadStream extends stream.Readable { - close(): void; - bytesRead: number; - path: string | Buffer; - pending: boolean; - - /** - * events.EventEmitter - * 1. open - * 2. close - * 3. ready - */ - addListener(event: "close", listener: () => void): this; - addListener(event: "data", listener: (chunk: Buffer | string) => void): this; - addListener(event: "end", listener: () => void): this; - addListener(event: "error", listener: (err: Error) => void): this; - addListener(event: "open", listener: (fd: number) => void): this; - addListener(event: "pause", listener: () => void): this; - addListener(event: "readable", listener: () => void): this; - addListener(event: "ready", listener: () => void): this; - addListener(event: "resume", listener: () => void): this; - addListener(event: string | symbol, listener: (...args: any[]) => void): this; - - on(event: "close", listener: () => void): this; - on(event: "data", listener: (chunk: Buffer | string) => void): this; - on(event: "end", listener: () => void): this; - on(event: "error", listener: (err: Error) => void): this; - on(event: "open", listener: (fd: number) => void): this; - on(event: "pause", listener: () => void): this; - on(event: "readable", listener: () => void): this; - on(event: "ready", listener: () => void): this; - on(event: "resume", listener: () => void): this; - on(event: string | symbol, listener: (...args: any[]) => void): this; - - once(event: "close", listener: () => void): this; - once(event: "data", listener: (chunk: Buffer | string) => void): this; - once(event: "end", listener: () => void): this; - once(event: "error", listener: (err: Error) => void): this; - once(event: "open", listener: (fd: number) => void): this; - once(event: "pause", listener: () => void): this; - once(event: "readable", listener: () => void): this; - once(event: "ready", listener: () => void): this; - once(event: "resume", listener: () => void): this; - once(event: string | symbol, listener: (...args: any[]) => void): this; - - prependListener(event: "close", listener: () => void): this; - prependListener(event: "data", listener: (chunk: Buffer | string) => void): this; - prependListener(event: "end", listener: () => void): this; - prependListener(event: "error", listener: (err: Error) => void): this; - prependListener(event: "open", listener: (fd: number) => void): this; - prependListener(event: "pause", listener: () => void): this; - prependListener(event: "readable", listener: () => void): this; - prependListener(event: "ready", listener: () => void): this; - prependListener(event: "resume", listener: () => void): this; - prependListener(event: string | symbol, listener: (...args: any[]) => void): this; - - prependOnceListener(event: "close", listener: () => void): this; - prependOnceListener(event: "data", listener: (chunk: Buffer | string) => void): this; - prependOnceListener(event: "end", listener: () => void): this; - prependOnceListener(event: "error", listener: (err: Error) => void): this; - prependOnceListener(event: "open", listener: (fd: number) => void): this; - prependOnceListener(event: "pause", listener: () => void): this; - prependOnceListener(event: "readable", listener: () => void): this; - prependOnceListener(event: "ready", listener: () => void): this; - prependOnceListener(event: "resume", listener: () => void): this; - prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; - } - - export class WriteStream extends stream.Writable { - close(): void; - bytesWritten: number; - path: string | Buffer; - pending: boolean; - - /** - * events.EventEmitter - * 1. open - * 2. close - * 3. ready - */ - addListener(event: "close", listener: () => void): this; - addListener(event: "drain", listener: () => void): this; - addListener(event: "error", listener: (err: Error) => void): this; - addListener(event: "finish", listener: () => void): this; - addListener(event: "open", listener: (fd: number) => void): this; - addListener(event: "pipe", listener: (src: stream.Readable) => void): this; - addListener(event: "ready", listener: () => void): this; - addListener(event: "unpipe", listener: (src: stream.Readable) => void): this; - addListener(event: string | symbol, listener: (...args: any[]) => void): this; - - on(event: "close", listener: () => void): this; - on(event: "drain", listener: () => void): this; - on(event: "error", listener: (err: Error) => void): this; - on(event: "finish", listener: () => void): this; - on(event: "open", listener: (fd: number) => void): this; - on(event: "pipe", listener: (src: stream.Readable) => void): this; - on(event: "ready", listener: () => void): this; - on(event: "unpipe", listener: (src: stream.Readable) => void): this; - on(event: string | symbol, listener: (...args: any[]) => void): this; - - once(event: "close", listener: () => void): this; - once(event: "drain", listener: () => void): this; - once(event: "error", listener: (err: Error) => void): this; - once(event: "finish", listener: () => void): this; - once(event: "open", listener: (fd: number) => void): this; - once(event: "pipe", listener: (src: stream.Readable) => void): this; - once(event: "ready", listener: () => void): this; - once(event: "unpipe", listener: (src: stream.Readable) => void): this; - once(event: string | symbol, listener: (...args: any[]) => void): this; - - prependListener(event: "close", listener: () => void): this; - prependListener(event: "drain", listener: () => void): this; - prependListener(event: "error", listener: (err: Error) => void): this; - prependListener(event: "finish", listener: () => void): this; - prependListener(event: "open", listener: (fd: number) => void): this; - prependListener(event: "pipe", listener: (src: stream.Readable) => void): this; - prependListener(event: "ready", listener: () => void): this; - prependListener(event: "unpipe", listener: (src: stream.Readable) => void): this; - prependListener(event: string | symbol, listener: (...args: any[]) => void): this; - - prependOnceListener(event: "close", listener: () => void): this; - prependOnceListener(event: "drain", listener: () => void): this; - prependOnceListener(event: "error", listener: (err: Error) => void): this; - prependOnceListener(event: "finish", listener: () => void): this; - prependOnceListener(event: "open", listener: (fd: number) => void): this; - prependOnceListener(event: "pipe", listener: (src: stream.Readable) => void): this; - prependOnceListener(event: "ready", listener: () => void): this; - prependOnceListener(event: "unpipe", listener: (src: stream.Readable) => void): this; - prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; - } - - /** - * Asynchronous rename(2) - Change the name or location of a file or directory. - * @param oldPath A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - */ - export function rename(oldPath: PathLike, newPath: PathLike, callback: NoParamCallback): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - export namespace rename { - /** - * Asynchronous rename(2) - Change the name or location of a file or directory. - * @param oldPath A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - */ - function __promisify__(oldPath: PathLike, newPath: PathLike): Promise; - } - - /** - * Synchronous rename(2) - Change the name or location of a file or directory. - * @param oldPath A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - */ - export function renameSync(oldPath: PathLike, newPath: PathLike): void; - - /** - * Asynchronous truncate(2) - Truncate a file to a specified length. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param len If not specified, defaults to `0`. - */ - export function truncate(path: PathLike, len: number | undefined | null, callback: NoParamCallback): void; - - /** - * Asynchronous truncate(2) - Truncate a file to a specified length. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - */ - export function truncate(path: PathLike, callback: NoParamCallback): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - export namespace truncate { - /** - * Asynchronous truncate(2) - Truncate a file to a specified length. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param len If not specified, defaults to `0`. - */ - function __promisify__(path: PathLike, len?: number | null): Promise; - } - - /** - * Synchronous truncate(2) - Truncate a file to a specified length. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param len If not specified, defaults to `0`. - */ - export function truncateSync(path: PathLike, len?: number | null): void; - - /** - * Asynchronous ftruncate(2) - Truncate a file to a specified length. - * @param fd A file descriptor. - * @param len If not specified, defaults to `0`. - */ - export function ftruncate(fd: number, len: number | undefined | null, callback: NoParamCallback): void; - - /** - * Asynchronous ftruncate(2) - Truncate a file to a specified length. - * @param fd A file descriptor. - */ - export function ftruncate(fd: number, callback: NoParamCallback): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - export namespace ftruncate { - /** - * Asynchronous ftruncate(2) - Truncate a file to a specified length. - * @param fd A file descriptor. - * @param len If not specified, defaults to `0`. - */ - function __promisify__(fd: number, len?: number | null): Promise; - } - - /** - * Synchronous ftruncate(2) - Truncate a file to a specified length. - * @param fd A file descriptor. - * @param len If not specified, defaults to `0`. - */ - export function ftruncateSync(fd: number, len?: number | null): void; - - /** - * Asynchronous chown(2) - Change ownership of a file. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - export function chown(path: PathLike, uid: number, gid: number, callback: NoParamCallback): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - export namespace chown { - /** - * Asynchronous chown(2) - Change ownership of a file. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - function __promisify__(path: PathLike, uid: number, gid: number): Promise; - } - - /** - * Synchronous chown(2) - Change ownership of a file. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - export function chownSync(path: PathLike, uid: number, gid: number): void; - - /** - * Asynchronous fchown(2) - Change ownership of a file. - * @param fd A file descriptor. - */ - export function fchown(fd: number, uid: number, gid: number, callback: NoParamCallback): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - export namespace fchown { - /** - * Asynchronous fchown(2) - Change ownership of a file. - * @param fd A file descriptor. - */ - function __promisify__(fd: number, uid: number, gid: number): Promise; - } - - /** - * Synchronous fchown(2) - Change ownership of a file. - * @param fd A file descriptor. - */ - export function fchownSync(fd: number, uid: number, gid: number): void; - - /** - * Asynchronous lchown(2) - Change ownership of a file. Does not dereference symbolic links. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - export function lchown(path: PathLike, uid: number, gid: number, callback: NoParamCallback): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - export namespace lchown { - /** - * Asynchronous lchown(2) - Change ownership of a file. Does not dereference symbolic links. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - function __promisify__(path: PathLike, uid: number, gid: number): Promise; - } - - /** - * Synchronous lchown(2) - Change ownership of a file. Does not dereference symbolic links. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - export function lchownSync(path: PathLike, uid: number, gid: number): void; - - /** - * Asynchronous chmod(2) - Change permissions of a file. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param mode A file mode. If a string is passed, it is parsed as an octal integer. - */ - export function chmod(path: PathLike, mode: Mode, callback: NoParamCallback): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - export namespace chmod { - /** - * Asynchronous chmod(2) - Change permissions of a file. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param mode A file mode. If a string is passed, it is parsed as an octal integer. - */ - function __promisify__(path: PathLike, mode: Mode): Promise; - } - - /** - * Synchronous chmod(2) - Change permissions of a file. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param mode A file mode. If a string is passed, it is parsed as an octal integer. - */ - export function chmodSync(path: PathLike, mode: Mode): void; - - /** - * Asynchronous fchmod(2) - Change permissions of a file. - * @param fd A file descriptor. - * @param mode A file mode. If a string is passed, it is parsed as an octal integer. - */ - export function fchmod(fd: number, mode: Mode, callback: NoParamCallback): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - export namespace fchmod { - /** - * Asynchronous fchmod(2) - Change permissions of a file. - * @param fd A file descriptor. - * @param mode A file mode. If a string is passed, it is parsed as an octal integer. - */ - function __promisify__(fd: number, mode: Mode): Promise; - } - - /** - * Synchronous fchmod(2) - Change permissions of a file. - * @param fd A file descriptor. - * @param mode A file mode. If a string is passed, it is parsed as an octal integer. - */ - export function fchmodSync(fd: number, mode: Mode): void; - - /** - * Asynchronous lchmod(2) - Change permissions of a file. Does not dereference symbolic links. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param mode A file mode. If a string is passed, it is parsed as an octal integer. - */ - export function lchmod(path: PathLike, mode: Mode, callback: NoParamCallback): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - export namespace lchmod { - /** - * Asynchronous lchmod(2) - Change permissions of a file. Does not dereference symbolic links. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param mode A file mode. If a string is passed, it is parsed as an octal integer. - */ - function __promisify__(path: PathLike, mode: Mode): Promise; - } - - /** - * Synchronous lchmod(2) - Change permissions of a file. Does not dereference symbolic links. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param mode A file mode. If a string is passed, it is parsed as an octal integer. - */ - export function lchmodSync(path: PathLike, mode: Mode): void; - - /** - * Asynchronous stat(2) - Get file status. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - export function stat(path: PathLike, options: BigIntOptions, callback: (err: NodeJS.ErrnoException | null, stats: BigIntStats) => void): void; - export function stat(path: PathLike, options: StatOptions, callback: (err: NodeJS.ErrnoException | null, stats: Stats | BigIntStats) => void): void; - export function stat(path: PathLike, callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - export namespace stat { - /** - * Asynchronous stat(2) - Get file status. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - function __promisify__(path: PathLike, options: BigIntOptions): Promise; - function __promisify__(path: PathLike, options: StatOptions): Promise; - function __promisify__(path: PathLike): Promise; - } - - /** - * Synchronous stat(2) - Get file status. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - export function statSync(path: PathLike, options: BigIntOptions): BigIntStats; - export function statSync(path: PathLike, options: StatOptions): Stats | BigIntStats; - export function statSync(path: PathLike): Stats; - - /** - * Asynchronous fstat(2) - Get file status. - * @param fd A file descriptor. - */ - export function fstat(fd: number, callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - export namespace fstat { - /** - * Asynchronous fstat(2) - Get file status. - * @param fd A file descriptor. - */ - function __promisify__(fd: number): Promise; - } - - /** - * Synchronous fstat(2) - Get file status. - * @param fd A file descriptor. - */ - export function fstatSync(fd: number): Stats; - - /** - * Asynchronous lstat(2) - Get file status. Does not dereference symbolic links. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - export function lstat(path: PathLike, callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - export namespace lstat { - /** - * Asynchronous lstat(2) - Get file status. Does not dereference symbolic links. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - function __promisify__(path: PathLike): Promise; - } - - /** - * Synchronous lstat(2) - Get file status. Does not dereference symbolic links. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - export function lstatSync(path: PathLike): Stats; - - /** - * Asynchronous link(2) - Create a new link (also known as a hard link) to an existing file. - * @param existingPath A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - export function link(existingPath: PathLike, newPath: PathLike, callback: NoParamCallback): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - export namespace link { - /** - * Asynchronous link(2) - Create a new link (also known as a hard link) to an existing file. - * @param existingPath A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - function __promisify__(existingPath: PathLike, newPath: PathLike): Promise; - } - - /** - * Synchronous link(2) - Create a new link (also known as a hard link) to an existing file. - * @param existingPath A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - export function linkSync(existingPath: PathLike, newPath: PathLike): void; - - /** - * Asynchronous symlink(2) - Create a new symbolic link to an existing file. - * @param target A path to an existing file. If a URL is provided, it must use the `file:` protocol. - * @param path A path to the new symlink. If a URL is provided, it must use the `file:` protocol. - * @param type May be set to `'dir'`, `'file'`, or `'junction'` (default is `'file'`) and is only available on Windows (ignored on other platforms). - * When using `'junction'`, the `target` argument will automatically be normalized to an absolute path. - */ - export function symlink(target: PathLike, path: PathLike, type: symlink.Type | undefined | null, callback: NoParamCallback): void; - - /** - * Asynchronous symlink(2) - Create a new symbolic link to an existing file. - * @param target A path to an existing file. If a URL is provided, it must use the `file:` protocol. - * @param path A path to the new symlink. If a URL is provided, it must use the `file:` protocol. - */ - export function symlink(target: PathLike, path: PathLike, callback: NoParamCallback): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - export namespace symlink { - /** - * Asynchronous symlink(2) - Create a new symbolic link to an existing file. - * @param target A path to an existing file. If a URL is provided, it must use the `file:` protocol. - * @param path A path to the new symlink. If a URL is provided, it must use the `file:` protocol. - * @param type May be set to `'dir'`, `'file'`, or `'junction'` (default is `'file'`) and is only available on Windows (ignored on other platforms). - * When using `'junction'`, the `target` argument will automatically be normalized to an absolute path. - */ - function __promisify__(target: PathLike, path: PathLike, type?: string | null): Promise; - - type Type = "dir" | "file" | "junction"; - } - - /** - * Synchronous symlink(2) - Create a new symbolic link to an existing file. - * @param target A path to an existing file. If a URL is provided, it must use the `file:` protocol. - * @param path A path to the new symlink. If a URL is provided, it must use the `file:` protocol. - * @param type May be set to `'dir'`, `'file'`, or `'junction'` (default is `'file'`) and is only available on Windows (ignored on other platforms). - * When using `'junction'`, the `target` argument will automatically be normalized to an absolute path. - */ - export function symlinkSync(target: PathLike, path: PathLike, type?: symlink.Type | null): void; - - /** - * Asynchronous readlink(2) - read value of a symbolic link. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - export function readlink( - path: PathLike, - options: BaseEncodingOptions | BufferEncoding | undefined | null, - callback: (err: NodeJS.ErrnoException | null, linkString: string) => void - ): void; - - /** - * Asynchronous readlink(2) - read value of a symbolic link. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - export function readlink(path: PathLike, options: BufferEncodingOption, callback: (err: NodeJS.ErrnoException | null, linkString: Buffer) => void): void; - - /** - * Asynchronous readlink(2) - read value of a symbolic link. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - export function readlink(path: PathLike, options: BaseEncodingOptions | string | undefined | null, callback: (err: NodeJS.ErrnoException | null, linkString: string | Buffer) => void): void; - - /** - * Asynchronous readlink(2) - read value of a symbolic link. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - export function readlink(path: PathLike, callback: (err: NodeJS.ErrnoException | null, linkString: string) => void): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - export namespace readlink { - /** - * Asynchronous readlink(2) - read value of a symbolic link. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function __promisify__(path: PathLike, options?: BaseEncodingOptions | BufferEncoding | null): Promise; - - /** - * Asynchronous readlink(2) - read value of a symbolic link. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function __promisify__(path: PathLike, options: BufferEncodingOption): Promise; - - /** - * Asynchronous readlink(2) - read value of a symbolic link. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function __promisify__(path: PathLike, options?: BaseEncodingOptions | string | null): Promise; - } - - /** - * Synchronous readlink(2) - read value of a symbolic link. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - export function readlinkSync(path: PathLike, options?: BaseEncodingOptions | BufferEncoding | null): string; - - /** - * Synchronous readlink(2) - read value of a symbolic link. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - export function readlinkSync(path: PathLike, options: BufferEncodingOption): Buffer; - - /** - * Synchronous readlink(2) - read value of a symbolic link. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - export function readlinkSync(path: PathLike, options?: BaseEncodingOptions | string | null): string | Buffer; - - /** - * Asynchronous realpath(3) - return the canonicalized absolute pathname. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - export function realpath( - path: PathLike, - options: BaseEncodingOptions | BufferEncoding | undefined | null, - callback: (err: NodeJS.ErrnoException | null, resolvedPath: string) => void - ): void; - - /** - * Asynchronous realpath(3) - return the canonicalized absolute pathname. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - export function realpath(path: PathLike, options: BufferEncodingOption, callback: (err: NodeJS.ErrnoException | null, resolvedPath: Buffer) => void): void; - - /** - * Asynchronous realpath(3) - return the canonicalized absolute pathname. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - export function realpath(path: PathLike, options: BaseEncodingOptions | string | undefined | null, callback: (err: NodeJS.ErrnoException | null, resolvedPath: string | Buffer) => void): void; - - /** - * Asynchronous realpath(3) - return the canonicalized absolute pathname. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - export function realpath(path: PathLike, callback: (err: NodeJS.ErrnoException | null, resolvedPath: string) => void): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - export namespace realpath { - /** - * Asynchronous realpath(3) - return the canonicalized absolute pathname. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function __promisify__(path: PathLike, options?: BaseEncodingOptions | BufferEncoding | null): Promise; - - /** - * Asynchronous realpath(3) - return the canonicalized absolute pathname. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function __promisify__(path: PathLike, options: BufferEncodingOption): Promise; - - /** - * Asynchronous realpath(3) - return the canonicalized absolute pathname. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function __promisify__(path: PathLike, options?: BaseEncodingOptions | string | null): Promise; - - function native( - path: PathLike, - options: BaseEncodingOptions | BufferEncoding | undefined | null, - callback: (err: NodeJS.ErrnoException | null, resolvedPath: string) => void - ): void; - function native(path: PathLike, options: BufferEncodingOption, callback: (err: NodeJS.ErrnoException | null, resolvedPath: Buffer) => void): void; - function native(path: PathLike, options: BaseEncodingOptions | string | undefined | null, callback: (err: NodeJS.ErrnoException | null, resolvedPath: string | Buffer) => void): void; - function native(path: PathLike, callback: (err: NodeJS.ErrnoException | null, resolvedPath: string) => void): void; - } - - /** - * Synchronous realpath(3) - return the canonicalized absolute pathname. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - export function realpathSync(path: PathLike, options?: BaseEncodingOptions | BufferEncoding | null): string; - - /** - * Synchronous realpath(3) - return the canonicalized absolute pathname. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - export function realpathSync(path: PathLike, options: BufferEncodingOption): Buffer; - - /** - * Synchronous realpath(3) - return the canonicalized absolute pathname. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - export function realpathSync(path: PathLike, options?: BaseEncodingOptions | string | null): string | Buffer; - - export namespace realpathSync { - function native(path: PathLike, options?: BaseEncodingOptions | BufferEncoding | null): string; - function native(path: PathLike, options: BufferEncodingOption): Buffer; - function native(path: PathLike, options?: BaseEncodingOptions | string | null): string | Buffer; - } - - /** - * Asynchronous unlink(2) - delete a name and possibly the file it refers to. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - export function unlink(path: PathLike, callback: NoParamCallback): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - export namespace unlink { - /** - * Asynchronous unlink(2) - delete a name and possibly the file it refers to. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - function __promisify__(path: PathLike): Promise; - } - - /** - * Synchronous unlink(2) - delete a name and possibly the file it refers to. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - export function unlinkSync(path: PathLike): void; - - export interface RmDirOptions { - /** - * If `true`, perform a recursive directory removal. In - * recursive mode, errors are not reported if `path` does not exist, and - * operations are retried on failure. - * @experimental - * @default false - */ - recursive?: boolean; - } - - export interface RmDirAsyncOptions extends RmDirOptions { - /** - * The amount of time in milliseconds to wait between retries. - * This option is ignored if the `recursive` option is not `true`. - * @default 100 - */ - retryDelay?: number; - /** - * If an `EBUSY`, `EMFILE`, `ENFILE`, `ENOTEMPTY`, or - * `EPERM` error is encountered, Node.js will retry the operation with a linear - * backoff wait of `retryDelay` ms longer on each try. This option represents the - * number of retries. This option is ignored if the `recursive` option is not - * `true`. - * @default 0 - */ - maxRetries?: number; - } - - /** - * Asynchronous rmdir(2) - delete a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - export function rmdir(path: PathLike, callback: NoParamCallback): void; - export function rmdir(path: PathLike, options: RmDirAsyncOptions, callback: NoParamCallback): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - export namespace rmdir { - /** - * Asynchronous rmdir(2) - delete a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - function __promisify__(path: PathLike, options?: RmDirAsyncOptions): Promise; - } - - /** - * Synchronous rmdir(2) - delete a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - export function rmdirSync(path: PathLike, options?: RmDirOptions): void; - - export interface MakeDirectoryOptions { - /** - * Indicates whether parent folders should be created. - * If a folder was created, the path to the first created folder will be returned. - * @default false - */ - recursive?: boolean; - /** - * A file mode. If a string is passed, it is parsed as an octal integer. If not specified - * @default 0o777 - */ - mode?: Mode; - } - - /** - * Asynchronous mkdir(2) - create a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders - * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. - */ - export function mkdir(path: PathLike, options: MakeDirectoryOptions & { recursive: true }, callback: (err: NodeJS.ErrnoException | null, path: string) => void): void; - - /** - * Asynchronous mkdir(2) - create a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders - * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. - */ - export function mkdir(path: PathLike, options: Mode | (MakeDirectoryOptions & { recursive?: false; }) | null | undefined, callback: NoParamCallback): void; - - /** - * Asynchronous mkdir(2) - create a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders - * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. - */ - export function mkdir(path: PathLike, options: Mode | MakeDirectoryOptions | null | undefined, callback: (err: NodeJS.ErrnoException | null, path: string | undefined) => void): void; - - /** - * Asynchronous mkdir(2) - create a directory with a mode of `0o777`. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - export function mkdir(path: PathLike, callback: NoParamCallback): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - export namespace mkdir { - /** - * Asynchronous mkdir(2) - create a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders - * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. - */ - function __promisify__(path: PathLike, options: MakeDirectoryOptions & { recursive: true; }): Promise; - - /** - * Asynchronous mkdir(2) - create a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders - * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. - */ - function __promisify__(path: PathLike, options?: Mode | (MakeDirectoryOptions & { recursive?: false; }) | null): Promise; - - /** - * Asynchronous mkdir(2) - create a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders - * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. - */ - function __promisify__(path: PathLike, options?: Mode | MakeDirectoryOptions | null): Promise; - } - - /** - * Synchronous mkdir(2) - create a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders - * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. - */ - export function mkdirSync(path: PathLike, options: MakeDirectoryOptions & { recursive: true; }): string; - - /** - * Synchronous mkdir(2) - create a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders - * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. - */ - export function mkdirSync(path: PathLike, options?: Mode | (MakeDirectoryOptions & { recursive?: false; }) | null): void; - - /** - * Synchronous mkdir(2) - create a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders - * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. - */ - export function mkdirSync(path: PathLike, options?: Mode | MakeDirectoryOptions | null): string | undefined; - - /** - * Asynchronously creates a unique temporary directory. - * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - export function mkdtemp(prefix: string, options: BaseEncodingOptions | BufferEncoding | undefined | null, callback: (err: NodeJS.ErrnoException | null, folder: string) => void): void; - - /** - * Asynchronously creates a unique temporary directory. - * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - export function mkdtemp(prefix: string, options: "buffer" | { encoding: "buffer" }, callback: (err: NodeJS.ErrnoException | null, folder: Buffer) => void): void; - - /** - * Asynchronously creates a unique temporary directory. - * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - export function mkdtemp(prefix: string, options: BaseEncodingOptions | string | undefined | null, callback: (err: NodeJS.ErrnoException | null, folder: string | Buffer) => void): void; - - /** - * Asynchronously creates a unique temporary directory. - * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. - */ - export function mkdtemp(prefix: string, callback: (err: NodeJS.ErrnoException | null, folder: string) => void): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - export namespace mkdtemp { - /** - * Asynchronously creates a unique temporary directory. - * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function __promisify__(prefix: string, options?: BaseEncodingOptions | BufferEncoding | null): Promise; - - /** - * Asynchronously creates a unique temporary directory. - * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function __promisify__(prefix: string, options: BufferEncodingOption): Promise; - - /** - * Asynchronously creates a unique temporary directory. - * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function __promisify__(prefix: string, options?: BaseEncodingOptions | string | null): Promise; - } - - /** - * Synchronously creates a unique temporary directory. - * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - export function mkdtempSync(prefix: string, options?: BaseEncodingOptions | BufferEncoding | null): string; - - /** - * Synchronously creates a unique temporary directory. - * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - export function mkdtempSync(prefix: string, options: BufferEncodingOption): Buffer; - - /** - * Synchronously creates a unique temporary directory. - * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - export function mkdtempSync(prefix: string, options?: BaseEncodingOptions | string | null): string | Buffer; - - /** - * Asynchronous readdir(3) - read a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - export function readdir( - path: PathLike, - options: { encoding: BufferEncoding | null; withFileTypes?: false } | BufferEncoding | undefined | null, - callback: (err: NodeJS.ErrnoException | null, files: string[]) => void, - ): void; - - /** - * Asynchronous readdir(3) - read a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - export function readdir(path: PathLike, options: { encoding: "buffer"; withFileTypes?: false } | "buffer", callback: (err: NodeJS.ErrnoException | null, files: Buffer[]) => void): void; - - /** - * Asynchronous readdir(3) - read a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - export function readdir( - path: PathLike, - options: BaseEncodingOptions & { withFileTypes?: false } | BufferEncoding | undefined | null, - callback: (err: NodeJS.ErrnoException | null, files: string[] | Buffer[]) => void, - ): void; - - /** - * Asynchronous readdir(3) - read a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - export function readdir(path: PathLike, callback: (err: NodeJS.ErrnoException | null, files: string[]) => void): void; - - /** - * Asynchronous readdir(3) - read a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options If called with `withFileTypes: true` the result data will be an array of Dirent. - */ - export function readdir(path: PathLike, options: BaseEncodingOptions & { withFileTypes: true }, callback: (err: NodeJS.ErrnoException | null, files: Dirent[]) => void): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - export namespace readdir { - /** - * Asynchronous readdir(3) - read a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function __promisify__(path: PathLike, options?: { encoding: BufferEncoding | null; withFileTypes?: false } | BufferEncoding | null): Promise; - - /** - * Asynchronous readdir(3) - read a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function __promisify__(path: PathLike, options: "buffer" | { encoding: "buffer"; withFileTypes?: false }): Promise; - - /** - * Asynchronous readdir(3) - read a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function __promisify__(path: PathLike, options?: BaseEncodingOptions & { withFileTypes?: false } | BufferEncoding | null): Promise; - - /** - * Asynchronous readdir(3) - read a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options If called with `withFileTypes: true` the result data will be an array of Dirent - */ - function __promisify__(path: PathLike, options: BaseEncodingOptions & { withFileTypes: true }): Promise; - } - - /** - * Synchronous readdir(3) - read a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - export function readdirSync(path: PathLike, options?: { encoding: BufferEncoding | null; withFileTypes?: false } | BufferEncoding | null): string[]; - - /** - * Synchronous readdir(3) - read a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - export function readdirSync(path: PathLike, options: { encoding: "buffer"; withFileTypes?: false } | "buffer"): Buffer[]; - - /** - * Synchronous readdir(3) - read a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - export function readdirSync(path: PathLike, options?: BaseEncodingOptions & { withFileTypes?: false } | BufferEncoding | null): string[] | Buffer[]; - - /** - * Synchronous readdir(3) - read a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options If called with `withFileTypes: true` the result data will be an array of Dirent. - */ - export function readdirSync(path: PathLike, options: BaseEncodingOptions & { withFileTypes: true }): Dirent[]; - - /** - * Asynchronous close(2) - close a file descriptor. - * @param fd A file descriptor. - */ - export function close(fd: number, callback: NoParamCallback): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - export namespace close { - /** - * Asynchronous close(2) - close a file descriptor. - * @param fd A file descriptor. - */ - function __promisify__(fd: number): Promise; - } - - /** - * Synchronous close(2) - close a file descriptor. - * @param fd A file descriptor. - */ - export function closeSync(fd: number): void; - - /** - * Asynchronous open(2) - open and possibly create a file. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param mode A file mode. If a string is passed, it is parsed as an octal integer. If not supplied, defaults to `0o666`. - */ - export function open(path: PathLike, flags: OpenMode, mode: Mode | undefined | null, callback: (err: NodeJS.ErrnoException | null, fd: number) => void): void; - - /** - * Asynchronous open(2) - open and possibly create a file. If the file is created, its mode will be `0o666`. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - export function open(path: PathLike, flags: OpenMode, callback: (err: NodeJS.ErrnoException | null, fd: number) => void): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - export namespace open { - /** - * Asynchronous open(2) - open and possibly create a file. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param mode A file mode. If a string is passed, it is parsed as an octal integer. If not supplied, defaults to `0o666`. - */ - function __promisify__(path: PathLike, flags: OpenMode, mode?: Mode | null): Promise; - } - - /** - * Synchronous open(2) - open and possibly create a file, returning a file descriptor.. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param mode A file mode. If a string is passed, it is parsed as an octal integer. If not supplied, defaults to `0o666`. - */ - export function openSync(path: PathLike, flags: OpenMode, mode?: Mode | null): number; - - /** - * Asynchronously change file timestamps of the file referenced by the supplied path. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param atime The last access time. If a string is provided, it will be coerced to number. - * @param mtime The last modified time. If a string is provided, it will be coerced to number. - */ - export function utimes(path: PathLike, atime: string | number | Date, mtime: string | number | Date, callback: NoParamCallback): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - export namespace utimes { - /** - * Asynchronously change file timestamps of the file referenced by the supplied path. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param atime The last access time. If a string is provided, it will be coerced to number. - * @param mtime The last modified time. If a string is provided, it will be coerced to number. - */ - function __promisify__(path: PathLike, atime: string | number | Date, mtime: string | number | Date): Promise; - } - - /** - * Synchronously change file timestamps of the file referenced by the supplied path. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param atime The last access time. If a string is provided, it will be coerced to number. - * @param mtime The last modified time. If a string is provided, it will be coerced to number. - */ - export function utimesSync(path: PathLike, atime: string | number | Date, mtime: string | number | Date): void; - - /** - * Asynchronously change file timestamps of the file referenced by the supplied file descriptor. - * @param fd A file descriptor. - * @param atime The last access time. If a string is provided, it will be coerced to number. - * @param mtime The last modified time. If a string is provided, it will be coerced to number. - */ - export function futimes(fd: number, atime: string | number | Date, mtime: string | number | Date, callback: NoParamCallback): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - export namespace futimes { - /** - * Asynchronously change file timestamps of the file referenced by the supplied file descriptor. - * @param fd A file descriptor. - * @param atime The last access time. If a string is provided, it will be coerced to number. - * @param mtime The last modified time. If a string is provided, it will be coerced to number. - */ - function __promisify__(fd: number, atime: string | number | Date, mtime: string | number | Date): Promise; - } - - /** - * Synchronously change file timestamps of the file referenced by the supplied file descriptor. - * @param fd A file descriptor. - * @param atime The last access time. If a string is provided, it will be coerced to number. - * @param mtime The last modified time. If a string is provided, it will be coerced to number. - */ - export function futimesSync(fd: number, atime: string | number | Date, mtime: string | number | Date): void; - - /** - * Asynchronous fsync(2) - synchronize a file's in-core state with the underlying storage device. - * @param fd A file descriptor. - */ - export function fsync(fd: number, callback: NoParamCallback): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - export namespace fsync { - /** - * Asynchronous fsync(2) - synchronize a file's in-core state with the underlying storage device. - * @param fd A file descriptor. - */ - function __promisify__(fd: number): Promise; - } - - /** - * Synchronous fsync(2) - synchronize a file's in-core state with the underlying storage device. - * @param fd A file descriptor. - */ - export function fsyncSync(fd: number): void; - - /** - * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. - * @param fd A file descriptor. - * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. - * @param length The number of bytes to write. If not supplied, defaults to `buffer.length - offset`. - * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. - */ - export function write( - fd: number, - buffer: TBuffer, - offset: number | undefined | null, - length: number | undefined | null, - position: number | undefined | null, - callback: (err: NodeJS.ErrnoException | null, written: number, buffer: TBuffer) => void, - ): void; - - /** - * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. - * @param fd A file descriptor. - * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. - * @param length The number of bytes to write. If not supplied, defaults to `buffer.length - offset`. - */ - export function write( - fd: number, - buffer: TBuffer, - offset: number | undefined | null, - length: number | undefined | null, - callback: (err: NodeJS.ErrnoException | null, written: number, buffer: TBuffer) => void, - ): void; - - /** - * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. - * @param fd A file descriptor. - * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. - */ - export function write( - fd: number, - buffer: TBuffer, - offset: number | undefined | null, - callback: (err: NodeJS.ErrnoException | null, written: number, buffer: TBuffer) => void - ): void; - - /** - * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. - * @param fd A file descriptor. - */ - export function write(fd: number, buffer: TBuffer, callback: (err: NodeJS.ErrnoException | null, written: number, buffer: TBuffer) => void): void; - - /** - * Asynchronously writes `string` to the file referenced by the supplied file descriptor. - * @param fd A file descriptor. - * @param string A string to write. - * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. - * @param encoding The expected string encoding. - */ - export function write( - fd: number, - string: string, - position: number | undefined | null, - encoding: BufferEncoding | undefined | null, - callback: (err: NodeJS.ErrnoException | null, written: number, str: string) => void, - ): void; - - /** - * Asynchronously writes `string` to the file referenced by the supplied file descriptor. - * @param fd A file descriptor. - * @param string A string to write. - * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. - */ - export function write(fd: number, string: string, position: number | undefined | null, callback: (err: NodeJS.ErrnoException | null, written: number, str: string) => void): void; - - /** - * Asynchronously writes `string` to the file referenced by the supplied file descriptor. - * @param fd A file descriptor. - * @param string A string to write. - */ - export function write(fd: number, string: string, callback: (err: NodeJS.ErrnoException | null, written: number, str: string) => void): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - export namespace write { - /** - * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. - * @param fd A file descriptor. - * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. - * @param length The number of bytes to write. If not supplied, defaults to `buffer.length - offset`. - * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. - */ - function __promisify__( - fd: number, - buffer?: TBuffer, - offset?: number, - length?: number, - position?: number | null, - ): Promise<{ bytesWritten: number, buffer: TBuffer }>; - - /** - * Asynchronously writes `string` to the file referenced by the supplied file descriptor. - * @param fd A file descriptor. - * @param string A string to write. - * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. - * @param encoding The expected string encoding. - */ - function __promisify__(fd: number, string: string, position?: number | null, encoding?: BufferEncoding | null): Promise<{ bytesWritten: number, buffer: string }>; - } - - /** - * Synchronously writes `buffer` to the file referenced by the supplied file descriptor, returning the number of bytes written. - * @param fd A file descriptor. - * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. - * @param length The number of bytes to write. If not supplied, defaults to `buffer.length - offset`. - * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. - */ - export function writeSync(fd: number, buffer: NodeJS.ArrayBufferView, offset?: number | null, length?: number | null, position?: number | null): number; - - /** - * Synchronously writes `string` to the file referenced by the supplied file descriptor, returning the number of bytes written. - * @param fd A file descriptor. - * @param string A string to write. - * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. - * @param encoding The expected string encoding. - */ - export function writeSync(fd: number, string: string, position?: number | null, encoding?: BufferEncoding | null): number; - - /** - * Asynchronously reads data from the file referenced by the supplied file descriptor. - * @param fd A file descriptor. - * @param buffer The buffer that the data will be written to. - * @param offset The offset in the buffer at which to start writing. - * @param length The number of bytes to read. - * @param position The offset from the beginning of the file from which data should be read. If `null`, data will be read from the current position. - */ - export function read( - fd: number, - buffer: TBuffer, - offset: number, - length: number, - position: number | null, - callback: (err: NodeJS.ErrnoException | null, bytesRead: number, buffer: TBuffer) => void, - ): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - export namespace read { - /** - * @param fd A file descriptor. - * @param buffer The buffer that the data will be written to. - * @param offset The offset in the buffer at which to start writing. - * @param length The number of bytes to read. - * @param position The offset from the beginning of the file from which data should be read. If `null`, data will be read from the current position. - */ - function __promisify__( - fd: number, - buffer: TBuffer, - offset: number, - length: number, - position: number | null - ): Promise<{ bytesRead: number, buffer: TBuffer }>; - } - - export interface ReadSyncOptions { - /** - * @default 0 - */ - offset?: number; - /** - * @default `length of buffer` - */ - length?: number; - /** - * @default null - */ - position?: number | null; - } - - /** - * Synchronously reads data from the file referenced by the supplied file descriptor, returning the number of bytes read. - * @param fd A file descriptor. - * @param buffer The buffer that the data will be written to. - * @param offset The offset in the buffer at which to start writing. - * @param length The number of bytes to read. - * @param position The offset from the beginning of the file from which data should be read. If `null`, data will be read from the current position. - */ - export function readSync(fd: number, buffer: NodeJS.ArrayBufferView, offset: number, length: number, position: number | null): number; - - /** - * Similar to the above `fs.readSync` function, this version takes an optional `options` object. - * If no `options` object is specified, it will default with the above values. - */ - export function readSync(fd: number, buffer: NodeJS.ArrayBufferView, opts?: ReadSyncOptions): number; - - /** - * Asynchronously reads the entire contents of a file. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * If a file descriptor is provided, the underlying file will _not_ be closed automatically. - * @param options An object that may contain an optional flag. - * If a flag is not provided, it defaults to `'r'`. - */ - export function readFile(path: PathLike | number, options: { encoding?: null; flag?: string; } | undefined | null, callback: (err: NodeJS.ErrnoException | null, data: Buffer) => void): void; - - /** - * Asynchronously reads the entire contents of a file. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - * If a file descriptor is provided, the underlying file will _not_ be closed automatically. - * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. - * If a flag is not provided, it defaults to `'r'`. - */ - export function readFile(path: PathLike | number, options: { encoding: BufferEncoding; flag?: string; } | string, callback: (err: NodeJS.ErrnoException | null, data: string) => void): void; - - /** - * Asynchronously reads the entire contents of a file. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - * If a file descriptor is provided, the underlying file will _not_ be closed automatically. - * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. - * If a flag is not provided, it defaults to `'r'`. - */ - export function readFile( - path: PathLike | number, - options: BaseEncodingOptions & { flag?: string; } | string | undefined | null, - callback: (err: NodeJS.ErrnoException | null, data: string | Buffer) => void, - ): void; - - /** - * Asynchronously reads the entire contents of a file. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * If a file descriptor is provided, the underlying file will _not_ be closed automatically. - */ - export function readFile(path: PathLike | number, callback: (err: NodeJS.ErrnoException | null, data: Buffer) => void): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - export namespace readFile { - /** - * Asynchronously reads the entire contents of a file. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * If a file descriptor is provided, the underlying file will _not_ be closed automatically. - * @param options An object that may contain an optional flag. - * If a flag is not provided, it defaults to `'r'`. - */ - function __promisify__(path: PathLike | number, options?: { encoding?: null; flag?: string; } | null): Promise; - - /** - * Asynchronously reads the entire contents of a file. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - * If a file descriptor is provided, the underlying file will _not_ be closed automatically. - * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. - * If a flag is not provided, it defaults to `'r'`. - */ - function __promisify__(path: PathLike | number, options: { encoding: BufferEncoding; flag?: string; } | string): Promise; - - /** - * Asynchronously reads the entire contents of a file. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - * If a file descriptor is provided, the underlying file will _not_ be closed automatically. - * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. - * If a flag is not provided, it defaults to `'r'`. - */ - function __promisify__(path: PathLike | number, options?: BaseEncodingOptions & { flag?: string; } | string | null): Promise; - } - - /** - * Synchronously reads the entire contents of a file. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - * If a file descriptor is provided, the underlying file will _not_ be closed automatically. - * @param options An object that may contain an optional flag. If a flag is not provided, it defaults to `'r'`. - */ - export function readFileSync(path: PathLike | number, options?: { encoding?: null; flag?: string; } | null): Buffer; - - /** - * Synchronously reads the entire contents of a file. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - * If a file descriptor is provided, the underlying file will _not_ be closed automatically. - * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. - * If a flag is not provided, it defaults to `'r'`. - */ - export function readFileSync(path: PathLike | number, options: { encoding: BufferEncoding; flag?: string; } | BufferEncoding): string; - - /** - * Synchronously reads the entire contents of a file. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - * If a file descriptor is provided, the underlying file will _not_ be closed automatically. - * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. - * If a flag is not provided, it defaults to `'r'`. - */ - export function readFileSync(path: PathLike | number, options?: BaseEncodingOptions & { flag?: string; } | BufferEncoding | null): string | Buffer; - - export type WriteFileOptions = BaseEncodingOptions & { mode?: Mode; flag?: string; } | string | null; - - /** - * Asynchronously writes data to a file, replacing the file if it already exists. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - * If a file descriptor is provided, the underlying file will _not_ be closed automatically. - * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. - * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. - * If `encoding` is not supplied, the default of `'utf8'` is used. - * If `mode` is not supplied, the default of `0o666` is used. - * If `mode` is a string, it is parsed as an octal integer. - * If `flag` is not supplied, the default of `'w'` is used. - */ - export function writeFile(path: PathLike | number, data: string | NodeJS.ArrayBufferView, options: WriteFileOptions, callback: NoParamCallback): void; - - /** - * Asynchronously writes data to a file, replacing the file if it already exists. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - * If a file descriptor is provided, the underlying file will _not_ be closed automatically. - * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. - */ - export function writeFile(path: PathLike | number, data: string | NodeJS.ArrayBufferView, callback: NoParamCallback): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - export namespace writeFile { - /** - * Asynchronously writes data to a file, replacing the file if it already exists. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - * If a file descriptor is provided, the underlying file will _not_ be closed automatically. - * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. - * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. - * If `encoding` is not supplied, the default of `'utf8'` is used. - * If `mode` is not supplied, the default of `0o666` is used. - * If `mode` is a string, it is parsed as an octal integer. - * If `flag` is not supplied, the default of `'w'` is used. - */ - function __promisify__(path: PathLike | number, data: string | NodeJS.ArrayBufferView, options?: WriteFileOptions): Promise; - } - - /** - * Synchronously writes data to a file, replacing the file if it already exists. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - * If a file descriptor is provided, the underlying file will _not_ be closed automatically. - * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. - * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. - * If `encoding` is not supplied, the default of `'utf8'` is used. - * If `mode` is not supplied, the default of `0o666` is used. - * If `mode` is a string, it is parsed as an octal integer. - * If `flag` is not supplied, the default of `'w'` is used. - */ - export function writeFileSync(path: PathLike | number, data: string | NodeJS.ArrayBufferView, options?: WriteFileOptions): void; - - /** - * Asynchronously append data to a file, creating the file if it does not exist. - * @param file A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - * If a file descriptor is provided, the underlying file will _not_ be closed automatically. - * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. - * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. - * If `encoding` is not supplied, the default of `'utf8'` is used. - * If `mode` is not supplied, the default of `0o666` is used. - * If `mode` is a string, it is parsed as an octal integer. - * If `flag` is not supplied, the default of `'a'` is used. - */ - export function appendFile(file: PathLike | number, data: string | Uint8Array, options: WriteFileOptions, callback: NoParamCallback): void; - - /** - * Asynchronously append data to a file, creating the file if it does not exist. - * @param file A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - * If a file descriptor is provided, the underlying file will _not_ be closed automatically. - * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. - */ - export function appendFile(file: PathLike | number, data: string | Uint8Array, callback: NoParamCallback): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - export namespace appendFile { - /** - * Asynchronously append data to a file, creating the file if it does not exist. - * @param file A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - * If a file descriptor is provided, the underlying file will _not_ be closed automatically. - * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. - * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. - * If `encoding` is not supplied, the default of `'utf8'` is used. - * If `mode` is not supplied, the default of `0o666` is used. - * If `mode` is a string, it is parsed as an octal integer. - * If `flag` is not supplied, the default of `'a'` is used. - */ - function __promisify__(file: PathLike | number, data: string | Uint8Array, options?: WriteFileOptions): Promise; - } - - /** - * Synchronously append data to a file, creating the file if it does not exist. - * @param file A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - * If a file descriptor is provided, the underlying file will _not_ be closed automatically. - * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. - * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. - * If `encoding` is not supplied, the default of `'utf8'` is used. - * If `mode` is not supplied, the default of `0o666` is used. - * If `mode` is a string, it is parsed as an octal integer. - * If `flag` is not supplied, the default of `'a'` is used. - */ - export function appendFileSync(file: PathLike | number, data: string | Uint8Array, options?: WriteFileOptions): void; - - /** - * Watch for changes on `filename`. The callback `listener` will be called each time the file is accessed. - */ - export function watchFile(filename: PathLike, options: { persistent?: boolean; interval?: number; } | undefined, listener: (curr: Stats, prev: Stats) => void): void; - - /** - * Watch for changes on `filename`. The callback `listener` will be called each time the file is accessed. - * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - */ - export function watchFile(filename: PathLike, listener: (curr: Stats, prev: Stats) => void): void; - - /** - * Stop watching for changes on `filename`. - * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - */ - export function unwatchFile(filename: PathLike, listener?: (curr: Stats, prev: Stats) => void): void; - - /** - * Watch for changes on `filename`, where `filename` is either a file or a directory, returning an `FSWatcher`. - * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - * @param options Either the encoding for the filename provided to the listener, or an object optionally specifying encoding, persistent, and recursive options. - * If `encoding` is not supplied, the default of `'utf8'` is used. - * If `persistent` is not supplied, the default of `true` is used. - * If `recursive` is not supplied, the default of `false` is used. - */ - export function watch( - filename: PathLike, - options: { encoding?: BufferEncoding | null, persistent?: boolean, recursive?: boolean } | BufferEncoding | undefined | null, - listener?: (event: string, filename: string) => void, - ): FSWatcher; - - /** - * Watch for changes on `filename`, where `filename` is either a file or a directory, returning an `FSWatcher`. - * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - * @param options Either the encoding for the filename provided to the listener, or an object optionally specifying encoding, persistent, and recursive options. - * If `encoding` is not supplied, the default of `'utf8'` is used. - * If `persistent` is not supplied, the default of `true` is used. - * If `recursive` is not supplied, the default of `false` is used. - */ - export function watch(filename: PathLike, options: { encoding: "buffer", persistent?: boolean, recursive?: boolean } | "buffer", listener?: (event: string, filename: Buffer) => void): FSWatcher; - - /** - * Watch for changes on `filename`, where `filename` is either a file or a directory, returning an `FSWatcher`. - * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - * @param options Either the encoding for the filename provided to the listener, or an object optionally specifying encoding, persistent, and recursive options. - * If `encoding` is not supplied, the default of `'utf8'` is used. - * If `persistent` is not supplied, the default of `true` is used. - * If `recursive` is not supplied, the default of `false` is used. - */ - export function watch( - filename: PathLike, - options: { encoding?: BufferEncoding | null, persistent?: boolean, recursive?: boolean } | string | null, - listener?: (event: string, filename: string | Buffer) => void, - ): FSWatcher; - - /** - * Watch for changes on `filename`, where `filename` is either a file or a directory, returning an `FSWatcher`. - * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - */ - export function watch(filename: PathLike, listener?: (event: string, filename: string) => any): FSWatcher; - - /** - * Asynchronously tests whether or not the given path exists by checking with the file system. - * @deprecated since v1.0.0 Use `fs.stat()` or `fs.access()` instead - * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - */ - export function exists(path: PathLike, callback: (exists: boolean) => void): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - export namespace exists { - /** - * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - */ - function __promisify__(path: PathLike): Promise; - } - - /** - * Synchronously tests whether or not the given path exists by checking with the file system. - * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - */ - export function existsSync(path: PathLike): boolean; - - export namespace constants { - // File Access Constants - - /** Constant for fs.access(). File is visible to the calling process. */ - const F_OK: number; - - /** Constant for fs.access(). File can be read by the calling process. */ - const R_OK: number; - - /** Constant for fs.access(). File can be written by the calling process. */ - const W_OK: number; - - /** Constant for fs.access(). File can be executed by the calling process. */ - const X_OK: number; - - // File Copy Constants - - /** Constant for fs.copyFile. Flag indicating the destination file should not be overwritten if it already exists. */ - const COPYFILE_EXCL: number; - - /** - * Constant for fs.copyFile. copy operation will attempt to create a copy-on-write reflink. - * If the underlying platform does not support copy-on-write, then a fallback copy mechanism is used. - */ - const COPYFILE_FICLONE: number; - - /** - * Constant for fs.copyFile. Copy operation will attempt to create a copy-on-write reflink. - * If the underlying platform does not support copy-on-write, then the operation will fail with an error. - */ - const COPYFILE_FICLONE_FORCE: number; - - // File Open Constants - - /** Constant for fs.open(). Flag indicating to open a file for read-only access. */ - const O_RDONLY: number; - - /** Constant for fs.open(). Flag indicating to open a file for write-only access. */ - const O_WRONLY: number; - - /** Constant for fs.open(). Flag indicating to open a file for read-write access. */ - const O_RDWR: number; - - /** Constant for fs.open(). Flag indicating to create the file if it does not already exist. */ - const O_CREAT: number; - - /** Constant for fs.open(). Flag indicating that opening a file should fail if the O_CREAT flag is set and the file already exists. */ - const O_EXCL: number; - - /** - * Constant for fs.open(). Flag indicating that if path identifies a terminal device, - * opening the path shall not cause that terminal to become the controlling terminal for the process - * (if the process does not already have one). - */ - const O_NOCTTY: number; - - /** Constant for fs.open(). Flag indicating that if the file exists and is a regular file, and the file is opened successfully for write access, its length shall be truncated to zero. */ - const O_TRUNC: number; - - /** Constant for fs.open(). Flag indicating that data will be appended to the end of the file. */ - const O_APPEND: number; - - /** Constant for fs.open(). Flag indicating that the open should fail if the path is not a directory. */ - const O_DIRECTORY: number; - - /** - * constant for fs.open(). - * Flag indicating reading accesses to the file system will no longer result in - * an update to the atime information associated with the file. - * This flag is available on Linux operating systems only. - */ - const O_NOATIME: number; - - /** Constant for fs.open(). Flag indicating that the open should fail if the path is a symbolic link. */ - const O_NOFOLLOW: number; - - /** Constant for fs.open(). Flag indicating that the file is opened for synchronous I/O. */ - const O_SYNC: number; - - /** Constant for fs.open(). Flag indicating that the file is opened for synchronous I/O with write operations waiting for data integrity. */ - const O_DSYNC: number; - - /** Constant for fs.open(). Flag indicating to open the symbolic link itself rather than the resource it is pointing to. */ - const O_SYMLINK: number; - - /** Constant for fs.open(). When set, an attempt will be made to minimize caching effects of file I/O. */ - const O_DIRECT: number; - - /** Constant for fs.open(). Flag indicating to open the file in nonblocking mode when possible. */ - const O_NONBLOCK: number; - - // File Type Constants - - /** Constant for fs.Stats mode property for determining a file's type. Bit mask used to extract the file type code. */ - const S_IFMT: number; - - /** Constant for fs.Stats mode property for determining a file's type. File type constant for a regular file. */ - const S_IFREG: number; - - /** Constant for fs.Stats mode property for determining a file's type. File type constant for a directory. */ - const S_IFDIR: number; - - /** Constant for fs.Stats mode property for determining a file's type. File type constant for a character-oriented device file. */ - const S_IFCHR: number; - - /** Constant for fs.Stats mode property for determining a file's type. File type constant for a block-oriented device file. */ - const S_IFBLK: number; - - /** Constant for fs.Stats mode property for determining a file's type. File type constant for a FIFO/pipe. */ - const S_IFIFO: number; - - /** Constant for fs.Stats mode property for determining a file's type. File type constant for a symbolic link. */ - const S_IFLNK: number; - - /** Constant for fs.Stats mode property for determining a file's type. File type constant for a socket. */ - const S_IFSOCK: number; - - // File Mode Constants - - /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable, writable and executable by owner. */ - const S_IRWXU: number; - - /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by owner. */ - const S_IRUSR: number; - - /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by owner. */ - const S_IWUSR: number; - - /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by owner. */ - const S_IXUSR: number; - - /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable, writable and executable by group. */ - const S_IRWXG: number; - - /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by group. */ - const S_IRGRP: number; - - /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by group. */ - const S_IWGRP: number; - - /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by group. */ - const S_IXGRP: number; - - /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable, writable and executable by others. */ - const S_IRWXO: number; - - /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by others. */ - const S_IROTH: number; - - /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by others. */ - const S_IWOTH: number; - - /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by others. */ - const S_IXOTH: number; - - /** - * When set, a memory file mapping is used to access the file. This flag - * is available on Windows operating systems only. On other operating systems, - * this flag is ignored. - */ - const UV_FS_O_FILEMAP: number; - } - - /** - * Asynchronously tests a user's permissions for the file specified by path. - * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - */ - export function access(path: PathLike, mode: number | undefined, callback: NoParamCallback): void; - - /** - * Asynchronously tests a user's permissions for the file specified by path. - * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - */ - export function access(path: PathLike, callback: NoParamCallback): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - export namespace access { - /** - * Asynchronously tests a user's permissions for the file specified by path. - * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - */ - function __promisify__(path: PathLike, mode?: number): Promise; - } - - /** - * Synchronously tests a user's permissions for the file specified by path. - * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - */ - export function accessSync(path: PathLike, mode?: number): void; - - /** - * Returns a new `ReadStream` object. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - */ - export function createReadStream(path: PathLike, options?: string | { - flags?: string; - encoding?: BufferEncoding; - fd?: number; - mode?: number; - autoClose?: boolean; - /** - * @default false - */ - emitClose?: boolean; - start?: number; - end?: number; - highWaterMark?: number; - }): ReadStream; - - /** - * Returns a new `WriteStream` object. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - */ - export function createWriteStream(path: PathLike, options?: string | { - flags?: string; - encoding?: BufferEncoding; - fd?: number; - mode?: number; - autoClose?: boolean; - emitClose?: boolean; - start?: number; - highWaterMark?: number; - }): WriteStream; - - /** - * Asynchronous fdatasync(2) - synchronize a file's in-core state with storage device. - * @param fd A file descriptor. - */ - export function fdatasync(fd: number, callback: NoParamCallback): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - export namespace fdatasync { - /** - * Asynchronous fdatasync(2) - synchronize a file's in-core state with storage device. - * @param fd A file descriptor. - */ - function __promisify__(fd: number): Promise; - } - - /** - * Synchronous fdatasync(2) - synchronize a file's in-core state with storage device. - * @param fd A file descriptor. - */ - export function fdatasyncSync(fd: number): void; - - /** - * Asynchronously copies src to dest. By default, dest is overwritten if it already exists. - * No arguments other than a possible exception are given to the callback function. - * Node.js makes no guarantees about the atomicity of the copy operation. - * If an error occurs after the destination file has been opened for writing, Node.js will attempt - * to remove the destination. - * @param src A path to the source file. - * @param dest A path to the destination file. - */ - export function copyFile(src: PathLike, dest: PathLike, callback: NoParamCallback): void; - /** - * Asynchronously copies src to dest. By default, dest is overwritten if it already exists. - * No arguments other than a possible exception are given to the callback function. - * Node.js makes no guarantees about the atomicity of the copy operation. - * If an error occurs after the destination file has been opened for writing, Node.js will attempt - * to remove the destination. - * @param src A path to the source file. - * @param dest A path to the destination file. - * @param flags An integer that specifies the behavior of the copy operation. The only supported flag is fs.constants.COPYFILE_EXCL, which causes the copy operation to fail if dest already exists. - */ - export function copyFile(src: PathLike, dest: PathLike, flags: number, callback: NoParamCallback): void; - - // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. - export namespace copyFile { - /** - * Asynchronously copies src to dest. By default, dest is overwritten if it already exists. - * No arguments other than a possible exception are given to the callback function. - * Node.js makes no guarantees about the atomicity of the copy operation. - * If an error occurs after the destination file has been opened for writing, Node.js will attempt - * to remove the destination. - * @param src A path to the source file. - * @param dest A path to the destination file. - * @param flags An optional integer that specifies the behavior of the copy operation. - * The only supported flag is fs.constants.COPYFILE_EXCL, - * which causes the copy operation to fail if dest already exists. - */ - function __promisify__(src: PathLike, dst: PathLike, flags?: number): Promise; - } - - /** - * Synchronously copies src to dest. By default, dest is overwritten if it already exists. - * Node.js makes no guarantees about the atomicity of the copy operation. - * If an error occurs after the destination file has been opened for writing, Node.js will attempt - * to remove the destination. - * @param src A path to the source file. - * @param dest A path to the destination file. - * @param flags An optional integer that specifies the behavior of the copy operation. - * The only supported flag is fs.constants.COPYFILE_EXCL, which causes the copy operation to fail if dest already exists. - */ - export function copyFileSync(src: PathLike, dest: PathLike, flags?: number): void; - - /** - * Write an array of ArrayBufferViews to the file specified by fd using writev(). - * position is the offset from the beginning of the file where this data should be written. - * It is unsafe to use fs.writev() multiple times on the same file without waiting for the callback. For this scenario, use fs.createWriteStream(). - * On Linux, positional writes don't work when the file is opened in append mode. - * The kernel ignores the position argument and always appends the data to the end of the file. - */ - export function writev( - fd: number, - buffers: ReadonlyArray, - cb: (err: NodeJS.ErrnoException | null, bytesWritten: number, buffers: NodeJS.ArrayBufferView[]) => void - ): void; - export function writev( - fd: number, - buffers: ReadonlyArray, - position: number, - cb: (err: NodeJS.ErrnoException | null, bytesWritten: number, buffers: NodeJS.ArrayBufferView[]) => void - ): void; - - export interface WriteVResult { - bytesWritten: number; - buffers: NodeJS.ArrayBufferView[]; - } - - export namespace writev { - function __promisify__(fd: number, buffers: ReadonlyArray, position?: number): Promise; - } - - /** - * See `writev`. - */ - export function writevSync(fd: number, buffers: ReadonlyArray, position?: number): number; - - export function readv( - fd: number, - buffers: ReadonlyArray, - cb: (err: NodeJS.ErrnoException | null, bytesRead: number, buffers: NodeJS.ArrayBufferView[]) => void - ): void; - export function readv( - fd: number, - buffers: ReadonlyArray, - position: number, - cb: (err: NodeJS.ErrnoException | null, bytesRead: number, buffers: NodeJS.ArrayBufferView[]) => void - ): void; - - export interface ReadVResult { - bytesRead: number; - buffers: NodeJS.ArrayBufferView[]; - } - - export namespace readv { - function __promisify__(fd: number, buffers: ReadonlyArray, position?: number): Promise; - } - - /** - * See `readv`. - */ - export function readvSync(fd: number, buffers: ReadonlyArray, position?: number): number; - - export interface OpenDirOptions { - encoding?: BufferEncoding; - /** - * Number of directory entries that are buffered - * internally when reading from the directory. Higher values lead to better - * performance but higher memory usage. - * @default 32 - */ - bufferSize?: number; - } - - export function opendirSync(path: string, options?: OpenDirOptions): Dir; - - export function opendir(path: string, cb: (err: NodeJS.ErrnoException | null, dir: Dir) => void): void; - export function opendir(path: string, options: OpenDirOptions, cb: (err: NodeJS.ErrnoException | null, dir: Dir) => void): void; - - export namespace opendir { - function __promisify__(path: string, options?: OpenDirOptions): Promise; - } - - export interface BigIntStats extends StatsBase { - } - - export class BigIntStats { - atimeNs: bigint; - mtimeNs: bigint; - ctimeNs: bigint; - birthtimeNs: bigint; - } - - export interface BigIntOptions { - bigint: true; - } - - export interface StatOptions { - bigint: boolean; - } -} diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/node/fs/promises.d.ts b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/node/fs/promises.d.ts deleted file mode 100644 index a7a1b829c9..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/node/fs/promises.d.ts +++ /dev/null @@ -1,539 +0,0 @@ -declare module 'fs/promises' { - import { - Stats, - WriteVResult, - ReadVResult, - PathLike, - RmDirAsyncOptions, - MakeDirectoryOptions, - Dirent, - OpenDirOptions, - Dir, - BaseEncodingOptions, - BufferEncodingOption, - OpenMode, - Mode, - } from 'fs'; - - interface FileHandle { - /** - * Gets the file descriptor for this file handle. - */ - readonly fd: number; - - /** - * Asynchronously append data to a file, creating the file if it does not exist. The underlying file will _not_ be closed automatically. - * The `FileHandle` must have been opened for appending. - * @param data The data to write. If something other than a `Buffer` or `Uint8Array` is provided, the value is coerced to a string. - * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. - * If `encoding` is not supplied, the default of `'utf8'` is used. - * If `mode` is not supplied, the default of `0o666` is used. - * If `mode` is a string, it is parsed as an octal integer. - * If `flag` is not supplied, the default of `'a'` is used. - */ - appendFile(data: string | Uint8Array, options?: BaseEncodingOptions & { mode?: Mode, flag?: OpenMode } | BufferEncoding | null): Promise; - - /** - * Asynchronous fchown(2) - Change ownership of a file. - */ - chown(uid: number, gid: number): Promise; - - /** - * Asynchronous fchmod(2) - Change permissions of a file. - * @param mode A file mode. If a string is passed, it is parsed as an octal integer. - */ - chmod(mode: Mode): Promise; - - /** - * Asynchronous fdatasync(2) - synchronize a file's in-core state with storage device. - */ - datasync(): Promise; - - /** - * Asynchronous fsync(2) - synchronize a file's in-core state with the underlying storage device. - */ - sync(): Promise; - - /** - * Asynchronously reads data from the file. - * The `FileHandle` must have been opened for reading. - * @param buffer The buffer that the data will be written to. - * @param offset The offset in the buffer at which to start writing. - * @param length The number of bytes to read. - * @param position The offset from the beginning of the file from which data should be read. If `null`, data will be read from the current position. - */ - read(buffer: TBuffer, offset?: number | null, length?: number | null, position?: number | null): Promise<{ bytesRead: number, buffer: TBuffer }>; - - /** - * Asynchronously reads the entire contents of a file. The underlying file will _not_ be closed automatically. - * The `FileHandle` must have been opened for reading. - * @param options An object that may contain an optional flag. - * If a flag is not provided, it defaults to `'r'`. - */ - readFile(options?: { encoding?: null, flag?: OpenMode } | null): Promise; - - /** - * Asynchronously reads the entire contents of a file. The underlying file will _not_ be closed automatically. - * The `FileHandle` must have been opened for reading. - * @param options An object that may contain an optional flag. - * If a flag is not provided, it defaults to `'r'`. - */ - readFile(options: { encoding: BufferEncoding, flag?: OpenMode } | BufferEncoding): Promise; - - /** - * Asynchronously reads the entire contents of a file. The underlying file will _not_ be closed automatically. - * The `FileHandle` must have been opened for reading. - * @param options An object that may contain an optional flag. - * If a flag is not provided, it defaults to `'r'`. - */ - readFile(options?: BaseEncodingOptions & { flag?: OpenMode } | BufferEncoding | null): Promise; - - /** - * Asynchronous fstat(2) - Get file status. - */ - stat(): Promise; - - /** - * Asynchronous ftruncate(2) - Truncate a file to a specified length. - * @param len If not specified, defaults to `0`. - */ - truncate(len?: number): Promise; - - /** - * Asynchronously change file timestamps of the file. - * @param atime The last access time. If a string is provided, it will be coerced to number. - * @param mtime The last modified time. If a string is provided, it will be coerced to number. - */ - utimes(atime: string | number | Date, mtime: string | number | Date): Promise; - - /** - * Asynchronously writes `buffer` to the file. - * The `FileHandle` must have been opened for writing. - * @param buffer The buffer that the data will be written to. - * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. - * @param length The number of bytes to write. If not supplied, defaults to `buffer.length - offset`. - * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. - */ - write(buffer: TBuffer, offset?: number | null, length?: number | null, position?: number | null): Promise<{ bytesWritten: number, buffer: TBuffer }>; - - /** - * Asynchronously writes `string` to the file. - * The `FileHandle` must have been opened for writing. - * It is unsafe to call `write()` multiple times on the same file without waiting for the `Promise` - * to be resolved (or rejected). For this scenario, `fs.createWriteStream` is strongly recommended. - * @param string A string to write. - * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. - * @param encoding The expected string encoding. - */ - write(data: string | Uint8Array, position?: number | null, encoding?: BufferEncoding | null): Promise<{ bytesWritten: number, buffer: string }>; - - /** - * Asynchronously writes data to a file, replacing the file if it already exists. The underlying file will _not_ be closed automatically. - * The `FileHandle` must have been opened for writing. - * It is unsafe to call `writeFile()` multiple times on the same file without waiting for the `Promise` to be resolved (or rejected). - * @param data The data to write. If something other than a `Buffer` or `Uint8Array` is provided, the value is coerced to a string. - * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. - * If `encoding` is not supplied, the default of `'utf8'` is used. - * If `mode` is not supplied, the default of `0o666` is used. - * If `mode` is a string, it is parsed as an octal integer. - * If `flag` is not supplied, the default of `'w'` is used. - */ - writeFile(data: string | Uint8Array, options?: BaseEncodingOptions & { mode?: Mode, flag?: OpenMode } | BufferEncoding | null): Promise; - - /** - * See `fs.writev` promisified version. - */ - writev(buffers: ReadonlyArray, position?: number): Promise; - - /** - * See `fs.readv` promisified version. - */ - readv(buffers: ReadonlyArray, position?: number): Promise; - - /** - * Asynchronous close(2) - close a `FileHandle`. - */ - close(): Promise; - } - - /** - * Asynchronously tests a user's permissions for the file specified by path. - * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - */ - function access(path: PathLike, mode?: number): Promise; - - /** - * Asynchronously copies `src` to `dest`. By default, `dest` is overwritten if it already exists. - * Node.js makes no guarantees about the atomicity of the copy operation. - * If an error occurs after the destination file has been opened for writing, Node.js will attempt - * to remove the destination. - * @param src A path to the source file. - * @param dest A path to the destination file. - * @param flags An optional integer that specifies the behavior of the copy operation. The only - * supported flag is `fs.constants.COPYFILE_EXCL`, which causes the copy operation to fail if - * `dest` already exists. - */ - function copyFile(src: PathLike, dest: PathLike, flags?: number): Promise; - - /** - * Asynchronous open(2) - open and possibly create a file. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param mode A file mode. If a string is passed, it is parsed as an octal integer. If not - * supplied, defaults to `0o666`. - */ - function open(path: PathLike, flags: string | number, mode?: Mode): Promise; - - /** - * Asynchronously reads data from the file referenced by the supplied `FileHandle`. - * @param handle A `FileHandle`. - * @param buffer The buffer that the data will be written to. - * @param offset The offset in the buffer at which to start writing. - * @param length The number of bytes to read. - * @param position The offset from the beginning of the file from which data should be read. If - * `null`, data will be read from the current position. - */ - function read( - handle: FileHandle, - buffer: TBuffer, - offset?: number | null, - length?: number | null, - position?: number | null, - ): Promise<{ bytesRead: number, buffer: TBuffer }>; - - /** - * Asynchronously writes `buffer` to the file referenced by the supplied `FileHandle`. - * It is unsafe to call `fsPromises.write()` multiple times on the same file without waiting for the `Promise` - * to be resolved (or rejected). For this scenario, `fs.createWriteStream` is strongly recommended. - * @param handle A `FileHandle`. - * @param buffer The buffer that the data will be written to. - * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. - * @param length The number of bytes to write. If not supplied, defaults to `buffer.length - offset`. - * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. - */ - function write( - handle: FileHandle, - buffer: TBuffer, - offset?: number | null, - length?: number | null, position?: number | null): Promise<{ bytesWritten: number, buffer: TBuffer }>; - - /** - * Asynchronously writes `string` to the file referenced by the supplied `FileHandle`. - * It is unsafe to call `fsPromises.write()` multiple times on the same file without waiting for the `Promise` - * to be resolved (or rejected). For this scenario, `fs.createWriteStream` is strongly recommended. - * @param handle A `FileHandle`. - * @param string A string to write. - * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. - * @param encoding The expected string encoding. - */ - function write(handle: FileHandle, string: string, position?: number | null, encoding?: BufferEncoding | null): Promise<{ bytesWritten: number, buffer: string }>; - - /** - * Asynchronous rename(2) - Change the name or location of a file or directory. - * @param oldPath A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - */ - function rename(oldPath: PathLike, newPath: PathLike): Promise; - - /** - * Asynchronous truncate(2) - Truncate a file to a specified length. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param len If not specified, defaults to `0`. - */ - function truncate(path: PathLike, len?: number): Promise; - - /** - * Asynchronous ftruncate(2) - Truncate a file to a specified length. - * @param handle A `FileHandle`. - * @param len If not specified, defaults to `0`. - */ - function ftruncate(handle: FileHandle, len?: number): Promise; - - /** - * Asynchronous rmdir(2) - delete a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - function rmdir(path: PathLike, options?: RmDirAsyncOptions): Promise; - - /** - * Asynchronous fdatasync(2) - synchronize a file's in-core state with storage device. - * @param handle A `FileHandle`. - */ - function fdatasync(handle: FileHandle): Promise; - - /** - * Asynchronous fsync(2) - synchronize a file's in-core state with the underlying storage device. - * @param handle A `FileHandle`. - */ - function fsync(handle: FileHandle): Promise; - - /** - * Asynchronous mkdir(2) - create a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders - * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. - */ - function mkdir(path: PathLike, options: MakeDirectoryOptions & { recursive: true; }): Promise; - - /** - * Asynchronous mkdir(2) - create a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders - * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. - */ - function mkdir(path: PathLike, options?: Mode | (MakeDirectoryOptions & { recursive?: false; }) | null): Promise; - - /** - * Asynchronous mkdir(2) - create a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders - * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. - */ - function mkdir(path: PathLike, options?: Mode | MakeDirectoryOptions | null): Promise; - - /** - * Asynchronous readdir(3) - read a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function readdir(path: PathLike, options?: BaseEncodingOptions & { withFileTypes?: false } | BufferEncoding | null): Promise; - - /** - * Asynchronous readdir(3) - read a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function readdir(path: PathLike, options: { encoding: "buffer"; withFileTypes?: false } | "buffer"): Promise; - - /** - * Asynchronous readdir(3) - read a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function readdir(path: PathLike, options?: BaseEncodingOptions & { withFileTypes?: false } | BufferEncoding | null): Promise; - - /** - * Asynchronous readdir(3) - read a directory. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options If called with `withFileTypes: true` the result data will be an array of Dirent. - */ - function readdir(path: PathLike, options: BaseEncodingOptions & { withFileTypes: true }): Promise; - - /** - * Asynchronous readlink(2) - read value of a symbolic link. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function readlink(path: PathLike, options?: BaseEncodingOptions | BufferEncoding | null): Promise; - - /** - * Asynchronous readlink(2) - read value of a symbolic link. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function readlink(path: PathLike, options: BufferEncodingOption): Promise; - - /** - * Asynchronous readlink(2) - read value of a symbolic link. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function readlink(path: PathLike, options?: BaseEncodingOptions | string | null): Promise; - - /** - * Asynchronous symlink(2) - Create a new symbolic link to an existing file. - * @param target A path to an existing file. If a URL is provided, it must use the `file:` protocol. - * @param path A path to the new symlink. If a URL is provided, it must use the `file:` protocol. - * @param type May be set to `'dir'`, `'file'`, or `'junction'` (default is `'file'`) and is only available on Windows (ignored on other platforms). - * When using `'junction'`, the `target` argument will automatically be normalized to an absolute path. - */ - function symlink(target: PathLike, path: PathLike, type?: string | null): Promise; - - /** - * Asynchronous fstat(2) - Get file status. - * @param handle A `FileHandle`. - */ - function fstat(handle: FileHandle): Promise; - - /** - * Asynchronous lstat(2) - Get file status. Does not dereference symbolic links. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - function lstat(path: PathLike): Promise; - - /** - * Asynchronous stat(2) - Get file status. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - function stat(path: PathLike): Promise; - - /** - * Asynchronous link(2) - Create a new link (also known as a hard link) to an existing file. - * @param existingPath A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - function link(existingPath: PathLike, newPath: PathLike): Promise; - - /** - * Asynchronous unlink(2) - delete a name and possibly the file it refers to. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - function unlink(path: PathLike): Promise; - - /** - * Asynchronous fchmod(2) - Change permissions of a file. - * @param handle A `FileHandle`. - * @param mode A file mode. If a string is passed, it is parsed as an octal integer. - */ - function fchmod(handle: FileHandle, mode: Mode): Promise; - - /** - * Asynchronous chmod(2) - Change permissions of a file. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param mode A file mode. If a string is passed, it is parsed as an octal integer. - */ - function chmod(path: PathLike, mode: Mode): Promise; - - /** - * Asynchronous lchmod(2) - Change permissions of a file. Does not dereference symbolic links. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param mode A file mode. If a string is passed, it is parsed as an octal integer. - */ - function lchmod(path: PathLike, mode: Mode): Promise; - - /** - * Asynchronous lchown(2) - Change ownership of a file. Does not dereference symbolic links. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - function lchown(path: PathLike, uid: number, gid: number): Promise; - - /** - * Asynchronous fchown(2) - Change ownership of a file. - * @param handle A `FileHandle`. - */ - function fchown(handle: FileHandle, uid: number, gid: number): Promise; - - /** - * Asynchronous chown(2) - Change ownership of a file. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - */ - function chown(path: PathLike, uid: number, gid: number): Promise; - - /** - * Asynchronously change file timestamps of the file referenced by the supplied path. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param atime The last access time. If a string is provided, it will be coerced to number. - * @param mtime The last modified time. If a string is provided, it will be coerced to number. - */ - function utimes(path: PathLike, atime: string | number | Date, mtime: string | number | Date): Promise; - - /** - * Asynchronously change file timestamps of the file referenced by the supplied `FileHandle`. - * @param handle A `FileHandle`. - * @param atime The last access time. If a string is provided, it will be coerced to number. - * @param mtime The last modified time. If a string is provided, it will be coerced to number. - */ - function futimes(handle: FileHandle, atime: string | number | Date, mtime: string | number | Date): Promise; - - /** - * Asynchronous realpath(3) - return the canonicalized absolute pathname. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function realpath(path: PathLike, options?: BaseEncodingOptions | BufferEncoding | null): Promise; - - /** - * Asynchronous realpath(3) - return the canonicalized absolute pathname. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function realpath(path: PathLike, options: BufferEncodingOption): Promise; - - /** - * Asynchronous realpath(3) - return the canonicalized absolute pathname. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function realpath(path: PathLike, options?: BaseEncodingOptions | BufferEncoding | null): Promise; - - /** - * Asynchronously creates a unique temporary directory. - * Generates six random characters to be appended behind a required `prefix` to create a unique temporary directory. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function mkdtemp(prefix: string, options?: BaseEncodingOptions | BufferEncoding | null): Promise; - - /** - * Asynchronously creates a unique temporary directory. - * Generates six random characters to be appended behind a required `prefix` to create a unique temporary directory. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function mkdtemp(prefix: string, options: BufferEncodingOption): Promise; - - /** - * Asynchronously creates a unique temporary directory. - * Generates six random characters to be appended behind a required `prefix` to create a unique temporary directory. - * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. - */ - function mkdtemp(prefix: string, options?: BaseEncodingOptions | BufferEncoding | null): Promise; - - /** - * Asynchronously writes data to a file, replacing the file if it already exists. - * It is unsafe to call `fsPromises.writeFile()` multiple times on the same file without waiting for the `Promise` to be resolved (or rejected). - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - * If a `FileHandle` is provided, the underlying file will _not_ be closed automatically. - * @param data The data to write. If something other than a `Buffer` or `Uint8Array` is provided, the value is coerced to a string. - * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. - * If `encoding` is not supplied, the default of `'utf8'` is used. - * If `mode` is not supplied, the default of `0o666` is used. - * If `mode` is a string, it is parsed as an octal integer. - * If `flag` is not supplied, the default of `'w'` is used. - */ - function writeFile(path: PathLike | FileHandle, data: string | Uint8Array, options?: BaseEncodingOptions & { mode?: Mode, flag?: OpenMode } | BufferEncoding | null): Promise; - - /** - * Asynchronously append data to a file, creating the file if it does not exist. - * @param file A path to a file. If a URL is provided, it must use the `file:` protocol. - * URL support is _experimental_. - * If a `FileHandle` is provided, the underlying file will _not_ be closed automatically. - * @param data The data to write. If something other than a `Buffer` or `Uint8Array` is provided, the value is coerced to a string. - * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. - * If `encoding` is not supplied, the default of `'utf8'` is used. - * If `mode` is not supplied, the default of `0o666` is used. - * If `mode` is a string, it is parsed as an octal integer. - * If `flag` is not supplied, the default of `'a'` is used. - */ - function appendFile(path: PathLike | FileHandle, data: string | Uint8Array, options?: BaseEncodingOptions & { mode?: Mode, flag?: OpenMode } | BufferEncoding | null): Promise; - - /** - * Asynchronously reads the entire contents of a file. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * If a `FileHandle` is provided, the underlying file will _not_ be closed automatically. - * @param options An object that may contain an optional flag. - * If a flag is not provided, it defaults to `'r'`. - */ - function readFile(path: PathLike | FileHandle, options?: { encoding?: null, flag?: OpenMode } | null): Promise; - - /** - * Asynchronously reads the entire contents of a file. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * If a `FileHandle` is provided, the underlying file will _not_ be closed automatically. - * @param options An object that may contain an optional flag. - * If a flag is not provided, it defaults to `'r'`. - */ - function readFile(path: PathLike | FileHandle, options: { encoding: BufferEncoding, flag?: OpenMode } | BufferEncoding): Promise; - - /** - * Asynchronously reads the entire contents of a file. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * If a `FileHandle` is provided, the underlying file will _not_ be closed automatically. - * @param options An object that may contain an optional flag. - * If a flag is not provided, it defaults to `'r'`. - */ - function readFile(path: PathLike | FileHandle, options?: BaseEncodingOptions & { flag?: OpenMode } | BufferEncoding | null): Promise; - - function opendir(path: string, options?: OpenDirOptions): Promise; -} diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/node/globals.d.ts b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/node/globals.d.ts deleted file mode 100644 index b8609c4fa9..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/node/globals.d.ts +++ /dev/null @@ -1,606 +0,0 @@ -// Declare "static" methods in Error -interface ErrorConstructor { - /** Create .stack property on a target object */ - captureStackTrace(targetObject: object, constructorOpt?: Function): void; - - /** - * Optional override for formatting stack traces - * - * @see https://github.com/v8/v8/wiki/Stack%20Trace%20API#customizing-stack-traces - */ - prepareStackTrace?: (err: Error, stackTraces: NodeJS.CallSite[]) => any; - - stackTraceLimit: number; -} - -// Node.js ESNEXT support -interface String { - /** Removes whitespace from the left end of a string. */ - trimLeft(): string; - /** Removes whitespace from the right end of a string. */ - trimRight(): string; - - /** Returns a copy with leading whitespace removed. */ - trimStart(): string; - /** Returns a copy with trailing whitespace removed. */ - trimEnd(): string; -} - -interface ImportMeta { - url: string; -} - -/*-----------------------------------------------* - * * - * GLOBAL * - * * - ------------------------------------------------*/ - -// For backwards compability -interface NodeRequire extends NodeJS.Require {} -interface RequireResolve extends NodeJS.RequireResolve {} -interface NodeModule extends NodeJS.Module {} - -declare var process: NodeJS.Process; -declare var console: Console; - -declare var __filename: string; -declare var __dirname: string; - -declare function setTimeout(callback: (...args: any[]) => void, ms: number, ...args: any[]): NodeJS.Timeout; -declare namespace setTimeout { - function __promisify__(ms: number): Promise; - function __promisify__(ms: number, value: T): Promise; -} -declare function clearTimeout(timeoutId: NodeJS.Timeout): void; -declare function setInterval(callback: (...args: any[]) => void, ms: number, ...args: any[]): NodeJS.Timeout; -declare function clearInterval(intervalId: NodeJS.Timeout): void; -declare function setImmediate(callback: (...args: any[]) => void, ...args: any[]): NodeJS.Immediate; -declare namespace setImmediate { - function __promisify__(): Promise; - function __promisify__(value: T): Promise; -} -declare function clearImmediate(immediateId: NodeJS.Immediate): void; - -declare function queueMicrotask(callback: () => void): void; - -declare var require: NodeRequire; -declare var module: NodeModule; - -// Same as module.exports -declare var exports: any; - -// Buffer class -type BufferEncoding = "ascii" | "utf8" | "utf-8" | "utf16le" | "ucs2" | "ucs-2" | "base64" | "latin1" | "binary" | "hex"; - -/** - * Raw data is stored in instances of the Buffer class. - * A Buffer is similar to an array of integers but corresponds to a raw memory allocation outside the V8 heap. A Buffer cannot be resized. - * Valid string encodings: 'ascii'|'utf8'|'utf16le'|'ucs2'(alias of 'utf16le')|'base64'|'binary'(deprecated)|'hex' - */ -declare class Buffer extends Uint8Array { - /** - * Allocates a new buffer containing the given {str}. - * - * @param str String to store in buffer. - * @param encoding encoding to use, optional. Default is 'utf8' - * @deprecated since v10.0.0 - Use `Buffer.from(string[, encoding])` instead. - */ - constructor(str: string, encoding?: BufferEncoding); - /** - * Allocates a new buffer of {size} octets. - * - * @param size count of octets to allocate. - * @deprecated since v10.0.0 - Use `Buffer.alloc()` instead (also see `Buffer.allocUnsafe()`). - */ - constructor(size: number); - /** - * Allocates a new buffer containing the given {array} of octets. - * - * @param array The octets to store. - * @deprecated since v10.0.0 - Use `Buffer.from(array)` instead. - */ - constructor(array: Uint8Array); - /** - * Produces a Buffer backed by the same allocated memory as - * the given {ArrayBuffer}/{SharedArrayBuffer}. - * - * - * @param arrayBuffer The ArrayBuffer with which to share memory. - * @deprecated since v10.0.0 - Use `Buffer.from(arrayBuffer[, byteOffset[, length]])` instead. - */ - constructor(arrayBuffer: ArrayBuffer | SharedArrayBuffer); - /** - * Allocates a new buffer containing the given {array} of octets. - * - * @param array The octets to store. - * @deprecated since v10.0.0 - Use `Buffer.from(array)` instead. - */ - constructor(array: ReadonlyArray); - /** - * Copies the passed {buffer} data onto a new {Buffer} instance. - * - * @param buffer The buffer to copy. - * @deprecated since v10.0.0 - Use `Buffer.from(buffer)` instead. - */ - constructor(buffer: Buffer); - /** - * When passed a reference to the .buffer property of a TypedArray instance, - * the newly created Buffer will share the same allocated memory as the TypedArray. - * The optional {byteOffset} and {length} arguments specify a memory range - * within the {arrayBuffer} that will be shared by the Buffer. - * - * @param arrayBuffer The .buffer property of any TypedArray or a new ArrayBuffer() - */ - static from(arrayBuffer: ArrayBuffer | SharedArrayBuffer, byteOffset?: number, length?: number): Buffer; - /** - * Creates a new Buffer using the passed {data} - * @param data data to create a new Buffer - */ - static from(data: ReadonlyArray): Buffer; - static from(data: Uint8Array): Buffer; - /** - * Creates a new buffer containing the coerced value of an object - * A `TypeError` will be thrown if {obj} has not mentioned methods or is not of other type appropriate for `Buffer.from()` variants. - * @param obj An object supporting `Symbol.toPrimitive` or `valueOf()`. - */ - static from(obj: { valueOf(): string | object } | { [Symbol.toPrimitive](hint: 'string'): string }, byteOffset?: number, length?: number): Buffer; - /** - * Creates a new Buffer containing the given JavaScript string {str}. - * If provided, the {encoding} parameter identifies the character encoding. - * If not provided, {encoding} defaults to 'utf8'. - */ - static from(str: string, encoding?: BufferEncoding): Buffer; - /** - * Creates a new Buffer using the passed {data} - * @param values to create a new Buffer - */ - static of(...items: number[]): Buffer; - /** - * Returns true if {obj} is a Buffer - * - * @param obj object to test. - */ - static isBuffer(obj: any): obj is Buffer; - /** - * Returns true if {encoding} is a valid encoding argument. - * Valid string encodings in Node 0.12: 'ascii'|'utf8'|'utf16le'|'ucs2'(alias of 'utf16le')|'base64'|'binary'(deprecated)|'hex' - * - * @param encoding string to test. - */ - static isEncoding(encoding: string): encoding is BufferEncoding; - /** - * Gives the actual byte length of a string. encoding defaults to 'utf8'. - * This is not the same as String.prototype.length since that returns the number of characters in a string. - * - * @param string string to test. - * @param encoding encoding used to evaluate (defaults to 'utf8') - */ - static byteLength( - string: string | NodeJS.ArrayBufferView | ArrayBuffer | SharedArrayBuffer, - encoding?: BufferEncoding - ): number; - /** - * Returns a buffer which is the result of concatenating all the buffers in the list together. - * - * If the list has no items, or if the totalLength is 0, then it returns a zero-length buffer. - * If the list has exactly one item, then the first item of the list is returned. - * If the list has more than one item, then a new Buffer is created. - * - * @param list An array of Buffer objects to concatenate - * @param totalLength Total length of the buffers when concatenated. - * If totalLength is not provided, it is read from the buffers in the list. However, this adds an additional loop to the function, so it is faster to provide the length explicitly. - */ - static concat(list: ReadonlyArray, totalLength?: number): Buffer; - /** - * The same as buf1.compare(buf2). - */ - static compare(buf1: Uint8Array, buf2: Uint8Array): number; - /** - * Allocates a new buffer of {size} octets. - * - * @param size count of octets to allocate. - * @param fill if specified, buffer will be initialized by calling buf.fill(fill). - * If parameter is omitted, buffer will be filled with zeros. - * @param encoding encoding used for call to buf.fill while initalizing - */ - static alloc(size: number, fill?: string | Buffer | number, encoding?: BufferEncoding): Buffer; - /** - * Allocates a new buffer of {size} octets, leaving memory not initialized, so the contents - * of the newly created Buffer are unknown and may contain sensitive data. - * - * @param size count of octets to allocate - */ - static allocUnsafe(size: number): Buffer; - /** - * Allocates a new non-pooled buffer of {size} octets, leaving memory not initialized, so the contents - * of the newly created Buffer are unknown and may contain sensitive data. - * - * @param size count of octets to allocate - */ - static allocUnsafeSlow(size: number): Buffer; - /** - * This is the number of bytes used to determine the size of pre-allocated, internal Buffer instances used for pooling. This value may be modified. - */ - static poolSize: number; - - write(string: string, encoding?: BufferEncoding): number; - write(string: string, offset: number, encoding?: BufferEncoding): number; - write(string: string, offset: number, length: number, encoding?: BufferEncoding): number; - toString(encoding?: BufferEncoding, start?: number, end?: number): string; - toJSON(): { type: 'Buffer'; data: number[] }; - equals(otherBuffer: Uint8Array): boolean; - compare( - otherBuffer: Uint8Array, - targetStart?: number, - targetEnd?: number, - sourceStart?: number, - sourceEnd?: number - ): number; - copy(targetBuffer: Uint8Array, targetStart?: number, sourceStart?: number, sourceEnd?: number): number; - /** - * Returns a new `Buffer` that references **the same memory as the original**, but offset and cropped by the start and end indices. - * - * This method is incompatible with `Uint8Array#slice()`, which returns a copy of the original memory. - * - * @param begin Where the new `Buffer` will start. Default: `0`. - * @param end Where the new `Buffer` will end (not inclusive). Default: `buf.length`. - */ - slice(begin?: number, end?: number): Buffer; - /** - * Returns a new `Buffer` that references **the same memory as the original**, but offset and cropped by the start and end indices. - * - * This method is compatible with `Uint8Array#subarray()`. - * - * @param begin Where the new `Buffer` will start. Default: `0`. - * @param end Where the new `Buffer` will end (not inclusive). Default: `buf.length`. - */ - subarray(begin?: number, end?: number): Buffer; - writeBigInt64BE(value: bigint, offset?: number): number; - writeBigInt64LE(value: bigint, offset?: number): number; - writeBigUInt64BE(value: bigint, offset?: number): number; - writeBigUInt64LE(value: bigint, offset?: number): number; - writeUIntLE(value: number, offset: number, byteLength: number): number; - writeUIntBE(value: number, offset: number, byteLength: number): number; - writeIntLE(value: number, offset: number, byteLength: number): number; - writeIntBE(value: number, offset: number, byteLength: number): number; - readBigUInt64BE(offset?: number): bigint; - readBigUInt64LE(offset?: number): bigint; - readBigInt64BE(offset?: number): bigint; - readBigInt64LE(offset?: number): bigint; - readUIntLE(offset: number, byteLength: number): number; - readUIntBE(offset: number, byteLength: number): number; - readIntLE(offset: number, byteLength: number): number; - readIntBE(offset: number, byteLength: number): number; - readUInt8(offset?: number): number; - readUInt16LE(offset?: number): number; - readUInt16BE(offset?: number): number; - readUInt32LE(offset?: number): number; - readUInt32BE(offset?: number): number; - readInt8(offset?: number): number; - readInt16LE(offset?: number): number; - readInt16BE(offset?: number): number; - readInt32LE(offset?: number): number; - readInt32BE(offset?: number): number; - readFloatLE(offset?: number): number; - readFloatBE(offset?: number): number; - readDoubleLE(offset?: number): number; - readDoubleBE(offset?: number): number; - reverse(): this; - swap16(): Buffer; - swap32(): Buffer; - swap64(): Buffer; - writeUInt8(value: number, offset?: number): number; - writeUInt16LE(value: number, offset?: number): number; - writeUInt16BE(value: number, offset?: number): number; - writeUInt32LE(value: number, offset?: number): number; - writeUInt32BE(value: number, offset?: number): number; - writeInt8(value: number, offset?: number): number; - writeInt16LE(value: number, offset?: number): number; - writeInt16BE(value: number, offset?: number): number; - writeInt32LE(value: number, offset?: number): number; - writeInt32BE(value: number, offset?: number): number; - writeFloatLE(value: number, offset?: number): number; - writeFloatBE(value: number, offset?: number): number; - writeDoubleLE(value: number, offset?: number): number; - writeDoubleBE(value: number, offset?: number): number; - - fill(value: string | Uint8Array | number, offset?: number, end?: number, encoding?: BufferEncoding): this; - - indexOf(value: string | number | Uint8Array, byteOffset?: number, encoding?: BufferEncoding): number; - lastIndexOf(value: string | number | Uint8Array, byteOffset?: number, encoding?: BufferEncoding): number; - entries(): IterableIterator<[number, number]>; - includes(value: string | number | Buffer, byteOffset?: number, encoding?: BufferEncoding): boolean; - keys(): IterableIterator; - values(): IterableIterator; -} - -/*----------------------------------------------* -* * -* GLOBAL INTERFACES * -* * -*-----------------------------------------------*/ -declare namespace NodeJS { - interface InspectOptions { - /** - * If set to `true`, getters are going to be - * inspected as well. If set to `'get'` only getters without setter are going - * to be inspected. If set to `'set'` only getters having a corresponding - * setter are going to be inspected. This might cause side effects depending on - * the getter function. - * @default `false` - */ - getters?: 'get' | 'set' | boolean; - showHidden?: boolean; - /** - * @default 2 - */ - depth?: number | null; - colors?: boolean; - customInspect?: boolean; - showProxy?: boolean; - maxArrayLength?: number | null; - /** - * Specifies the maximum number of characters to - * include when formatting. Set to `null` or `Infinity` to show all elements. - * Set to `0` or negative to show no characters. - * @default Infinity - */ - maxStringLength?: number | null; - breakLength?: number; - /** - * Setting this to `false` causes each object key - * to be displayed on a new line. It will also add new lines to text that is - * longer than `breakLength`. If set to a number, the most `n` inner elements - * are united on a single line as long as all properties fit into - * `breakLength`. Short array elements are also grouped together. Note that no - * text will be reduced below 16 characters, no matter the `breakLength` size. - * For more information, see the example below. - * @default `true` - */ - compact?: boolean | number; - sorted?: boolean | ((a: string, b: string) => number); - } - - interface CallSite { - /** - * Value of "this" - */ - getThis(): any; - - /** - * Type of "this" as a string. - * This is the name of the function stored in the constructor field of - * "this", if available. Otherwise the object's [[Class]] internal - * property. - */ - getTypeName(): string | null; - - /** - * Current function - */ - getFunction(): Function | undefined; - - /** - * Name of the current function, typically its name property. - * If a name property is not available an attempt will be made to try - * to infer a name from the function's context. - */ - getFunctionName(): string | null; - - /** - * Name of the property [of "this" or one of its prototypes] that holds - * the current function - */ - getMethodName(): string | null; - - /** - * Name of the script [if this function was defined in a script] - */ - getFileName(): string | null; - - /** - * Current line number [if this function was defined in a script] - */ - getLineNumber(): number | null; - - /** - * Current column number [if this function was defined in a script] - */ - getColumnNumber(): number | null; - - /** - * A call site object representing the location where eval was called - * [if this function was created using a call to eval] - */ - getEvalOrigin(): string | undefined; - - /** - * Is this a toplevel invocation, that is, is "this" the global object? - */ - isToplevel(): boolean; - - /** - * Does this call take place in code defined by a call to eval? - */ - isEval(): boolean; - - /** - * Is this call in native V8 code? - */ - isNative(): boolean; - - /** - * Is this a constructor call? - */ - isConstructor(): boolean; - } - - interface ErrnoException extends Error { - errno?: number; - code?: string; - path?: string; - syscall?: string; - stack?: string; - } - - interface ReadableStream extends EventEmitter { - readable: boolean; - read(size?: number): string | Buffer; - setEncoding(encoding: BufferEncoding): this; - pause(): this; - resume(): this; - isPaused(): boolean; - pipe(destination: T, options?: { end?: boolean; }): T; - unpipe(destination?: WritableStream): this; - unshift(chunk: string | Uint8Array, encoding?: BufferEncoding): void; - wrap(oldStream: ReadableStream): this; - [Symbol.asyncIterator](): AsyncIterableIterator; - } - - interface WritableStream extends EventEmitter { - writable: boolean; - write(buffer: Uint8Array | string, cb?: (err?: Error | null) => void): boolean; - write(str: string, encoding?: BufferEncoding, cb?: (err?: Error | null) => void): boolean; - end(cb?: () => void): void; - end(data: string | Uint8Array, cb?: () => void): void; - end(str: string, encoding?: BufferEncoding, cb?: () => void): void; - } - - interface ReadWriteStream extends ReadableStream, WritableStream { } - - interface Global { - Array: typeof Array; - ArrayBuffer: typeof ArrayBuffer; - Boolean: typeof Boolean; - Buffer: typeof Buffer; - DataView: typeof DataView; - Date: typeof Date; - Error: typeof Error; - EvalError: typeof EvalError; - Float32Array: typeof Float32Array; - Float64Array: typeof Float64Array; - Function: typeof Function; - Infinity: typeof Infinity; - Int16Array: typeof Int16Array; - Int32Array: typeof Int32Array; - Int8Array: typeof Int8Array; - Intl: typeof Intl; - JSON: typeof JSON; - Map: MapConstructor; - Math: typeof Math; - NaN: typeof NaN; - Number: typeof Number; - Object: typeof Object; - Promise: typeof Promise; - RangeError: typeof RangeError; - ReferenceError: typeof ReferenceError; - RegExp: typeof RegExp; - Set: SetConstructor; - String: typeof String; - Symbol: Function; - SyntaxError: typeof SyntaxError; - TypeError: typeof TypeError; - URIError: typeof URIError; - Uint16Array: typeof Uint16Array; - Uint32Array: typeof Uint32Array; - Uint8Array: typeof Uint8Array; - Uint8ClampedArray: typeof Uint8ClampedArray; - WeakMap: WeakMapConstructor; - WeakSet: WeakSetConstructor; - clearImmediate: (immediateId: Immediate) => void; - clearInterval: (intervalId: Timeout) => void; - clearTimeout: (timeoutId: Timeout) => void; - decodeURI: typeof decodeURI; - decodeURIComponent: typeof decodeURIComponent; - encodeURI: typeof encodeURI; - encodeURIComponent: typeof encodeURIComponent; - escape: (str: string) => string; - eval: typeof eval; - global: Global; - isFinite: typeof isFinite; - isNaN: typeof isNaN; - parseFloat: typeof parseFloat; - parseInt: typeof parseInt; - setImmediate: (callback: (...args: any[]) => void, ...args: any[]) => Immediate; - setInterval: (callback: (...args: any[]) => void, ms: number, ...args: any[]) => Timeout; - setTimeout: (callback: (...args: any[]) => void, ms: number, ...args: any[]) => Timeout; - queueMicrotask: typeof queueMicrotask; - undefined: typeof undefined; - unescape: (str: string) => string; - gc: () => void; - v8debug?: any; - } - - interface RefCounted { - ref(): this; - unref(): this; - } - - // compatibility with older typings - interface Timer extends RefCounted { - hasRef(): boolean; - refresh(): this; - } - - interface Immediate extends RefCounted { - hasRef(): boolean; - _onImmediate: Function; // to distinguish it from the Timeout class - } - - interface Timeout extends Timer { - hasRef(): boolean; - refresh(): this; - } - - type TypedArray = Uint8Array | Uint8ClampedArray | Uint16Array | Uint32Array | Int8Array | Int16Array | Int32Array | Float32Array | Float64Array; - type ArrayBufferView = TypedArray | DataView; - - interface Require { - /* tslint:disable-next-line:callable-types */ - (id: string): any; - resolve: RequireResolve; - cache: Dict; - /** - * @deprecated - */ - extensions: RequireExtensions; - main: Module | undefined; - } - - interface RequireResolve { - (id: string, options?: { paths?: string[]; }): string; - paths(request: string): string[] | null; - } - - interface RequireExtensions extends Dict<(m: Module, filename: string) => any> { - '.js': (m: Module, filename: string) => any; - '.json': (m: Module, filename: string) => any; - '.node': (m: Module, filename: string) => any; - } - interface Module { - exports: any; - require: Require; - id: string; - filename: string; - loaded: boolean; - /** @deprecated since 14.6.0 Please use `require.main` and `module.children` instead. */ - parent: Module | null | undefined; - children: Module[]; - /** - * @since 11.14.0 - * - * The directory name of the module. This is usually the same as the path.dirname() of the module.id. - */ - path: string; - paths: string[]; - } - - interface Dict { - [key: string]: T | undefined; - } - - interface ReadOnlyDict { - readonly [key: string]: T | undefined; - } -} diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/node/globals.global.d.ts b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/node/globals.global.d.ts deleted file mode 100644 index d66acba63e..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/node/globals.global.d.ts +++ /dev/null @@ -1 +0,0 @@ -declare var global: NodeJS.Global & typeof globalThis; diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/node/http.d.ts b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/node/http.d.ts deleted file mode 100644 index b4932e6934..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/node/http.d.ts +++ /dev/null @@ -1,412 +0,0 @@ -declare module "http" { - import * as stream from "stream"; - import { URL } from "url"; - import { Socket, Server as NetServer } from "net"; - - // incoming headers will never contain number - interface IncomingHttpHeaders extends NodeJS.Dict { - 'accept'?: string; - 'accept-language'?: string; - 'accept-patch'?: string; - 'accept-ranges'?: string; - 'access-control-allow-credentials'?: string; - 'access-control-allow-headers'?: string; - 'access-control-allow-methods'?: string; - 'access-control-allow-origin'?: string; - 'access-control-expose-headers'?: string; - 'access-control-max-age'?: string; - 'access-control-request-headers'?: string; - 'access-control-request-method'?: string; - 'age'?: string; - 'allow'?: string; - 'alt-svc'?: string; - 'authorization'?: string; - 'cache-control'?: string; - 'connection'?: string; - 'content-disposition'?: string; - 'content-encoding'?: string; - 'content-language'?: string; - 'content-length'?: string; - 'content-location'?: string; - 'content-range'?: string; - 'content-type'?: string; - 'cookie'?: string; - 'date'?: string; - 'expect'?: string; - 'expires'?: string; - 'forwarded'?: string; - 'from'?: string; - 'host'?: string; - 'if-match'?: string; - 'if-modified-since'?: string; - 'if-none-match'?: string; - 'if-unmodified-since'?: string; - 'last-modified'?: string; - 'location'?: string; - 'origin'?: string; - 'pragma'?: string; - 'proxy-authenticate'?: string; - 'proxy-authorization'?: string; - 'public-key-pins'?: string; - 'range'?: string; - 'referer'?: string; - 'retry-after'?: string; - 'set-cookie'?: string[]; - 'strict-transport-security'?: string; - 'tk'?: string; - 'trailer'?: string; - 'transfer-encoding'?: string; - 'upgrade'?: string; - 'user-agent'?: string; - 'vary'?: string; - 'via'?: string; - 'warning'?: string; - 'www-authenticate'?: string; - } - - // outgoing headers allows numbers (as they are converted internally to strings) - interface OutgoingHttpHeaders extends NodeJS.Dict { - } - - interface ClientRequestArgs { - protocol?: string | null; - host?: string | null; - hostname?: string | null; - family?: number; - port?: number | string | null; - defaultPort?: number | string; - localAddress?: string; - socketPath?: string; - /** - * @default 8192 - */ - maxHeaderSize?: number; - method?: string; - path?: string | null; - headers?: OutgoingHttpHeaders; - auth?: string | null; - agent?: Agent | boolean; - _defaultAgent?: Agent; - timeout?: number; - setHost?: boolean; - // https://github.com/nodejs/node/blob/master/lib/_http_client.js#L278 - createConnection?: (options: ClientRequestArgs, oncreate: (err: Error, socket: Socket) => void) => Socket; - } - - interface ServerOptions { - IncomingMessage?: typeof IncomingMessage; - ServerResponse?: typeof ServerResponse; - /** - * Optionally overrides the value of - * [`--max-http-header-size`][] for requests received by this server, i.e. - * the maximum length of request headers in bytes. - * @default 8192 - */ - maxHeaderSize?: number; - /** - * Use an insecure HTTP parser that accepts invalid HTTP headers when true. - * Using the insecure parser should be avoided. - * See --insecure-http-parser for more information. - * @default false - */ - insecureHTTPParser?: boolean; - } - - type RequestListener = (req: IncomingMessage, res: ServerResponse) => void; - - interface HttpBase { - setTimeout(msecs?: number, callback?: () => void): this; - setTimeout(callback: () => void): this; - /** - * Limits maximum incoming headers count. If set to 0, no limit will be applied. - * @default 2000 - * {@link https://nodejs.org/api/http.html#http_server_maxheaderscount} - */ - maxHeadersCount: number | null; - timeout: number; - /** - * Limit the amount of time the parser will wait to receive the complete HTTP headers. - * @default 60000 - * {@link https://nodejs.org/api/http.html#http_server_headerstimeout} - */ - headersTimeout: number; - keepAliveTimeout: number; - /** - * Sets the timeout value in milliseconds for receiving the entire request from the client. - * @default 0 - * {@link https://nodejs.org/api/http.html#http_server_requesttimeout} - */ - requestTimeout: number; - } - - interface Server extends HttpBase {} - class Server extends NetServer { - constructor(requestListener?: RequestListener); - constructor(options: ServerOptions, requestListener?: RequestListener); - } - - // https://github.com/nodejs/node/blob/master/lib/_http_outgoing.js - class OutgoingMessage extends stream.Writable { - upgrading: boolean; - chunkedEncoding: boolean; - shouldKeepAlive: boolean; - useChunkedEncodingByDefault: boolean; - sendDate: boolean; - /** - * @deprecated Use `writableEnded` instead. - */ - finished: boolean; - headersSent: boolean; - /** - * @deprecate Use `socket` instead. - */ - connection: Socket | null; - socket: Socket | null; - - constructor(); - - setTimeout(msecs: number, callback?: () => void): this; - setHeader(name: string, value: number | string | ReadonlyArray): void; - getHeader(name: string): number | string | string[] | undefined; - getHeaders(): OutgoingHttpHeaders; - getHeaderNames(): string[]; - hasHeader(name: string): boolean; - removeHeader(name: string): void; - addTrailers(headers: OutgoingHttpHeaders | ReadonlyArray<[string, string]>): void; - flushHeaders(): void; - } - - // https://github.com/nodejs/node/blob/master/lib/_http_server.js#L108-L256 - class ServerResponse extends OutgoingMessage { - statusCode: number; - statusMessage: string; - - constructor(req: IncomingMessage); - - assignSocket(socket: Socket): void; - detachSocket(socket: Socket): void; - // https://github.com/nodejs/node/blob/master/test/parallel/test-http-write-callbacks.js#L53 - // no args in writeContinue callback - writeContinue(callback?: () => void): void; - writeHead(statusCode: number, reasonPhrase?: string, headers?: OutgoingHttpHeaders): this; - writeHead(statusCode: number, headers?: OutgoingHttpHeaders): this; - writeProcessing(): void; - } - - interface InformationEvent { - statusCode: number; - statusMessage: string; - httpVersion: string; - httpVersionMajor: number; - httpVersionMinor: number; - headers: IncomingHttpHeaders; - rawHeaders: string[]; - } - - // https://github.com/nodejs/node/blob/master/lib/_http_client.js#L77 - class ClientRequest extends OutgoingMessage { - aborted: number; - - constructor(url: string | URL | ClientRequestArgs, cb?: (res: IncomingMessage) => void); - - method: string; - path: string; - abort(): void; - onSocket(socket: Socket): void; - setTimeout(timeout: number, callback?: () => void): this; - setNoDelay(noDelay?: boolean): void; - setSocketKeepAlive(enable?: boolean, initialDelay?: number): void; - - addListener(event: 'abort', listener: () => void): this; - addListener(event: 'connect', listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this; - addListener(event: 'continue', listener: () => void): this; - addListener(event: 'information', listener: (info: InformationEvent) => void): this; - addListener(event: 'response', listener: (response: IncomingMessage) => void): this; - addListener(event: 'socket', listener: (socket: Socket) => void): this; - addListener(event: 'timeout', listener: () => void): this; - addListener(event: 'upgrade', listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this; - addListener(event: 'close', listener: () => void): this; - addListener(event: 'drain', listener: () => void): this; - addListener(event: 'error', listener: (err: Error) => void): this; - addListener(event: 'finish', listener: () => void): this; - addListener(event: 'pipe', listener: (src: stream.Readable) => void): this; - addListener(event: 'unpipe', listener: (src: stream.Readable) => void): this; - addListener(event: string | symbol, listener: (...args: any[]) => void): this; - - on(event: 'abort', listener: () => void): this; - on(event: 'connect', listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this; - on(event: 'continue', listener: () => void): this; - on(event: 'information', listener: (info: InformationEvent) => void): this; - on(event: 'response', listener: (response: IncomingMessage) => void): this; - on(event: 'socket', listener: (socket: Socket) => void): this; - on(event: 'timeout', listener: () => void): this; - on(event: 'upgrade', listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this; - on(event: 'close', listener: () => void): this; - on(event: 'drain', listener: () => void): this; - on(event: 'error', listener: (err: Error) => void): this; - on(event: 'finish', listener: () => void): this; - on(event: 'pipe', listener: (src: stream.Readable) => void): this; - on(event: 'unpipe', listener: (src: stream.Readable) => void): this; - on(event: string | symbol, listener: (...args: any[]) => void): this; - - once(event: 'abort', listener: () => void): this; - once(event: 'connect', listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this; - once(event: 'continue', listener: () => void): this; - once(event: 'information', listener: (info: InformationEvent) => void): this; - once(event: 'response', listener: (response: IncomingMessage) => void): this; - once(event: 'socket', listener: (socket: Socket) => void): this; - once(event: 'timeout', listener: () => void): this; - once(event: 'upgrade', listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this; - once(event: 'close', listener: () => void): this; - once(event: 'drain', listener: () => void): this; - once(event: 'error', listener: (err: Error) => void): this; - once(event: 'finish', listener: () => void): this; - once(event: 'pipe', listener: (src: stream.Readable) => void): this; - once(event: 'unpipe', listener: (src: stream.Readable) => void): this; - once(event: string | symbol, listener: (...args: any[]) => void): this; - - prependListener(event: 'abort', listener: () => void): this; - prependListener(event: 'connect', listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this; - prependListener(event: 'continue', listener: () => void): this; - prependListener(event: 'information', listener: (info: InformationEvent) => void): this; - prependListener(event: 'response', listener: (response: IncomingMessage) => void): this; - prependListener(event: 'socket', listener: (socket: Socket) => void): this; - prependListener(event: 'timeout', listener: () => void): this; - prependListener(event: 'upgrade', listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this; - prependListener(event: 'close', listener: () => void): this; - prependListener(event: 'drain', listener: () => void): this; - prependListener(event: 'error', listener: (err: Error) => void): this; - prependListener(event: 'finish', listener: () => void): this; - prependListener(event: 'pipe', listener: (src: stream.Readable) => void): this; - prependListener(event: 'unpipe', listener: (src: stream.Readable) => void): this; - prependListener(event: string | symbol, listener: (...args: any[]) => void): this; - - prependOnceListener(event: 'abort', listener: () => void): this; - prependOnceListener(event: 'connect', listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this; - prependOnceListener(event: 'continue', listener: () => void): this; - prependOnceListener(event: 'information', listener: (info: InformationEvent) => void): this; - prependOnceListener(event: 'response', listener: (response: IncomingMessage) => void): this; - prependOnceListener(event: 'socket', listener: (socket: Socket) => void): this; - prependOnceListener(event: 'timeout', listener: () => void): this; - prependOnceListener(event: 'upgrade', listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this; - prependOnceListener(event: 'close', listener: () => void): this; - prependOnceListener(event: 'drain', listener: () => void): this; - prependOnceListener(event: 'error', listener: (err: Error) => void): this; - prependOnceListener(event: 'finish', listener: () => void): this; - prependOnceListener(event: 'pipe', listener: (src: stream.Readable) => void): this; - prependOnceListener(event: 'unpipe', listener: (src: stream.Readable) => void): this; - prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; - } - - class IncomingMessage extends stream.Readable { - constructor(socket: Socket); - - aborted: boolean; - httpVersion: string; - httpVersionMajor: number; - httpVersionMinor: number; - complete: boolean; - /** - * @deprecate Use `socket` instead. - */ - connection: Socket; - socket: Socket; - headers: IncomingHttpHeaders; - rawHeaders: string[]; - trailers: NodeJS.Dict; - rawTrailers: string[]; - setTimeout(msecs: number, callback?: () => void): this; - /** - * Only valid for request obtained from http.Server. - */ - method?: string; - /** - * Only valid for request obtained from http.Server. - */ - url?: string; - /** - * Only valid for response obtained from http.ClientRequest. - */ - statusCode?: number; - /** - * Only valid for response obtained from http.ClientRequest. - */ - statusMessage?: string; - destroy(error?: Error): void; - } - - interface AgentOptions { - /** - * Keep sockets around in a pool to be used by other requests in the future. Default = false - */ - keepAlive?: boolean; - /** - * When using HTTP KeepAlive, how often to send TCP KeepAlive packets over sockets being kept alive. Default = 1000. - * Only relevant if keepAlive is set to true. - */ - keepAliveMsecs?: number; - /** - * Maximum number of sockets to allow per host. Default for Node 0.10 is 5, default for Node 0.12 is Infinity - */ - maxSockets?: number; - /** - * Maximum number of sockets allowed for all hosts in total. Each request will use a new socket until the maximum is reached. Default: Infinity. - */ - maxTotalSockets?: number; - /** - * Maximum number of sockets to leave open in a free state. Only relevant if keepAlive is set to true. Default = 256. - */ - maxFreeSockets?: number; - /** - * Socket timeout in milliseconds. This will set the timeout after the socket is connected. - */ - timeout?: number; - /** - * Scheduling strategy to apply when picking the next free socket to use. Default: 'fifo'. - */ - scheduling?: 'fifo' | 'lifo'; - } - - class Agent { - maxFreeSockets: number; - maxSockets: number; - readonly freeSockets: NodeJS.ReadOnlyDict; - readonly sockets: NodeJS.ReadOnlyDict; - readonly requests: NodeJS.ReadOnlyDict; - - constructor(opts?: AgentOptions); - - /** - * Destroy any sockets that are currently in use by the agent. - * It is usually not necessary to do this. However, if you are using an agent with KeepAlive enabled, - * then it is best to explicitly shut down the agent when you know that it will no longer be used. Otherwise, - * sockets may hang open for quite a long time before the server terminates them. - */ - destroy(): void; - } - - const METHODS: string[]; - - const STATUS_CODES: { - [errorCode: number]: string | undefined; - [errorCode: string]: string | undefined; - }; - - function createServer(requestListener?: RequestListener): Server; - function createServer(options: ServerOptions, requestListener?: RequestListener): Server; - - // although RequestOptions are passed as ClientRequestArgs to ClientRequest directly, - // create interface RequestOptions would make the naming more clear to developers - interface RequestOptions extends ClientRequestArgs { } - function request(options: RequestOptions | string | URL, callback?: (res: IncomingMessage) => void): ClientRequest; - function request(url: string | URL, options: RequestOptions, callback?: (res: IncomingMessage) => void): ClientRequest; - function get(options: RequestOptions | string | URL, callback?: (res: IncomingMessage) => void): ClientRequest; - function get(url: string | URL, options: RequestOptions, callback?: (res: IncomingMessage) => void): ClientRequest; - let globalAgent: Agent; - - /** - * Read-only property specifying the maximum allowed size of HTTP headers in bytes. - * Defaults to 16KB. Configurable using the [`--max-http-header-size`][] CLI option. - */ - const maxHeaderSize: number; -} diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/node/http2.d.ts b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/node/http2.d.ts deleted file mode 100644 index 0788293189..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/node/http2.d.ts +++ /dev/null @@ -1,952 +0,0 @@ -declare module "http2" { - import * as events from "events"; - import * as fs from "fs"; - import * as net from "net"; - import * as stream from "stream"; - import * as tls from "tls"; - import * as url from "url"; - - import { IncomingHttpHeaders as Http1IncomingHttpHeaders, OutgoingHttpHeaders, IncomingMessage, ServerResponse } from "http"; - export { OutgoingHttpHeaders } from "http"; - - export interface IncomingHttpStatusHeader { - ":status"?: number; - } - - export interface IncomingHttpHeaders extends Http1IncomingHttpHeaders { - ":path"?: string; - ":method"?: string; - ":authority"?: string; - ":scheme"?: string; - } - - // Http2Stream - - export interface StreamPriorityOptions { - exclusive?: boolean; - parent?: number; - weight?: number; - silent?: boolean; - } - - export interface StreamState { - localWindowSize?: number; - state?: number; - localClose?: number; - remoteClose?: number; - sumDependencyWeight?: number; - weight?: number; - } - - export interface ServerStreamResponseOptions { - endStream?: boolean; - waitForTrailers?: boolean; - } - - export interface StatOptions { - offset: number; - length: number; - } - - export interface ServerStreamFileResponseOptions { - statCheck?(stats: fs.Stats, headers: OutgoingHttpHeaders, statOptions: StatOptions): void | boolean; - waitForTrailers?: boolean; - offset?: number; - length?: number; - } - - export interface ServerStreamFileResponseOptionsWithError extends ServerStreamFileResponseOptions { - onError?(err: NodeJS.ErrnoException): void; - } - - export interface Http2Stream extends stream.Duplex { - readonly aborted: boolean; - readonly bufferSize: number; - readonly closed: boolean; - readonly destroyed: boolean; - /** - * Set the true if the END_STREAM flag was set in the request or response HEADERS frame received, - * indicating that no additional data should be received and the readable side of the Http2Stream will be closed. - */ - readonly endAfterHeaders: boolean; - readonly id?: number; - readonly pending: boolean; - readonly rstCode: number; - readonly sentHeaders: OutgoingHttpHeaders; - readonly sentInfoHeaders?: OutgoingHttpHeaders[]; - readonly sentTrailers?: OutgoingHttpHeaders; - readonly session: Http2Session; - readonly state: StreamState; - - close(code?: number, callback?: () => void): void; - priority(options: StreamPriorityOptions): void; - setTimeout(msecs: number, callback?: () => void): void; - sendTrailers(headers: OutgoingHttpHeaders): void; - - addListener(event: "aborted", listener: () => void): this; - addListener(event: "close", listener: () => void): this; - addListener(event: "data", listener: (chunk: Buffer | string) => void): this; - addListener(event: "drain", listener: () => void): this; - addListener(event: "end", listener: () => void): this; - addListener(event: "error", listener: (err: Error) => void): this; - addListener(event: "finish", listener: () => void): this; - addListener(event: "frameError", listener: (frameType: number, errorCode: number) => void): this; - addListener(event: "pipe", listener: (src: stream.Readable) => void): this; - addListener(event: "unpipe", listener: (src: stream.Readable) => void): this; - addListener(event: "streamClosed", listener: (code: number) => void): this; - addListener(event: "timeout", listener: () => void): this; - addListener(event: "trailers", listener: (trailers: IncomingHttpHeaders, flags: number) => void): this; - addListener(event: "wantTrailers", listener: () => void): this; - addListener(event: string | symbol, listener: (...args: any[]) => void): this; - - emit(event: "aborted"): boolean; - emit(event: "close"): boolean; - emit(event: "data", chunk: Buffer | string): boolean; - emit(event: "drain"): boolean; - emit(event: "end"): boolean; - emit(event: "error", err: Error): boolean; - emit(event: "finish"): boolean; - emit(event: "frameError", frameType: number, errorCode: number): boolean; - emit(event: "pipe", src: stream.Readable): boolean; - emit(event: "unpipe", src: stream.Readable): boolean; - emit(event: "streamClosed", code: number): boolean; - emit(event: "timeout"): boolean; - emit(event: "trailers", trailers: IncomingHttpHeaders, flags: number): boolean; - emit(event: "wantTrailers"): boolean; - emit(event: string | symbol, ...args: any[]): boolean; - - on(event: "aborted", listener: () => void): this; - on(event: "close", listener: () => void): this; - on(event: "data", listener: (chunk: Buffer | string) => void): this; - on(event: "drain", listener: () => void): this; - on(event: "end", listener: () => void): this; - on(event: "error", listener: (err: Error) => void): this; - on(event: "finish", listener: () => void): this; - on(event: "frameError", listener: (frameType: number, errorCode: number) => void): this; - on(event: "pipe", listener: (src: stream.Readable) => void): this; - on(event: "unpipe", listener: (src: stream.Readable) => void): this; - on(event: "streamClosed", listener: (code: number) => void): this; - on(event: "timeout", listener: () => void): this; - on(event: "trailers", listener: (trailers: IncomingHttpHeaders, flags: number) => void): this; - on(event: "wantTrailers", listener: () => void): this; - on(event: string | symbol, listener: (...args: any[]) => void): this; - - once(event: "aborted", listener: () => void): this; - once(event: "close", listener: () => void): this; - once(event: "data", listener: (chunk: Buffer | string) => void): this; - once(event: "drain", listener: () => void): this; - once(event: "end", listener: () => void): this; - once(event: "error", listener: (err: Error) => void): this; - once(event: "finish", listener: () => void): this; - once(event: "frameError", listener: (frameType: number, errorCode: number) => void): this; - once(event: "pipe", listener: (src: stream.Readable) => void): this; - once(event: "unpipe", listener: (src: stream.Readable) => void): this; - once(event: "streamClosed", listener: (code: number) => void): this; - once(event: "timeout", listener: () => void): this; - once(event: "trailers", listener: (trailers: IncomingHttpHeaders, flags: number) => void): this; - once(event: "wantTrailers", listener: () => void): this; - once(event: string | symbol, listener: (...args: any[]) => void): this; - - prependListener(event: "aborted", listener: () => void): this; - prependListener(event: "close", listener: () => void): this; - prependListener(event: "data", listener: (chunk: Buffer | string) => void): this; - prependListener(event: "drain", listener: () => void): this; - prependListener(event: "end", listener: () => void): this; - prependListener(event: "error", listener: (err: Error) => void): this; - prependListener(event: "finish", listener: () => void): this; - prependListener(event: "frameError", listener: (frameType: number, errorCode: number) => void): this; - prependListener(event: "pipe", listener: (src: stream.Readable) => void): this; - prependListener(event: "unpipe", listener: (src: stream.Readable) => void): this; - prependListener(event: "streamClosed", listener: (code: number) => void): this; - prependListener(event: "timeout", listener: () => void): this; - prependListener(event: "trailers", listener: (trailers: IncomingHttpHeaders, flags: number) => void): this; - prependListener(event: "wantTrailers", listener: () => void): this; - prependListener(event: string | symbol, listener: (...args: any[]) => void): this; - - prependOnceListener(event: "aborted", listener: () => void): this; - prependOnceListener(event: "close", listener: () => void): this; - prependOnceListener(event: "data", listener: (chunk: Buffer | string) => void): this; - prependOnceListener(event: "drain", listener: () => void): this; - prependOnceListener(event: "end", listener: () => void): this; - prependOnceListener(event: "error", listener: (err: Error) => void): this; - prependOnceListener(event: "finish", listener: () => void): this; - prependOnceListener(event: "frameError", listener: (frameType: number, errorCode: number) => void): this; - prependOnceListener(event: "pipe", listener: (src: stream.Readable) => void): this; - prependOnceListener(event: "unpipe", listener: (src: stream.Readable) => void): this; - prependOnceListener(event: "streamClosed", listener: (code: number) => void): this; - prependOnceListener(event: "timeout", listener: () => void): this; - prependOnceListener(event: "trailers", listener: (trailers: IncomingHttpHeaders, flags: number) => void): this; - prependOnceListener(event: "wantTrailers", listener: () => void): this; - prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; - } - - export interface ClientHttp2Stream extends Http2Stream { - addListener(event: "continue", listener: () => {}): this; - addListener(event: "headers", listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; - addListener(event: "push", listener: (headers: IncomingHttpHeaders, flags: number) => void): this; - addListener(event: "response", listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; - addListener(event: string | symbol, listener: (...args: any[]) => void): this; - - emit(event: "continue"): boolean; - emit(event: "headers", headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number): boolean; - emit(event: "push", headers: IncomingHttpHeaders, flags: number): boolean; - emit(event: "response", headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number): boolean; - emit(event: string | symbol, ...args: any[]): boolean; - - on(event: "continue", listener: () => {}): this; - on(event: "headers", listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; - on(event: "push", listener: (headers: IncomingHttpHeaders, flags: number) => void): this; - on(event: "response", listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; - on(event: string | symbol, listener: (...args: any[]) => void): this; - - once(event: "continue", listener: () => {}): this; - once(event: "headers", listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; - once(event: "push", listener: (headers: IncomingHttpHeaders, flags: number) => void): this; - once(event: "response", listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; - once(event: string | symbol, listener: (...args: any[]) => void): this; - - prependListener(event: "continue", listener: () => {}): this; - prependListener(event: "headers", listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; - prependListener(event: "push", listener: (headers: IncomingHttpHeaders, flags: number) => void): this; - prependListener(event: "response", listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; - prependListener(event: string | symbol, listener: (...args: any[]) => void): this; - - prependOnceListener(event: "continue", listener: () => {}): this; - prependOnceListener(event: "headers", listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; - prependOnceListener(event: "push", listener: (headers: IncomingHttpHeaders, flags: number) => void): this; - prependOnceListener(event: "response", listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; - prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; - } - - export interface ServerHttp2Stream extends Http2Stream { - readonly headersSent: boolean; - readonly pushAllowed: boolean; - additionalHeaders(headers: OutgoingHttpHeaders): void; - pushStream(headers: OutgoingHttpHeaders, callback?: (err: Error | null, pushStream: ServerHttp2Stream, headers: OutgoingHttpHeaders) => void): void; - pushStream(headers: OutgoingHttpHeaders, options?: StreamPriorityOptions, callback?: (err: Error | null, pushStream: ServerHttp2Stream, headers: OutgoingHttpHeaders) => void): void; - respond(headers?: OutgoingHttpHeaders, options?: ServerStreamResponseOptions): void; - respondWithFD(fd: number | fs.promises.FileHandle, headers?: OutgoingHttpHeaders, options?: ServerStreamFileResponseOptions): void; - respondWithFile(path: string, headers?: OutgoingHttpHeaders, options?: ServerStreamFileResponseOptionsWithError): void; - } - - // Http2Session - - export interface Settings { - headerTableSize?: number; - enablePush?: boolean; - initialWindowSize?: number; - maxFrameSize?: number; - maxConcurrentStreams?: number; - maxHeaderListSize?: number; - enableConnectProtocol?: boolean; - } - - export interface ClientSessionRequestOptions { - endStream?: boolean; - exclusive?: boolean; - parent?: number; - weight?: number; - waitForTrailers?: boolean; - } - - export interface SessionState { - effectiveLocalWindowSize?: number; - effectiveRecvDataLength?: number; - nextStreamID?: number; - localWindowSize?: number; - lastProcStreamID?: number; - remoteWindowSize?: number; - outboundQueueSize?: number; - deflateDynamicTableSize?: number; - inflateDynamicTableSize?: number; - } - - export interface Http2Session extends events.EventEmitter { - readonly alpnProtocol?: string; - readonly closed: boolean; - readonly connecting: boolean; - readonly destroyed: boolean; - readonly encrypted?: boolean; - readonly localSettings: Settings; - readonly originSet?: string[]; - readonly pendingSettingsAck: boolean; - readonly remoteSettings: Settings; - readonly socket: net.Socket | tls.TLSSocket; - readonly state: SessionState; - readonly type: number; - - close(callback?: () => void): void; - destroy(error?: Error, code?: number): void; - goaway(code?: number, lastStreamID?: number, opaqueData?: NodeJS.ArrayBufferView): void; - ping(callback: (err: Error | null, duration: number, payload: Buffer) => void): boolean; - ping(payload: NodeJS.ArrayBufferView, callback: (err: Error | null, duration: number, payload: Buffer) => void): boolean; - ref(): void; - setTimeout(msecs: number, callback?: () => void): void; - settings(settings: Settings): void; - unref(): void; - - addListener(event: "close", listener: () => void): this; - addListener(event: "error", listener: (err: Error) => void): this; - addListener(event: "frameError", listener: (frameType: number, errorCode: number, streamID: number) => void): this; - addListener(event: "goaway", listener: (errorCode: number, lastStreamID: number, opaqueData: Buffer) => void): this; - addListener(event: "localSettings", listener: (settings: Settings) => void): this; - addListener(event: "ping", listener: () => void): this; - addListener(event: "remoteSettings", listener: (settings: Settings) => void): this; - addListener(event: "timeout", listener: () => void): this; - addListener(event: string | symbol, listener: (...args: any[]) => void): this; - - emit(event: "close"): boolean; - emit(event: "error", err: Error): boolean; - emit(event: "frameError", frameType: number, errorCode: number, streamID: number): boolean; - emit(event: "goaway", errorCode: number, lastStreamID: number, opaqueData: Buffer): boolean; - emit(event: "localSettings", settings: Settings): boolean; - emit(event: "ping"): boolean; - emit(event: "remoteSettings", settings: Settings): boolean; - emit(event: "timeout"): boolean; - emit(event: string | symbol, ...args: any[]): boolean; - - on(event: "close", listener: () => void): this; - on(event: "error", listener: (err: Error) => void): this; - on(event: "frameError", listener: (frameType: number, errorCode: number, streamID: number) => void): this; - on(event: "goaway", listener: (errorCode: number, lastStreamID: number, opaqueData: Buffer) => void): this; - on(event: "localSettings", listener: (settings: Settings) => void): this; - on(event: "ping", listener: () => void): this; - on(event: "remoteSettings", listener: (settings: Settings) => void): this; - on(event: "timeout", listener: () => void): this; - on(event: string | symbol, listener: (...args: any[]) => void): this; - - once(event: "close", listener: () => void): this; - once(event: "error", listener: (err: Error) => void): this; - once(event: "frameError", listener: (frameType: number, errorCode: number, streamID: number) => void): this; - once(event: "goaway", listener: (errorCode: number, lastStreamID: number, opaqueData: Buffer) => void): this; - once(event: "localSettings", listener: (settings: Settings) => void): this; - once(event: "ping", listener: () => void): this; - once(event: "remoteSettings", listener: (settings: Settings) => void): this; - once(event: "timeout", listener: () => void): this; - once(event: string | symbol, listener: (...args: any[]) => void): this; - - prependListener(event: "close", listener: () => void): this; - prependListener(event: "error", listener: (err: Error) => void): this; - prependListener(event: "frameError", listener: (frameType: number, errorCode: number, streamID: number) => void): this; - prependListener(event: "goaway", listener: (errorCode: number, lastStreamID: number, opaqueData: Buffer) => void): this; - prependListener(event: "localSettings", listener: (settings: Settings) => void): this; - prependListener(event: "ping", listener: () => void): this; - prependListener(event: "remoteSettings", listener: (settings: Settings) => void): this; - prependListener(event: "timeout", listener: () => void): this; - prependListener(event: string | symbol, listener: (...args: any[]) => void): this; - - prependOnceListener(event: "close", listener: () => void): this; - prependOnceListener(event: "error", listener: (err: Error) => void): this; - prependOnceListener(event: "frameError", listener: (frameType: number, errorCode: number, streamID: number) => void): this; - prependOnceListener(event: "goaway", listener: (errorCode: number, lastStreamID: number, opaqueData: Buffer) => void): this; - prependOnceListener(event: "localSettings", listener: (settings: Settings) => void): this; - prependOnceListener(event: "ping", listener: () => void): this; - prependOnceListener(event: "remoteSettings", listener: (settings: Settings) => void): this; - prependOnceListener(event: "timeout", listener: () => void): this; - prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; - } - - export interface ClientHttp2Session extends Http2Session { - request(headers?: OutgoingHttpHeaders, options?: ClientSessionRequestOptions): ClientHttp2Stream; - - addListener(event: "altsvc", listener: (alt: string, origin: string, stream: number) => void): this; - addListener(event: "origin", listener: (origins: string[]) => void): this; - addListener(event: "connect", listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; - addListener(event: "stream", listener: (stream: ClientHttp2Stream, headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; - addListener(event: string | symbol, listener: (...args: any[]) => void): this; - - emit(event: "altsvc", alt: string, origin: string, stream: number): boolean; - emit(event: "origin", origins: ReadonlyArray): boolean; - emit(event: "connect", session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket): boolean; - emit(event: "stream", stream: ClientHttp2Stream, headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number): boolean; - emit(event: string | symbol, ...args: any[]): boolean; - - on(event: "altsvc", listener: (alt: string, origin: string, stream: number) => void): this; - on(event: "origin", listener: (origins: string[]) => void): this; - on(event: "connect", listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; - on(event: "stream", listener: (stream: ClientHttp2Stream, headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; - on(event: string | symbol, listener: (...args: any[]) => void): this; - - once(event: "altsvc", listener: (alt: string, origin: string, stream: number) => void): this; - once(event: "origin", listener: (origins: string[]) => void): this; - once(event: "connect", listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; - once(event: "stream", listener: (stream: ClientHttp2Stream, headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; - once(event: string | symbol, listener: (...args: any[]) => void): this; - - prependListener(event: "altsvc", listener: (alt: string, origin: string, stream: number) => void): this; - prependListener(event: "origin", listener: (origins: string[]) => void): this; - prependListener(event: "connect", listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; - prependListener(event: "stream", listener: (stream: ClientHttp2Stream, headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; - prependListener(event: string | symbol, listener: (...args: any[]) => void): this; - - prependOnceListener(event: "altsvc", listener: (alt: string, origin: string, stream: number) => void): this; - prependOnceListener(event: "origin", listener: (origins: string[]) => void): this; - prependOnceListener(event: "connect", listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; - prependOnceListener(event: "stream", listener: (stream: ClientHttp2Stream, headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; - prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; - } - - export interface AlternativeServiceOptions { - origin: number | string | url.URL; - } - - export interface ServerHttp2Session extends Http2Session { - readonly server: Http2Server | Http2SecureServer; - - altsvc(alt: string, originOrStream: number | string | url.URL | AlternativeServiceOptions): void; - origin(...args: Array): void; - - addListener(event: "connect", listener: (session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; - addListener(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; - addListener(event: string | symbol, listener: (...args: any[]) => void): this; - - emit(event: "connect", session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket): boolean; - emit(event: "stream", stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number): boolean; - emit(event: string | symbol, ...args: any[]): boolean; - - on(event: "connect", listener: (session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; - on(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; - on(event: string | symbol, listener: (...args: any[]) => void): this; - - once(event: "connect", listener: (session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; - once(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; - once(event: string | symbol, listener: (...args: any[]) => void): this; - - prependListener(event: "connect", listener: (session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; - prependListener(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; - prependListener(event: string | symbol, listener: (...args: any[]) => void): this; - - prependOnceListener(event: "connect", listener: (session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; - prependOnceListener(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; - prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; - } - - // Http2Server - - export interface SessionOptions { - maxDeflateDynamicTableSize?: number; - maxSessionMemory?: number; - maxHeaderListPairs?: number; - maxOutstandingPings?: number; - maxSendHeaderBlockLength?: number; - paddingStrategy?: number; - peerMaxConcurrentStreams?: number; - settings?: Settings; - - selectPadding?(frameLen: number, maxFrameLen: number): number; - createConnection?(authority: url.URL, option: SessionOptions): stream.Duplex; - } - - export interface ClientSessionOptions extends SessionOptions { - maxReservedRemoteStreams?: number; - createConnection?: (authority: url.URL, option: SessionOptions) => stream.Duplex; - protocol?: 'http:' | 'https:'; - } - - export interface ServerSessionOptions extends SessionOptions { - Http1IncomingMessage?: typeof IncomingMessage; - Http1ServerResponse?: typeof ServerResponse; - Http2ServerRequest?: typeof Http2ServerRequest; - Http2ServerResponse?: typeof Http2ServerResponse; - } - - export interface SecureClientSessionOptions extends ClientSessionOptions, tls.ConnectionOptions { } - export interface SecureServerSessionOptions extends ServerSessionOptions, tls.TlsOptions { } - - export interface ServerOptions extends ServerSessionOptions { } - - export interface SecureServerOptions extends SecureServerSessionOptions { - allowHTTP1?: boolean; - origins?: string[]; - } - - export interface Http2Server extends net.Server { - addListener(event: "checkContinue", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; - addListener(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; - addListener(event: "session", listener: (session: ServerHttp2Session) => void): this; - addListener(event: "sessionError", listener: (err: Error) => void): this; - addListener(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; - addListener(event: "timeout", listener: () => void): this; - addListener(event: string | symbol, listener: (...args: any[]) => void): this; - - emit(event: "checkContinue", request: Http2ServerRequest, response: Http2ServerResponse): boolean; - emit(event: "request", request: Http2ServerRequest, response: Http2ServerResponse): boolean; - emit(event: "session", session: ServerHttp2Session): boolean; - emit(event: "sessionError", err: Error): boolean; - emit(event: "stream", stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number): boolean; - emit(event: "timeout"): boolean; - emit(event: string | symbol, ...args: any[]): boolean; - - on(event: "checkContinue", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; - on(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; - on(event: "session", listener: (session: ServerHttp2Session) => void): this; - on(event: "sessionError", listener: (err: Error) => void): this; - on(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; - on(event: "timeout", listener: () => void): this; - on(event: string | symbol, listener: (...args: any[]) => void): this; - - once(event: "checkContinue", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; - once(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; - once(event: "session", listener: (session: ServerHttp2Session) => void): this; - once(event: "sessionError", listener: (err: Error) => void): this; - once(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; - once(event: "timeout", listener: () => void): this; - once(event: string | symbol, listener: (...args: any[]) => void): this; - - prependListener(event: "checkContinue", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; - prependListener(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; - prependListener(event: "session", listener: (session: ServerHttp2Session) => void): this; - prependListener(event: "sessionError", listener: (err: Error) => void): this; - prependListener(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; - prependListener(event: "timeout", listener: () => void): this; - prependListener(event: string | symbol, listener: (...args: any[]) => void): this; - - prependOnceListener(event: "checkContinue", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; - prependOnceListener(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; - prependOnceListener(event: "session", listener: (session: ServerHttp2Session) => void): this; - prependOnceListener(event: "sessionError", listener: (err: Error) => void): this; - prependOnceListener(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; - prependOnceListener(event: "timeout", listener: () => void): this; - prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; - - setTimeout(msec?: number, callback?: () => void): this; - } - - export interface Http2SecureServer extends tls.Server { - addListener(event: "checkContinue", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; - addListener(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; - addListener(event: "session", listener: (session: ServerHttp2Session) => void): this; - addListener(event: "sessionError", listener: (err: Error) => void): this; - addListener(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; - addListener(event: "timeout", listener: () => void): this; - addListener(event: "unknownProtocol", listener: (socket: tls.TLSSocket) => void): this; - addListener(event: string | symbol, listener: (...args: any[]) => void): this; - - emit(event: "checkContinue", request: Http2ServerRequest, response: Http2ServerResponse): boolean; - emit(event: "request", request: Http2ServerRequest, response: Http2ServerResponse): boolean; - emit(event: "session", session: ServerHttp2Session): boolean; - emit(event: "sessionError", err: Error): boolean; - emit(event: "stream", stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number): boolean; - emit(event: "timeout"): boolean; - emit(event: "unknownProtocol", socket: tls.TLSSocket): boolean; - emit(event: string | symbol, ...args: any[]): boolean; - - on(event: "checkContinue", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; - on(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; - on(event: "session", listener: (session: ServerHttp2Session) => void): this; - on(event: "sessionError", listener: (err: Error) => void): this; - on(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; - on(event: "timeout", listener: () => void): this; - on(event: "unknownProtocol", listener: (socket: tls.TLSSocket) => void): this; - on(event: string | symbol, listener: (...args: any[]) => void): this; - - once(event: "checkContinue", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; - once(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; - once(event: "session", listener: (session: ServerHttp2Session) => void): this; - once(event: "sessionError", listener: (err: Error) => void): this; - once(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; - once(event: "timeout", listener: () => void): this; - once(event: "unknownProtocol", listener: (socket: tls.TLSSocket) => void): this; - once(event: string | symbol, listener: (...args: any[]) => void): this; - - prependListener(event: "checkContinue", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; - prependListener(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; - prependListener(event: "session", listener: (session: ServerHttp2Session) => void): this; - prependListener(event: "sessionError", listener: (err: Error) => void): this; - prependListener(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; - prependListener(event: "timeout", listener: () => void): this; - prependListener(event: "unknownProtocol", listener: (socket: tls.TLSSocket) => void): this; - prependListener(event: string | symbol, listener: (...args: any[]) => void): this; - - prependOnceListener(event: "checkContinue", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; - prependOnceListener(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; - prependOnceListener(event: "session", listener: (session: ServerHttp2Session) => void): this; - prependOnceListener(event: "sessionError", listener: (err: Error) => void): this; - prependOnceListener(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; - prependOnceListener(event: "timeout", listener: () => void): this; - prependOnceListener(event: "unknownProtocol", listener: (socket: tls.TLSSocket) => void): this; - prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; - - setTimeout(msec?: number, callback?: () => void): this; - } - - export class Http2ServerRequest extends stream.Readable { - constructor(stream: ServerHttp2Stream, headers: IncomingHttpHeaders, options: stream.ReadableOptions, rawHeaders: ReadonlyArray); - - readonly aborted: boolean; - readonly authority: string; - readonly connection: net.Socket | tls.TLSSocket; - readonly complete: boolean; - readonly headers: IncomingHttpHeaders; - readonly httpVersion: string; - readonly httpVersionMinor: number; - readonly httpVersionMajor: number; - readonly method: string; - readonly rawHeaders: string[]; - readonly rawTrailers: string[]; - readonly scheme: string; - readonly socket: net.Socket | tls.TLSSocket; - readonly stream: ServerHttp2Stream; - readonly trailers: IncomingHttpHeaders; - readonly url: string; - - setTimeout(msecs: number, callback?: () => void): void; - read(size?: number): Buffer | string | null; - - addListener(event: "aborted", listener: (hadError: boolean, code: number) => void): this; - addListener(event: "close", listener: () => void): this; - addListener(event: "data", listener: (chunk: Buffer | string) => void): this; - addListener(event: "end", listener: () => void): this; - addListener(event: "readable", listener: () => void): this; - addListener(event: "error", listener: (err: Error) => void): this; - addListener(event: string | symbol, listener: (...args: any[]) => void): this; - - emit(event: "aborted", hadError: boolean, code: number): boolean; - emit(event: "close"): boolean; - emit(event: "data", chunk: Buffer | string): boolean; - emit(event: "end"): boolean; - emit(event: "readable"): boolean; - emit(event: "error", err: Error): boolean; - emit(event: string | symbol, ...args: any[]): boolean; - - on(event: "aborted", listener: (hadError: boolean, code: number) => void): this; - on(event: "close", listener: () => void): this; - on(event: "data", listener: (chunk: Buffer | string) => void): this; - on(event: "end", listener: () => void): this; - on(event: "readable", listener: () => void): this; - on(event: "error", listener: (err: Error) => void): this; - on(event: string | symbol, listener: (...args: any[]) => void): this; - - once(event: "aborted", listener: (hadError: boolean, code: number) => void): this; - once(event: "close", listener: () => void): this; - once(event: "data", listener: (chunk: Buffer | string) => void): this; - once(event: "end", listener: () => void): this; - once(event: "readable", listener: () => void): this; - once(event: "error", listener: (err: Error) => void): this; - once(event: string | symbol, listener: (...args: any[]) => void): this; - - prependListener(event: "aborted", listener: (hadError: boolean, code: number) => void): this; - prependListener(event: "close", listener: () => void): this; - prependListener(event: "data", listener: (chunk: Buffer | string) => void): this; - prependListener(event: "end", listener: () => void): this; - prependListener(event: "readable", listener: () => void): this; - prependListener(event: "error", listener: (err: Error) => void): this; - prependListener(event: string | symbol, listener: (...args: any[]) => void): this; - - prependOnceListener(event: "aborted", listener: (hadError: boolean, code: number) => void): this; - prependOnceListener(event: "close", listener: () => void): this; - prependOnceListener(event: "data", listener: (chunk: Buffer | string) => void): this; - prependOnceListener(event: "end", listener: () => void): this; - prependOnceListener(event: "readable", listener: () => void): this; - prependOnceListener(event: "error", listener: (err: Error) => void): this; - prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; - } - - export class Http2ServerResponse extends stream.Stream { - constructor(stream: ServerHttp2Stream); - - readonly connection: net.Socket | tls.TLSSocket; - readonly finished: boolean; - readonly headersSent: boolean; - readonly socket: net.Socket | tls.TLSSocket; - readonly stream: ServerHttp2Stream; - sendDate: boolean; - statusCode: number; - statusMessage: ''; - addTrailers(trailers: OutgoingHttpHeaders): void; - end(callback?: () => void): void; - end(data: string | Uint8Array, callback?: () => void): void; - end(data: string | Uint8Array, encoding: BufferEncoding, callback?: () => void): void; - getHeader(name: string): string; - getHeaderNames(): string[]; - getHeaders(): OutgoingHttpHeaders; - hasHeader(name: string): boolean; - removeHeader(name: string): void; - setHeader(name: string, value: number | string | ReadonlyArray): void; - setTimeout(msecs: number, callback?: () => void): void; - write(chunk: string | Uint8Array, callback?: (err: Error) => void): boolean; - write(chunk: string | Uint8Array, encoding: BufferEncoding, callback?: (err: Error) => void): boolean; - writeContinue(): void; - writeHead(statusCode: number, headers?: OutgoingHttpHeaders): this; - writeHead(statusCode: number, statusMessage: string, headers?: OutgoingHttpHeaders): this; - createPushResponse(headers: OutgoingHttpHeaders, callback: (err: Error | null, res: Http2ServerResponse) => void): void; - - addListener(event: "close", listener: () => void): this; - addListener(event: "drain", listener: () => void): this; - addListener(event: "error", listener: (error: Error) => void): this; - addListener(event: "finish", listener: () => void): this; - addListener(event: "pipe", listener: (src: stream.Readable) => void): this; - addListener(event: "unpipe", listener: (src: stream.Readable) => void): this; - addListener(event: string | symbol, listener: (...args: any[]) => void): this; - - emit(event: "close"): boolean; - emit(event: "drain"): boolean; - emit(event: "error", error: Error): boolean; - emit(event: "finish"): boolean; - emit(event: "pipe", src: stream.Readable): boolean; - emit(event: "unpipe", src: stream.Readable): boolean; - emit(event: string | symbol, ...args: any[]): boolean; - - on(event: "close", listener: () => void): this; - on(event: "drain", listener: () => void): this; - on(event: "error", listener: (error: Error) => void): this; - on(event: "finish", listener: () => void): this; - on(event: "pipe", listener: (src: stream.Readable) => void): this; - on(event: "unpipe", listener: (src: stream.Readable) => void): this; - on(event: string | symbol, listener: (...args: any[]) => void): this; - - once(event: "close", listener: () => void): this; - once(event: "drain", listener: () => void): this; - once(event: "error", listener: (error: Error) => void): this; - once(event: "finish", listener: () => void): this; - once(event: "pipe", listener: (src: stream.Readable) => void): this; - once(event: "unpipe", listener: (src: stream.Readable) => void): this; - once(event: string | symbol, listener: (...args: any[]) => void): this; - - prependListener(event: "close", listener: () => void): this; - prependListener(event: "drain", listener: () => void): this; - prependListener(event: "error", listener: (error: Error) => void): this; - prependListener(event: "finish", listener: () => void): this; - prependListener(event: "pipe", listener: (src: stream.Readable) => void): this; - prependListener(event: "unpipe", listener: (src: stream.Readable) => void): this; - prependListener(event: string | symbol, listener: (...args: any[]) => void): this; - - prependOnceListener(event: "close", listener: () => void): this; - prependOnceListener(event: "drain", listener: () => void): this; - prependOnceListener(event: "error", listener: (error: Error) => void): this; - prependOnceListener(event: "finish", listener: () => void): this; - prependOnceListener(event: "pipe", listener: (src: stream.Readable) => void): this; - prependOnceListener(event: "unpipe", listener: (src: stream.Readable) => void): this; - prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; - } - - // Public API - - export namespace constants { - const NGHTTP2_SESSION_SERVER: number; - const NGHTTP2_SESSION_CLIENT: number; - const NGHTTP2_STREAM_STATE_IDLE: number; - const NGHTTP2_STREAM_STATE_OPEN: number; - const NGHTTP2_STREAM_STATE_RESERVED_LOCAL: number; - const NGHTTP2_STREAM_STATE_RESERVED_REMOTE: number; - const NGHTTP2_STREAM_STATE_HALF_CLOSED_LOCAL: number; - const NGHTTP2_STREAM_STATE_HALF_CLOSED_REMOTE: number; - const NGHTTP2_STREAM_STATE_CLOSED: number; - const NGHTTP2_NO_ERROR: number; - const NGHTTP2_PROTOCOL_ERROR: number; - const NGHTTP2_INTERNAL_ERROR: number; - const NGHTTP2_FLOW_CONTROL_ERROR: number; - const NGHTTP2_SETTINGS_TIMEOUT: number; - const NGHTTP2_STREAM_CLOSED: number; - const NGHTTP2_FRAME_SIZE_ERROR: number; - const NGHTTP2_REFUSED_STREAM: number; - const NGHTTP2_CANCEL: number; - const NGHTTP2_COMPRESSION_ERROR: number; - const NGHTTP2_CONNECT_ERROR: number; - const NGHTTP2_ENHANCE_YOUR_CALM: number; - const NGHTTP2_INADEQUATE_SECURITY: number; - const NGHTTP2_HTTP_1_1_REQUIRED: number; - const NGHTTP2_ERR_FRAME_SIZE_ERROR: number; - const NGHTTP2_FLAG_NONE: number; - const NGHTTP2_FLAG_END_STREAM: number; - const NGHTTP2_FLAG_END_HEADERS: number; - const NGHTTP2_FLAG_ACK: number; - const NGHTTP2_FLAG_PADDED: number; - const NGHTTP2_FLAG_PRIORITY: number; - const DEFAULT_SETTINGS_HEADER_TABLE_SIZE: number; - const DEFAULT_SETTINGS_ENABLE_PUSH: number; - const DEFAULT_SETTINGS_INITIAL_WINDOW_SIZE: number; - const DEFAULT_SETTINGS_MAX_FRAME_SIZE: number; - const MAX_MAX_FRAME_SIZE: number; - const MIN_MAX_FRAME_SIZE: number; - const MAX_INITIAL_WINDOW_SIZE: number; - const NGHTTP2_DEFAULT_WEIGHT: number; - const NGHTTP2_SETTINGS_HEADER_TABLE_SIZE: number; - const NGHTTP2_SETTINGS_ENABLE_PUSH: number; - const NGHTTP2_SETTINGS_MAX_CONCURRENT_STREAMS: number; - const NGHTTP2_SETTINGS_INITIAL_WINDOW_SIZE: number; - const NGHTTP2_SETTINGS_MAX_FRAME_SIZE: number; - const NGHTTP2_SETTINGS_MAX_HEADER_LIST_SIZE: number; - const PADDING_STRATEGY_NONE: number; - const PADDING_STRATEGY_MAX: number; - const PADDING_STRATEGY_CALLBACK: number; - const HTTP2_HEADER_STATUS: string; - const HTTP2_HEADER_METHOD: string; - const HTTP2_HEADER_AUTHORITY: string; - const HTTP2_HEADER_SCHEME: string; - const HTTP2_HEADER_PATH: string; - const HTTP2_HEADER_ACCEPT_CHARSET: string; - const HTTP2_HEADER_ACCEPT_ENCODING: string; - const HTTP2_HEADER_ACCEPT_LANGUAGE: string; - const HTTP2_HEADER_ACCEPT_RANGES: string; - const HTTP2_HEADER_ACCEPT: string; - const HTTP2_HEADER_ACCESS_CONTROL_ALLOW_ORIGIN: string; - const HTTP2_HEADER_AGE: string; - const HTTP2_HEADER_ALLOW: string; - const HTTP2_HEADER_AUTHORIZATION: string; - const HTTP2_HEADER_CACHE_CONTROL: string; - const HTTP2_HEADER_CONNECTION: string; - const HTTP2_HEADER_CONTENT_DISPOSITION: string; - const HTTP2_HEADER_CONTENT_ENCODING: string; - const HTTP2_HEADER_CONTENT_LANGUAGE: string; - const HTTP2_HEADER_CONTENT_LENGTH: string; - const HTTP2_HEADER_CONTENT_LOCATION: string; - const HTTP2_HEADER_CONTENT_MD5: string; - const HTTP2_HEADER_CONTENT_RANGE: string; - const HTTP2_HEADER_CONTENT_TYPE: string; - const HTTP2_HEADER_COOKIE: string; - const HTTP2_HEADER_DATE: string; - const HTTP2_HEADER_ETAG: string; - const HTTP2_HEADER_EXPECT: string; - const HTTP2_HEADER_EXPIRES: string; - const HTTP2_HEADER_FROM: string; - const HTTP2_HEADER_HOST: string; - const HTTP2_HEADER_IF_MATCH: string; - const HTTP2_HEADER_IF_MODIFIED_SINCE: string; - const HTTP2_HEADER_IF_NONE_MATCH: string; - const HTTP2_HEADER_IF_RANGE: string; - const HTTP2_HEADER_IF_UNMODIFIED_SINCE: string; - const HTTP2_HEADER_LAST_MODIFIED: string; - const HTTP2_HEADER_LINK: string; - const HTTP2_HEADER_LOCATION: string; - const HTTP2_HEADER_MAX_FORWARDS: string; - const HTTP2_HEADER_PREFER: string; - const HTTP2_HEADER_PROXY_AUTHENTICATE: string; - const HTTP2_HEADER_PROXY_AUTHORIZATION: string; - const HTTP2_HEADER_RANGE: string; - const HTTP2_HEADER_REFERER: string; - const HTTP2_HEADER_REFRESH: string; - const HTTP2_HEADER_RETRY_AFTER: string; - const HTTP2_HEADER_SERVER: string; - const HTTP2_HEADER_SET_COOKIE: string; - const HTTP2_HEADER_STRICT_TRANSPORT_SECURITY: string; - const HTTP2_HEADER_TRANSFER_ENCODING: string; - const HTTP2_HEADER_TE: string; - const HTTP2_HEADER_UPGRADE: string; - const HTTP2_HEADER_USER_AGENT: string; - const HTTP2_HEADER_VARY: string; - const HTTP2_HEADER_VIA: string; - const HTTP2_HEADER_WWW_AUTHENTICATE: string; - const HTTP2_HEADER_HTTP2_SETTINGS: string; - const HTTP2_HEADER_KEEP_ALIVE: string; - const HTTP2_HEADER_PROXY_CONNECTION: string; - const HTTP2_METHOD_ACL: string; - const HTTP2_METHOD_BASELINE_CONTROL: string; - const HTTP2_METHOD_BIND: string; - const HTTP2_METHOD_CHECKIN: string; - const HTTP2_METHOD_CHECKOUT: string; - const HTTP2_METHOD_CONNECT: string; - const HTTP2_METHOD_COPY: string; - const HTTP2_METHOD_DELETE: string; - const HTTP2_METHOD_GET: string; - const HTTP2_METHOD_HEAD: string; - const HTTP2_METHOD_LABEL: string; - const HTTP2_METHOD_LINK: string; - const HTTP2_METHOD_LOCK: string; - const HTTP2_METHOD_MERGE: string; - const HTTP2_METHOD_MKACTIVITY: string; - const HTTP2_METHOD_MKCALENDAR: string; - const HTTP2_METHOD_MKCOL: string; - const HTTP2_METHOD_MKREDIRECTREF: string; - const HTTP2_METHOD_MKWORKSPACE: string; - const HTTP2_METHOD_MOVE: string; - const HTTP2_METHOD_OPTIONS: string; - const HTTP2_METHOD_ORDERPATCH: string; - const HTTP2_METHOD_PATCH: string; - const HTTP2_METHOD_POST: string; - const HTTP2_METHOD_PRI: string; - const HTTP2_METHOD_PROPFIND: string; - const HTTP2_METHOD_PROPPATCH: string; - const HTTP2_METHOD_PUT: string; - const HTTP2_METHOD_REBIND: string; - const HTTP2_METHOD_REPORT: string; - const HTTP2_METHOD_SEARCH: string; - const HTTP2_METHOD_TRACE: string; - const HTTP2_METHOD_UNBIND: string; - const HTTP2_METHOD_UNCHECKOUT: string; - const HTTP2_METHOD_UNLINK: string; - const HTTP2_METHOD_UNLOCK: string; - const HTTP2_METHOD_UPDATE: string; - const HTTP2_METHOD_UPDATEREDIRECTREF: string; - const HTTP2_METHOD_VERSION_CONTROL: string; - const HTTP_STATUS_CONTINUE: number; - const HTTP_STATUS_SWITCHING_PROTOCOLS: number; - const HTTP_STATUS_PROCESSING: number; - const HTTP_STATUS_OK: number; - const HTTP_STATUS_CREATED: number; - const HTTP_STATUS_ACCEPTED: number; - const HTTP_STATUS_NON_AUTHORITATIVE_INFORMATION: number; - const HTTP_STATUS_NO_CONTENT: number; - const HTTP_STATUS_RESET_CONTENT: number; - const HTTP_STATUS_PARTIAL_CONTENT: number; - const HTTP_STATUS_MULTI_STATUS: number; - const HTTP_STATUS_ALREADY_REPORTED: number; - const HTTP_STATUS_IM_USED: number; - const HTTP_STATUS_MULTIPLE_CHOICES: number; - const HTTP_STATUS_MOVED_PERMANENTLY: number; - const HTTP_STATUS_FOUND: number; - const HTTP_STATUS_SEE_OTHER: number; - const HTTP_STATUS_NOT_MODIFIED: number; - const HTTP_STATUS_USE_PROXY: number; - const HTTP_STATUS_TEMPORARY_REDIRECT: number; - const HTTP_STATUS_PERMANENT_REDIRECT: number; - const HTTP_STATUS_BAD_REQUEST: number; - const HTTP_STATUS_UNAUTHORIZED: number; - const HTTP_STATUS_PAYMENT_REQUIRED: number; - const HTTP_STATUS_FORBIDDEN: number; - const HTTP_STATUS_NOT_FOUND: number; - const HTTP_STATUS_METHOD_NOT_ALLOWED: number; - const HTTP_STATUS_NOT_ACCEPTABLE: number; - const HTTP_STATUS_PROXY_AUTHENTICATION_REQUIRED: number; - const HTTP_STATUS_REQUEST_TIMEOUT: number; - const HTTP_STATUS_CONFLICT: number; - const HTTP_STATUS_GONE: number; - const HTTP_STATUS_LENGTH_REQUIRED: number; - const HTTP_STATUS_PRECONDITION_FAILED: number; - const HTTP_STATUS_PAYLOAD_TOO_LARGE: number; - const HTTP_STATUS_URI_TOO_LONG: number; - const HTTP_STATUS_UNSUPPORTED_MEDIA_TYPE: number; - const HTTP_STATUS_RANGE_NOT_SATISFIABLE: number; - const HTTP_STATUS_EXPECTATION_FAILED: number; - const HTTP_STATUS_TEAPOT: number; - const HTTP_STATUS_MISDIRECTED_REQUEST: number; - const HTTP_STATUS_UNPROCESSABLE_ENTITY: number; - const HTTP_STATUS_LOCKED: number; - const HTTP_STATUS_FAILED_DEPENDENCY: number; - const HTTP_STATUS_UNORDERED_COLLECTION: number; - const HTTP_STATUS_UPGRADE_REQUIRED: number; - const HTTP_STATUS_PRECONDITION_REQUIRED: number; - const HTTP_STATUS_TOO_MANY_REQUESTS: number; - const HTTP_STATUS_REQUEST_HEADER_FIELDS_TOO_LARGE: number; - const HTTP_STATUS_UNAVAILABLE_FOR_LEGAL_REASONS: number; - const HTTP_STATUS_INTERNAL_SERVER_ERROR: number; - const HTTP_STATUS_NOT_IMPLEMENTED: number; - const HTTP_STATUS_BAD_GATEWAY: number; - const HTTP_STATUS_SERVICE_UNAVAILABLE: number; - const HTTP_STATUS_GATEWAY_TIMEOUT: number; - const HTTP_STATUS_HTTP_VERSION_NOT_SUPPORTED: number; - const HTTP_STATUS_VARIANT_ALSO_NEGOTIATES: number; - const HTTP_STATUS_INSUFFICIENT_STORAGE: number; - const HTTP_STATUS_LOOP_DETECTED: number; - const HTTP_STATUS_BANDWIDTH_LIMIT_EXCEEDED: number; - const HTTP_STATUS_NOT_EXTENDED: number; - const HTTP_STATUS_NETWORK_AUTHENTICATION_REQUIRED: number; - } - - export function getDefaultSettings(): Settings; - export function getPackedSettings(settings: Settings): Buffer; - export function getUnpackedSettings(buf: Uint8Array): Settings; - - export function createServer(onRequestHandler?: (request: Http2ServerRequest, response: Http2ServerResponse) => void): Http2Server; - export function createServer(options: ServerOptions, onRequestHandler?: (request: Http2ServerRequest, response: Http2ServerResponse) => void): Http2Server; - - export function createSecureServer(onRequestHandler?: (request: Http2ServerRequest, response: Http2ServerResponse) => void): Http2SecureServer; - export function createSecureServer(options: SecureServerOptions, onRequestHandler?: (request: Http2ServerRequest, response: Http2ServerResponse) => void): Http2SecureServer; - - export function connect(authority: string | url.URL, listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void): ClientHttp2Session; - export function connect( - authority: string | url.URL, - options?: ClientSessionOptions | SecureClientSessionOptions, - listener?: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void - ): ClientHttp2Session; -} diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/node/https.d.ts b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/node/https.d.ts deleted file mode 100644 index 24326c9d1f..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/node/https.d.ts +++ /dev/null @@ -1,37 +0,0 @@ -declare module "https" { - import * as tls from "tls"; - import * as events from "events"; - import * as http from "http"; - import { URL } from "url"; - - type ServerOptions = tls.SecureContextOptions & tls.TlsOptions & http.ServerOptions; - - type RequestOptions = http.RequestOptions & tls.SecureContextOptions & { - rejectUnauthorized?: boolean; // Defaults to true - servername?: string; // SNI TLS Extension - }; - - interface AgentOptions extends http.AgentOptions, tls.ConnectionOptions { - rejectUnauthorized?: boolean; - maxCachedSessions?: number; - } - - class Agent extends http.Agent { - constructor(options?: AgentOptions); - options: AgentOptions; - } - - interface Server extends http.HttpBase {} - class Server extends tls.Server { - constructor(requestListener?: http.RequestListener); - constructor(options: ServerOptions, requestListener?: http.RequestListener); - } - - function createServer(requestListener?: http.RequestListener): Server; - function createServer(options: ServerOptions, requestListener?: http.RequestListener): Server; - function request(options: RequestOptions | string | URL, callback?: (res: http.IncomingMessage) => void): http.ClientRequest; - function request(url: string | URL, options: RequestOptions, callback?: (res: http.IncomingMessage) => void): http.ClientRequest; - function get(options: RequestOptions | string | URL, callback?: (res: http.IncomingMessage) => void): http.ClientRequest; - function get(url: string | URL, options: RequestOptions, callback?: (res: http.IncomingMessage) => void): http.ClientRequest; - let globalAgent: Agent; -} diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/node/index.d.ts b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/node/index.d.ts deleted file mode 100644 index e65d170f0d..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/node/index.d.ts +++ /dev/null @@ -1,61 +0,0 @@ -// Type definitions for non-npm package Node.js 14.11 -// Project: http://nodejs.org/ -// Definitions by: Microsoft TypeScript -// DefinitelyTyped -// Alberto Schiabel -// Alexander T. -// Alvis HT Tang -// Andrew Makarov -// Benjamin Toueg -// Bruno Scheufler -// Chigozirim C. -// David Junger -// Deividas Bakanas -// Eugene Y. Q. Shen -// Flarna -// Hannes Magnusson -// Hoàng Văn Khải -// Huw -// Kelvin Jin -// Klaus Meinhardt -// Lishude -// Mariusz Wiktorczyk -// Mohsen Azimi -// Nicolas Even -// Nikita Galkin -// Parambir Singh -// Sebastian Silbermann -// Simon Schick -// Thomas den Hollander -// Wilco Bakker -// wwwy3y3 -// Samuel Ainsworth -// Kyle Uehlein -// Jordi Oliveras Rovira -// Thanik Bhongbhibhat -// Marcin Kopacz -// Trivikram Kamat -// Minh Son Nguyen -// Junxiao Shi -// Ilia Baryshnikov -// ExE Boss -// Surasak Chaisurin -// Piotr Błażejewicz -// Anna Henningsen -// Jason Kwok -// Victor Perin -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -// NOTE: These definitions support NodeJS and TypeScript 3.7. -// Typically type modifications should be made in base.d.ts instead of here - -/// - -// NOTE: TypeScript version-specific augmentations can be found in the following paths: -// - ~/base.d.ts - Shared definitions common to all TypeScript versions -// - ~/index.d.ts - Definitions specific to TypeScript 2.8 -// - ~/ts3.5/index.d.ts - Definitions specific to TypeScript 3.5 - -// NOTE: Augmentations for TypeScript 3.5 and later should use individual files for overrides -// within the respective ~/ts3.5 (or later) folder. However, this is disallowed for versions -// prior to TypeScript 3.5, so the older definitions will be found here. diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/node/inspector.d.ts b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/node/inspector.d.ts deleted file mode 100644 index 1c577346ed..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/node/inspector.d.ts +++ /dev/null @@ -1,3041 +0,0 @@ -// tslint:disable-next-line:dt-header -// Type definitions for inspector - -// These definitions are auto-generated. -// Please see https://github.com/DefinitelyTyped/DefinitelyTyped/pull/19330 -// for more information. - -// tslint:disable:max-line-length - -/** - * The inspector module provides an API for interacting with the V8 inspector. - */ -declare module "inspector" { - import { EventEmitter } from 'events'; - - interface InspectorNotification { - method: string; - params: T; - } - - namespace Schema { - /** - * Description of the protocol domain. - */ - interface Domain { - /** - * Domain name. - */ - name: string; - /** - * Domain version. - */ - version: string; - } - - interface GetDomainsReturnType { - /** - * List of supported domains. - */ - domains: Domain[]; - } - } - - namespace Runtime { - /** - * Unique script identifier. - */ - type ScriptId = string; - - /** - * Unique object identifier. - */ - type RemoteObjectId = string; - - /** - * Primitive value which cannot be JSON-stringified. - */ - type UnserializableValue = string; - - /** - * Mirror object referencing original JavaScript object. - */ - interface RemoteObject { - /** - * Object type. - */ - type: string; - /** - * Object subtype hint. Specified for object type values only. - */ - subtype?: string; - /** - * Object class (constructor) name. Specified for object type values only. - */ - className?: string; - /** - * Remote object value in case of primitive values or JSON values (if it was requested). - */ - value?: any; - /** - * Primitive value which can not be JSON-stringified does not have value, but gets this property. - */ - unserializableValue?: UnserializableValue; - /** - * String representation of the object. - */ - description?: string; - /** - * Unique object identifier (for non-primitive values). - */ - objectId?: RemoteObjectId; - /** - * Preview containing abbreviated property values. Specified for object type values only. - * @experimental - */ - preview?: ObjectPreview; - /** - * @experimental - */ - customPreview?: CustomPreview; - } - - /** - * @experimental - */ - interface CustomPreview { - header: string; - hasBody: boolean; - formatterObjectId: RemoteObjectId; - bindRemoteObjectFunctionId: RemoteObjectId; - configObjectId?: RemoteObjectId; - } - - /** - * Object containing abbreviated remote object value. - * @experimental - */ - interface ObjectPreview { - /** - * Object type. - */ - type: string; - /** - * Object subtype hint. Specified for object type values only. - */ - subtype?: string; - /** - * String representation of the object. - */ - description?: string; - /** - * True iff some of the properties or entries of the original object did not fit. - */ - overflow: boolean; - /** - * List of the properties. - */ - properties: PropertyPreview[]; - /** - * List of the entries. Specified for map and set subtype values only. - */ - entries?: EntryPreview[]; - } - - /** - * @experimental - */ - interface PropertyPreview { - /** - * Property name. - */ - name: string; - /** - * Object type. Accessor means that the property itself is an accessor property. - */ - type: string; - /** - * User-friendly property value string. - */ - value?: string; - /** - * Nested value preview. - */ - valuePreview?: ObjectPreview; - /** - * Object subtype hint. Specified for object type values only. - */ - subtype?: string; - } - - /** - * @experimental - */ - interface EntryPreview { - /** - * Preview of the key. Specified for map-like collection entries. - */ - key?: ObjectPreview; - /** - * Preview of the value. - */ - value: ObjectPreview; - } - - /** - * Object property descriptor. - */ - interface PropertyDescriptor { - /** - * Property name or symbol description. - */ - name: string; - /** - * The value associated with the property. - */ - value?: RemoteObject; - /** - * True if the value associated with the property may be changed (data descriptors only). - */ - writable?: boolean; - /** - * A function which serves as a getter for the property, or undefined if there is no getter (accessor descriptors only). - */ - get?: RemoteObject; - /** - * A function which serves as a setter for the property, or undefined if there is no setter (accessor descriptors only). - */ - set?: RemoteObject; - /** - * True if the type of this property descriptor may be changed and if the property may be deleted from the corresponding object. - */ - configurable: boolean; - /** - * True if this property shows up during enumeration of the properties on the corresponding object. - */ - enumerable: boolean; - /** - * True if the result was thrown during the evaluation. - */ - wasThrown?: boolean; - /** - * True if the property is owned for the object. - */ - isOwn?: boolean; - /** - * Property symbol object, if the property is of the symbol type. - */ - symbol?: RemoteObject; - } - - /** - * Object internal property descriptor. This property isn't normally visible in JavaScript code. - */ - interface InternalPropertyDescriptor { - /** - * Conventional property name. - */ - name: string; - /** - * The value associated with the property. - */ - value?: RemoteObject; - } - - /** - * Represents function call argument. Either remote object id objectId, primitive value, unserializable primitive value or neither of (for undefined) them should be specified. - */ - interface CallArgument { - /** - * Primitive value or serializable javascript object. - */ - value?: any; - /** - * Primitive value which can not be JSON-stringified. - */ - unserializableValue?: UnserializableValue; - /** - * Remote object handle. - */ - objectId?: RemoteObjectId; - } - - /** - * Id of an execution context. - */ - type ExecutionContextId = number; - - /** - * Description of an isolated world. - */ - interface ExecutionContextDescription { - /** - * Unique id of the execution context. It can be used to specify in which execution context script evaluation should be performed. - */ - id: ExecutionContextId; - /** - * Execution context origin. - */ - origin: string; - /** - * Human readable name describing given context. - */ - name: string; - /** - * Embedder-specific auxiliary data. - */ - auxData?: {}; - } - - /** - * Detailed information about exception (or error) that was thrown during script compilation or execution. - */ - interface ExceptionDetails { - /** - * Exception id. - */ - exceptionId: number; - /** - * Exception text, which should be used together with exception object when available. - */ - text: string; - /** - * Line number of the exception location (0-based). - */ - lineNumber: number; - /** - * Column number of the exception location (0-based). - */ - columnNumber: number; - /** - * Script ID of the exception location. - */ - scriptId?: ScriptId; - /** - * URL of the exception location, to be used when the script was not reported. - */ - url?: string; - /** - * JavaScript stack trace if available. - */ - stackTrace?: StackTrace; - /** - * Exception object if available. - */ - exception?: RemoteObject; - /** - * Identifier of the context where exception happened. - */ - executionContextId?: ExecutionContextId; - } - - /** - * Number of milliseconds since epoch. - */ - type Timestamp = number; - - /** - * Stack entry for runtime errors and assertions. - */ - interface CallFrame { - /** - * JavaScript function name. - */ - functionName: string; - /** - * JavaScript script id. - */ - scriptId: ScriptId; - /** - * JavaScript script name or url. - */ - url: string; - /** - * JavaScript script line number (0-based). - */ - lineNumber: number; - /** - * JavaScript script column number (0-based). - */ - columnNumber: number; - } - - /** - * Call frames for assertions or error messages. - */ - interface StackTrace { - /** - * String label of this stack trace. For async traces this may be a name of the function that initiated the async call. - */ - description?: string; - /** - * JavaScript function name. - */ - callFrames: CallFrame[]; - /** - * Asynchronous JavaScript stack trace that preceded this stack, if available. - */ - parent?: StackTrace; - /** - * Asynchronous JavaScript stack trace that preceded this stack, if available. - * @experimental - */ - parentId?: StackTraceId; - } - - /** - * Unique identifier of current debugger. - * @experimental - */ - type UniqueDebuggerId = string; - - /** - * If debuggerId is set stack trace comes from another debugger and can be resolved there. This allows to track cross-debugger calls. See Runtime.StackTrace and Debugger.paused for usages. - * @experimental - */ - interface StackTraceId { - id: string; - debuggerId?: UniqueDebuggerId; - } - - interface EvaluateParameterType { - /** - * Expression to evaluate. - */ - expression: string; - /** - * Symbolic group name that can be used to release multiple objects. - */ - objectGroup?: string; - /** - * Determines whether Command Line API should be available during the evaluation. - */ - includeCommandLineAPI?: boolean; - /** - * In silent mode exceptions thrown during evaluation are not reported and do not pause execution. Overrides setPauseOnException state. - */ - silent?: boolean; - /** - * Specifies in which execution context to perform evaluation. If the parameter is omitted the evaluation will be performed in the context of the inspected page. - */ - contextId?: ExecutionContextId; - /** - * Whether the result is expected to be a JSON object that should be sent by value. - */ - returnByValue?: boolean; - /** - * Whether preview should be generated for the result. - * @experimental - */ - generatePreview?: boolean; - /** - * Whether execution should be treated as initiated by user in the UI. - */ - userGesture?: boolean; - /** - * Whether execution should await for resulting value and return once awaited promise is resolved. - */ - awaitPromise?: boolean; - } - - interface AwaitPromiseParameterType { - /** - * Identifier of the promise. - */ - promiseObjectId: RemoteObjectId; - /** - * Whether the result is expected to be a JSON object that should be sent by value. - */ - returnByValue?: boolean; - /** - * Whether preview should be generated for the result. - */ - generatePreview?: boolean; - } - - interface CallFunctionOnParameterType { - /** - * Declaration of the function to call. - */ - functionDeclaration: string; - /** - * Identifier of the object to call function on. Either objectId or executionContextId should be specified. - */ - objectId?: RemoteObjectId; - /** - * Call arguments. All call arguments must belong to the same JavaScript world as the target object. - */ - arguments?: CallArgument[]; - /** - * In silent mode exceptions thrown during evaluation are not reported and do not pause execution. Overrides setPauseOnException state. - */ - silent?: boolean; - /** - * Whether the result is expected to be a JSON object which should be sent by value. - */ - returnByValue?: boolean; - /** - * Whether preview should be generated for the result. - * @experimental - */ - generatePreview?: boolean; - /** - * Whether execution should be treated as initiated by user in the UI. - */ - userGesture?: boolean; - /** - * Whether execution should await for resulting value and return once awaited promise is resolved. - */ - awaitPromise?: boolean; - /** - * Specifies execution context which global object will be used to call function on. Either executionContextId or objectId should be specified. - */ - executionContextId?: ExecutionContextId; - /** - * Symbolic group name that can be used to release multiple objects. If objectGroup is not specified and objectId is, objectGroup will be inherited from object. - */ - objectGroup?: string; - } - - interface GetPropertiesParameterType { - /** - * Identifier of the object to return properties for. - */ - objectId: RemoteObjectId; - /** - * If true, returns properties belonging only to the element itself, not to its prototype chain. - */ - ownProperties?: boolean; - /** - * If true, returns accessor properties (with getter/setter) only; internal properties are not returned either. - * @experimental - */ - accessorPropertiesOnly?: boolean; - /** - * Whether preview should be generated for the results. - * @experimental - */ - generatePreview?: boolean; - } - - interface ReleaseObjectParameterType { - /** - * Identifier of the object to release. - */ - objectId: RemoteObjectId; - } - - interface ReleaseObjectGroupParameterType { - /** - * Symbolic object group name. - */ - objectGroup: string; - } - - interface SetCustomObjectFormatterEnabledParameterType { - enabled: boolean; - } - - interface CompileScriptParameterType { - /** - * Expression to compile. - */ - expression: string; - /** - * Source url to be set for the script. - */ - sourceURL: string; - /** - * Specifies whether the compiled script should be persisted. - */ - persistScript: boolean; - /** - * Specifies in which execution context to perform script run. If the parameter is omitted the evaluation will be performed in the context of the inspected page. - */ - executionContextId?: ExecutionContextId; - } - - interface RunScriptParameterType { - /** - * Id of the script to run. - */ - scriptId: ScriptId; - /** - * Specifies in which execution context to perform script run. If the parameter is omitted the evaluation will be performed in the context of the inspected page. - */ - executionContextId?: ExecutionContextId; - /** - * Symbolic group name that can be used to release multiple objects. - */ - objectGroup?: string; - /** - * In silent mode exceptions thrown during evaluation are not reported and do not pause execution. Overrides setPauseOnException state. - */ - silent?: boolean; - /** - * Determines whether Command Line API should be available during the evaluation. - */ - includeCommandLineAPI?: boolean; - /** - * Whether the result is expected to be a JSON object which should be sent by value. - */ - returnByValue?: boolean; - /** - * Whether preview should be generated for the result. - */ - generatePreview?: boolean; - /** - * Whether execution should await for resulting value and return once awaited promise is resolved. - */ - awaitPromise?: boolean; - } - - interface QueryObjectsParameterType { - /** - * Identifier of the prototype to return objects for. - */ - prototypeObjectId: RemoteObjectId; - } - - interface GlobalLexicalScopeNamesParameterType { - /** - * Specifies in which execution context to lookup global scope variables. - */ - executionContextId?: ExecutionContextId; - } - - interface EvaluateReturnType { - /** - * Evaluation result. - */ - result: RemoteObject; - /** - * Exception details. - */ - exceptionDetails?: ExceptionDetails; - } - - interface AwaitPromiseReturnType { - /** - * Promise result. Will contain rejected value if promise was rejected. - */ - result: RemoteObject; - /** - * Exception details if stack strace is available. - */ - exceptionDetails?: ExceptionDetails; - } - - interface CallFunctionOnReturnType { - /** - * Call result. - */ - result: RemoteObject; - /** - * Exception details. - */ - exceptionDetails?: ExceptionDetails; - } - - interface GetPropertiesReturnType { - /** - * Object properties. - */ - result: PropertyDescriptor[]; - /** - * Internal object properties (only of the element itself). - */ - internalProperties?: InternalPropertyDescriptor[]; - /** - * Exception details. - */ - exceptionDetails?: ExceptionDetails; - } - - interface CompileScriptReturnType { - /** - * Id of the script. - */ - scriptId?: ScriptId; - /** - * Exception details. - */ - exceptionDetails?: ExceptionDetails; - } - - interface RunScriptReturnType { - /** - * Run result. - */ - result: RemoteObject; - /** - * Exception details. - */ - exceptionDetails?: ExceptionDetails; - } - - interface QueryObjectsReturnType { - /** - * Array with objects. - */ - objects: RemoteObject; - } - - interface GlobalLexicalScopeNamesReturnType { - names: string[]; - } - - interface ExecutionContextCreatedEventDataType { - /** - * A newly created execution context. - */ - context: ExecutionContextDescription; - } - - interface ExecutionContextDestroyedEventDataType { - /** - * Id of the destroyed context - */ - executionContextId: ExecutionContextId; - } - - interface ExceptionThrownEventDataType { - /** - * Timestamp of the exception. - */ - timestamp: Timestamp; - exceptionDetails: ExceptionDetails; - } - - interface ExceptionRevokedEventDataType { - /** - * Reason describing why exception was revoked. - */ - reason: string; - /** - * The id of revoked exception, as reported in exceptionThrown. - */ - exceptionId: number; - } - - interface ConsoleAPICalledEventDataType { - /** - * Type of the call. - */ - type: string; - /** - * Call arguments. - */ - args: RemoteObject[]; - /** - * Identifier of the context where the call was made. - */ - executionContextId: ExecutionContextId; - /** - * Call timestamp. - */ - timestamp: Timestamp; - /** - * Stack trace captured when the call was made. - */ - stackTrace?: StackTrace; - /** - * Console context descriptor for calls on non-default console context (not console.*): 'anonymous#unique-logger-id' for call on unnamed context, 'name#unique-logger-id' for call on named context. - * @experimental - */ - context?: string; - } - - interface InspectRequestedEventDataType { - object: RemoteObject; - hints: {}; - } - } - - namespace Debugger { - /** - * Breakpoint identifier. - */ - type BreakpointId = string; - - /** - * Call frame identifier. - */ - type CallFrameId = string; - - /** - * Location in the source code. - */ - interface Location { - /** - * Script identifier as reported in the Debugger.scriptParsed. - */ - scriptId: Runtime.ScriptId; - /** - * Line number in the script (0-based). - */ - lineNumber: number; - /** - * Column number in the script (0-based). - */ - columnNumber?: number; - } - - /** - * Location in the source code. - * @experimental - */ - interface ScriptPosition { - lineNumber: number; - columnNumber: number; - } - - /** - * JavaScript call frame. Array of call frames form the call stack. - */ - interface CallFrame { - /** - * Call frame identifier. This identifier is only valid while the virtual machine is paused. - */ - callFrameId: CallFrameId; - /** - * Name of the JavaScript function called on this call frame. - */ - functionName: string; - /** - * Location in the source code. - */ - functionLocation?: Location; - /** - * Location in the source code. - */ - location: Location; - /** - * JavaScript script name or url. - */ - url: string; - /** - * Scope chain for this call frame. - */ - scopeChain: Scope[]; - /** - * this object for this call frame. - */ - this: Runtime.RemoteObject; - /** - * The value being returned, if the function is at return point. - */ - returnValue?: Runtime.RemoteObject; - } - - /** - * Scope description. - */ - interface Scope { - /** - * Scope type. - */ - type: string; - /** - * Object representing the scope. For global and with scopes it represents the actual object; for the rest of the scopes, it is artificial transient object enumerating scope variables as its properties. - */ - object: Runtime.RemoteObject; - name?: string; - /** - * Location in the source code where scope starts - */ - startLocation?: Location; - /** - * Location in the source code where scope ends - */ - endLocation?: Location; - } - - /** - * Search match for resource. - */ - interface SearchMatch { - /** - * Line number in resource content. - */ - lineNumber: number; - /** - * Line with match content. - */ - lineContent: string; - } - - interface BreakLocation { - /** - * Script identifier as reported in the Debugger.scriptParsed. - */ - scriptId: Runtime.ScriptId; - /** - * Line number in the script (0-based). - */ - lineNumber: number; - /** - * Column number in the script (0-based). - */ - columnNumber?: number; - type?: string; - } - - interface SetBreakpointsActiveParameterType { - /** - * New value for breakpoints active state. - */ - active: boolean; - } - - interface SetSkipAllPausesParameterType { - /** - * New value for skip pauses state. - */ - skip: boolean; - } - - interface SetBreakpointByUrlParameterType { - /** - * Line number to set breakpoint at. - */ - lineNumber: number; - /** - * URL of the resources to set breakpoint on. - */ - url?: string; - /** - * Regex pattern for the URLs of the resources to set breakpoints on. Either url or urlRegex must be specified. - */ - urlRegex?: string; - /** - * Script hash of the resources to set breakpoint on. - */ - scriptHash?: string; - /** - * Offset in the line to set breakpoint at. - */ - columnNumber?: number; - /** - * Expression to use as a breakpoint condition. When specified, debugger will only stop on the breakpoint if this expression evaluates to true. - */ - condition?: string; - } - - interface SetBreakpointParameterType { - /** - * Location to set breakpoint in. - */ - location: Location; - /** - * Expression to use as a breakpoint condition. When specified, debugger will only stop on the breakpoint if this expression evaluates to true. - */ - condition?: string; - } - - interface RemoveBreakpointParameterType { - breakpointId: BreakpointId; - } - - interface GetPossibleBreakpointsParameterType { - /** - * Start of range to search possible breakpoint locations in. - */ - start: Location; - /** - * End of range to search possible breakpoint locations in (excluding). When not specified, end of scripts is used as end of range. - */ - end?: Location; - /** - * Only consider locations which are in the same (non-nested) function as start. - */ - restrictToFunction?: boolean; - } - - interface ContinueToLocationParameterType { - /** - * Location to continue to. - */ - location: Location; - targetCallFrames?: string; - } - - interface PauseOnAsyncCallParameterType { - /** - * Debugger will pause when async call with given stack trace is started. - */ - parentStackTraceId: Runtime.StackTraceId; - } - - interface StepIntoParameterType { - /** - * Debugger will issue additional Debugger.paused notification if any async task is scheduled before next pause. - * @experimental - */ - breakOnAsyncCall?: boolean; - } - - interface GetStackTraceParameterType { - stackTraceId: Runtime.StackTraceId; - } - - interface SearchInContentParameterType { - /** - * Id of the script to search in. - */ - scriptId: Runtime.ScriptId; - /** - * String to search for. - */ - query: string; - /** - * If true, search is case sensitive. - */ - caseSensitive?: boolean; - /** - * If true, treats string parameter as regex. - */ - isRegex?: boolean; - } - - interface SetScriptSourceParameterType { - /** - * Id of the script to edit. - */ - scriptId: Runtime.ScriptId; - /** - * New content of the script. - */ - scriptSource: string; - /** - * If true the change will not actually be applied. Dry run may be used to get result description without actually modifying the code. - */ - dryRun?: boolean; - } - - interface RestartFrameParameterType { - /** - * Call frame identifier to evaluate on. - */ - callFrameId: CallFrameId; - } - - interface GetScriptSourceParameterType { - /** - * Id of the script to get source for. - */ - scriptId: Runtime.ScriptId; - } - - interface SetPauseOnExceptionsParameterType { - /** - * Pause on exceptions mode. - */ - state: string; - } - - interface EvaluateOnCallFrameParameterType { - /** - * Call frame identifier to evaluate on. - */ - callFrameId: CallFrameId; - /** - * Expression to evaluate. - */ - expression: string; - /** - * String object group name to put result into (allows rapid releasing resulting object handles using releaseObjectGroup). - */ - objectGroup?: string; - /** - * Specifies whether command line API should be available to the evaluated expression, defaults to false. - */ - includeCommandLineAPI?: boolean; - /** - * In silent mode exceptions thrown during evaluation are not reported and do not pause execution. Overrides setPauseOnException state. - */ - silent?: boolean; - /** - * Whether the result is expected to be a JSON object that should be sent by value. - */ - returnByValue?: boolean; - /** - * Whether preview should be generated for the result. - * @experimental - */ - generatePreview?: boolean; - /** - * Whether to throw an exception if side effect cannot be ruled out during evaluation. - */ - throwOnSideEffect?: boolean; - } - - interface SetVariableValueParameterType { - /** - * 0-based number of scope as was listed in scope chain. Only 'local', 'closure' and 'catch' scope types are allowed. Other scopes could be manipulated manually. - */ - scopeNumber: number; - /** - * Variable name. - */ - variableName: string; - /** - * New variable value. - */ - newValue: Runtime.CallArgument; - /** - * Id of callframe that holds variable. - */ - callFrameId: CallFrameId; - } - - interface SetReturnValueParameterType { - /** - * New return value. - */ - newValue: Runtime.CallArgument; - } - - interface SetAsyncCallStackDepthParameterType { - /** - * Maximum depth of async call stacks. Setting to 0 will effectively disable collecting async call stacks (default). - */ - maxDepth: number; - } - - interface SetBlackboxPatternsParameterType { - /** - * Array of regexps that will be used to check script url for blackbox state. - */ - patterns: string[]; - } - - interface SetBlackboxedRangesParameterType { - /** - * Id of the script. - */ - scriptId: Runtime.ScriptId; - positions: ScriptPosition[]; - } - - interface EnableReturnType { - /** - * Unique identifier of the debugger. - * @experimental - */ - debuggerId: Runtime.UniqueDebuggerId; - } - - interface SetBreakpointByUrlReturnType { - /** - * Id of the created breakpoint for further reference. - */ - breakpointId: BreakpointId; - /** - * List of the locations this breakpoint resolved into upon addition. - */ - locations: Location[]; - } - - interface SetBreakpointReturnType { - /** - * Id of the created breakpoint for further reference. - */ - breakpointId: BreakpointId; - /** - * Location this breakpoint resolved into. - */ - actualLocation: Location; - } - - interface GetPossibleBreakpointsReturnType { - /** - * List of the possible breakpoint locations. - */ - locations: BreakLocation[]; - } - - interface GetStackTraceReturnType { - stackTrace: Runtime.StackTrace; - } - - interface SearchInContentReturnType { - /** - * List of search matches. - */ - result: SearchMatch[]; - } - - interface SetScriptSourceReturnType { - /** - * New stack trace in case editing has happened while VM was stopped. - */ - callFrames?: CallFrame[]; - /** - * Whether current call stack was modified after applying the changes. - */ - stackChanged?: boolean; - /** - * Async stack trace, if any. - */ - asyncStackTrace?: Runtime.StackTrace; - /** - * Async stack trace, if any. - * @experimental - */ - asyncStackTraceId?: Runtime.StackTraceId; - /** - * Exception details if any. - */ - exceptionDetails?: Runtime.ExceptionDetails; - } - - interface RestartFrameReturnType { - /** - * New stack trace. - */ - callFrames: CallFrame[]; - /** - * Async stack trace, if any. - */ - asyncStackTrace?: Runtime.StackTrace; - /** - * Async stack trace, if any. - * @experimental - */ - asyncStackTraceId?: Runtime.StackTraceId; - } - - interface GetScriptSourceReturnType { - /** - * Script source. - */ - scriptSource: string; - } - - interface EvaluateOnCallFrameReturnType { - /** - * Object wrapper for the evaluation result. - */ - result: Runtime.RemoteObject; - /** - * Exception details. - */ - exceptionDetails?: Runtime.ExceptionDetails; - } - - interface ScriptParsedEventDataType { - /** - * Identifier of the script parsed. - */ - scriptId: Runtime.ScriptId; - /** - * URL or name of the script parsed (if any). - */ - url: string; - /** - * Line offset of the script within the resource with given URL (for script tags). - */ - startLine: number; - /** - * Column offset of the script within the resource with given URL. - */ - startColumn: number; - /** - * Last line of the script. - */ - endLine: number; - /** - * Length of the last line of the script. - */ - endColumn: number; - /** - * Specifies script creation context. - */ - executionContextId: Runtime.ExecutionContextId; - /** - * Content hash of the script. - */ - hash: string; - /** - * Embedder-specific auxiliary data. - */ - executionContextAuxData?: {}; - /** - * True, if this script is generated as a result of the live edit operation. - * @experimental - */ - isLiveEdit?: boolean; - /** - * URL of source map associated with script (if any). - */ - sourceMapURL?: string; - /** - * True, if this script has sourceURL. - */ - hasSourceURL?: boolean; - /** - * True, if this script is ES6 module. - */ - isModule?: boolean; - /** - * This script length. - */ - length?: number; - /** - * JavaScript top stack frame of where the script parsed event was triggered if available. - * @experimental - */ - stackTrace?: Runtime.StackTrace; - } - - interface ScriptFailedToParseEventDataType { - /** - * Identifier of the script parsed. - */ - scriptId: Runtime.ScriptId; - /** - * URL or name of the script parsed (if any). - */ - url: string; - /** - * Line offset of the script within the resource with given URL (for script tags). - */ - startLine: number; - /** - * Column offset of the script within the resource with given URL. - */ - startColumn: number; - /** - * Last line of the script. - */ - endLine: number; - /** - * Length of the last line of the script. - */ - endColumn: number; - /** - * Specifies script creation context. - */ - executionContextId: Runtime.ExecutionContextId; - /** - * Content hash of the script. - */ - hash: string; - /** - * Embedder-specific auxiliary data. - */ - executionContextAuxData?: {}; - /** - * URL of source map associated with script (if any). - */ - sourceMapURL?: string; - /** - * True, if this script has sourceURL. - */ - hasSourceURL?: boolean; - /** - * True, if this script is ES6 module. - */ - isModule?: boolean; - /** - * This script length. - */ - length?: number; - /** - * JavaScript top stack frame of where the script parsed event was triggered if available. - * @experimental - */ - stackTrace?: Runtime.StackTrace; - } - - interface BreakpointResolvedEventDataType { - /** - * Breakpoint unique identifier. - */ - breakpointId: BreakpointId; - /** - * Actual breakpoint location. - */ - location: Location; - } - - interface PausedEventDataType { - /** - * Call stack the virtual machine stopped on. - */ - callFrames: CallFrame[]; - /** - * Pause reason. - */ - reason: string; - /** - * Object containing break-specific auxiliary properties. - */ - data?: {}; - /** - * Hit breakpoints IDs - */ - hitBreakpoints?: string[]; - /** - * Async stack trace, if any. - */ - asyncStackTrace?: Runtime.StackTrace; - /** - * Async stack trace, if any. - * @experimental - */ - asyncStackTraceId?: Runtime.StackTraceId; - /** - * Just scheduled async call will have this stack trace as parent stack during async execution. This field is available only after Debugger.stepInto call with breakOnAsynCall flag. - * @experimental - */ - asyncCallStackTraceId?: Runtime.StackTraceId; - } - } - - namespace Console { - /** - * Console message. - */ - interface ConsoleMessage { - /** - * Message source. - */ - source: string; - /** - * Message severity. - */ - level: string; - /** - * Message text. - */ - text: string; - /** - * URL of the message origin. - */ - url?: string; - /** - * Line number in the resource that generated this message (1-based). - */ - line?: number; - /** - * Column number in the resource that generated this message (1-based). - */ - column?: number; - } - - interface MessageAddedEventDataType { - /** - * Console message that has been added. - */ - message: ConsoleMessage; - } - } - - namespace Profiler { - /** - * Profile node. Holds callsite information, execution statistics and child nodes. - */ - interface ProfileNode { - /** - * Unique id of the node. - */ - id: number; - /** - * Function location. - */ - callFrame: Runtime.CallFrame; - /** - * Number of samples where this node was on top of the call stack. - */ - hitCount?: number; - /** - * Child node ids. - */ - children?: number[]; - /** - * The reason of being not optimized. The function may be deoptimized or marked as don't optimize. - */ - deoptReason?: string; - /** - * An array of source position ticks. - */ - positionTicks?: PositionTickInfo[]; - } - - /** - * Profile. - */ - interface Profile { - /** - * The list of profile nodes. First item is the root node. - */ - nodes: ProfileNode[]; - /** - * Profiling start timestamp in microseconds. - */ - startTime: number; - /** - * Profiling end timestamp in microseconds. - */ - endTime: number; - /** - * Ids of samples top nodes. - */ - samples?: number[]; - /** - * Time intervals between adjacent samples in microseconds. The first delta is relative to the profile startTime. - */ - timeDeltas?: number[]; - } - - /** - * Specifies a number of samples attributed to a certain source position. - */ - interface PositionTickInfo { - /** - * Source line number (1-based). - */ - line: number; - /** - * Number of samples attributed to the source line. - */ - ticks: number; - } - - /** - * Coverage data for a source range. - */ - interface CoverageRange { - /** - * JavaScript script source offset for the range start. - */ - startOffset: number; - /** - * JavaScript script source offset for the range end. - */ - endOffset: number; - /** - * Collected execution count of the source range. - */ - count: number; - } - - /** - * Coverage data for a JavaScript function. - */ - interface FunctionCoverage { - /** - * JavaScript function name. - */ - functionName: string; - /** - * Source ranges inside the function with coverage data. - */ - ranges: CoverageRange[]; - /** - * Whether coverage data for this function has block granularity. - */ - isBlockCoverage: boolean; - } - - /** - * Coverage data for a JavaScript script. - */ - interface ScriptCoverage { - /** - * JavaScript script id. - */ - scriptId: Runtime.ScriptId; - /** - * JavaScript script name or url. - */ - url: string; - /** - * Functions contained in the script that has coverage data. - */ - functions: FunctionCoverage[]; - } - - /** - * Describes a type collected during runtime. - * @experimental - */ - interface TypeObject { - /** - * Name of a type collected with type profiling. - */ - name: string; - } - - /** - * Source offset and types for a parameter or return value. - * @experimental - */ - interface TypeProfileEntry { - /** - * Source offset of the parameter or end of function for return values. - */ - offset: number; - /** - * The types for this parameter or return value. - */ - types: TypeObject[]; - } - - /** - * Type profile data collected during runtime for a JavaScript script. - * @experimental - */ - interface ScriptTypeProfile { - /** - * JavaScript script id. - */ - scriptId: Runtime.ScriptId; - /** - * JavaScript script name or url. - */ - url: string; - /** - * Type profile entries for parameters and return values of the functions in the script. - */ - entries: TypeProfileEntry[]; - } - - interface SetSamplingIntervalParameterType { - /** - * New sampling interval in microseconds. - */ - interval: number; - } - - interface StartPreciseCoverageParameterType { - /** - * Collect accurate call counts beyond simple 'covered' or 'not covered'. - */ - callCount?: boolean; - /** - * Collect block-based coverage. - */ - detailed?: boolean; - } - - interface StopReturnType { - /** - * Recorded profile. - */ - profile: Profile; - } - - interface TakePreciseCoverageReturnType { - /** - * Coverage data for the current isolate. - */ - result: ScriptCoverage[]; - } - - interface GetBestEffortCoverageReturnType { - /** - * Coverage data for the current isolate. - */ - result: ScriptCoverage[]; - } - - interface TakeTypeProfileReturnType { - /** - * Type profile for all scripts since startTypeProfile() was turned on. - */ - result: ScriptTypeProfile[]; - } - - interface ConsoleProfileStartedEventDataType { - id: string; - /** - * Location of console.profile(). - */ - location: Debugger.Location; - /** - * Profile title passed as an argument to console.profile(). - */ - title?: string; - } - - interface ConsoleProfileFinishedEventDataType { - id: string; - /** - * Location of console.profileEnd(). - */ - location: Debugger.Location; - profile: Profile; - /** - * Profile title passed as an argument to console.profile(). - */ - title?: string; - } - } - - namespace HeapProfiler { - /** - * Heap snapshot object id. - */ - type HeapSnapshotObjectId = string; - - /** - * Sampling Heap Profile node. Holds callsite information, allocation statistics and child nodes. - */ - interface SamplingHeapProfileNode { - /** - * Function location. - */ - callFrame: Runtime.CallFrame; - /** - * Allocations size in bytes for the node excluding children. - */ - selfSize: number; - /** - * Child nodes. - */ - children: SamplingHeapProfileNode[]; - } - - /** - * Profile. - */ - interface SamplingHeapProfile { - head: SamplingHeapProfileNode; - } - - interface StartTrackingHeapObjectsParameterType { - trackAllocations?: boolean; - } - - interface StopTrackingHeapObjectsParameterType { - /** - * If true 'reportHeapSnapshotProgress' events will be generated while snapshot is being taken when the tracking is stopped. - */ - reportProgress?: boolean; - } - - interface TakeHeapSnapshotParameterType { - /** - * If true 'reportHeapSnapshotProgress' events will be generated while snapshot is being taken. - */ - reportProgress?: boolean; - } - - interface GetObjectByHeapObjectIdParameterType { - objectId: HeapSnapshotObjectId; - /** - * Symbolic group name that can be used to release multiple objects. - */ - objectGroup?: string; - } - - interface AddInspectedHeapObjectParameterType { - /** - * Heap snapshot object id to be accessible by means of $x command line API. - */ - heapObjectId: HeapSnapshotObjectId; - } - - interface GetHeapObjectIdParameterType { - /** - * Identifier of the object to get heap object id for. - */ - objectId: Runtime.RemoteObjectId; - } - - interface StartSamplingParameterType { - /** - * Average sample interval in bytes. Poisson distribution is used for the intervals. The default value is 32768 bytes. - */ - samplingInterval?: number; - } - - interface GetObjectByHeapObjectIdReturnType { - /** - * Evaluation result. - */ - result: Runtime.RemoteObject; - } - - interface GetHeapObjectIdReturnType { - /** - * Id of the heap snapshot object corresponding to the passed remote object id. - */ - heapSnapshotObjectId: HeapSnapshotObjectId; - } - - interface StopSamplingReturnType { - /** - * Recorded sampling heap profile. - */ - profile: SamplingHeapProfile; - } - - interface GetSamplingProfileReturnType { - /** - * Return the sampling profile being collected. - */ - profile: SamplingHeapProfile; - } - - interface AddHeapSnapshotChunkEventDataType { - chunk: string; - } - - interface ReportHeapSnapshotProgressEventDataType { - done: number; - total: number; - finished?: boolean; - } - - interface LastSeenObjectIdEventDataType { - lastSeenObjectId: number; - timestamp: number; - } - - interface HeapStatsUpdateEventDataType { - /** - * An array of triplets. Each triplet describes a fragment. The first integer is the fragment index, the second integer is a total count of objects for the fragment, the third integer is a total size of the objects for the fragment. - */ - statsUpdate: number[]; - } - } - - namespace NodeTracing { - interface TraceConfig { - /** - * Controls how the trace buffer stores data. - */ - recordMode?: string; - /** - * Included category filters. - */ - includedCategories: string[]; - } - - interface StartParameterType { - traceConfig: TraceConfig; - } - - interface GetCategoriesReturnType { - /** - * A list of supported tracing categories. - */ - categories: string[]; - } - - interface DataCollectedEventDataType { - value: Array<{}>; - } - } - - namespace NodeWorker { - type WorkerID = string; - - /** - * Unique identifier of attached debugging session. - */ - type SessionID = string; - - interface WorkerInfo { - workerId: WorkerID; - type: string; - title: string; - url: string; - } - - interface SendMessageToWorkerParameterType { - message: string; - /** - * Identifier of the session. - */ - sessionId: SessionID; - } - - interface EnableParameterType { - /** - * Whether to new workers should be paused until the frontend sends `Runtime.runIfWaitingForDebugger` - * message to run them. - */ - waitForDebuggerOnStart: boolean; - } - - interface DetachParameterType { - sessionId: SessionID; - } - - interface AttachedToWorkerEventDataType { - /** - * Identifier assigned to the session used to send/receive messages. - */ - sessionId: SessionID; - workerInfo: WorkerInfo; - waitingForDebugger: boolean; - } - - interface DetachedFromWorkerEventDataType { - /** - * Detached session identifier. - */ - sessionId: SessionID; - } - - interface ReceivedMessageFromWorkerEventDataType { - /** - * Identifier of a session which sends a message. - */ - sessionId: SessionID; - message: string; - } - } - - namespace NodeRuntime { - interface NotifyWhenWaitingForDisconnectParameterType { - enabled: boolean; - } - } - - /** - * The inspector.Session is used for dispatching messages to the V8 inspector back-end and receiving message responses and notifications. - */ - class Session extends EventEmitter { - /** - * Create a new instance of the inspector.Session class. - * The inspector session needs to be connected through session.connect() before the messages can be dispatched to the inspector backend. - */ - constructor(); - - /** - * Connects a session to the inspector back-end. - * An exception will be thrown if there is already a connected session established either - * through the API or by a front-end connected to the Inspector WebSocket port. - */ - connect(): void; - - /** - * Immediately close the session. All pending message callbacks will be called with an error. - * session.connect() will need to be called to be able to send messages again. - * Reconnected session will lose all inspector state, such as enabled agents or configured breakpoints. - */ - disconnect(): void; - - /** - * Posts a message to the inspector back-end. callback will be notified when a response is received. - * callback is a function that accepts two optional arguments - error and message-specific result. - */ - post(method: string, params?: {}, callback?: (err: Error | null, params?: {}) => void): void; - post(method: string, callback?: (err: Error | null, params?: {}) => void): void; - - /** - * Returns supported domains. - */ - post(method: "Schema.getDomains", callback?: (err: Error | null, params: Schema.GetDomainsReturnType) => void): void; - - /** - * Evaluates expression on global object. - */ - post(method: "Runtime.evaluate", params?: Runtime.EvaluateParameterType, callback?: (err: Error | null, params: Runtime.EvaluateReturnType) => void): void; - post(method: "Runtime.evaluate", callback?: (err: Error | null, params: Runtime.EvaluateReturnType) => void): void; - - /** - * Add handler to promise with given promise object id. - */ - post(method: "Runtime.awaitPromise", params?: Runtime.AwaitPromiseParameterType, callback?: (err: Error | null, params: Runtime.AwaitPromiseReturnType) => void): void; - post(method: "Runtime.awaitPromise", callback?: (err: Error | null, params: Runtime.AwaitPromiseReturnType) => void): void; - - /** - * Calls function with given declaration on the given object. Object group of the result is inherited from the target object. - */ - post(method: "Runtime.callFunctionOn", params?: Runtime.CallFunctionOnParameterType, callback?: (err: Error | null, params: Runtime.CallFunctionOnReturnType) => void): void; - post(method: "Runtime.callFunctionOn", callback?: (err: Error | null, params: Runtime.CallFunctionOnReturnType) => void): void; - - /** - * Returns properties of a given object. Object group of the result is inherited from the target object. - */ - post(method: "Runtime.getProperties", params?: Runtime.GetPropertiesParameterType, callback?: (err: Error | null, params: Runtime.GetPropertiesReturnType) => void): void; - post(method: "Runtime.getProperties", callback?: (err: Error | null, params: Runtime.GetPropertiesReturnType) => void): void; - - /** - * Releases remote object with given id. - */ - post(method: "Runtime.releaseObject", params?: Runtime.ReleaseObjectParameterType, callback?: (err: Error | null) => void): void; - post(method: "Runtime.releaseObject", callback?: (err: Error | null) => void): void; - - /** - * Releases all remote objects that belong to a given group. - */ - post(method: "Runtime.releaseObjectGroup", params?: Runtime.ReleaseObjectGroupParameterType, callback?: (err: Error | null) => void): void; - post(method: "Runtime.releaseObjectGroup", callback?: (err: Error | null) => void): void; - - /** - * Tells inspected instance to run if it was waiting for debugger to attach. - */ - post(method: "Runtime.runIfWaitingForDebugger", callback?: (err: Error | null) => void): void; - - /** - * Enables reporting of execution contexts creation by means of executionContextCreated event. When the reporting gets enabled the event will be sent immediately for each existing execution context. - */ - post(method: "Runtime.enable", callback?: (err: Error | null) => void): void; - - /** - * Disables reporting of execution contexts creation. - */ - post(method: "Runtime.disable", callback?: (err: Error | null) => void): void; - - /** - * Discards collected exceptions and console API calls. - */ - post(method: "Runtime.discardConsoleEntries", callback?: (err: Error | null) => void): void; - - /** - * @experimental - */ - post(method: "Runtime.setCustomObjectFormatterEnabled", params?: Runtime.SetCustomObjectFormatterEnabledParameterType, callback?: (err: Error | null) => void): void; - post(method: "Runtime.setCustomObjectFormatterEnabled", callback?: (err: Error | null) => void): void; - - /** - * Compiles expression. - */ - post(method: "Runtime.compileScript", params?: Runtime.CompileScriptParameterType, callback?: (err: Error | null, params: Runtime.CompileScriptReturnType) => void): void; - post(method: "Runtime.compileScript", callback?: (err: Error | null, params: Runtime.CompileScriptReturnType) => void): void; - - /** - * Runs script with given id in a given context. - */ - post(method: "Runtime.runScript", params?: Runtime.RunScriptParameterType, callback?: (err: Error | null, params: Runtime.RunScriptReturnType) => void): void; - post(method: "Runtime.runScript", callback?: (err: Error | null, params: Runtime.RunScriptReturnType) => void): void; - - post(method: "Runtime.queryObjects", params?: Runtime.QueryObjectsParameterType, callback?: (err: Error | null, params: Runtime.QueryObjectsReturnType) => void): void; - post(method: "Runtime.queryObjects", callback?: (err: Error | null, params: Runtime.QueryObjectsReturnType) => void): void; - - /** - * Returns all let, const and class variables from global scope. - */ - post( - method: "Runtime.globalLexicalScopeNames", - params?: Runtime.GlobalLexicalScopeNamesParameterType, - callback?: (err: Error | null, params: Runtime.GlobalLexicalScopeNamesReturnType) => void - ): void; - post(method: "Runtime.globalLexicalScopeNames", callback?: (err: Error | null, params: Runtime.GlobalLexicalScopeNamesReturnType) => void): void; - - /** - * Enables debugger for the given page. Clients should not assume that the debugging has been enabled until the result for this command is received. - */ - post(method: "Debugger.enable", callback?: (err: Error | null, params: Debugger.EnableReturnType) => void): void; - - /** - * Disables debugger for given page. - */ - post(method: "Debugger.disable", callback?: (err: Error | null) => void): void; - - /** - * Activates / deactivates all breakpoints on the page. - */ - post(method: "Debugger.setBreakpointsActive", params?: Debugger.SetBreakpointsActiveParameterType, callback?: (err: Error | null) => void): void; - post(method: "Debugger.setBreakpointsActive", callback?: (err: Error | null) => void): void; - - /** - * Makes page not interrupt on any pauses (breakpoint, exception, dom exception etc). - */ - post(method: "Debugger.setSkipAllPauses", params?: Debugger.SetSkipAllPausesParameterType, callback?: (err: Error | null) => void): void; - post(method: "Debugger.setSkipAllPauses", callback?: (err: Error | null) => void): void; - - /** - * Sets JavaScript breakpoint at given location specified either by URL or URL regex. Once this command is issued, all existing parsed scripts will have breakpoints resolved and returned in locations property. Further matching script parsing will result in subsequent breakpointResolved events issued. This logical breakpoint will survive page reloads. - */ - post(method: "Debugger.setBreakpointByUrl", params?: Debugger.SetBreakpointByUrlParameterType, callback?: (err: Error | null, params: Debugger.SetBreakpointByUrlReturnType) => void): void; - post(method: "Debugger.setBreakpointByUrl", callback?: (err: Error | null, params: Debugger.SetBreakpointByUrlReturnType) => void): void; - - /** - * Sets JavaScript breakpoint at a given location. - */ - post(method: "Debugger.setBreakpoint", params?: Debugger.SetBreakpointParameterType, callback?: (err: Error | null, params: Debugger.SetBreakpointReturnType) => void): void; - post(method: "Debugger.setBreakpoint", callback?: (err: Error | null, params: Debugger.SetBreakpointReturnType) => void): void; - - /** - * Removes JavaScript breakpoint. - */ - post(method: "Debugger.removeBreakpoint", params?: Debugger.RemoveBreakpointParameterType, callback?: (err: Error | null) => void): void; - post(method: "Debugger.removeBreakpoint", callback?: (err: Error | null) => void): void; - - /** - * Returns possible locations for breakpoint. scriptId in start and end range locations should be the same. - */ - post( - method: "Debugger.getPossibleBreakpoints", - params?: Debugger.GetPossibleBreakpointsParameterType, - callback?: (err: Error | null, params: Debugger.GetPossibleBreakpointsReturnType) => void - ): void; - post(method: "Debugger.getPossibleBreakpoints", callback?: (err: Error | null, params: Debugger.GetPossibleBreakpointsReturnType) => void): void; - - /** - * Continues execution until specific location is reached. - */ - post(method: "Debugger.continueToLocation", params?: Debugger.ContinueToLocationParameterType, callback?: (err: Error | null) => void): void; - post(method: "Debugger.continueToLocation", callback?: (err: Error | null) => void): void; - - /** - * @experimental - */ - post(method: "Debugger.pauseOnAsyncCall", params?: Debugger.PauseOnAsyncCallParameterType, callback?: (err: Error | null) => void): void; - post(method: "Debugger.pauseOnAsyncCall", callback?: (err: Error | null) => void): void; - - /** - * Steps over the statement. - */ - post(method: "Debugger.stepOver", callback?: (err: Error | null) => void): void; - - /** - * Steps into the function call. - */ - post(method: "Debugger.stepInto", params?: Debugger.StepIntoParameterType, callback?: (err: Error | null) => void): void; - post(method: "Debugger.stepInto", callback?: (err: Error | null) => void): void; - - /** - * Steps out of the function call. - */ - post(method: "Debugger.stepOut", callback?: (err: Error | null) => void): void; - - /** - * Stops on the next JavaScript statement. - */ - post(method: "Debugger.pause", callback?: (err: Error | null) => void): void; - - /** - * This method is deprecated - use Debugger.stepInto with breakOnAsyncCall and Debugger.pauseOnAsyncTask instead. Steps into next scheduled async task if any is scheduled before next pause. Returns success when async task is actually scheduled, returns error if no task were scheduled or another scheduleStepIntoAsync was called. - * @experimental - */ - post(method: "Debugger.scheduleStepIntoAsync", callback?: (err: Error | null) => void): void; - - /** - * Resumes JavaScript execution. - */ - post(method: "Debugger.resume", callback?: (err: Error | null) => void): void; - - /** - * Returns stack trace with given stackTraceId. - * @experimental - */ - post(method: "Debugger.getStackTrace", params?: Debugger.GetStackTraceParameterType, callback?: (err: Error | null, params: Debugger.GetStackTraceReturnType) => void): void; - post(method: "Debugger.getStackTrace", callback?: (err: Error | null, params: Debugger.GetStackTraceReturnType) => void): void; - - /** - * Searches for given string in script content. - */ - post(method: "Debugger.searchInContent", params?: Debugger.SearchInContentParameterType, callback?: (err: Error | null, params: Debugger.SearchInContentReturnType) => void): void; - post(method: "Debugger.searchInContent", callback?: (err: Error | null, params: Debugger.SearchInContentReturnType) => void): void; - - /** - * Edits JavaScript source live. - */ - post(method: "Debugger.setScriptSource", params?: Debugger.SetScriptSourceParameterType, callback?: (err: Error | null, params: Debugger.SetScriptSourceReturnType) => void): void; - post(method: "Debugger.setScriptSource", callback?: (err: Error | null, params: Debugger.SetScriptSourceReturnType) => void): void; - - /** - * Restarts particular call frame from the beginning. - */ - post(method: "Debugger.restartFrame", params?: Debugger.RestartFrameParameterType, callback?: (err: Error | null, params: Debugger.RestartFrameReturnType) => void): void; - post(method: "Debugger.restartFrame", callback?: (err: Error | null, params: Debugger.RestartFrameReturnType) => void): void; - - /** - * Returns source for the script with given id. - */ - post(method: "Debugger.getScriptSource", params?: Debugger.GetScriptSourceParameterType, callback?: (err: Error | null, params: Debugger.GetScriptSourceReturnType) => void): void; - post(method: "Debugger.getScriptSource", callback?: (err: Error | null, params: Debugger.GetScriptSourceReturnType) => void): void; - - /** - * Defines pause on exceptions state. Can be set to stop on all exceptions, uncaught exceptions or no exceptions. Initial pause on exceptions state is none. - */ - post(method: "Debugger.setPauseOnExceptions", params?: Debugger.SetPauseOnExceptionsParameterType, callback?: (err: Error | null) => void): void; - post(method: "Debugger.setPauseOnExceptions", callback?: (err: Error | null) => void): void; - - /** - * Evaluates expression on a given call frame. - */ - post(method: "Debugger.evaluateOnCallFrame", params?: Debugger.EvaluateOnCallFrameParameterType, callback?: (err: Error | null, params: Debugger.EvaluateOnCallFrameReturnType) => void): void; - post(method: "Debugger.evaluateOnCallFrame", callback?: (err: Error | null, params: Debugger.EvaluateOnCallFrameReturnType) => void): void; - - /** - * Changes value of variable in a callframe. Object-based scopes are not supported and must be mutated manually. - */ - post(method: "Debugger.setVariableValue", params?: Debugger.SetVariableValueParameterType, callback?: (err: Error | null) => void): void; - post(method: "Debugger.setVariableValue", callback?: (err: Error | null) => void): void; - - /** - * Changes return value in top frame. Available only at return break position. - * @experimental - */ - post(method: "Debugger.setReturnValue", params?: Debugger.SetReturnValueParameterType, callback?: (err: Error | null) => void): void; - post(method: "Debugger.setReturnValue", callback?: (err: Error | null) => void): void; - - /** - * Enables or disables async call stacks tracking. - */ - post(method: "Debugger.setAsyncCallStackDepth", params?: Debugger.SetAsyncCallStackDepthParameterType, callback?: (err: Error | null) => void): void; - post(method: "Debugger.setAsyncCallStackDepth", callback?: (err: Error | null) => void): void; - - /** - * Replace previous blackbox patterns with passed ones. Forces backend to skip stepping/pausing in scripts with url matching one of the patterns. VM will try to leave blackboxed script by performing 'step in' several times, finally resorting to 'step out' if unsuccessful. - * @experimental - */ - post(method: "Debugger.setBlackboxPatterns", params?: Debugger.SetBlackboxPatternsParameterType, callback?: (err: Error | null) => void): void; - post(method: "Debugger.setBlackboxPatterns", callback?: (err: Error | null) => void): void; - - /** - * Makes backend skip steps in the script in blackboxed ranges. VM will try leave blacklisted scripts by performing 'step in' several times, finally resorting to 'step out' if unsuccessful. Positions array contains positions where blackbox state is changed. First interval isn't blackboxed. Array should be sorted. - * @experimental - */ - post(method: "Debugger.setBlackboxedRanges", params?: Debugger.SetBlackboxedRangesParameterType, callback?: (err: Error | null) => void): void; - post(method: "Debugger.setBlackboxedRanges", callback?: (err: Error | null) => void): void; - - /** - * Enables console domain, sends the messages collected so far to the client by means of the messageAdded notification. - */ - post(method: "Console.enable", callback?: (err: Error | null) => void): void; - - /** - * Disables console domain, prevents further console messages from being reported to the client. - */ - post(method: "Console.disable", callback?: (err: Error | null) => void): void; - - /** - * Does nothing. - */ - post(method: "Console.clearMessages", callback?: (err: Error | null) => void): void; - - post(method: "Profiler.enable", callback?: (err: Error | null) => void): void; - - post(method: "Profiler.disable", callback?: (err: Error | null) => void): void; - - /** - * Changes CPU profiler sampling interval. Must be called before CPU profiles recording started. - */ - post(method: "Profiler.setSamplingInterval", params?: Profiler.SetSamplingIntervalParameterType, callback?: (err: Error | null) => void): void; - post(method: "Profiler.setSamplingInterval", callback?: (err: Error | null) => void): void; - - post(method: "Profiler.start", callback?: (err: Error | null) => void): void; - - post(method: "Profiler.stop", callback?: (err: Error | null, params: Profiler.StopReturnType) => void): void; - - /** - * Enable precise code coverage. Coverage data for JavaScript executed before enabling precise code coverage may be incomplete. Enabling prevents running optimized code and resets execution counters. - */ - post(method: "Profiler.startPreciseCoverage", params?: Profiler.StartPreciseCoverageParameterType, callback?: (err: Error | null) => void): void; - post(method: "Profiler.startPreciseCoverage", callback?: (err: Error | null) => void): void; - - /** - * Disable precise code coverage. Disabling releases unnecessary execution count records and allows executing optimized code. - */ - post(method: "Profiler.stopPreciseCoverage", callback?: (err: Error | null) => void): void; - - /** - * Collect coverage data for the current isolate, and resets execution counters. Precise code coverage needs to have started. - */ - post(method: "Profiler.takePreciseCoverage", callback?: (err: Error | null, params: Profiler.TakePreciseCoverageReturnType) => void): void; - - /** - * Collect coverage data for the current isolate. The coverage data may be incomplete due to garbage collection. - */ - post(method: "Profiler.getBestEffortCoverage", callback?: (err: Error | null, params: Profiler.GetBestEffortCoverageReturnType) => void): void; - - /** - * Enable type profile. - * @experimental - */ - post(method: "Profiler.startTypeProfile", callback?: (err: Error | null) => void): void; - - /** - * Disable type profile. Disabling releases type profile data collected so far. - * @experimental - */ - post(method: "Profiler.stopTypeProfile", callback?: (err: Error | null) => void): void; - - /** - * Collect type profile. - * @experimental - */ - post(method: "Profiler.takeTypeProfile", callback?: (err: Error | null, params: Profiler.TakeTypeProfileReturnType) => void): void; - - post(method: "HeapProfiler.enable", callback?: (err: Error | null) => void): void; - - post(method: "HeapProfiler.disable", callback?: (err: Error | null) => void): void; - - post(method: "HeapProfiler.startTrackingHeapObjects", params?: HeapProfiler.StartTrackingHeapObjectsParameterType, callback?: (err: Error | null) => void): void; - post(method: "HeapProfiler.startTrackingHeapObjects", callback?: (err: Error | null) => void): void; - - post(method: "HeapProfiler.stopTrackingHeapObjects", params?: HeapProfiler.StopTrackingHeapObjectsParameterType, callback?: (err: Error | null) => void): void; - post(method: "HeapProfiler.stopTrackingHeapObjects", callback?: (err: Error | null) => void): void; - - post(method: "HeapProfiler.takeHeapSnapshot", params?: HeapProfiler.TakeHeapSnapshotParameterType, callback?: (err: Error | null) => void): void; - post(method: "HeapProfiler.takeHeapSnapshot", callback?: (err: Error | null) => void): void; - - post(method: "HeapProfiler.collectGarbage", callback?: (err: Error | null) => void): void; - - post( - method: "HeapProfiler.getObjectByHeapObjectId", - params?: HeapProfiler.GetObjectByHeapObjectIdParameterType, - callback?: (err: Error | null, params: HeapProfiler.GetObjectByHeapObjectIdReturnType) => void - ): void; - post(method: "HeapProfiler.getObjectByHeapObjectId", callback?: (err: Error | null, params: HeapProfiler.GetObjectByHeapObjectIdReturnType) => void): void; - - /** - * Enables console to refer to the node with given id via $x (see Command Line API for more details $x functions). - */ - post(method: "HeapProfiler.addInspectedHeapObject", params?: HeapProfiler.AddInspectedHeapObjectParameterType, callback?: (err: Error | null) => void): void; - post(method: "HeapProfiler.addInspectedHeapObject", callback?: (err: Error | null) => void): void; - - post(method: "HeapProfiler.getHeapObjectId", params?: HeapProfiler.GetHeapObjectIdParameterType, callback?: (err: Error | null, params: HeapProfiler.GetHeapObjectIdReturnType) => void): void; - post(method: "HeapProfiler.getHeapObjectId", callback?: (err: Error | null, params: HeapProfiler.GetHeapObjectIdReturnType) => void): void; - - post(method: "HeapProfiler.startSampling", params?: HeapProfiler.StartSamplingParameterType, callback?: (err: Error | null) => void): void; - post(method: "HeapProfiler.startSampling", callback?: (err: Error | null) => void): void; - - post(method: "HeapProfiler.stopSampling", callback?: (err: Error | null, params: HeapProfiler.StopSamplingReturnType) => void): void; - - post(method: "HeapProfiler.getSamplingProfile", callback?: (err: Error | null, params: HeapProfiler.GetSamplingProfileReturnType) => void): void; - - /** - * Gets supported tracing categories. - */ - post(method: "NodeTracing.getCategories", callback?: (err: Error | null, params: NodeTracing.GetCategoriesReturnType) => void): void; - - /** - * Start trace events collection. - */ - post(method: "NodeTracing.start", params?: NodeTracing.StartParameterType, callback?: (err: Error | null) => void): void; - post(method: "NodeTracing.start", callback?: (err: Error | null) => void): void; - - /** - * Stop trace events collection. Remaining collected events will be sent as a sequence of - * dataCollected events followed by tracingComplete event. - */ - post(method: "NodeTracing.stop", callback?: (err: Error | null) => void): void; - - /** - * Sends protocol message over session with given id. - */ - post(method: "NodeWorker.sendMessageToWorker", params?: NodeWorker.SendMessageToWorkerParameterType, callback?: (err: Error | null) => void): void; - post(method: "NodeWorker.sendMessageToWorker", callback?: (err: Error | null) => void): void; - - /** - * Instructs the inspector to attach to running workers. Will also attach to new workers - * as they start - */ - post(method: "NodeWorker.enable", params?: NodeWorker.EnableParameterType, callback?: (err: Error | null) => void): void; - post(method: "NodeWorker.enable", callback?: (err: Error | null) => void): void; - - /** - * Detaches from all running workers and disables attaching to new workers as they are started. - */ - post(method: "NodeWorker.disable", callback?: (err: Error | null) => void): void; - - /** - * Detached from the worker with given sessionId. - */ - post(method: "NodeWorker.detach", params?: NodeWorker.DetachParameterType, callback?: (err: Error | null) => void): void; - post(method: "NodeWorker.detach", callback?: (err: Error | null) => void): void; - - /** - * Enable the `NodeRuntime.waitingForDisconnect`. - */ - post(method: "NodeRuntime.notifyWhenWaitingForDisconnect", params?: NodeRuntime.NotifyWhenWaitingForDisconnectParameterType, callback?: (err: Error | null) => void): void; - post(method: "NodeRuntime.notifyWhenWaitingForDisconnect", callback?: (err: Error | null) => void): void; - - // Events - - addListener(event: string, listener: (...args: any[]) => void): this; - - /** - * Emitted when any notification from the V8 Inspector is received. - */ - addListener(event: "inspectorNotification", listener: (message: InspectorNotification<{}>) => void): this; - - /** - * Issued when new execution context is created. - */ - addListener(event: "Runtime.executionContextCreated", listener: (message: InspectorNotification) => void): this; - - /** - * Issued when execution context is destroyed. - */ - addListener(event: "Runtime.executionContextDestroyed", listener: (message: InspectorNotification) => void): this; - - /** - * Issued when all executionContexts were cleared in browser - */ - addListener(event: "Runtime.executionContextsCleared", listener: () => void): this; - - /** - * Issued when exception was thrown and unhandled. - */ - addListener(event: "Runtime.exceptionThrown", listener: (message: InspectorNotification) => void): this; - - /** - * Issued when unhandled exception was revoked. - */ - addListener(event: "Runtime.exceptionRevoked", listener: (message: InspectorNotification) => void): this; - - /** - * Issued when console API was called. - */ - addListener(event: "Runtime.consoleAPICalled", listener: (message: InspectorNotification) => void): this; - - /** - * Issued when object should be inspected (for example, as a result of inspect() command line API call). - */ - addListener(event: "Runtime.inspectRequested", listener: (message: InspectorNotification) => void): this; - - /** - * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. - */ - addListener(event: "Debugger.scriptParsed", listener: (message: InspectorNotification) => void): this; - - /** - * Fired when virtual machine fails to parse the script. - */ - addListener(event: "Debugger.scriptFailedToParse", listener: (message: InspectorNotification) => void): this; - - /** - * Fired when breakpoint is resolved to an actual script and location. - */ - addListener(event: "Debugger.breakpointResolved", listener: (message: InspectorNotification) => void): this; - - /** - * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. - */ - addListener(event: "Debugger.paused", listener: (message: InspectorNotification) => void): this; - - /** - * Fired when the virtual machine resumed execution. - */ - addListener(event: "Debugger.resumed", listener: () => void): this; - - /** - * Issued when new console message is added. - */ - addListener(event: "Console.messageAdded", listener: (message: InspectorNotification) => void): this; - - /** - * Sent when new profile recording is started using console.profile() call. - */ - addListener(event: "Profiler.consoleProfileStarted", listener: (message: InspectorNotification) => void): this; - - addListener(event: "Profiler.consoleProfileFinished", listener: (message: InspectorNotification) => void): this; - addListener(event: "HeapProfiler.addHeapSnapshotChunk", listener: (message: InspectorNotification) => void): this; - addListener(event: "HeapProfiler.resetProfiles", listener: () => void): this; - addListener(event: "HeapProfiler.reportHeapSnapshotProgress", listener: (message: InspectorNotification) => void): this; - - /** - * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. - */ - addListener(event: "HeapProfiler.lastSeenObjectId", listener: (message: InspectorNotification) => void): this; - - /** - * If heap objects tracking has been started then backend may send update for one or more fragments - */ - addListener(event: "HeapProfiler.heapStatsUpdate", listener: (message: InspectorNotification) => void): this; - - /** - * Contains an bucket of collected trace events. - */ - addListener(event: "NodeTracing.dataCollected", listener: (message: InspectorNotification) => void): this; - - /** - * Signals that tracing is stopped and there is no trace buffers pending flush, all data were - * delivered via dataCollected events. - */ - addListener(event: "NodeTracing.tracingComplete", listener: () => void): this; - - /** - * Issued when attached to a worker. - */ - addListener(event: "NodeWorker.attachedToWorker", listener: (message: InspectorNotification) => void): this; - - /** - * Issued when detached from the worker. - */ - addListener(event: "NodeWorker.detachedFromWorker", listener: (message: InspectorNotification) => void): this; - - /** - * Notifies about a new protocol message received from the session - * (session ID is provided in attachedToWorker notification). - */ - addListener(event: "NodeWorker.receivedMessageFromWorker", listener: (message: InspectorNotification) => void): this; - - /** - * This event is fired instead of `Runtime.executionContextDestroyed` when - * enabled. - * It is fired when the Node process finished all code execution and is - * waiting for all frontends to disconnect. - */ - addListener(event: "NodeRuntime.waitingForDisconnect", listener: () => void): this; - - emit(event: string | symbol, ...args: any[]): boolean; - emit(event: "inspectorNotification", message: InspectorNotification<{}>): boolean; - emit(event: "Runtime.executionContextCreated", message: InspectorNotification): boolean; - emit(event: "Runtime.executionContextDestroyed", message: InspectorNotification): boolean; - emit(event: "Runtime.executionContextsCleared"): boolean; - emit(event: "Runtime.exceptionThrown", message: InspectorNotification): boolean; - emit(event: "Runtime.exceptionRevoked", message: InspectorNotification): boolean; - emit(event: "Runtime.consoleAPICalled", message: InspectorNotification): boolean; - emit(event: "Runtime.inspectRequested", message: InspectorNotification): boolean; - emit(event: "Debugger.scriptParsed", message: InspectorNotification): boolean; - emit(event: "Debugger.scriptFailedToParse", message: InspectorNotification): boolean; - emit(event: "Debugger.breakpointResolved", message: InspectorNotification): boolean; - emit(event: "Debugger.paused", message: InspectorNotification): boolean; - emit(event: "Debugger.resumed"): boolean; - emit(event: "Console.messageAdded", message: InspectorNotification): boolean; - emit(event: "Profiler.consoleProfileStarted", message: InspectorNotification): boolean; - emit(event: "Profiler.consoleProfileFinished", message: InspectorNotification): boolean; - emit(event: "HeapProfiler.addHeapSnapshotChunk", message: InspectorNotification): boolean; - emit(event: "HeapProfiler.resetProfiles"): boolean; - emit(event: "HeapProfiler.reportHeapSnapshotProgress", message: InspectorNotification): boolean; - emit(event: "HeapProfiler.lastSeenObjectId", message: InspectorNotification): boolean; - emit(event: "HeapProfiler.heapStatsUpdate", message: InspectorNotification): boolean; - emit(event: "NodeTracing.dataCollected", message: InspectorNotification): boolean; - emit(event: "NodeTracing.tracingComplete"): boolean; - emit(event: "NodeWorker.attachedToWorker", message: InspectorNotification): boolean; - emit(event: "NodeWorker.detachedFromWorker", message: InspectorNotification): boolean; - emit(event: "NodeWorker.receivedMessageFromWorker", message: InspectorNotification): boolean; - emit(event: "NodeRuntime.waitingForDisconnect"): boolean; - - on(event: string, listener: (...args: any[]) => void): this; - - /** - * Emitted when any notification from the V8 Inspector is received. - */ - on(event: "inspectorNotification", listener: (message: InspectorNotification<{}>) => void): this; - - /** - * Issued when new execution context is created. - */ - on(event: "Runtime.executionContextCreated", listener: (message: InspectorNotification) => void): this; - - /** - * Issued when execution context is destroyed. - */ - on(event: "Runtime.executionContextDestroyed", listener: (message: InspectorNotification) => void): this; - - /** - * Issued when all executionContexts were cleared in browser - */ - on(event: "Runtime.executionContextsCleared", listener: () => void): this; - - /** - * Issued when exception was thrown and unhandled. - */ - on(event: "Runtime.exceptionThrown", listener: (message: InspectorNotification) => void): this; - - /** - * Issued when unhandled exception was revoked. - */ - on(event: "Runtime.exceptionRevoked", listener: (message: InspectorNotification) => void): this; - - /** - * Issued when console API was called. - */ - on(event: "Runtime.consoleAPICalled", listener: (message: InspectorNotification) => void): this; - - /** - * Issued when object should be inspected (for example, as a result of inspect() command line API call). - */ - on(event: "Runtime.inspectRequested", listener: (message: InspectorNotification) => void): this; - - /** - * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. - */ - on(event: "Debugger.scriptParsed", listener: (message: InspectorNotification) => void): this; - - /** - * Fired when virtual machine fails to parse the script. - */ - on(event: "Debugger.scriptFailedToParse", listener: (message: InspectorNotification) => void): this; - - /** - * Fired when breakpoint is resolved to an actual script and location. - */ - on(event: "Debugger.breakpointResolved", listener: (message: InspectorNotification) => void): this; - - /** - * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. - */ - on(event: "Debugger.paused", listener: (message: InspectorNotification) => void): this; - - /** - * Fired when the virtual machine resumed execution. - */ - on(event: "Debugger.resumed", listener: () => void): this; - - /** - * Issued when new console message is added. - */ - on(event: "Console.messageAdded", listener: (message: InspectorNotification) => void): this; - - /** - * Sent when new profile recording is started using console.profile() call. - */ - on(event: "Profiler.consoleProfileStarted", listener: (message: InspectorNotification) => void): this; - - on(event: "Profiler.consoleProfileFinished", listener: (message: InspectorNotification) => void): this; - on(event: "HeapProfiler.addHeapSnapshotChunk", listener: (message: InspectorNotification) => void): this; - on(event: "HeapProfiler.resetProfiles", listener: () => void): this; - on(event: "HeapProfiler.reportHeapSnapshotProgress", listener: (message: InspectorNotification) => void): this; - - /** - * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. - */ - on(event: "HeapProfiler.lastSeenObjectId", listener: (message: InspectorNotification) => void): this; - - /** - * If heap objects tracking has been started then backend may send update for one or more fragments - */ - on(event: "HeapProfiler.heapStatsUpdate", listener: (message: InspectorNotification) => void): this; - - /** - * Contains an bucket of collected trace events. - */ - on(event: "NodeTracing.dataCollected", listener: (message: InspectorNotification) => void): this; - - /** - * Signals that tracing is stopped and there is no trace buffers pending flush, all data were - * delivered via dataCollected events. - */ - on(event: "NodeTracing.tracingComplete", listener: () => void): this; - - /** - * Issued when attached to a worker. - */ - on(event: "NodeWorker.attachedToWorker", listener: (message: InspectorNotification) => void): this; - - /** - * Issued when detached from the worker. - */ - on(event: "NodeWorker.detachedFromWorker", listener: (message: InspectorNotification) => void): this; - - /** - * Notifies about a new protocol message received from the session - * (session ID is provided in attachedToWorker notification). - */ - on(event: "NodeWorker.receivedMessageFromWorker", listener: (message: InspectorNotification) => void): this; - - /** - * This event is fired instead of `Runtime.executionContextDestroyed` when - * enabled. - * It is fired when the Node process finished all code execution and is - * waiting for all frontends to disconnect. - */ - on(event: "NodeRuntime.waitingForDisconnect", listener: () => void): this; - - once(event: string, listener: (...args: any[]) => void): this; - - /** - * Emitted when any notification from the V8 Inspector is received. - */ - once(event: "inspectorNotification", listener: (message: InspectorNotification<{}>) => void): this; - - /** - * Issued when new execution context is created. - */ - once(event: "Runtime.executionContextCreated", listener: (message: InspectorNotification) => void): this; - - /** - * Issued when execution context is destroyed. - */ - once(event: "Runtime.executionContextDestroyed", listener: (message: InspectorNotification) => void): this; - - /** - * Issued when all executionContexts were cleared in browser - */ - once(event: "Runtime.executionContextsCleared", listener: () => void): this; - - /** - * Issued when exception was thrown and unhandled. - */ - once(event: "Runtime.exceptionThrown", listener: (message: InspectorNotification) => void): this; - - /** - * Issued when unhandled exception was revoked. - */ - once(event: "Runtime.exceptionRevoked", listener: (message: InspectorNotification) => void): this; - - /** - * Issued when console API was called. - */ - once(event: "Runtime.consoleAPICalled", listener: (message: InspectorNotification) => void): this; - - /** - * Issued when object should be inspected (for example, as a result of inspect() command line API call). - */ - once(event: "Runtime.inspectRequested", listener: (message: InspectorNotification) => void): this; - - /** - * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. - */ - once(event: "Debugger.scriptParsed", listener: (message: InspectorNotification) => void): this; - - /** - * Fired when virtual machine fails to parse the script. - */ - once(event: "Debugger.scriptFailedToParse", listener: (message: InspectorNotification) => void): this; - - /** - * Fired when breakpoint is resolved to an actual script and location. - */ - once(event: "Debugger.breakpointResolved", listener: (message: InspectorNotification) => void): this; - - /** - * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. - */ - once(event: "Debugger.paused", listener: (message: InspectorNotification) => void): this; - - /** - * Fired when the virtual machine resumed execution. - */ - once(event: "Debugger.resumed", listener: () => void): this; - - /** - * Issued when new console message is added. - */ - once(event: "Console.messageAdded", listener: (message: InspectorNotification) => void): this; - - /** - * Sent when new profile recording is started using console.profile() call. - */ - once(event: "Profiler.consoleProfileStarted", listener: (message: InspectorNotification) => void): this; - - once(event: "Profiler.consoleProfileFinished", listener: (message: InspectorNotification) => void): this; - once(event: "HeapProfiler.addHeapSnapshotChunk", listener: (message: InspectorNotification) => void): this; - once(event: "HeapProfiler.resetProfiles", listener: () => void): this; - once(event: "HeapProfiler.reportHeapSnapshotProgress", listener: (message: InspectorNotification) => void): this; - - /** - * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. - */ - once(event: "HeapProfiler.lastSeenObjectId", listener: (message: InspectorNotification) => void): this; - - /** - * If heap objects tracking has been started then backend may send update for one or more fragments - */ - once(event: "HeapProfiler.heapStatsUpdate", listener: (message: InspectorNotification) => void): this; - - /** - * Contains an bucket of collected trace events. - */ - once(event: "NodeTracing.dataCollected", listener: (message: InspectorNotification) => void): this; - - /** - * Signals that tracing is stopped and there is no trace buffers pending flush, all data were - * delivered via dataCollected events. - */ - once(event: "NodeTracing.tracingComplete", listener: () => void): this; - - /** - * Issued when attached to a worker. - */ - once(event: "NodeWorker.attachedToWorker", listener: (message: InspectorNotification) => void): this; - - /** - * Issued when detached from the worker. - */ - once(event: "NodeWorker.detachedFromWorker", listener: (message: InspectorNotification) => void): this; - - /** - * Notifies about a new protocol message received from the session - * (session ID is provided in attachedToWorker notification). - */ - once(event: "NodeWorker.receivedMessageFromWorker", listener: (message: InspectorNotification) => void): this; - - /** - * This event is fired instead of `Runtime.executionContextDestroyed` when - * enabled. - * It is fired when the Node process finished all code execution and is - * waiting for all frontends to disconnect. - */ - once(event: "NodeRuntime.waitingForDisconnect", listener: () => void): this; - - prependListener(event: string, listener: (...args: any[]) => void): this; - - /** - * Emitted when any notification from the V8 Inspector is received. - */ - prependListener(event: "inspectorNotification", listener: (message: InspectorNotification<{}>) => void): this; - - /** - * Issued when new execution context is created. - */ - prependListener(event: "Runtime.executionContextCreated", listener: (message: InspectorNotification) => void): this; - - /** - * Issued when execution context is destroyed. - */ - prependListener(event: "Runtime.executionContextDestroyed", listener: (message: InspectorNotification) => void): this; - - /** - * Issued when all executionContexts were cleared in browser - */ - prependListener(event: "Runtime.executionContextsCleared", listener: () => void): this; - - /** - * Issued when exception was thrown and unhandled. - */ - prependListener(event: "Runtime.exceptionThrown", listener: (message: InspectorNotification) => void): this; - - /** - * Issued when unhandled exception was revoked. - */ - prependListener(event: "Runtime.exceptionRevoked", listener: (message: InspectorNotification) => void): this; - - /** - * Issued when console API was called. - */ - prependListener(event: "Runtime.consoleAPICalled", listener: (message: InspectorNotification) => void): this; - - /** - * Issued when object should be inspected (for example, as a result of inspect() command line API call). - */ - prependListener(event: "Runtime.inspectRequested", listener: (message: InspectorNotification) => void): this; - - /** - * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. - */ - prependListener(event: "Debugger.scriptParsed", listener: (message: InspectorNotification) => void): this; - - /** - * Fired when virtual machine fails to parse the script. - */ - prependListener(event: "Debugger.scriptFailedToParse", listener: (message: InspectorNotification) => void): this; - - /** - * Fired when breakpoint is resolved to an actual script and location. - */ - prependListener(event: "Debugger.breakpointResolved", listener: (message: InspectorNotification) => void): this; - - /** - * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. - */ - prependListener(event: "Debugger.paused", listener: (message: InspectorNotification) => void): this; - - /** - * Fired when the virtual machine resumed execution. - */ - prependListener(event: "Debugger.resumed", listener: () => void): this; - - /** - * Issued when new console message is added. - */ - prependListener(event: "Console.messageAdded", listener: (message: InspectorNotification) => void): this; - - /** - * Sent when new profile recording is started using console.profile() call. - */ - prependListener(event: "Profiler.consoleProfileStarted", listener: (message: InspectorNotification) => void): this; - - prependListener(event: "Profiler.consoleProfileFinished", listener: (message: InspectorNotification) => void): this; - prependListener(event: "HeapProfiler.addHeapSnapshotChunk", listener: (message: InspectorNotification) => void): this; - prependListener(event: "HeapProfiler.resetProfiles", listener: () => void): this; - prependListener(event: "HeapProfiler.reportHeapSnapshotProgress", listener: (message: InspectorNotification) => void): this; - - /** - * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. - */ - prependListener(event: "HeapProfiler.lastSeenObjectId", listener: (message: InspectorNotification) => void): this; - - /** - * If heap objects tracking has been started then backend may send update for one or more fragments - */ - prependListener(event: "HeapProfiler.heapStatsUpdate", listener: (message: InspectorNotification) => void): this; - - /** - * Contains an bucket of collected trace events. - */ - prependListener(event: "NodeTracing.dataCollected", listener: (message: InspectorNotification) => void): this; - - /** - * Signals that tracing is stopped and there is no trace buffers pending flush, all data were - * delivered via dataCollected events. - */ - prependListener(event: "NodeTracing.tracingComplete", listener: () => void): this; - - /** - * Issued when attached to a worker. - */ - prependListener(event: "NodeWorker.attachedToWorker", listener: (message: InspectorNotification) => void): this; - - /** - * Issued when detached from the worker. - */ - prependListener(event: "NodeWorker.detachedFromWorker", listener: (message: InspectorNotification) => void): this; - - /** - * Notifies about a new protocol message received from the session - * (session ID is provided in attachedToWorker notification). - */ - prependListener(event: "NodeWorker.receivedMessageFromWorker", listener: (message: InspectorNotification) => void): this; - - /** - * This event is fired instead of `Runtime.executionContextDestroyed` when - * enabled. - * It is fired when the Node process finished all code execution and is - * waiting for all frontends to disconnect. - */ - prependListener(event: "NodeRuntime.waitingForDisconnect", listener: () => void): this; - - prependOnceListener(event: string, listener: (...args: any[]) => void): this; - - /** - * Emitted when any notification from the V8 Inspector is received. - */ - prependOnceListener(event: "inspectorNotification", listener: (message: InspectorNotification<{}>) => void): this; - - /** - * Issued when new execution context is created. - */ - prependOnceListener(event: "Runtime.executionContextCreated", listener: (message: InspectorNotification) => void): this; - - /** - * Issued when execution context is destroyed. - */ - prependOnceListener(event: "Runtime.executionContextDestroyed", listener: (message: InspectorNotification) => void): this; - - /** - * Issued when all executionContexts were cleared in browser - */ - prependOnceListener(event: "Runtime.executionContextsCleared", listener: () => void): this; - - /** - * Issued when exception was thrown and unhandled. - */ - prependOnceListener(event: "Runtime.exceptionThrown", listener: (message: InspectorNotification) => void): this; - - /** - * Issued when unhandled exception was revoked. - */ - prependOnceListener(event: "Runtime.exceptionRevoked", listener: (message: InspectorNotification) => void): this; - - /** - * Issued when console API was called. - */ - prependOnceListener(event: "Runtime.consoleAPICalled", listener: (message: InspectorNotification) => void): this; - - /** - * Issued when object should be inspected (for example, as a result of inspect() command line API call). - */ - prependOnceListener(event: "Runtime.inspectRequested", listener: (message: InspectorNotification) => void): this; - - /** - * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. - */ - prependOnceListener(event: "Debugger.scriptParsed", listener: (message: InspectorNotification) => void): this; - - /** - * Fired when virtual machine fails to parse the script. - */ - prependOnceListener(event: "Debugger.scriptFailedToParse", listener: (message: InspectorNotification) => void): this; - - /** - * Fired when breakpoint is resolved to an actual script and location. - */ - prependOnceListener(event: "Debugger.breakpointResolved", listener: (message: InspectorNotification) => void): this; - - /** - * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. - */ - prependOnceListener(event: "Debugger.paused", listener: (message: InspectorNotification) => void): this; - - /** - * Fired when the virtual machine resumed execution. - */ - prependOnceListener(event: "Debugger.resumed", listener: () => void): this; - - /** - * Issued when new console message is added. - */ - prependOnceListener(event: "Console.messageAdded", listener: (message: InspectorNotification) => void): this; - - /** - * Sent when new profile recording is started using console.profile() call. - */ - prependOnceListener(event: "Profiler.consoleProfileStarted", listener: (message: InspectorNotification) => void): this; - - prependOnceListener(event: "Profiler.consoleProfileFinished", listener: (message: InspectorNotification) => void): this; - prependOnceListener(event: "HeapProfiler.addHeapSnapshotChunk", listener: (message: InspectorNotification) => void): this; - prependOnceListener(event: "HeapProfiler.resetProfiles", listener: () => void): this; - prependOnceListener(event: "HeapProfiler.reportHeapSnapshotProgress", listener: (message: InspectorNotification) => void): this; - - /** - * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. - */ - prependOnceListener(event: "HeapProfiler.lastSeenObjectId", listener: (message: InspectorNotification) => void): this; - - /** - * If heap objects tracking has been started then backend may send update for one or more fragments - */ - prependOnceListener(event: "HeapProfiler.heapStatsUpdate", listener: (message: InspectorNotification) => void): this; - - /** - * Contains an bucket of collected trace events. - */ - prependOnceListener(event: "NodeTracing.dataCollected", listener: (message: InspectorNotification) => void): this; - - /** - * Signals that tracing is stopped and there is no trace buffers pending flush, all data were - * delivered via dataCollected events. - */ - prependOnceListener(event: "NodeTracing.tracingComplete", listener: () => void): this; - - /** - * Issued when attached to a worker. - */ - prependOnceListener(event: "NodeWorker.attachedToWorker", listener: (message: InspectorNotification) => void): this; - - /** - * Issued when detached from the worker. - */ - prependOnceListener(event: "NodeWorker.detachedFromWorker", listener: (message: InspectorNotification) => void): this; - - /** - * Notifies about a new protocol message received from the session - * (session ID is provided in attachedToWorker notification). - */ - prependOnceListener(event: "NodeWorker.receivedMessageFromWorker", listener: (message: InspectorNotification) => void): this; - - /** - * This event is fired instead of `Runtime.executionContextDestroyed` when - * enabled. - * It is fired when the Node process finished all code execution and is - * waiting for all frontends to disconnect. - */ - prependOnceListener(event: "NodeRuntime.waitingForDisconnect", listener: () => void): this; - } - - // Top Level API - - /** - * Activate inspector on host and port. Equivalent to node --inspect=[[host:]port], but can be done programatically after node has started. - * If wait is true, will block until a client has connected to the inspect port and flow control has been passed to the debugger client. - * @param port Port to listen on for inspector connections. Optional, defaults to what was specified on the CLI. - * @param host Host to listen on for inspector connections. Optional, defaults to what was specified on the CLI. - * @param wait Block until a client has connected. Optional, defaults to false. - */ - function open(port?: number, host?: string, wait?: boolean): void; - - /** - * Deactivate the inspector. Blocks until there are no active connections. - */ - function close(): void; - - /** - * Return the URL of the active inspector, or `undefined` if there is none. - */ - function url(): string | undefined; - - /** - * Blocks until a client (existing or connected later) has sent - * `Runtime.runIfWaitingForDebugger` command. - * An exception will be thrown if there is no active inspector. - */ - function waitForDebugger(): void; -} diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/node/module.d.ts b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/node/module.d.ts deleted file mode 100644 index ffb4a6eefb..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/node/module.d.ts +++ /dev/null @@ -1,52 +0,0 @@ -declare module "module" { - import { URL } from "url"; - namespace Module { - /** - * Updates all the live bindings for builtin ES Modules to match the properties of the CommonJS exports. - * It does not add or remove exported names from the ES Modules. - */ - function syncBuiltinESMExports(): void; - - function findSourceMap(path: string, error?: Error): SourceMap; - interface SourceMapPayload { - file: string; - version: number; - sources: string[]; - sourcesContent: string[]; - names: string[]; - mappings: string; - sourceRoot: string; - } - - interface SourceMapping { - generatedLine: number; - generatedColumn: number; - originalSource: string; - originalLine: number; - originalColumn: number; - } - - class SourceMap { - readonly payload: SourceMapPayload; - constructor(payload: SourceMapPayload); - findEntry(line: number, column: number): SourceMapping; - } - } - interface Module extends NodeModule {} - class Module { - static runMain(): void; - static wrap(code: string): string; - - /** - * @deprecated Deprecated since: v12.2.0. Please use createRequire() instead. - */ - static createRequireFromPath(path: string): NodeRequire; - static createRequire(path: string | URL): NodeRequire; - static builtinModules: string[]; - - static Module: typeof Module; - - constructor(id: string, parent?: Module); - } - export = Module; -} diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/node/net.d.ts b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/node/net.d.ts deleted file mode 100644 index e6ee1bb9f1..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/node/net.d.ts +++ /dev/null @@ -1,268 +0,0 @@ -declare module "net" { - import * as stream from "stream"; - import * as events from "events"; - import * as dns from "dns"; - - type LookupFunction = (hostname: string, options: dns.LookupOneOptions, callback: (err: NodeJS.ErrnoException | null, address: string, family: number) => void) => void; - - interface AddressInfo { - address: string; - family: string; - port: number; - } - - interface SocketConstructorOpts { - fd?: number; - allowHalfOpen?: boolean; - readable?: boolean; - writable?: boolean; - } - - interface OnReadOpts { - buffer: Uint8Array | (() => Uint8Array); - /** - * This function is called for every chunk of incoming data. - * Two arguments are passed to it: the number of bytes written to buffer and a reference to buffer. - * Return false from this function to implicitly pause() the socket. - */ - callback(bytesWritten: number, buf: Uint8Array): boolean; - } - - interface ConnectOpts { - /** - * If specified, incoming data is stored in a single buffer and passed to the supplied callback when data arrives on the socket. - * Note: this will cause the streaming functionality to not provide any data, however events like 'error', 'end', and 'close' will - * still be emitted as normal and methods like pause() and resume() will also behave as expected. - */ - onread?: OnReadOpts; - } - - interface TcpSocketConnectOpts extends ConnectOpts { - port: number; - host?: string; - localAddress?: string; - localPort?: number; - hints?: number; - family?: number; - lookup?: LookupFunction; - } - - interface IpcSocketConnectOpts extends ConnectOpts { - path: string; - } - - type SocketConnectOpts = TcpSocketConnectOpts | IpcSocketConnectOpts; - - class Socket extends stream.Duplex { - constructor(options?: SocketConstructorOpts); - - // Extended base methods - write(buffer: Uint8Array | string, cb?: (err?: Error) => void): boolean; - write(str: Uint8Array | string, encoding?: BufferEncoding, cb?: (err?: Error) => void): boolean; - - connect(options: SocketConnectOpts, connectionListener?: () => void): this; - connect(port: number, host: string, connectionListener?: () => void): this; - connect(port: number, connectionListener?: () => void): this; - connect(path: string, connectionListener?: () => void): this; - - setEncoding(encoding?: BufferEncoding): this; - pause(): this; - resume(): this; - setTimeout(timeout: number, callback?: () => void): this; - setNoDelay(noDelay?: boolean): this; - setKeepAlive(enable?: boolean, initialDelay?: number): this; - address(): AddressInfo | {}; - unref(): this; - ref(): this; - - readonly bufferSize: number; - readonly bytesRead: number; - readonly bytesWritten: number; - readonly connecting: boolean; - readonly destroyed: boolean; - readonly localAddress: string; - readonly localPort: number; - readonly remoteAddress?: string; - readonly remoteFamily?: string; - readonly remotePort?: number; - - // Extended base methods - end(cb?: () => void): void; - end(buffer: Uint8Array | string, cb?: () => void): void; - end(str: Uint8Array | string, encoding?: BufferEncoding, cb?: () => void): void; - - /** - * events.EventEmitter - * 1. close - * 2. connect - * 3. data - * 4. drain - * 5. end - * 6. error - * 7. lookup - * 8. timeout - */ - addListener(event: string, listener: (...args: any[]) => void): this; - addListener(event: "close", listener: (had_error: boolean) => void): this; - addListener(event: "connect", listener: () => void): this; - addListener(event: "data", listener: (data: Buffer) => void): this; - addListener(event: "drain", listener: () => void): this; - addListener(event: "end", listener: () => void): this; - addListener(event: "error", listener: (err: Error) => void): this; - addListener(event: "lookup", listener: (err: Error, address: string, family: string | number, host: string) => void): this; - addListener(event: "timeout", listener: () => void): this; - - emit(event: string | symbol, ...args: any[]): boolean; - emit(event: "close", had_error: boolean): boolean; - emit(event: "connect"): boolean; - emit(event: "data", data: Buffer): boolean; - emit(event: "drain"): boolean; - emit(event: "end"): boolean; - emit(event: "error", err: Error): boolean; - emit(event: "lookup", err: Error, address: string, family: string | number, host: string): boolean; - emit(event: "timeout"): boolean; - - on(event: string, listener: (...args: any[]) => void): this; - on(event: "close", listener: (had_error: boolean) => void): this; - on(event: "connect", listener: () => void): this; - on(event: "data", listener: (data: Buffer) => void): this; - on(event: "drain", listener: () => void): this; - on(event: "end", listener: () => void): this; - on(event: "error", listener: (err: Error) => void): this; - on(event: "lookup", listener: (err: Error, address: string, family: string | number, host: string) => void): this; - on(event: "timeout", listener: () => void): this; - - once(event: string, listener: (...args: any[]) => void): this; - once(event: "close", listener: (had_error: boolean) => void): this; - once(event: "connect", listener: () => void): this; - once(event: "data", listener: (data: Buffer) => void): this; - once(event: "drain", listener: () => void): this; - once(event: "end", listener: () => void): this; - once(event: "error", listener: (err: Error) => void): this; - once(event: "lookup", listener: (err: Error, address: string, family: string | number, host: string) => void): this; - once(event: "timeout", listener: () => void): this; - - prependListener(event: string, listener: (...args: any[]) => void): this; - prependListener(event: "close", listener: (had_error: boolean) => void): this; - prependListener(event: "connect", listener: () => void): this; - prependListener(event: "data", listener: (data: Buffer) => void): this; - prependListener(event: "drain", listener: () => void): this; - prependListener(event: "end", listener: () => void): this; - prependListener(event: "error", listener: (err: Error) => void): this; - prependListener(event: "lookup", listener: (err: Error, address: string, family: string | number, host: string) => void): this; - prependListener(event: "timeout", listener: () => void): this; - - prependOnceListener(event: string, listener: (...args: any[]) => void): this; - prependOnceListener(event: "close", listener: (had_error: boolean) => void): this; - prependOnceListener(event: "connect", listener: () => void): this; - prependOnceListener(event: "data", listener: (data: Buffer) => void): this; - prependOnceListener(event: "drain", listener: () => void): this; - prependOnceListener(event: "end", listener: () => void): this; - prependOnceListener(event: "error", listener: (err: Error) => void): this; - prependOnceListener(event: "lookup", listener: (err: Error, address: string, family: string | number, host: string) => void): this; - prependOnceListener(event: "timeout", listener: () => void): this; - } - - interface ListenOptions { - port?: number; - host?: string; - backlog?: number; - path?: string; - exclusive?: boolean; - readableAll?: boolean; - writableAll?: boolean; - /** - * @default false - */ - ipv6Only?: boolean; - } - - // https://github.com/nodejs/node/blob/master/lib/net.js - class Server extends events.EventEmitter { - constructor(connectionListener?: (socket: Socket) => void); - constructor(options?: { allowHalfOpen?: boolean, pauseOnConnect?: boolean }, connectionListener?: (socket: Socket) => void); - - listen(port?: number, hostname?: string, backlog?: number, listeningListener?: () => void): this; - listen(port?: number, hostname?: string, listeningListener?: () => void): this; - listen(port?: number, backlog?: number, listeningListener?: () => void): this; - listen(port?: number, listeningListener?: () => void): this; - listen(path: string, backlog?: number, listeningListener?: () => void): this; - listen(path: string, listeningListener?: () => void): this; - listen(options: ListenOptions, listeningListener?: () => void): this; - listen(handle: any, backlog?: number, listeningListener?: () => void): this; - listen(handle: any, listeningListener?: () => void): this; - close(callback?: (err?: Error) => void): this; - address(): AddressInfo | string | null; - getConnections(cb: (error: Error | null, count: number) => void): void; - ref(): this; - unref(): this; - maxConnections: number; - connections: number; - listening: boolean; - - /** - * events.EventEmitter - * 1. close - * 2. connection - * 3. error - * 4. listening - */ - addListener(event: string, listener: (...args: any[]) => void): this; - addListener(event: "close", listener: () => void): this; - addListener(event: "connection", listener: (socket: Socket) => void): this; - addListener(event: "error", listener: (err: Error) => void): this; - addListener(event: "listening", listener: () => void): this; - - emit(event: string | symbol, ...args: any[]): boolean; - emit(event: "close"): boolean; - emit(event: "connection", socket: Socket): boolean; - emit(event: "error", err: Error): boolean; - emit(event: "listening"): boolean; - - on(event: string, listener: (...args: any[]) => void): this; - on(event: "close", listener: () => void): this; - on(event: "connection", listener: (socket: Socket) => void): this; - on(event: "error", listener: (err: Error) => void): this; - on(event: "listening", listener: () => void): this; - - once(event: string, listener: (...args: any[]) => void): this; - once(event: "close", listener: () => void): this; - once(event: "connection", listener: (socket: Socket) => void): this; - once(event: "error", listener: (err: Error) => void): this; - once(event: "listening", listener: () => void): this; - - prependListener(event: string, listener: (...args: any[]) => void): this; - prependListener(event: "close", listener: () => void): this; - prependListener(event: "connection", listener: (socket: Socket) => void): this; - prependListener(event: "error", listener: (err: Error) => void): this; - prependListener(event: "listening", listener: () => void): this; - - prependOnceListener(event: string, listener: (...args: any[]) => void): this; - prependOnceListener(event: "close", listener: () => void): this; - prependOnceListener(event: "connection", listener: (socket: Socket) => void): this; - prependOnceListener(event: "error", listener: (err: Error) => void): this; - prependOnceListener(event: "listening", listener: () => void): this; - } - - interface TcpNetConnectOpts extends TcpSocketConnectOpts, SocketConstructorOpts { - timeout?: number; - } - - interface IpcNetConnectOpts extends IpcSocketConnectOpts, SocketConstructorOpts { - timeout?: number; - } - - type NetConnectOpts = TcpNetConnectOpts | IpcNetConnectOpts; - - function createServer(connectionListener?: (socket: Socket) => void): Server; - function createServer(options?: { allowHalfOpen?: boolean, pauseOnConnect?: boolean }, connectionListener?: (socket: Socket) => void): Server; - function connect(options: NetConnectOpts, connectionListener?: () => void): Socket; - function connect(port: number, host?: string, connectionListener?: () => void): Socket; - function connect(path: string, connectionListener?: () => void): Socket; - function createConnection(options: NetConnectOpts, connectionListener?: () => void): Socket; - function createConnection(port: number, host?: string, connectionListener?: () => void): Socket; - function createConnection(path: string, connectionListener?: () => void): Socket; - function isIP(input: string): number; - function isIPv4(input: string): boolean; - function isIPv6(input: string): boolean; -} diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/node/os.d.ts b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/node/os.d.ts deleted file mode 100644 index 1aadc68e22..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/node/os.d.ts +++ /dev/null @@ -1,239 +0,0 @@ -declare module "os" { - interface CpuInfo { - model: string; - speed: number; - times: { - user: number; - nice: number; - sys: number; - idle: number; - irq: number; - }; - } - - interface NetworkInterfaceBase { - address: string; - netmask: string; - mac: string; - internal: boolean; - cidr: string | null; - } - - interface NetworkInterfaceInfoIPv4 extends NetworkInterfaceBase { - family: "IPv4"; - } - - interface NetworkInterfaceInfoIPv6 extends NetworkInterfaceBase { - family: "IPv6"; - scopeid: number; - } - - interface UserInfo { - username: T; - uid: number; - gid: number; - shell: T; - homedir: T; - } - - type NetworkInterfaceInfo = NetworkInterfaceInfoIPv4 | NetworkInterfaceInfoIPv6; - - function hostname(): string; - function loadavg(): number[]; - function uptime(): number; - function freemem(): number; - function totalmem(): number; - function cpus(): CpuInfo[]; - function type(): string; - function release(): string; - function networkInterfaces(): NodeJS.Dict; - function homedir(): string; - function userInfo(options: { encoding: 'buffer' }): UserInfo; - function userInfo(options?: { encoding: BufferEncoding }): UserInfo; - - type SignalConstants = { - [key in NodeJS.Signals]: number; - }; - - namespace constants { - const UV_UDP_REUSEADDR: number; - namespace signals {} - const signals: SignalConstants; - namespace errno { - const E2BIG: number; - const EACCES: number; - const EADDRINUSE: number; - const EADDRNOTAVAIL: number; - const EAFNOSUPPORT: number; - const EAGAIN: number; - const EALREADY: number; - const EBADF: number; - const EBADMSG: number; - const EBUSY: number; - const ECANCELED: number; - const ECHILD: number; - const ECONNABORTED: number; - const ECONNREFUSED: number; - const ECONNRESET: number; - const EDEADLK: number; - const EDESTADDRREQ: number; - const EDOM: number; - const EDQUOT: number; - const EEXIST: number; - const EFAULT: number; - const EFBIG: number; - const EHOSTUNREACH: number; - const EIDRM: number; - const EILSEQ: number; - const EINPROGRESS: number; - const EINTR: number; - const EINVAL: number; - const EIO: number; - const EISCONN: number; - const EISDIR: number; - const ELOOP: number; - const EMFILE: number; - const EMLINK: number; - const EMSGSIZE: number; - const EMULTIHOP: number; - const ENAMETOOLONG: number; - const ENETDOWN: number; - const ENETRESET: number; - const ENETUNREACH: number; - const ENFILE: number; - const ENOBUFS: number; - const ENODATA: number; - const ENODEV: number; - const ENOENT: number; - const ENOEXEC: number; - const ENOLCK: number; - const ENOLINK: number; - const ENOMEM: number; - const ENOMSG: number; - const ENOPROTOOPT: number; - const ENOSPC: number; - const ENOSR: number; - const ENOSTR: number; - const ENOSYS: number; - const ENOTCONN: number; - const ENOTDIR: number; - const ENOTEMPTY: number; - const ENOTSOCK: number; - const ENOTSUP: number; - const ENOTTY: number; - const ENXIO: number; - const EOPNOTSUPP: number; - const EOVERFLOW: number; - const EPERM: number; - const EPIPE: number; - const EPROTO: number; - const EPROTONOSUPPORT: number; - const EPROTOTYPE: number; - const ERANGE: number; - const EROFS: number; - const ESPIPE: number; - const ESRCH: number; - const ESTALE: number; - const ETIME: number; - const ETIMEDOUT: number; - const ETXTBSY: number; - const EWOULDBLOCK: number; - const EXDEV: number; - const WSAEINTR: number; - const WSAEBADF: number; - const WSAEACCES: number; - const WSAEFAULT: number; - const WSAEINVAL: number; - const WSAEMFILE: number; - const WSAEWOULDBLOCK: number; - const WSAEINPROGRESS: number; - const WSAEALREADY: number; - const WSAENOTSOCK: number; - const WSAEDESTADDRREQ: number; - const WSAEMSGSIZE: number; - const WSAEPROTOTYPE: number; - const WSAENOPROTOOPT: number; - const WSAEPROTONOSUPPORT: number; - const WSAESOCKTNOSUPPORT: number; - const WSAEOPNOTSUPP: number; - const WSAEPFNOSUPPORT: number; - const WSAEAFNOSUPPORT: number; - const WSAEADDRINUSE: number; - const WSAEADDRNOTAVAIL: number; - const WSAENETDOWN: number; - const WSAENETUNREACH: number; - const WSAENETRESET: number; - const WSAECONNABORTED: number; - const WSAECONNRESET: number; - const WSAENOBUFS: number; - const WSAEISCONN: number; - const WSAENOTCONN: number; - const WSAESHUTDOWN: number; - const WSAETOOMANYREFS: number; - const WSAETIMEDOUT: number; - const WSAECONNREFUSED: number; - const WSAELOOP: number; - const WSAENAMETOOLONG: number; - const WSAEHOSTDOWN: number; - const WSAEHOSTUNREACH: number; - const WSAENOTEMPTY: number; - const WSAEPROCLIM: number; - const WSAEUSERS: number; - const WSAEDQUOT: number; - const WSAESTALE: number; - const WSAEREMOTE: number; - const WSASYSNOTREADY: number; - const WSAVERNOTSUPPORTED: number; - const WSANOTINITIALISED: number; - const WSAEDISCON: number; - const WSAENOMORE: number; - const WSAECANCELLED: number; - const WSAEINVALIDPROCTABLE: number; - const WSAEINVALIDPROVIDER: number; - const WSAEPROVIDERFAILEDINIT: number; - const WSASYSCALLFAILURE: number; - const WSASERVICE_NOT_FOUND: number; - const WSATYPE_NOT_FOUND: number; - const WSA_E_NO_MORE: number; - const WSA_E_CANCELLED: number; - const WSAEREFUSED: number; - } - namespace priority { - const PRIORITY_LOW: number; - const PRIORITY_BELOW_NORMAL: number; - const PRIORITY_NORMAL: number; - const PRIORITY_ABOVE_NORMAL: number; - const PRIORITY_HIGH: number; - const PRIORITY_HIGHEST: number; - } - } - - function arch(): string; - /** - * Returns a string identifying the kernel version. - * On POSIX systems, the operating system release is determined by calling - * [uname(3)][]. On Windows, `pRtlGetVersion` is used, and if it is not available, - * `GetVersionExW()` will be used. See - * https://en.wikipedia.org/wiki/Uname#Examples for more information. - */ - function version(): string; - function platform(): NodeJS.Platform; - function tmpdir(): string; - const EOL: string; - function endianness(): "BE" | "LE"; - /** - * Gets the priority of a process. - * Defaults to current process. - */ - function getPriority(pid?: number): number; - /** - * Sets the priority of the current process. - * @param priority Must be in range of -20 to 19 - */ - function setPriority(priority: number): void; - /** - * Sets the priority of the process specified process. - * @param priority Must be in range of -20 to 19 - */ - function setPriority(pid: number, priority: number): void; -} diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/node/package.json b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/node/package.json deleted file mode 100644 index afcfd203d6..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/node/package.json +++ /dev/null @@ -1,237 +0,0 @@ -{ - "_from": "@types/node@>=8", - "_id": "@types/node@14.11.10", - "_inBundle": false, - "_integrity": "sha512-yV1nWZPlMFpoXyoknm4S56y2nlTAuFYaJuQtYRAOU7xA/FJ9RY0Xm7QOkaYMMmr8ESdHIuUb6oQgR/0+2NqlyA==", - "_location": "/@types/node", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "@types/node@>=8", - "name": "@types/node", - "escapedName": "@types%2fnode", - "scope": "@types", - "rawSpec": ">=8", - "saveSpec": null, - "fetchSpec": ">=8" - }, - "_requiredBy": [ - "/cassandra-driver" - ], - "_resolved": "https://registry.npmjs.org/@types/node/-/node-14.11.10.tgz", - "_shasum": "8c102aba13bf5253f35146affbf8b26275069bef", - "_spec": "@types/node@>=8", - "_where": "/home/jan/Documents/skweb/node_modules/cassandra-driver", - "bugs": { - "url": "https://github.com/DefinitelyTyped/DefinitelyTyped/issues" - }, - "bundleDependencies": false, - "contributors": [ - { - "name": "Microsoft TypeScript", - "url": "https://github.com/Microsoft" - }, - { - "name": "DefinitelyTyped", - "url": "https://github.com/DefinitelyTyped" - }, - { - "name": "Alberto Schiabel", - "url": "https://github.com/jkomyno" - }, - { - "name": "Alexander T.", - "url": "https://github.com/a-tarasyuk" - }, - { - "name": "Alvis HT Tang", - "url": "https://github.com/alvis" - }, - { - "name": "Andrew Makarov", - "url": "https://github.com/r3nya" - }, - { - "name": "Benjamin Toueg", - "url": "https://github.com/btoueg" - }, - { - "name": "Bruno Scheufler", - "url": "https://github.com/brunoscheufler" - }, - { - "name": "Chigozirim C.", - "url": "https://github.com/smac89" - }, - { - "name": "David Junger", - "url": "https://github.com/touffy" - }, - { - "name": "Deividas Bakanas", - "url": "https://github.com/DeividasBakanas" - }, - { - "name": "Eugene Y. Q. Shen", - "url": "https://github.com/eyqs" - }, - { - "name": "Flarna", - "url": "https://github.com/Flarna" - }, - { - "name": "Hannes Magnusson", - "url": "https://github.com/Hannes-Magnusson-CK" - }, - { - "name": "Hoàng Văn Khải", - "url": "https://github.com/KSXGitHub" - }, - { - "name": "Huw", - "url": "https://github.com/hoo29" - }, - { - "name": "Kelvin Jin", - "url": "https://github.com/kjin" - }, - { - "name": "Klaus Meinhardt", - "url": "https://github.com/ajafff" - }, - { - "name": "Lishude", - "url": "https://github.com/islishude" - }, - { - "name": "Mariusz Wiktorczyk", - "url": "https://github.com/mwiktorczyk" - }, - { - "name": "Mohsen Azimi", - "url": "https://github.com/mohsen1" - }, - { - "name": "Nicolas Even", - "url": "https://github.com/n-e" - }, - { - "name": "Nikita Galkin", - "url": "https://github.com/galkin" - }, - { - "name": "Parambir Singh", - "url": "https://github.com/parambirs" - }, - { - "name": "Sebastian Silbermann", - "url": "https://github.com/eps1lon" - }, - { - "name": "Simon Schick", - "url": "https://github.com/SimonSchick" - }, - { - "name": "Thomas den Hollander", - "url": "https://github.com/ThomasdenH" - }, - { - "name": "Wilco Bakker", - "url": "https://github.com/WilcoBakker" - }, - { - "name": "wwwy3y3", - "url": "https://github.com/wwwy3y3" - }, - { - "name": "Samuel Ainsworth", - "url": "https://github.com/samuela" - }, - { - "name": "Kyle Uehlein", - "url": "https://github.com/kuehlein" - }, - { - "name": "Jordi Oliveras Rovira", - "url": "https://github.com/j-oliveras" - }, - { - "name": "Thanik Bhongbhibhat", - "url": "https://github.com/bhongy" - }, - { - "name": "Marcin Kopacz", - "url": "https://github.com/chyzwar" - }, - { - "name": "Trivikram Kamat", - "url": "https://github.com/trivikr" - }, - { - "name": "Minh Son Nguyen", - "url": "https://github.com/nguymin4" - }, - { - "name": "Junxiao Shi", - "url": "https://github.com/yoursunny" - }, - { - "name": "Ilia Baryshnikov", - "url": "https://github.com/qwelias" - }, - { - "name": "ExE Boss", - "url": "https://github.com/ExE-Boss" - }, - { - "name": "Surasak Chaisurin", - "url": "https://github.com/Ryan-Willpower" - }, - { - "name": "Piotr Błażejewicz", - "url": "https://github.com/peterblazejewicz" - }, - { - "name": "Anna Henningsen", - "url": "https://github.com/addaleax" - }, - { - "name": "Jason Kwok", - "url": "https://github.com/JasonHK" - }, - { - "name": "Victor Perin", - "url": "https://github.com/victorperin" - } - ], - "dependencies": {}, - "deprecated": false, - "description": "TypeScript definitions for Node.js", - "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped#readme", - "license": "MIT", - "main": "", - "name": "@types/node", - "repository": { - "type": "git", - "url": "git+https://github.com/DefinitelyTyped/DefinitelyTyped.git", - "directory": "types/node" - }, - "scripts": {}, - "typeScriptVersion": "3.2", - "types": "index.d.ts", - "typesPublisherContentHash": "c59f30458de89822a9f39049caff741590f879e0d2de7dd3d3d00d2f074236b9", - "typesVersions": { - "<=3.4": { - "*": [ - "ts3.4/*" - ] - }, - "<=3.6": { - "*": [ - "ts3.6/*" - ] - } - }, - "version": "14.11.10" -} diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/node/path.d.ts b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/node/path.d.ts deleted file mode 100644 index 0273d58ea0..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/node/path.d.ts +++ /dev/null @@ -1,153 +0,0 @@ -declare module "path" { - namespace path { - /** - * A parsed path object generated by path.parse() or consumed by path.format(). - */ - interface ParsedPath { - /** - * The root of the path such as '/' or 'c:\' - */ - root: string; - /** - * The full directory path such as '/home/user/dir' or 'c:\path\dir' - */ - dir: string; - /** - * The file name including extension (if any) such as 'index.html' - */ - base: string; - /** - * The file extension (if any) such as '.html' - */ - ext: string; - /** - * The file name without extension (if any) such as 'index' - */ - name: string; - } - - interface FormatInputPathObject { - /** - * The root of the path such as '/' or 'c:\' - */ - root?: string; - /** - * The full directory path such as '/home/user/dir' or 'c:\path\dir' - */ - dir?: string; - /** - * The file name including extension (if any) such as 'index.html' - */ - base?: string; - /** - * The file extension (if any) such as '.html' - */ - ext?: string; - /** - * The file name without extension (if any) such as 'index' - */ - name?: string; - } - - interface PlatformPath { - /** - * Normalize a string path, reducing '..' and '.' parts. - * When multiple slashes are found, they're replaced by a single one; when the path contains a trailing slash, it is preserved. On Windows backslashes are used. - * - * @param p string path to normalize. - */ - normalize(p: string): string; - /** - * Join all arguments together and normalize the resulting path. - * Arguments must be strings. In v0.8, non-string arguments were silently ignored. In v0.10 and up, an exception is thrown. - * - * @param paths paths to join. - */ - join(...paths: string[]): string; - /** - * The right-most parameter is considered {to}. Other parameters are considered an array of {from}. - * - * Starting from leftmost {from} parameter, resolves {to} to an absolute path. - * - * If {to} isn't already absolute, {from} arguments are prepended in right to left order, - * until an absolute path is found. If after using all {from} paths still no absolute path is found, - * the current working directory is used as well. The resulting path is normalized, - * and trailing slashes are removed unless the path gets resolved to the root directory. - * - * @param pathSegments string paths to join. Non-string arguments are ignored. - */ - resolve(...pathSegments: string[]): string; - /** - * Determines whether {path} is an absolute path. An absolute path will always resolve to the same location, regardless of the working directory. - * - * @param path path to test. - */ - isAbsolute(p: string): boolean; - /** - * Solve the relative path from {from} to {to}. - * At times we have two absolute paths, and we need to derive the relative path from one to the other. This is actually the reverse transform of path.resolve. - */ - relative(from: string, to: string): string; - /** - * Return the directory name of a path. Similar to the Unix dirname command. - * - * @param p the path to evaluate. - */ - dirname(p: string): string; - /** - * Return the last portion of a path. Similar to the Unix basename command. - * Often used to extract the file name from a fully qualified path. - * - * @param p the path to evaluate. - * @param ext optionally, an extension to remove from the result. - */ - basename(p: string, ext?: string): string; - /** - * Return the extension of the path, from the last '.' to end of string in the last portion of the path. - * If there is no '.' in the last portion of the path or the first character of it is '.', then it returns an empty string - * - * @param p the path to evaluate. - */ - extname(p: string): string; - /** - * The platform-specific file separator. '\\' or '/'. - */ - readonly sep: string; - /** - * The platform-specific file delimiter. ';' or ':'. - */ - readonly delimiter: string; - /** - * Returns an object from a path string - the opposite of format(). - * - * @param pathString path to evaluate. - */ - parse(p: string): ParsedPath; - /** - * Returns a path string from an object - the opposite of parse(). - * - * @param pathString path to evaluate. - */ - format(pP: FormatInputPathObject): string; - /** - * On Windows systems only, returns an equivalent namespace-prefixed path for the given path. - * If path is not a string, path will be returned without modifications. - * This method is meaningful only on Windows system. - * On POSIX systems, the method is non-operational and always returns path without modifications. - */ - toNamespacedPath(path: string): string; - /** - * Posix specific pathing. - * Same as parent object on posix. - */ - readonly posix: PlatformPath; - /** - * Windows specific pathing. - * Same as parent object on windows - */ - readonly win32: PlatformPath; - } - } - const path: path.PlatformPath; - export = path; -} diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/node/perf_hooks.d.ts b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/node/perf_hooks.d.ts deleted file mode 100644 index bbea938747..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/node/perf_hooks.d.ts +++ /dev/null @@ -1,271 +0,0 @@ -declare module 'perf_hooks' { - import { AsyncResource } from 'async_hooks'; - - type EntryType = 'node' | 'mark' | 'measure' | 'gc' | 'function' | 'http2' | 'http'; - - interface PerformanceEntry { - /** - * The total number of milliseconds elapsed for this entry. - * This value will not be meaningful for all Performance Entry types. - */ - readonly duration: number; - - /** - * The name of the performance entry. - */ - readonly name: string; - - /** - * The high resolution millisecond timestamp marking the starting time of the Performance Entry. - */ - readonly startTime: number; - - /** - * The type of the performance entry. - * Currently it may be one of: 'node', 'mark', 'measure', 'gc', or 'function'. - */ - readonly entryType: EntryType; - - /** - * When `performanceEntry.entryType` is equal to 'gc', `the performance.kind` property identifies - * the type of garbage collection operation that occurred. - * See perf_hooks.constants for valid values. - */ - readonly kind?: number; - - /** - * When `performanceEntry.entryType` is equal to 'gc', the `performance.flags` - * property contains additional information about garbage collection operation. - * See perf_hooks.constants for valid values. - */ - readonly flags?: number; - } - - interface PerformanceNodeTiming extends PerformanceEntry { - /** - * The high resolution millisecond timestamp at which the Node.js process completed bootstrap. - */ - readonly bootstrapComplete: number; - - /** - * The high resolution millisecond timestamp at which the Node.js process completed bootstrapping. - * If bootstrapping has not yet finished, the property has the value of -1. - */ - readonly environment: number; - - /** - * The high resolution millisecond timestamp at which the Node.js environment was initialized. - */ - readonly idleTime: number; - - /** - * The high resolution millisecond timestamp of the amount of time the event loop has been idle - * within the event loop's event provider (e.g. `epoll_wait`). This does not take CPU usage - * into consideration. If the event loop has not yet started (e.g., in the first tick of the main script), - * the property has the value of 0. - */ - readonly loopExit: number; - - /** - * The high resolution millisecond timestamp at which the Node.js event loop started. - * If the event loop has not yet started (e.g., in the first tick of the main script), the property has the value of -1. - */ - readonly loopStart: number; - - /** - * The high resolution millisecond timestamp at which the V8 platform was initialized. - */ - readonly v8Start: number; - } - - interface EventLoopUtilization { - idle: number; - active: number; - utilization: number; - } - - interface Performance { - /** - * If name is not provided, removes all PerformanceMark objects from the Performance Timeline. - * If name is provided, removes only the named mark. - * @param name - */ - clearMarks(name?: string): void; - - /** - * Creates a new PerformanceMark entry in the Performance Timeline. - * A PerformanceMark is a subclass of PerformanceEntry whose performanceEntry.entryType is always 'mark', - * and whose performanceEntry.duration is always 0. - * Performance marks are used to mark specific significant moments in the Performance Timeline. - * @param name - */ - mark(name?: string): void; - - /** - * Creates a new PerformanceMeasure entry in the Performance Timeline. - * A PerformanceMeasure is a subclass of PerformanceEntry whose performanceEntry.entryType is always 'measure', - * and whose performanceEntry.duration measures the number of milliseconds elapsed since startMark and endMark. - * - * The startMark argument may identify any existing PerformanceMark in the the Performance Timeline, or may identify - * any of the timestamp properties provided by the PerformanceNodeTiming class. If the named startMark does not exist, - * then startMark is set to timeOrigin by default. - * - * The endMark argument must identify any existing PerformanceMark in the the Performance Timeline or any of the timestamp - * properties provided by the PerformanceNodeTiming class. If the named endMark does not exist, an error will be thrown. - * @param name - * @param startMark - * @param endMark - */ - measure(name: string, startMark: string, endMark: string): void; - - /** - * An instance of the PerformanceNodeTiming class that provides performance metrics for specific Node.js operational milestones. - */ - readonly nodeTiming: PerformanceNodeTiming; - - /** - * @return the current high resolution millisecond timestamp - */ - now(): number; - - /** - * The timeOrigin specifies the high resolution millisecond timestamp from which all performance metric durations are measured. - */ - readonly timeOrigin: number; - - /** - * Wraps a function within a new function that measures the running time of the wrapped function. - * A PerformanceObserver must be subscribed to the 'function' event type in order for the timing details to be accessed. - * @param fn - */ - timerify any>(fn: T): T; - - /** - * eventLoopUtilization is similar to CPU utilization except that it is calculated using high precision wall-clock time. - * It represents the percentage of time the event loop has spent outside the event loop's event provider (e.g. epoll_wait). - * No other CPU idle time is taken into consideration. - * - * @param util1 The result of a previous call to eventLoopUtilization() - * @param util2 The result of a previous call to eventLoopUtilization() prior to util1 - */ - eventLoopUtilization(util1?: EventLoopUtilization, util2?: EventLoopUtilization): EventLoopUtilization; - } - - interface PerformanceObserverEntryList { - /** - * @return a list of PerformanceEntry objects in chronological order with respect to performanceEntry.startTime. - */ - getEntries(): PerformanceEntry[]; - - /** - * @return a list of PerformanceEntry objects in chronological order with respect to performanceEntry.startTime - * whose performanceEntry.name is equal to name, and optionally, whose performanceEntry.entryType is equal to type. - */ - getEntriesByName(name: string, type?: EntryType): PerformanceEntry[]; - - /** - * @return Returns a list of PerformanceEntry objects in chronological order with respect to performanceEntry.startTime - * whose performanceEntry.entryType is equal to type. - */ - getEntriesByType(type: EntryType): PerformanceEntry[]; - } - - type PerformanceObserverCallback = (list: PerformanceObserverEntryList, observer: PerformanceObserver) => void; - - class PerformanceObserver extends AsyncResource { - constructor(callback: PerformanceObserverCallback); - - /** - * Disconnects the PerformanceObserver instance from all notifications. - */ - disconnect(): void; - - /** - * Subscribes the PerformanceObserver instance to notifications of new PerformanceEntry instances identified by options.entryTypes. - * When options.buffered is false, the callback will be invoked once for every PerformanceEntry instance. - * Property buffered defaults to false. - * @param options - */ - observe(options: { entryTypes: ReadonlyArray; buffered?: boolean }): void; - } - - namespace constants { - const NODE_PERFORMANCE_GC_MAJOR: number; - const NODE_PERFORMANCE_GC_MINOR: number; - const NODE_PERFORMANCE_GC_INCREMENTAL: number; - const NODE_PERFORMANCE_GC_WEAKCB: number; - - const NODE_PERFORMANCE_GC_FLAGS_NO: number; - const NODE_PERFORMANCE_GC_FLAGS_CONSTRUCT_RETAINED: number; - const NODE_PERFORMANCE_GC_FLAGS_FORCED: number; - const NODE_PERFORMANCE_GC_FLAGS_SYNCHRONOUS_PHANTOM_PROCESSING: number; - const NODE_PERFORMANCE_GC_FLAGS_ALL_AVAILABLE_GARBAGE: number; - const NODE_PERFORMANCE_GC_FLAGS_ALL_EXTERNAL_MEMORY: number; - const NODE_PERFORMANCE_GC_FLAGS_SCHEDULE_IDLE: number; - } - - const performance: Performance; - - interface EventLoopMonitorOptions { - /** - * The sampling rate in milliseconds. - * Must be greater than zero. - * @default 10 - */ - resolution?: number; - } - - interface EventLoopDelayMonitor { - /** - * Enables the event loop delay sample timer. Returns `true` if the timer was started, `false` if it was already started. - */ - enable(): boolean; - /** - * Disables the event loop delay sample timer. Returns `true` if the timer was stopped, `false` if it was already stopped. - */ - disable(): boolean; - - /** - * Resets the collected histogram data. - */ - reset(): void; - - /** - * Returns the value at the given percentile. - * @param percentile A percentile value between 1 and 100. - */ - percentile(percentile: number): number; - - /** - * A `Map` object detailing the accumulated percentile distribution. - */ - readonly percentiles: Map; - - /** - * The number of times the event loop delay exceeded the maximum 1 hour eventloop delay threshold. - */ - readonly exceeds: number; - - /** - * The minimum recorded event loop delay. - */ - readonly min: number; - - /** - * The maximum recorded event loop delay. - */ - readonly max: number; - - /** - * The mean of the recorded event loop delays. - */ - readonly mean: number; - - /** - * The standard deviation of the recorded event loop delays. - */ - readonly stddev: number; - } - - function monitorEventLoopDelay(options?: EventLoopMonitorOptions): EventLoopDelayMonitor; -} diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/node/process.d.ts b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/node/process.d.ts deleted file mode 100644 index f5c2252e65..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/node/process.d.ts +++ /dev/null @@ -1,406 +0,0 @@ -declare module "process" { - import * as tty from "tty"; - - global { - var process: NodeJS.Process; - - namespace NodeJS { - // this namespace merge is here because these are specifically used - // as the type for process.stdin, process.stdout, and process.stderr. - // they can't live in tty.d.ts because we need to disambiguate the imported name. - interface ReadStream extends tty.ReadStream {} - interface WriteStream extends tty.WriteStream {} - - interface MemoryUsage { - rss: number; - heapTotal: number; - heapUsed: number; - external: number; - arrayBuffers: number; - } - - interface CpuUsage { - user: number; - system: number; - } - - interface ProcessRelease { - name: string; - sourceUrl?: string; - headersUrl?: string; - libUrl?: string; - lts?: string; - } - - interface ProcessVersions extends Dict { - http_parser: string; - node: string; - v8: string; - ares: string; - uv: string; - zlib: string; - modules: string; - openssl: string; - } - - type Platform = 'aix' - | 'android' - | 'darwin' - | 'freebsd' - | 'linux' - | 'openbsd' - | 'sunos' - | 'win32' - | 'cygwin' - | 'netbsd'; - - type Signals = - "SIGABRT" | "SIGALRM" | "SIGBUS" | "SIGCHLD" | "SIGCONT" | "SIGFPE" | "SIGHUP" | "SIGILL" | "SIGINT" | "SIGIO" | - "SIGIOT" | "SIGKILL" | "SIGPIPE" | "SIGPOLL" | "SIGPROF" | "SIGPWR" | "SIGQUIT" | "SIGSEGV" | "SIGSTKFLT" | - "SIGSTOP" | "SIGSYS" | "SIGTERM" | "SIGTRAP" | "SIGTSTP" | "SIGTTIN" | "SIGTTOU" | "SIGUNUSED" | "SIGURG" | - "SIGUSR1" | "SIGUSR2" | "SIGVTALRM" | "SIGWINCH" | "SIGXCPU" | "SIGXFSZ" | "SIGBREAK" | "SIGLOST" | "SIGINFO"; - - type MultipleResolveType = 'resolve' | 'reject'; - - type BeforeExitListener = (code: number) => void; - type DisconnectListener = () => void; - type ExitListener = (code: number) => void; - type RejectionHandledListener = (promise: Promise) => void; - type UncaughtExceptionListener = (error: Error) => void; - type UnhandledRejectionListener = (reason: {} | null | undefined, promise: Promise) => void; - type WarningListener = (warning: Error) => void; - type MessageListener = (message: any, sendHandle: any) => void; - type SignalsListener = (signal: Signals) => void; - type NewListenerListener = (type: string | symbol, listener: (...args: any[]) => void) => void; - type RemoveListenerListener = (type: string | symbol, listener: (...args: any[]) => void) => void; - type MultipleResolveListener = (type: MultipleResolveType, promise: Promise, value: any) => void; - - interface Socket extends ReadWriteStream { - isTTY?: true; - } - - // Alias for compatibility - interface ProcessEnv extends Dict {} - - interface HRTime { - (time?: [number, number]): [number, number]; - bigint(): bigint; - } - - interface ProcessReport { - /** - * Directory where the report is written. - * working directory of the Node.js process. - * @default '' indicating that reports are written to the current - */ - directory: string; - - /** - * Filename where the report is written. - * The default value is the empty string. - * @default '' the output filename will be comprised of a timestamp, - * PID, and sequence number. - */ - filename: string; - - /** - * Returns a JSON-formatted diagnostic report for the running process. - * The report's JavaScript stack trace is taken from err, if present. - */ - getReport(err?: Error): string; - - /** - * If true, a diagnostic report is generated on fatal errors, - * such as out of memory errors or failed C++ assertions. - * @default false - */ - reportOnFatalError: boolean; - - /** - * If true, a diagnostic report is generated when the process - * receives the signal specified by process.report.signal. - * @defaul false - */ - reportOnSignal: boolean; - - /** - * If true, a diagnostic report is generated on uncaught exception. - * @default false - */ - reportOnUncaughtException: boolean; - - /** - * The signal used to trigger the creation of a diagnostic report. - * @default 'SIGUSR2' - */ - signal: Signals; - - /** - * Writes a diagnostic report to a file. If filename is not provided, the default filename - * includes the date, time, PID, and a sequence number. - * The report's JavaScript stack trace is taken from err, if present. - * - * @param fileName Name of the file where the report is written. - * This should be a relative path, that will be appended to the directory specified in - * `process.report.directory`, or the current working directory of the Node.js process, - * if unspecified. - * @param error A custom error used for reporting the JavaScript stack. - * @return Filename of the generated report. - */ - writeReport(fileName?: string): string; - writeReport(error?: Error): string; - writeReport(fileName?: string, err?: Error): string; - } - - interface ResourceUsage { - fsRead: number; - fsWrite: number; - involuntaryContextSwitches: number; - ipcReceived: number; - ipcSent: number; - majorPageFault: number; - maxRSS: number; - minorPageFault: number; - sharedMemorySize: number; - signalsCount: number; - swappedOut: number; - systemCPUTime: number; - unsharedDataSize: number; - unsharedStackSize: number; - userCPUTime: number; - voluntaryContextSwitches: number; - } - - interface Process extends EventEmitter { - /** - * Can also be a tty.WriteStream, not typed due to limitations. - */ - stdout: WriteStream & { - fd: 1; - }; - /** - * Can also be a tty.WriteStream, not typed due to limitations. - */ - stderr: WriteStream & { - fd: 2; - }; - stdin: ReadStream & { - fd: 0; - }; - openStdin(): Socket; - argv: string[]; - argv0: string; - execArgv: string[]; - execPath: string; - abort(): void; - chdir(directory: string): void; - cwd(): string; - debugPort: number; - emitWarning(warning: string | Error, name?: string, ctor?: Function): void; - env: ProcessEnv; - exit(code?: number): never; - exitCode?: number; - getgid(): number; - setgid(id: number | string): void; - getuid(): number; - setuid(id: number | string): void; - geteuid(): number; - seteuid(id: number | string): void; - getegid(): number; - setegid(id: number | string): void; - getgroups(): number[]; - setgroups(groups: ReadonlyArray): void; - setUncaughtExceptionCaptureCallback(cb: ((err: Error) => void) | null): void; - hasUncaughtExceptionCaptureCallback(): boolean; - version: string; - versions: ProcessVersions; - config: { - target_defaults: { - cflags: any[]; - default_configuration: string; - defines: string[]; - include_dirs: string[]; - libraries: string[]; - }; - variables: { - clang: number; - host_arch: string; - node_install_npm: boolean; - node_install_waf: boolean; - node_prefix: string; - node_shared_openssl: boolean; - node_shared_v8: boolean; - node_shared_zlib: boolean; - node_use_dtrace: boolean; - node_use_etw: boolean; - node_use_openssl: boolean; - target_arch: string; - v8_no_strict_aliasing: number; - v8_use_snapshot: boolean; - visibility: string; - }; - }; - kill(pid: number, signal?: string | number): true; - pid: number; - ppid: number; - title: string; - arch: string; - platform: Platform; - /** @deprecated since v14.0.0 - use `require.main` instead. */ - mainModule?: Module; - memoryUsage(): MemoryUsage; - cpuUsage(previousValue?: CpuUsage): CpuUsage; - nextTick(callback: Function, ...args: any[]): void; - release: ProcessRelease; - features: { - inspector: boolean; - debug: boolean; - uv: boolean; - ipv6: boolean; - tls_alpn: boolean; - tls_sni: boolean; - tls_ocsp: boolean; - tls: boolean; - }; - /** - * @deprecated since v14.0.0 - Calling process.umask() with no argument causes - * the process-wide umask to be written twice. This introduces a race condition between threads, - * and is a potential security vulnerability. There is no safe, cross-platform alternative API. - */ - umask(): number; - /** - * Can only be set if not in worker thread. - */ - umask(mask: number): number; - uptime(): number; - hrtime: HRTime; - domain: Domain; - - // Worker - send?(message: any, sendHandle?: any, options?: { swallowErrors?: boolean}, callback?: (error: Error | null) => void): boolean; - disconnect(): void; - connected: boolean; - - /** - * The `process.allowedNodeEnvironmentFlags` property is a special, - * read-only `Set` of flags allowable within the [`NODE_OPTIONS`][] - * environment variable. - */ - allowedNodeEnvironmentFlags: ReadonlySet; - - /** - * Only available with `--experimental-report` - */ - report?: ProcessReport; - - resourceUsage(): ResourceUsage; - - /* EventEmitter */ - addListener(event: "beforeExit", listener: BeforeExitListener): this; - addListener(event: "disconnect", listener: DisconnectListener): this; - addListener(event: "exit", listener: ExitListener): this; - addListener(event: "rejectionHandled", listener: RejectionHandledListener): this; - addListener(event: "uncaughtException", listener: UncaughtExceptionListener): this; - addListener(event: "uncaughtExceptionMonitor", listener: UncaughtExceptionListener): this; - addListener(event: "unhandledRejection", listener: UnhandledRejectionListener): this; - addListener(event: "warning", listener: WarningListener): this; - addListener(event: "message", listener: MessageListener): this; - addListener(event: Signals, listener: SignalsListener): this; - addListener(event: "newListener", listener: NewListenerListener): this; - addListener(event: "removeListener", listener: RemoveListenerListener): this; - addListener(event: "multipleResolves", listener: MultipleResolveListener): this; - - emit(event: "beforeExit", code: number): boolean; - emit(event: "disconnect"): boolean; - emit(event: "exit", code: number): boolean; - emit(event: "rejectionHandled", promise: Promise): boolean; - emit(event: "uncaughtException", error: Error): boolean; - emit(event: "uncaughtExceptionMonitor", error: Error): boolean; - emit(event: "unhandledRejection", reason: any, promise: Promise): boolean; - emit(event: "warning", warning: Error): boolean; - emit(event: "message", message: any, sendHandle: any): this; - emit(event: Signals, signal: Signals): boolean; - emit(event: "newListener", eventName: string | symbol, listener: (...args: any[]) => void): this; - emit(event: "removeListener", eventName: string, listener: (...args: any[]) => void): this; - emit(event: "multipleResolves", listener: MultipleResolveListener): this; - - on(event: "beforeExit", listener: BeforeExitListener): this; - on(event: "disconnect", listener: DisconnectListener): this; - on(event: "exit", listener: ExitListener): this; - on(event: "rejectionHandled", listener: RejectionHandledListener): this; - on(event: "uncaughtException", listener: UncaughtExceptionListener): this; - on(event: "uncaughtExceptionMonitor", listener: UncaughtExceptionListener): this; - on(event: "unhandledRejection", listener: UnhandledRejectionListener): this; - on(event: "warning", listener: WarningListener): this; - on(event: "message", listener: MessageListener): this; - on(event: Signals, listener: SignalsListener): this; - on(event: "newListener", listener: NewListenerListener): this; - on(event: "removeListener", listener: RemoveListenerListener): this; - on(event: "multipleResolves", listener: MultipleResolveListener): this; - on(event: string | symbol, listener: (...args: any[]) => void): this; - - once(event: "beforeExit", listener: BeforeExitListener): this; - once(event: "disconnect", listener: DisconnectListener): this; - once(event: "exit", listener: ExitListener): this; - once(event: "rejectionHandled", listener: RejectionHandledListener): this; - once(event: "uncaughtException", listener: UncaughtExceptionListener): this; - once(event: "uncaughtExceptionMonitor", listener: UncaughtExceptionListener): this; - once(event: "unhandledRejection", listener: UnhandledRejectionListener): this; - once(event: "warning", listener: WarningListener): this; - once(event: "message", listener: MessageListener): this; - once(event: Signals, listener: SignalsListener): this; - once(event: "newListener", listener: NewListenerListener): this; - once(event: "removeListener", listener: RemoveListenerListener): this; - once(event: "multipleResolves", listener: MultipleResolveListener): this; - - prependListener(event: "beforeExit", listener: BeforeExitListener): this; - prependListener(event: "disconnect", listener: DisconnectListener): this; - prependListener(event: "exit", listener: ExitListener): this; - prependListener(event: "rejectionHandled", listener: RejectionHandledListener): this; - prependListener(event: "uncaughtException", listener: UncaughtExceptionListener): this; - prependListener(event: "uncaughtExceptionMonitor", listener: UncaughtExceptionListener): this; - prependListener(event: "unhandledRejection", listener: UnhandledRejectionListener): this; - prependListener(event: "warning", listener: WarningListener): this; - prependListener(event: "message", listener: MessageListener): this; - prependListener(event: Signals, listener: SignalsListener): this; - prependListener(event: "newListener", listener: NewListenerListener): this; - prependListener(event: "removeListener", listener: RemoveListenerListener): this; - prependListener(event: "multipleResolves", listener: MultipleResolveListener): this; - - prependOnceListener(event: "beforeExit", listener: BeforeExitListener): this; - prependOnceListener(event: "disconnect", listener: DisconnectListener): this; - prependOnceListener(event: "exit", listener: ExitListener): this; - prependOnceListener(event: "rejectionHandled", listener: RejectionHandledListener): this; - prependOnceListener(event: "uncaughtException", listener: UncaughtExceptionListener): this; - prependOnceListener(event: "uncaughtExceptionMonitor", listener: UncaughtExceptionListener): this; - prependOnceListener(event: "unhandledRejection", listener: UnhandledRejectionListener): this; - prependOnceListener(event: "warning", listener: WarningListener): this; - prependOnceListener(event: "message", listener: MessageListener): this; - prependOnceListener(event: Signals, listener: SignalsListener): this; - prependOnceListener(event: "newListener", listener: NewListenerListener): this; - prependOnceListener(event: "removeListener", listener: RemoveListenerListener): this; - prependOnceListener(event: "multipleResolves", listener: MultipleResolveListener): this; - - listeners(event: "beforeExit"): BeforeExitListener[]; - listeners(event: "disconnect"): DisconnectListener[]; - listeners(event: "exit"): ExitListener[]; - listeners(event: "rejectionHandled"): RejectionHandledListener[]; - listeners(event: "uncaughtException"): UncaughtExceptionListener[]; - listeners(event: "uncaughtExceptionMonitor"): UncaughtExceptionListener[]; - listeners(event: "unhandledRejection"): UnhandledRejectionListener[]; - listeners(event: "warning"): WarningListener[]; - listeners(event: "message"): MessageListener[]; - listeners(event: Signals): SignalsListener[]; - listeners(event: "newListener"): NewListenerListener[]; - listeners(event: "removeListener"): RemoveListenerListener[]; - listeners(event: "multipleResolves"): MultipleResolveListener[]; - } - - interface Global { - process: Process; - } - } - } - - export = process; -} diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/node/punycode.d.ts b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/node/punycode.d.ts deleted file mode 100644 index 2b771d456d..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/node/punycode.d.ts +++ /dev/null @@ -1,68 +0,0 @@ -declare module "punycode" { - /** - * @deprecated since v7.0.0 - * The version of the punycode module bundled in Node.js is being deprecated. - * In a future major version of Node.js this module will be removed. - * Users currently depending on the punycode module should switch to using - * the userland-provided Punycode.js module instead. - */ - function decode(string: string): string; - /** - * @deprecated since v7.0.0 - * The version of the punycode module bundled in Node.js is being deprecated. - * In a future major version of Node.js this module will be removed. - * Users currently depending on the punycode module should switch to using - * the userland-provided Punycode.js module instead. - */ - function encode(string: string): string; - /** - * @deprecated since v7.0.0 - * The version of the punycode module bundled in Node.js is being deprecated. - * In a future major version of Node.js this module will be removed. - * Users currently depending on the punycode module should switch to using - * the userland-provided Punycode.js module instead. - */ - function toUnicode(domain: string): string; - /** - * @deprecated since v7.0.0 - * The version of the punycode module bundled in Node.js is being deprecated. - * In a future major version of Node.js this module will be removed. - * Users currently depending on the punycode module should switch to using - * the userland-provided Punycode.js module instead. - */ - function toASCII(domain: string): string; - /** - * @deprecated since v7.0.0 - * The version of the punycode module bundled in Node.js is being deprecated. - * In a future major version of Node.js this module will be removed. - * Users currently depending on the punycode module should switch to using - * the userland-provided Punycode.js module instead. - */ - const ucs2: ucs2; - interface ucs2 { - /** - * @deprecated since v7.0.0 - * The version of the punycode module bundled in Node.js is being deprecated. - * In a future major version of Node.js this module will be removed. - * Users currently depending on the punycode module should switch to using - * the userland-provided Punycode.js module instead. - */ - decode(string: string): number[]; - /** - * @deprecated since v7.0.0 - * The version of the punycode module bundled in Node.js is being deprecated. - * In a future major version of Node.js this module will be removed. - * Users currently depending on the punycode module should switch to using - * the userland-provided Punycode.js module instead. - */ - encode(codePoints: ReadonlyArray): string; - } - /** - * @deprecated since v7.0.0 - * The version of the punycode module bundled in Node.js is being deprecated. - * In a future major version of Node.js this module will be removed. - * Users currently depending on the punycode module should switch to using - * the userland-provided Punycode.js module instead. - */ - const version: string; -} diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/node/querystring.d.ts b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/node/querystring.d.ts deleted file mode 100644 index 3e204e7f06..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/node/querystring.d.ts +++ /dev/null @@ -1,28 +0,0 @@ -declare module "querystring" { - interface StringifyOptions { - encodeURIComponent?: (str: string) => string; - } - - interface ParseOptions { - maxKeys?: number; - decodeURIComponent?: (str: string) => string; - } - - interface ParsedUrlQuery extends NodeJS.Dict { } - - interface ParsedUrlQueryInput extends NodeJS.Dict | ReadonlyArray | ReadonlyArray | null> { - } - - function stringify(obj?: ParsedUrlQueryInput, sep?: string, eq?: string, options?: StringifyOptions): string; - function parse(str: string, sep?: string, eq?: string, options?: ParseOptions): ParsedUrlQuery; - /** - * The querystring.encode() function is an alias for querystring.stringify(). - */ - const encode: typeof stringify; - /** - * The querystring.decode() function is an alias for querystring.parse(). - */ - const decode: typeof parse; - function escape(str: string): string; - function unescape(str: string): string; -} diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/node/readline.d.ts b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/node/readline.d.ts deleted file mode 100644 index fbe4836f31..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/node/readline.d.ts +++ /dev/null @@ -1,171 +0,0 @@ -declare module "readline" { - import * as events from "events"; - import * as stream from "stream"; - - interface Key { - sequence?: string; - name?: string; - ctrl?: boolean; - meta?: boolean; - shift?: boolean; - } - - class Interface extends events.EventEmitter { - readonly terminal: boolean; - - // Need direct access to line/cursor data, for use in external processes - // see: https://github.com/nodejs/node/issues/30347 - /** The current input data */ - readonly line: string; - /** The current cursor position in the input line */ - readonly cursor: number; - - /** - * NOTE: According to the documentation: - * - * > Instances of the `readline.Interface` class are constructed using the - * > `readline.createInterface()` method. - * - * @see https://nodejs.org/dist/latest-v10.x/docs/api/readline.html#readline_class_interface - */ - protected constructor(input: NodeJS.ReadableStream, output?: NodeJS.WritableStream, completer?: Completer | AsyncCompleter, terminal?: boolean); - /** - * NOTE: According to the documentation: - * - * > Instances of the `readline.Interface` class are constructed using the - * > `readline.createInterface()` method. - * - * @see https://nodejs.org/dist/latest-v10.x/docs/api/readline.html#readline_class_interface - */ - protected constructor(options: ReadLineOptions); - - setPrompt(prompt: string): void; - prompt(preserveCursor?: boolean): void; - question(query: string, callback: (answer: string) => void): void; - pause(): this; - resume(): this; - close(): void; - write(data: string | Buffer, key?: Key): void; - - /** - * Returns the real position of the cursor in relation to the input - * prompt + string. Long input (wrapping) strings, as well as multiple - * line prompts are included in the calculations. - */ - getCursorPos(): CursorPos; - - /** - * events.EventEmitter - * 1. close - * 2. line - * 3. pause - * 4. resume - * 5. SIGCONT - * 6. SIGINT - * 7. SIGTSTP - */ - - addListener(event: string, listener: (...args: any[]) => void): this; - addListener(event: "close", listener: () => void): this; - addListener(event: "line", listener: (input: string) => void): this; - addListener(event: "pause", listener: () => void): this; - addListener(event: "resume", listener: () => void): this; - addListener(event: "SIGCONT", listener: () => void): this; - addListener(event: "SIGINT", listener: () => void): this; - addListener(event: "SIGTSTP", listener: () => void): this; - - emit(event: string | symbol, ...args: any[]): boolean; - emit(event: "close"): boolean; - emit(event: "line", input: string): boolean; - emit(event: "pause"): boolean; - emit(event: "resume"): boolean; - emit(event: "SIGCONT"): boolean; - emit(event: "SIGINT"): boolean; - emit(event: "SIGTSTP"): boolean; - - on(event: string, listener: (...args: any[]) => void): this; - on(event: "close", listener: () => void): this; - on(event: "line", listener: (input: string) => void): this; - on(event: "pause", listener: () => void): this; - on(event: "resume", listener: () => void): this; - on(event: "SIGCONT", listener: () => void): this; - on(event: "SIGINT", listener: () => void): this; - on(event: "SIGTSTP", listener: () => void): this; - - once(event: string, listener: (...args: any[]) => void): this; - once(event: "close", listener: () => void): this; - once(event: "line", listener: (input: string) => void): this; - once(event: "pause", listener: () => void): this; - once(event: "resume", listener: () => void): this; - once(event: "SIGCONT", listener: () => void): this; - once(event: "SIGINT", listener: () => void): this; - once(event: "SIGTSTP", listener: () => void): this; - - prependListener(event: string, listener: (...args: any[]) => void): this; - prependListener(event: "close", listener: () => void): this; - prependListener(event: "line", listener: (input: string) => void): this; - prependListener(event: "pause", listener: () => void): this; - prependListener(event: "resume", listener: () => void): this; - prependListener(event: "SIGCONT", listener: () => void): this; - prependListener(event: "SIGINT", listener: () => void): this; - prependListener(event: "SIGTSTP", listener: () => void): this; - - prependOnceListener(event: string, listener: (...args: any[]) => void): this; - prependOnceListener(event: "close", listener: () => void): this; - prependOnceListener(event: "line", listener: (input: string) => void): this; - prependOnceListener(event: "pause", listener: () => void): this; - prependOnceListener(event: "resume", listener: () => void): this; - prependOnceListener(event: "SIGCONT", listener: () => void): this; - prependOnceListener(event: "SIGINT", listener: () => void): this; - prependOnceListener(event: "SIGTSTP", listener: () => void): this; - [Symbol.asyncIterator](): AsyncIterableIterator; - } - - type ReadLine = Interface; // type forwarded for backwards compatiblity - - type Completer = (line: string) => CompleterResult; - type AsyncCompleter = (line: string, callback: (err?: null | Error, result?: CompleterResult) => void) => any; - - type CompleterResult = [string[], string]; - - interface ReadLineOptions { - input: NodeJS.ReadableStream; - output?: NodeJS.WritableStream; - completer?: Completer | AsyncCompleter; - terminal?: boolean; - historySize?: number; - prompt?: string; - crlfDelay?: number; - removeHistoryDuplicates?: boolean; - escapeCodeTimeout?: number; - tabSize?: number; - } - - function createInterface(input: NodeJS.ReadableStream, output?: NodeJS.WritableStream, completer?: Completer | AsyncCompleter, terminal?: boolean): Interface; - function createInterface(options: ReadLineOptions): Interface; - function emitKeypressEvents(stream: NodeJS.ReadableStream, readlineInterface?: Interface): void; - - type Direction = -1 | 0 | 1; - - interface CursorPos { - rows: number; - cols: number; - } - - /** - * Clears the current line of this WriteStream in a direction identified by `dir`. - */ - function clearLine(stream: NodeJS.WritableStream, dir: Direction, callback?: () => void): boolean; - /** - * Clears this `WriteStream` from the current cursor down. - */ - function clearScreenDown(stream: NodeJS.WritableStream, callback?: () => void): boolean; - /** - * Moves this WriteStream's cursor to the specified position. - */ - function cursorTo(stream: NodeJS.WritableStream, x: number, y?: number, callback?: () => void): boolean; - /** - * Moves this WriteStream's cursor relative to its current position. - */ - function moveCursor(stream: NodeJS.WritableStream, dx: number, dy: number, callback?: () => void): boolean; -} diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/node/repl.d.ts b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/node/repl.d.ts deleted file mode 100644 index ef9da3757e..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/node/repl.d.ts +++ /dev/null @@ -1,387 +0,0 @@ -declare module "repl" { - import { Interface, Completer, AsyncCompleter } from "readline"; - import { Context } from "vm"; - import { InspectOptions } from "util"; - - interface ReplOptions { - /** - * The input prompt to display. - * Default: `"> "` - */ - prompt?: string; - /** - * The `Readable` stream from which REPL input will be read. - * Default: `process.stdin` - */ - input?: NodeJS.ReadableStream; - /** - * The `Writable` stream to which REPL output will be written. - * Default: `process.stdout` - */ - output?: NodeJS.WritableStream; - /** - * If `true`, specifies that the output should be treated as a TTY terminal, and have - * ANSI/VT100 escape codes written to it. - * Default: checking the value of the `isTTY` property on the output stream upon - * instantiation. - */ - terminal?: boolean; - /** - * The function to be used when evaluating each given line of input. - * Default: an async wrapper for the JavaScript `eval()` function. An `eval` function can - * error with `repl.Recoverable` to indicate the input was incomplete and prompt for - * additional lines. - * - * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_default_evaluation - * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_custom_evaluation_functions - */ - eval?: REPLEval; - /** - * Defines if the repl prints output previews or not. - * @default `true` Always `false` in case `terminal` is falsy. - */ - preview?: boolean; - /** - * If `true`, specifies that the default `writer` function should include ANSI color - * styling to REPL output. If a custom `writer` function is provided then this has no - * effect. - * Default: the REPL instance's `terminal` value. - */ - useColors?: boolean; - /** - * If `true`, specifies that the default evaluation function will use the JavaScript - * `global` as the context as opposed to creating a new separate context for the REPL - * instance. The node CLI REPL sets this value to `true`. - * Default: `false`. - */ - useGlobal?: boolean; - /** - * If `true`, specifies that the default writer will not output the return value of a - * command if it evaluates to `undefined`. - * Default: `false`. - */ - ignoreUndefined?: boolean; - /** - * The function to invoke to format the output of each command before writing to `output`. - * Default: a wrapper for `util.inspect`. - * - * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_customizing_repl_output - */ - writer?: REPLWriter; - /** - * An optional function used for custom Tab auto completion. - * - * @see https://nodejs.org/dist/latest-v11.x/docs/api/readline.html#readline_use_of_the_completer_function - */ - completer?: Completer | AsyncCompleter; - /** - * A flag that specifies whether the default evaluator executes all JavaScript commands in - * strict mode or default (sloppy) mode. - * Accepted values are: - * - `repl.REPL_MODE_SLOPPY` - evaluates expressions in sloppy mode. - * - `repl.REPL_MODE_STRICT` - evaluates expressions in strict mode. This is equivalent to - * prefacing every repl statement with `'use strict'`. - */ - replMode?: typeof REPL_MODE_SLOPPY | typeof REPL_MODE_STRICT; - /** - * Stop evaluating the current piece of code when `SIGINT` is received, i.e. `Ctrl+C` is - * pressed. This cannot be used together with a custom `eval` function. - * Default: `false`. - */ - breakEvalOnSigint?: boolean; - } - - type REPLEval = (this: REPLServer, evalCmd: string, context: Context, file: string, cb: (err: Error | null, result: any) => void) => void; - type REPLWriter = (this: REPLServer, obj: any) => string; - - /** - * This is the default "writer" value, if none is passed in the REPL options, - * and it can be overridden by custom print functions. - */ - const writer: REPLWriter & { options: InspectOptions }; - - type REPLCommandAction = (this: REPLServer, text: string) => void; - - interface REPLCommand { - /** - * Help text to be displayed when `.help` is entered. - */ - help?: string; - /** - * The function to execute, optionally accepting a single string argument. - */ - action: REPLCommandAction; - } - - /** - * Provides a customizable Read-Eval-Print-Loop (REPL). - * - * Instances of `repl.REPLServer` will accept individual lines of user input, evaluate those - * according to a user-defined evaluation function, then output the result. Input and output - * may be from `stdin` and `stdout`, respectively, or may be connected to any Node.js `stream`. - * - * Instances of `repl.REPLServer` support automatic completion of inputs, simplistic Emacs-style - * line editing, multi-line inputs, ANSI-styled output, saving and restoring current REPL session - * state, error recovery, and customizable evaluation functions. - * - * Instances of `repl.REPLServer` are created using the `repl.start()` method and _should not_ - * be created directly using the JavaScript `new` keyword. - * - * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_repl - */ - class REPLServer extends Interface { - /** - * The `vm.Context` provided to the `eval` function to be used for JavaScript - * evaluation. - */ - readonly context: Context; - /** - * The `Readable` stream from which REPL input will be read. - */ - readonly inputStream: NodeJS.ReadableStream; - /** - * The `Writable` stream to which REPL output will be written. - */ - readonly outputStream: NodeJS.WritableStream; - /** - * The commands registered via `replServer.defineCommand()`. - */ - readonly commands: NodeJS.ReadOnlyDict; - /** - * A value indicating whether the REPL is currently in "editor mode". - * - * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_commands_and_special_keys - */ - readonly editorMode: boolean; - /** - * A value indicating whether the `_` variable has been assigned. - * - * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_assignment_of_the_underscore_variable - */ - readonly underscoreAssigned: boolean; - /** - * The last evaluation result from the REPL (assigned to the `_` variable inside of the REPL). - * - * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_assignment_of_the_underscore_variable - */ - readonly last: any; - /** - * A value indicating whether the `_error` variable has been assigned. - * - * @since v9.8.0 - * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_assignment_of_the_underscore_variable - */ - readonly underscoreErrAssigned: boolean; - /** - * The last error raised inside the REPL (assigned to the `_error` variable inside of the REPL). - * - * @since v9.8.0 - * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_assignment_of_the_underscore_variable - */ - readonly lastError: any; - /** - * Specified in the REPL options, this is the function to be used when evaluating each - * given line of input. If not specified in the REPL options, this is an async wrapper - * for the JavaScript `eval()` function. - */ - readonly eval: REPLEval; - /** - * Specified in the REPL options, this is a value indicating whether the default - * `writer` function should include ANSI color styling to REPL output. - */ - readonly useColors: boolean; - /** - * Specified in the REPL options, this is a value indicating whether the default `eval` - * function will use the JavaScript `global` as the context as opposed to creating a new - * separate context for the REPL instance. - */ - readonly useGlobal: boolean; - /** - * Specified in the REPL options, this is a value indicating whether the default `writer` - * function should output the result of a command if it evaluates to `undefined`. - */ - readonly ignoreUndefined: boolean; - /** - * Specified in the REPL options, this is the function to invoke to format the output of - * each command before writing to `outputStream`. If not specified in the REPL options, - * this will be a wrapper for `util.inspect`. - */ - readonly writer: REPLWriter; - /** - * Specified in the REPL options, this is the function to use for custom Tab auto-completion. - */ - readonly completer: Completer | AsyncCompleter; - /** - * Specified in the REPL options, this is a flag that specifies whether the default `eval` - * function should execute all JavaScript commands in strict mode or default (sloppy) mode. - * Possible values are: - * - `repl.REPL_MODE_SLOPPY` - evaluates expressions in sloppy mode. - * - `repl.REPL_MODE_STRICT` - evaluates expressions in strict mode. This is equivalent to - * prefacing every repl statement with `'use strict'`. - */ - readonly replMode: typeof REPL_MODE_SLOPPY | typeof REPL_MODE_STRICT; - - /** - * NOTE: According to the documentation: - * - * > Instances of `repl.REPLServer` are created using the `repl.start()` method and - * > _should not_ be created directly using the JavaScript `new` keyword. - * - * `REPLServer` cannot be subclassed due to implementation specifics in NodeJS. - * - * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_class_replserver - */ - private constructor(); - - /** - * Used to add new `.`-prefixed commands to the REPL instance. Such commands are invoked - * by typing a `.` followed by the `keyword`. - * - * @param keyword The command keyword (_without_ a leading `.` character). - * @param cmd The function to invoke when the command is processed. - * - * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_replserver_definecommand_keyword_cmd - */ - defineCommand(keyword: string, cmd: REPLCommandAction | REPLCommand): void; - /** - * Readies the REPL instance for input from the user, printing the configured `prompt` to a - * new line in the `output` and resuming the `input` to accept new input. - * - * When multi-line input is being entered, an ellipsis is printed rather than the 'prompt'. - * - * This method is primarily intended to be called from within the action function for - * commands registered using the `replServer.defineCommand()` method. - * - * @param preserveCursor When `true`, the cursor placement will not be reset to `0`. - */ - displayPrompt(preserveCursor?: boolean): void; - /** - * Clears any command that has been buffered but not yet executed. - * - * This method is primarily intended to be called from within the action function for - * commands registered using the `replServer.defineCommand()` method. - * - * @since v9.0.0 - */ - clearBufferedCommand(): void; - - /** - * Initializes a history log file for the REPL instance. When executing the - * Node.js binary and using the command line REPL, a history file is initialized - * by default. However, this is not the case when creating a REPL - * programmatically. Use this method to initialize a history log file when working - * with REPL instances programmatically. - * @param path The path to the history file - */ - setupHistory(path: string, cb: (err: Error | null, repl: this) => void): void; - - /** - * events.EventEmitter - * 1. close - inherited from `readline.Interface` - * 2. line - inherited from `readline.Interface` - * 3. pause - inherited from `readline.Interface` - * 4. resume - inherited from `readline.Interface` - * 5. SIGCONT - inherited from `readline.Interface` - * 6. SIGINT - inherited from `readline.Interface` - * 7. SIGTSTP - inherited from `readline.Interface` - * 8. exit - * 9. reset - */ - - addListener(event: string, listener: (...args: any[]) => void): this; - addListener(event: "close", listener: () => void): this; - addListener(event: "line", listener: (input: string) => void): this; - addListener(event: "pause", listener: () => void): this; - addListener(event: "resume", listener: () => void): this; - addListener(event: "SIGCONT", listener: () => void): this; - addListener(event: "SIGINT", listener: () => void): this; - addListener(event: "SIGTSTP", listener: () => void): this; - addListener(event: "exit", listener: () => void): this; - addListener(event: "reset", listener: (context: Context) => void): this; - - emit(event: string | symbol, ...args: any[]): boolean; - emit(event: "close"): boolean; - emit(event: "line", input: string): boolean; - emit(event: "pause"): boolean; - emit(event: "resume"): boolean; - emit(event: "SIGCONT"): boolean; - emit(event: "SIGINT"): boolean; - emit(event: "SIGTSTP"): boolean; - emit(event: "exit"): boolean; - emit(event: "reset", context: Context): boolean; - - on(event: string, listener: (...args: any[]) => void): this; - on(event: "close", listener: () => void): this; - on(event: "line", listener: (input: string) => void): this; - on(event: "pause", listener: () => void): this; - on(event: "resume", listener: () => void): this; - on(event: "SIGCONT", listener: () => void): this; - on(event: "SIGINT", listener: () => void): this; - on(event: "SIGTSTP", listener: () => void): this; - on(event: "exit", listener: () => void): this; - on(event: "reset", listener: (context: Context) => void): this; - - once(event: string, listener: (...args: any[]) => void): this; - once(event: "close", listener: () => void): this; - once(event: "line", listener: (input: string) => void): this; - once(event: "pause", listener: () => void): this; - once(event: "resume", listener: () => void): this; - once(event: "SIGCONT", listener: () => void): this; - once(event: "SIGINT", listener: () => void): this; - once(event: "SIGTSTP", listener: () => void): this; - once(event: "exit", listener: () => void): this; - once(event: "reset", listener: (context: Context) => void): this; - - prependListener(event: string, listener: (...args: any[]) => void): this; - prependListener(event: "close", listener: () => void): this; - prependListener(event: "line", listener: (input: string) => void): this; - prependListener(event: "pause", listener: () => void): this; - prependListener(event: "resume", listener: () => void): this; - prependListener(event: "SIGCONT", listener: () => void): this; - prependListener(event: "SIGINT", listener: () => void): this; - prependListener(event: "SIGTSTP", listener: () => void): this; - prependListener(event: "exit", listener: () => void): this; - prependListener(event: "reset", listener: (context: Context) => void): this; - - prependOnceListener(event: string, listener: (...args: any[]) => void): this; - prependOnceListener(event: "close", listener: () => void): this; - prependOnceListener(event: "line", listener: (input: string) => void): this; - prependOnceListener(event: "pause", listener: () => void): this; - prependOnceListener(event: "resume", listener: () => void): this; - prependOnceListener(event: "SIGCONT", listener: () => void): this; - prependOnceListener(event: "SIGINT", listener: () => void): this; - prependOnceListener(event: "SIGTSTP", listener: () => void): this; - prependOnceListener(event: "exit", listener: () => void): this; - prependOnceListener(event: "reset", listener: (context: Context) => void): this; - } - - /** - * A flag passed in the REPL options. Evaluates expressions in sloppy mode. - */ - const REPL_MODE_SLOPPY: unique symbol; - - /** - * A flag passed in the REPL options. Evaluates expressions in strict mode. - * This is equivalent to prefacing every repl statement with `'use strict'`. - */ - const REPL_MODE_STRICT: unique symbol; - - /** - * Creates and starts a `repl.REPLServer` instance. - * - * @param options The options for the `REPLServer`. If `options` is a string, then it specifies - * the input prompt. - */ - function start(options?: string | ReplOptions): REPLServer; - - /** - * Indicates a recoverable error that a `REPLServer` can use to support multi-line input. - * - * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_recoverable_errors - */ - class Recoverable extends SyntaxError { - err: Error; - - constructor(err: Error); - } -} diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/node/stream.d.ts b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/node/stream.d.ts deleted file mode 100644 index 7e189d9586..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/node/stream.d.ts +++ /dev/null @@ -1,354 +0,0 @@ -declare module "stream" { - import * as events from "events"; - - class internal extends events.EventEmitter { - pipe(destination: T, options?: { end?: boolean; }): T; - } - - namespace internal { - class Stream extends internal { - constructor(opts?: ReadableOptions); - } - - interface ReadableOptions { - highWaterMark?: number; - encoding?: BufferEncoding; - objectMode?: boolean; - read?(this: Readable, size: number): void; - destroy?(this: Readable, error: Error | null, callback: (error: Error | null) => void): void; - autoDestroy?: boolean; - } - - class Readable extends Stream implements NodeJS.ReadableStream { - /** - * A utility method for creating Readable Streams out of iterators. - */ - static from(iterable: Iterable | AsyncIterable, options?: ReadableOptions): Readable; - - readable: boolean; - readonly readableEncoding: BufferEncoding | null; - readonly readableEnded: boolean; - readonly readableFlowing: boolean | null; - readonly readableHighWaterMark: number; - readonly readableLength: number; - readonly readableObjectMode: boolean; - destroyed: boolean; - constructor(opts?: ReadableOptions); - _read(size: number): void; - read(size?: number): any; - setEncoding(encoding: BufferEncoding): this; - pause(): this; - resume(): this; - isPaused(): boolean; - unpipe(destination?: NodeJS.WritableStream): this; - unshift(chunk: any, encoding?: BufferEncoding): void; - wrap(oldStream: NodeJS.ReadableStream): this; - push(chunk: any, encoding?: BufferEncoding): boolean; - _destroy(error: Error | null, callback: (error?: Error | null) => void): void; - destroy(error?: Error): void; - - /** - * Event emitter - * The defined events on documents including: - * 1. close - * 2. data - * 3. end - * 4. error - * 5. pause - * 6. readable - * 7. resume - */ - addListener(event: "close", listener: () => void): this; - addListener(event: "data", listener: (chunk: any) => void): this; - addListener(event: "end", listener: () => void): this; - addListener(event: "error", listener: (err: Error) => void): this; - addListener(event: "pause", listener: () => void): this; - addListener(event: "readable", listener: () => void): this; - addListener(event: "resume", listener: () => void): this; - addListener(event: string | symbol, listener: (...args: any[]) => void): this; - - emit(event: "close"): boolean; - emit(event: "data", chunk: any): boolean; - emit(event: "end"): boolean; - emit(event: "error", err: Error): boolean; - emit(event: "pause"): boolean; - emit(event: "readable"): boolean; - emit(event: "resume"): boolean; - emit(event: string | symbol, ...args: any[]): boolean; - - on(event: "close", listener: () => void): this; - on(event: "data", listener: (chunk: any) => void): this; - on(event: "end", listener: () => void): this; - on(event: "error", listener: (err: Error) => void): this; - on(event: "pause", listener: () => void): this; - on(event: "readable", listener: () => void): this; - on(event: "resume", listener: () => void): this; - on(event: string | symbol, listener: (...args: any[]) => void): this; - - once(event: "close", listener: () => void): this; - once(event: "data", listener: (chunk: any) => void): this; - once(event: "end", listener: () => void): this; - once(event: "error", listener: (err: Error) => void): this; - once(event: "pause", listener: () => void): this; - once(event: "readable", listener: () => void): this; - once(event: "resume", listener: () => void): this; - once(event: string | symbol, listener: (...args: any[]) => void): this; - - prependListener(event: "close", listener: () => void): this; - prependListener(event: "data", listener: (chunk: any) => void): this; - prependListener(event: "end", listener: () => void): this; - prependListener(event: "error", listener: (err: Error) => void): this; - prependListener(event: "pause", listener: () => void): this; - prependListener(event: "readable", listener: () => void): this; - prependListener(event: "resume", listener: () => void): this; - prependListener(event: string | symbol, listener: (...args: any[]) => void): this; - - prependOnceListener(event: "close", listener: () => void): this; - prependOnceListener(event: "data", listener: (chunk: any) => void): this; - prependOnceListener(event: "end", listener: () => void): this; - prependOnceListener(event: "error", listener: (err: Error) => void): this; - prependOnceListener(event: "pause", listener: () => void): this; - prependOnceListener(event: "readable", listener: () => void): this; - prependOnceListener(event: "resume", listener: () => void): this; - prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; - - removeListener(event: "close", listener: () => void): this; - removeListener(event: "data", listener: (chunk: any) => void): this; - removeListener(event: "end", listener: () => void): this; - removeListener(event: "error", listener: (err: Error) => void): this; - removeListener(event: "pause", listener: () => void): this; - removeListener(event: "readable", listener: () => void): this; - removeListener(event: "resume", listener: () => void): this; - removeListener(event: string | symbol, listener: (...args: any[]) => void): this; - - [Symbol.asyncIterator](): AsyncIterableIterator; - } - - interface WritableOptions { - highWaterMark?: number; - decodeStrings?: boolean; - defaultEncoding?: BufferEncoding; - objectMode?: boolean; - emitClose?: boolean; - write?(this: Writable, chunk: any, encoding: BufferEncoding, callback: (error?: Error | null) => void): void; - writev?(this: Writable, chunks: Array<{ chunk: any, encoding: BufferEncoding }>, callback: (error?: Error | null) => void): void; - destroy?(this: Writable, error: Error | null, callback: (error: Error | null) => void): void; - final?(this: Writable, callback: (error?: Error | null) => void): void; - autoDestroy?: boolean; - } - - class Writable extends Stream implements NodeJS.WritableStream { - readonly writable: boolean; - readonly writableEnded: boolean; - readonly writableFinished: boolean; - readonly writableHighWaterMark: number; - readonly writableLength: number; - readonly writableObjectMode: boolean; - readonly writableCorked: number; - destroyed: boolean; - constructor(opts?: WritableOptions); - _write(chunk: any, encoding: BufferEncoding, callback: (error?: Error | null) => void): void; - _writev?(chunks: Array<{ chunk: any, encoding: BufferEncoding }>, callback: (error?: Error | null) => void): void; - _destroy(error: Error | null, callback: (error?: Error | null) => void): void; - _final(callback: (error?: Error | null) => void): void; - write(chunk: any, cb?: (error: Error | null | undefined) => void): boolean; - write(chunk: any, encoding: BufferEncoding, cb?: (error: Error | null | undefined) => void): boolean; - setDefaultEncoding(encoding: BufferEncoding): this; - end(cb?: () => void): void; - end(chunk: any, cb?: () => void): void; - end(chunk: any, encoding: BufferEncoding, cb?: () => void): void; - cork(): void; - uncork(): void; - destroy(error?: Error): void; - - /** - * Event emitter - * The defined events on documents including: - * 1. close - * 2. drain - * 3. error - * 4. finish - * 5. pipe - * 6. unpipe - */ - addListener(event: "close", listener: () => void): this; - addListener(event: "drain", listener: () => void): this; - addListener(event: "error", listener: (err: Error) => void): this; - addListener(event: "finish", listener: () => void): this; - addListener(event: "pipe", listener: (src: Readable) => void): this; - addListener(event: "unpipe", listener: (src: Readable) => void): this; - addListener(event: string | symbol, listener: (...args: any[]) => void): this; - - emit(event: "close"): boolean; - emit(event: "drain"): boolean; - emit(event: "error", err: Error): boolean; - emit(event: "finish"): boolean; - emit(event: "pipe", src: Readable): boolean; - emit(event: "unpipe", src: Readable): boolean; - emit(event: string | symbol, ...args: any[]): boolean; - - on(event: "close", listener: () => void): this; - on(event: "drain", listener: () => void): this; - on(event: "error", listener: (err: Error) => void): this; - on(event: "finish", listener: () => void): this; - on(event: "pipe", listener: (src: Readable) => void): this; - on(event: "unpipe", listener: (src: Readable) => void): this; - on(event: string | symbol, listener: (...args: any[]) => void): this; - - once(event: "close", listener: () => void): this; - once(event: "drain", listener: () => void): this; - once(event: "error", listener: (err: Error) => void): this; - once(event: "finish", listener: () => void): this; - once(event: "pipe", listener: (src: Readable) => void): this; - once(event: "unpipe", listener: (src: Readable) => void): this; - once(event: string | symbol, listener: (...args: any[]) => void): this; - - prependListener(event: "close", listener: () => void): this; - prependListener(event: "drain", listener: () => void): this; - prependListener(event: "error", listener: (err: Error) => void): this; - prependListener(event: "finish", listener: () => void): this; - prependListener(event: "pipe", listener: (src: Readable) => void): this; - prependListener(event: "unpipe", listener: (src: Readable) => void): this; - prependListener(event: string | symbol, listener: (...args: any[]) => void): this; - - prependOnceListener(event: "close", listener: () => void): this; - prependOnceListener(event: "drain", listener: () => void): this; - prependOnceListener(event: "error", listener: (err: Error) => void): this; - prependOnceListener(event: "finish", listener: () => void): this; - prependOnceListener(event: "pipe", listener: (src: Readable) => void): this; - prependOnceListener(event: "unpipe", listener: (src: Readable) => void): this; - prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; - - removeListener(event: "close", listener: () => void): this; - removeListener(event: "drain", listener: () => void): this; - removeListener(event: "error", listener: (err: Error) => void): this; - removeListener(event: "finish", listener: () => void): this; - removeListener(event: "pipe", listener: (src: Readable) => void): this; - removeListener(event: "unpipe", listener: (src: Readable) => void): this; - removeListener(event: string | symbol, listener: (...args: any[]) => void): this; - } - - interface DuplexOptions extends ReadableOptions, WritableOptions { - allowHalfOpen?: boolean; - readableObjectMode?: boolean; - writableObjectMode?: boolean; - readableHighWaterMark?: number; - writableHighWaterMark?: number; - writableCorked?: number; - read?(this: Duplex, size: number): void; - write?(this: Duplex, chunk: any, encoding: BufferEncoding, callback: (error?: Error | null) => void): void; - writev?(this: Duplex, chunks: Array<{ chunk: any, encoding: BufferEncoding }>, callback: (error?: Error | null) => void): void; - final?(this: Duplex, callback: (error?: Error | null) => void): void; - destroy?(this: Duplex, error: Error | null, callback: (error: Error | null) => void): void; - } - - // Note: Duplex extends both Readable and Writable. - class Duplex extends Readable implements Writable { - readonly writable: boolean; - readonly writableEnded: boolean; - readonly writableFinished: boolean; - readonly writableHighWaterMark: number; - readonly writableLength: number; - readonly writableObjectMode: boolean; - readonly writableCorked: number; - constructor(opts?: DuplexOptions); - _write(chunk: any, encoding: BufferEncoding, callback: (error?: Error | null) => void): void; - _writev?(chunks: Array<{ chunk: any, encoding: BufferEncoding }>, callback: (error?: Error | null) => void): void; - _destroy(error: Error | null, callback: (error: Error | null) => void): void; - _final(callback: (error?: Error | null) => void): void; - write(chunk: any, encoding?: BufferEncoding, cb?: (error: Error | null | undefined) => void): boolean; - write(chunk: any, cb?: (error: Error | null | undefined) => void): boolean; - setDefaultEncoding(encoding: BufferEncoding): this; - end(cb?: () => void): void; - end(chunk: any, cb?: () => void): void; - end(chunk: any, encoding?: BufferEncoding, cb?: () => void): void; - cork(): void; - uncork(): void; - } - - type TransformCallback = (error?: Error | null, data?: any) => void; - - interface TransformOptions extends DuplexOptions { - read?(this: Transform, size: number): void; - write?(this: Transform, chunk: any, encoding: BufferEncoding, callback: (error?: Error | null) => void): void; - writev?(this: Transform, chunks: Array<{ chunk: any, encoding: BufferEncoding }>, callback: (error?: Error | null) => void): void; - final?(this: Transform, callback: (error?: Error | null) => void): void; - destroy?(this: Transform, error: Error | null, callback: (error: Error | null) => void): void; - transform?(this: Transform, chunk: any, encoding: BufferEncoding, callback: TransformCallback): void; - flush?(this: Transform, callback: TransformCallback): void; - } - - class Transform extends Duplex { - constructor(opts?: TransformOptions); - _transform(chunk: any, encoding: BufferEncoding, callback: TransformCallback): void; - _flush(callback: TransformCallback): void; - } - - class PassThrough extends Transform { } - - interface FinishedOptions { - error?: boolean; - readable?: boolean; - writable?: boolean; - } - function finished(stream: NodeJS.ReadableStream | NodeJS.WritableStream | NodeJS.ReadWriteStream, options: FinishedOptions, callback: (err?: NodeJS.ErrnoException | null) => void): () => void; - function finished(stream: NodeJS.ReadableStream | NodeJS.WritableStream | NodeJS.ReadWriteStream, callback: (err?: NodeJS.ErrnoException | null) => void): () => void; - namespace finished { - function __promisify__(stream: NodeJS.ReadableStream | NodeJS.WritableStream | NodeJS.ReadWriteStream, options?: FinishedOptions): Promise; - } - - function pipeline(stream1: NodeJS.ReadableStream, stream2: T, callback?: (err: NodeJS.ErrnoException | null) => void): T; - function pipeline(stream1: NodeJS.ReadableStream, stream2: NodeJS.ReadWriteStream, stream3: T, callback?: (err: NodeJS.ErrnoException | null) => void): T; - function pipeline( - stream1: NodeJS.ReadableStream, - stream2: NodeJS.ReadWriteStream, - stream3: NodeJS.ReadWriteStream, - stream4: T, - callback?: (err: NodeJS.ErrnoException | null) => void, - ): T; - function pipeline( - stream1: NodeJS.ReadableStream, - stream2: NodeJS.ReadWriteStream, - stream3: NodeJS.ReadWriteStream, - stream4: NodeJS.ReadWriteStream, - stream5: T, - callback?: (err: NodeJS.ErrnoException | null) => void, - ): T; - function pipeline( - streams: ReadonlyArray, - callback?: (err: NodeJS.ErrnoException | null) => void, - ): NodeJS.WritableStream; - function pipeline( - stream1: NodeJS.ReadableStream, - stream2: NodeJS.ReadWriteStream | NodeJS.WritableStream, - ...streams: Array void)>, - ): NodeJS.WritableStream; - namespace pipeline { - function __promisify__(stream1: NodeJS.ReadableStream, stream2: NodeJS.WritableStream): Promise; - function __promisify__(stream1: NodeJS.ReadableStream, stream2: NodeJS.ReadWriteStream, stream3: NodeJS.WritableStream): Promise; - function __promisify__(stream1: NodeJS.ReadableStream, stream2: NodeJS.ReadWriteStream, stream3: NodeJS.ReadWriteStream, stream4: NodeJS.WritableStream): Promise; - function __promisify__( - stream1: NodeJS.ReadableStream, - stream2: NodeJS.ReadWriteStream, - stream3: NodeJS.ReadWriteStream, - stream4: NodeJS.ReadWriteStream, - stream5: NodeJS.WritableStream, - ): Promise; - function __promisify__(streams: ReadonlyArray): Promise; - function __promisify__( - stream1: NodeJS.ReadableStream, - stream2: NodeJS.ReadWriteStream | NodeJS.WritableStream, - ...streams: Array, - ): Promise; - } - - interface Pipe { - close(): void; - hasRef(): boolean; - ref(): void; - unref(): void; - } - } - - export = internal; -} diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/node/string_decoder.d.ts b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/node/string_decoder.d.ts deleted file mode 100644 index a6a40601f0..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/node/string_decoder.d.ts +++ /dev/null @@ -1,7 +0,0 @@ -declare module "string_decoder" { - class StringDecoder { - constructor(encoding?: BufferEncoding); - write(buffer: Buffer): string; - end(buffer?: Buffer): string; - } -} diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/node/timers.d.ts b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/node/timers.d.ts deleted file mode 100644 index e64a6735c3..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/node/timers.d.ts +++ /dev/null @@ -1,16 +0,0 @@ -declare module "timers" { - function setTimeout(callback: (...args: any[]) => void, ms: number, ...args: any[]): NodeJS.Timeout; - namespace setTimeout { - function __promisify__(ms: number): Promise; - function __promisify__(ms: number, value: T): Promise; - } - function clearTimeout(timeoutId: NodeJS.Timeout): void; - function setInterval(callback: (...args: any[]) => void, ms: number, ...args: any[]): NodeJS.Timeout; - function clearInterval(intervalId: NodeJS.Timeout): void; - function setImmediate(callback: (...args: any[]) => void, ...args: any[]): NodeJS.Immediate; - namespace setImmediate { - function __promisify__(): Promise; - function __promisify__(value: T): Promise; - } - function clearImmediate(immediateId: NodeJS.Immediate): void; -} diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/node/tls.d.ts b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/node/tls.d.ts deleted file mode 100644 index 6d28a37f00..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/node/tls.d.ts +++ /dev/null @@ -1,777 +0,0 @@ -declare module "tls" { - import * as crypto from "crypto"; - import * as dns from "dns"; - import * as net from "net"; - import * as stream from "stream"; - - const CLIENT_RENEG_LIMIT: number; - const CLIENT_RENEG_WINDOW: number; - - interface Certificate { - /** - * Country code. - */ - C: string; - /** - * Street. - */ - ST: string; - /** - * Locality. - */ - L: string; - /** - * Organization. - */ - O: string; - /** - * Organizational unit. - */ - OU: string; - /** - * Common name. - */ - CN: string; - } - - interface PeerCertificate { - subject: Certificate; - issuer: Certificate; - subjectaltname: string; - infoAccess: NodeJS.Dict; - modulus: string; - exponent: string; - valid_from: string; - valid_to: string; - fingerprint: string; - fingerprint256: string; - ext_key_usage: string[]; - serialNumber: string; - raw: Buffer; - } - - interface DetailedPeerCertificate extends PeerCertificate { - issuerCertificate: DetailedPeerCertificate; - } - - interface CipherNameAndProtocol { - /** - * The cipher name. - */ - name: string; - /** - * SSL/TLS protocol version. - */ - version: string; - - /** - * IETF name for the cipher suite. - */ - standardName: string; - } - - interface EphemeralKeyInfo { - /** - * The supported types are 'DH' and 'ECDH'. - */ - type: string; - /** - * The name property is available only when type is 'ECDH'. - */ - name?: string; - /** - * The size of parameter of an ephemeral key exchange. - */ - size: number; - } - - interface KeyObject { - /** - * Private keys in PEM format. - */ - pem: string | Buffer; - /** - * Optional passphrase. - */ - passphrase?: string; - } - - interface PxfObject { - /** - * PFX or PKCS12 encoded private key and certificate chain. - */ - buf: string | Buffer; - /** - * Optional passphrase. - */ - passphrase?: string; - } - - interface TLSSocketOptions extends SecureContextOptions, CommonConnectionOptions { - /** - * If true the TLS socket will be instantiated in server-mode. - * Defaults to false. - */ - isServer?: boolean; - /** - * An optional net.Server instance. - */ - server?: net.Server; - - /** - * An optional Buffer instance containing a TLS session. - */ - session?: Buffer; - /** - * If true, specifies that the OCSP status request extension will be - * added to the client hello and an 'OCSPResponse' event will be - * emitted on the socket before establishing a secure communication - */ - requestOCSP?: boolean; - } - - class TLSSocket extends net.Socket { - /** - * Construct a new tls.TLSSocket object from an existing TCP socket. - */ - constructor(socket: net.Socket, options?: TLSSocketOptions); - - /** - * A boolean that is true if the peer certificate was signed by one of the specified CAs, otherwise false. - */ - authorized: boolean; - /** - * The reason why the peer's certificate has not been verified. - * This property becomes available only when tlsSocket.authorized === false. - */ - authorizationError: Error; - /** - * Static boolean value, always true. - * May be used to distinguish TLS sockets from regular ones. - */ - encrypted: boolean; - - /** - * String containing the selected ALPN protocol. - * When ALPN has no selected protocol, tlsSocket.alpnProtocol equals false. - */ - alpnProtocol?: string; - - /** - * Returns an object representing the local certificate. The returned - * object has some properties corresponding to the fields of the - * certificate. - * - * See tls.TLSSocket.getPeerCertificate() for an example of the - * certificate structure. - * - * If there is no local certificate, an empty object will be returned. - * If the socket has been destroyed, null will be returned. - */ - getCertificate(): PeerCertificate | object | null; - /** - * Returns an object representing the cipher name and the SSL/TLS protocol version of the current connection. - * @returns Returns an object representing the cipher name - * and the SSL/TLS protocol version of the current connection. - */ - getCipher(): CipherNameAndProtocol; - /** - * Returns an object representing the type, name, and size of parameter - * of an ephemeral key exchange in Perfect Forward Secrecy on a client - * connection. It returns an empty object when the key exchange is not - * ephemeral. As this is only supported on a client socket; null is - * returned if called on a server socket. The supported types are 'DH' - * and 'ECDH'. The name property is available only when type is 'ECDH'. - * - * For example: { type: 'ECDH', name: 'prime256v1', size: 256 }. - */ - getEphemeralKeyInfo(): EphemeralKeyInfo | object | null; - /** - * Returns the latest Finished message that has - * been sent to the socket as part of a SSL/TLS handshake, or undefined - * if no Finished message has been sent yet. - * - * As the Finished messages are message digests of the complete - * handshake (with a total of 192 bits for TLS 1.0 and more for SSL - * 3.0), they can be used for external authentication procedures when - * the authentication provided by SSL/TLS is not desired or is not - * enough. - * - * Corresponds to the SSL_get_finished routine in OpenSSL and may be - * used to implement the tls-unique channel binding from RFC 5929. - */ - getFinished(): Buffer | undefined; - /** - * Returns an object representing the peer's certificate. - * The returned object has some properties corresponding to the field of the certificate. - * If detailed argument is true the full chain with issuer property will be returned, - * if false only the top certificate without issuer property. - * If the peer does not provide a certificate, it returns null or an empty object. - * @param detailed - If true; the full chain with issuer property will be returned. - * @returns An object representing the peer's certificate. - */ - getPeerCertificate(detailed: true): DetailedPeerCertificate; - getPeerCertificate(detailed?: false): PeerCertificate; - getPeerCertificate(detailed?: boolean): PeerCertificate | DetailedPeerCertificate; - /** - * Returns the latest Finished message that is expected or has actually - * been received from the socket as part of a SSL/TLS handshake, or - * undefined if there is no Finished message so far. - * - * As the Finished messages are message digests of the complete - * handshake (with a total of 192 bits for TLS 1.0 and more for SSL - * 3.0), they can be used for external authentication procedures when - * the authentication provided by SSL/TLS is not desired or is not - * enough. - * - * Corresponds to the SSL_get_peer_finished routine in OpenSSL and may - * be used to implement the tls-unique channel binding from RFC 5929. - */ - getPeerFinished(): Buffer | undefined; - /** - * Returns a string containing the negotiated SSL/TLS protocol version of the current connection. - * The value `'unknown'` will be returned for connected sockets that have not completed the handshaking process. - * The value `null` will be returned for server sockets or disconnected client sockets. - * See https://www.openssl.org/docs/man1.0.2/ssl/SSL_get_version.html for more information. - * @returns negotiated SSL/TLS protocol version of the current connection - */ - getProtocol(): string | null; - /** - * Could be used to speed up handshake establishment when reconnecting to the server. - * @returns ASN.1 encoded TLS session or undefined if none was negotiated. - */ - getSession(): Buffer | undefined; - /** - * Returns a list of signature algorithms shared between the server and - * the client in the order of decreasing preference. - */ - getSharedSigalgs(): string[]; - /** - * NOTE: Works only with client TLS sockets. - * Useful only for debugging, for session reuse provide session option to tls.connect(). - * @returns TLS session ticket or undefined if none was negotiated. - */ - getTLSTicket(): Buffer | undefined; - /** - * Returns true if the session was reused, false otherwise. - */ - isSessionReused(): boolean; - /** - * Initiate TLS renegotiation process. - * - * NOTE: Can be used to request peer's certificate after the secure connection has been established. - * ANOTHER NOTE: When running as the server, socket will be destroyed with an error after handshakeTimeout timeout. - * @param options - The options may contain the following fields: rejectUnauthorized, - * requestCert (See tls.createServer() for details). - * @param callback - callback(err) will be executed with null as err, once the renegotiation - * is successfully completed. - * @return `undefined` when socket is destroy, `false` if negotiaion can't be initiated. - */ - renegotiate(options: { rejectUnauthorized?: boolean, requestCert?: boolean }, callback: (err: Error | null) => void): undefined | boolean; - /** - * Set maximum TLS fragment size (default and maximum value is: 16384, minimum is: 512). - * Smaller fragment size decreases buffering latency on the client: large fragments are buffered by - * the TLS layer until the entire fragment is received and its integrity is verified; - * large fragments can span multiple roundtrips, and their processing can be delayed due to packet - * loss or reordering. However, smaller fragments add extra TLS framing bytes and CPU overhead, - * which may decrease overall server throughput. - * @param size - TLS fragment size (default and maximum value is: 16384, minimum is: 512). - * @returns Returns true on success, false otherwise. - */ - setMaxSendFragment(size: number): boolean; - - /** - * Disables TLS renegotiation for this TLSSocket instance. Once called, - * attempts to renegotiate will trigger an 'error' event on the - * TLSSocket. - */ - disableRenegotiation(): void; - - /** - * When enabled, TLS packet trace information is written to `stderr`. This can be - * used to debug TLS connection problems. - * - * Note: The format of the output is identical to the output of `openssl s_client - * -trace` or `openssl s_server -trace`. While it is produced by OpenSSL's - * `SSL_trace()` function, the format is undocumented, can change without notice, - * and should not be relied on. - */ - enableTrace(): void; - - /** - * @param length number of bytes to retrieve from keying material - * @param label an application specific label, typically this will be a value from the - * [IANA Exporter Label Registry](https://www.iana.org/assignments/tls-parameters/tls-parameters.xhtml#exporter-labels). - * @param context optionally provide a context. - */ - exportKeyingMaterial(length: number, label: string, context: Buffer): Buffer; - - addListener(event: string, listener: (...args: any[]) => void): this; - addListener(event: "OCSPResponse", listener: (response: Buffer) => void): this; - addListener(event: "secureConnect", listener: () => void): this; - addListener(event: "session", listener: (session: Buffer) => void): this; - addListener(event: "keylog", listener: (line: Buffer) => void): this; - - emit(event: string | symbol, ...args: any[]): boolean; - emit(event: "OCSPResponse", response: Buffer): boolean; - emit(event: "secureConnect"): boolean; - emit(event: "session", session: Buffer): boolean; - emit(event: "keylog", line: Buffer): boolean; - - on(event: string, listener: (...args: any[]) => void): this; - on(event: "OCSPResponse", listener: (response: Buffer) => void): this; - on(event: "secureConnect", listener: () => void): this; - on(event: "session", listener: (session: Buffer) => void): this; - on(event: "keylog", listener: (line: Buffer) => void): this; - - once(event: string, listener: (...args: any[]) => void): this; - once(event: "OCSPResponse", listener: (response: Buffer) => void): this; - once(event: "secureConnect", listener: () => void): this; - once(event: "session", listener: (session: Buffer) => void): this; - once(event: "keylog", listener: (line: Buffer) => void): this; - - prependListener(event: string, listener: (...args: any[]) => void): this; - prependListener(event: "OCSPResponse", listener: (response: Buffer) => void): this; - prependListener(event: "secureConnect", listener: () => void): this; - prependListener(event: "session", listener: (session: Buffer) => void): this; - prependListener(event: "keylog", listener: (line: Buffer) => void): this; - - prependOnceListener(event: string, listener: (...args: any[]) => void): this; - prependOnceListener(event: "OCSPResponse", listener: (response: Buffer) => void): this; - prependOnceListener(event: "secureConnect", listener: () => void): this; - prependOnceListener(event: "session", listener: (session: Buffer) => void): this; - prependOnceListener(event: "keylog", listener: (line: Buffer) => void): this; - } - - interface CommonConnectionOptions { - /** - * An optional TLS context object from tls.createSecureContext() - */ - secureContext?: SecureContext; - - /** - * When enabled, TLS packet trace information is written to `stderr`. This can be - * used to debug TLS connection problems. - * @default false - */ - enableTrace?: boolean; - /** - * If true the server will request a certificate from clients that - * connect and attempt to verify that certificate. Defaults to - * false. - */ - requestCert?: boolean; - /** - * An array of strings or a Buffer naming possible ALPN protocols. - * (Protocols should be ordered by their priority.) - */ - ALPNProtocols?: string[] | Uint8Array[] | Uint8Array; - /** - * SNICallback(servername, cb) A function that will be - * called if the client supports SNI TLS extension. Two arguments - * will be passed when called: servername and cb. SNICallback should - * invoke cb(null, ctx), where ctx is a SecureContext instance. - * (tls.createSecureContext(...) can be used to get a proper - * SecureContext.) If SNICallback wasn't provided the default callback - * with high-level API will be used (see below). - */ - SNICallback?: (servername: string, cb: (err: Error | null, ctx: SecureContext) => void) => void; - /** - * If true the server will reject any connection which is not - * authorized with the list of supplied CAs. This option only has an - * effect if requestCert is true. - * @default true - */ - rejectUnauthorized?: boolean; - } - - interface TlsOptions extends SecureContextOptions, CommonConnectionOptions { - /** - * Abort the connection if the SSL/TLS handshake does not finish in the - * specified number of milliseconds. A 'tlsClientError' is emitted on - * the tls.Server object whenever a handshake times out. Default: - * 120000 (120 seconds). - */ - handshakeTimeout?: number; - /** - * The number of seconds after which a TLS session created by the - * server will no longer be resumable. See Session Resumption for more - * information. Default: 300. - */ - sessionTimeout?: number; - /** - * 48-bytes of cryptographically strong pseudo-random data. - */ - ticketKeys?: Buffer; - - /** - * - * @param socket - * @param identity identity parameter sent from the client. - * @return pre-shared key that must either be - * a buffer or `null` to stop the negotiation process. Returned PSK must be - * compatible with the selected cipher's digest. - * - * When negotiating TLS-PSK (pre-shared keys), this function is called - * with the identity provided by the client. - * If the return value is `null` the negotiation process will stop and an - * "unknown_psk_identity" alert message will be sent to the other party. - * If the server wishes to hide the fact that the PSK identity was not known, - * the callback must provide some random data as `psk` to make the connection - * fail with "decrypt_error" before negotiation is finished. - * PSK ciphers are disabled by default, and using TLS-PSK thus - * requires explicitly specifying a cipher suite with the `ciphers` option. - * More information can be found in the RFC 4279. - */ - - pskCallback?(socket: TLSSocket, identity: string): DataView | NodeJS.TypedArray | null; - /** - * hint to send to a client to help - * with selecting the identity during TLS-PSK negotiation. Will be ignored - * in TLS 1.3. Upon failing to set pskIdentityHint `tlsClientError` will be - * emitted with `ERR_TLS_PSK_SET_IDENTIY_HINT_FAILED` code. - */ - pskIdentityHint?: string; - } - - interface PSKCallbackNegotation { - psk: DataView | NodeJS.TypedArray; - identitty: string; - } - - interface ConnectionOptions extends SecureContextOptions, CommonConnectionOptions { - host?: string; - port?: number; - path?: string; // Creates unix socket connection to path. If this option is specified, `host` and `port` are ignored. - socket?: net.Socket; // Establish secure connection on a given socket rather than creating a new socket - checkServerIdentity?: typeof checkServerIdentity; - servername?: string; // SNI TLS Extension - session?: Buffer; - minDHSize?: number; - lookup?: net.LookupFunction; - timeout?: number; - /** - * When negotiating TLS-PSK (pre-shared keys), this function is called - * with optional identity `hint` provided by the server or `null` - * in case of TLS 1.3 where `hint` was removed. - * It will be necessary to provide a custom `tls.checkServerIdentity()` - * for the connection as the default one will try to check hostname/IP - * of the server against the certificate but that's not applicable for PSK - * because there won't be a certificate present. - * More information can be found in the RFC 4279. - * - * @param hint message sent from the server to help client - * decide which identity to use during negotiation. - * Always `null` if TLS 1.3 is used. - * @returns Return `null` to stop the negotiation process. `psk` must be - * compatible with the selected cipher's digest. - * `identity` must use UTF-8 encoding. - */ - pskCallback?(hint: string | null): PSKCallbackNegotation | null; - } - - class Server extends net.Server { - /** - * The server.addContext() method adds a secure context that will be - * used if the client request's SNI name matches the supplied hostname - * (or wildcard). - */ - addContext(hostName: string, credentials: SecureContextOptions): void; - /** - * Returns the session ticket keys. - */ - getTicketKeys(): Buffer; - /** - * - * The server.setSecureContext() method replaces the - * secure context of an existing server. Existing connections to the - * server are not interrupted. - */ - setSecureContext(details: SecureContextOptions): void; - /** - * The server.setSecureContext() method replaces the secure context of - * an existing server. Existing connections to the server are not - * interrupted. - */ - setTicketKeys(keys: Buffer): void; - - /** - * events.EventEmitter - * 1. tlsClientError - * 2. newSession - * 3. OCSPRequest - * 4. resumeSession - * 5. secureConnection - * 6. keylog - */ - addListener(event: string, listener: (...args: any[]) => void): this; - addListener(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; - addListener(event: "newSession", listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void): this; - addListener(event: "OCSPRequest", listener: (certificate: Buffer, issuer: Buffer, callback: (err: Error | null, resp: Buffer) => void) => void): this; - addListener(event: "resumeSession", listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void): this; - addListener(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; - addListener(event: "keylog", listener: (line: Buffer, tlsSocket: TLSSocket) => void): this; - - emit(event: string | symbol, ...args: any[]): boolean; - emit(event: "tlsClientError", err: Error, tlsSocket: TLSSocket): boolean; - emit(event: "newSession", sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void): boolean; - emit(event: "OCSPRequest", certificate: Buffer, issuer: Buffer, callback: (err: Error | null, resp: Buffer) => void): boolean; - emit(event: "resumeSession", sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void): boolean; - emit(event: "secureConnection", tlsSocket: TLSSocket): boolean; - emit(event: "keylog", line: Buffer, tlsSocket: TLSSocket): boolean; - - on(event: string, listener: (...args: any[]) => void): this; - on(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; - on(event: "newSession", listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void): this; - on(event: "OCSPRequest", listener: (certificate: Buffer, issuer: Buffer, callback: (err: Error | null, resp: Buffer) => void) => void): this; - on(event: "resumeSession", listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void): this; - on(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; - on(event: "keylog", listener: (line: Buffer, tlsSocket: TLSSocket) => void): this; - - once(event: string, listener: (...args: any[]) => void): this; - once(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; - once(event: "newSession", listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void): this; - once(event: "OCSPRequest", listener: (certificate: Buffer, issuer: Buffer, callback: (err: Error | null, resp: Buffer) => void) => void): this; - once(event: "resumeSession", listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void): this; - once(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; - once(event: "keylog", listener: (line: Buffer, tlsSocket: TLSSocket) => void): this; - - prependListener(event: string, listener: (...args: any[]) => void): this; - prependListener(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; - prependListener(event: "newSession", listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void): this; - prependListener(event: "OCSPRequest", listener: (certificate: Buffer, issuer: Buffer, callback: (err: Error | null, resp: Buffer) => void) => void): this; - prependListener(event: "resumeSession", listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void): this; - prependListener(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; - prependListener(event: "keylog", listener: (line: Buffer, tlsSocket: TLSSocket) => void): this; - - prependOnceListener(event: string, listener: (...args: any[]) => void): this; - prependOnceListener(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; - prependOnceListener(event: "newSession", listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void): this; - prependOnceListener(event: "OCSPRequest", listener: (certificate: Buffer, issuer: Buffer, callback: (err: Error | null, resp: Buffer) => void) => void): this; - prependOnceListener(event: "resumeSession", listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void): this; - prependOnceListener(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; - prependOnceListener(event: "keylog", listener: (line: Buffer, tlsSocket: TLSSocket) => void): this; - } - - interface SecurePair { - encrypted: TLSSocket; - cleartext: TLSSocket; - } - - type SecureVersion = 'TLSv1.3' | 'TLSv1.2' | 'TLSv1.1' | 'TLSv1'; - - interface SecureContextOptions { - /** - * Optionally override the trusted CA certificates. Default is to trust - * the well-known CAs curated by Mozilla. Mozilla's CAs are completely - * replaced when CAs are explicitly specified using this option. - */ - ca?: string | Buffer | Array; - /** - * Cert chains in PEM format. One cert chain should be provided per - * private key. Each cert chain should consist of the PEM formatted - * certificate for a provided private key, followed by the PEM - * formatted intermediate certificates (if any), in order, and not - * including the root CA (the root CA must be pre-known to the peer, - * see ca). When providing multiple cert chains, they do not have to - * be in the same order as their private keys in key. If the - * intermediate certificates are not provided, the peer will not be - * able to validate the certificate, and the handshake will fail. - */ - cert?: string | Buffer | Array; - /** - * Colon-separated list of supported signature algorithms. The list - * can contain digest algorithms (SHA256, MD5 etc.), public key - * algorithms (RSA-PSS, ECDSA etc.), combination of both (e.g - * 'RSA+SHA384') or TLS v1.3 scheme names (e.g. rsa_pss_pss_sha512). - */ - sigalgs?: string; - /** - * Cipher suite specification, replacing the default. For more - * information, see modifying the default cipher suite. Permitted - * ciphers can be obtained via tls.getCiphers(). Cipher names must be - * uppercased in order for OpenSSL to accept them. - */ - ciphers?: string; - /** - * Name of an OpenSSL engine which can provide the client certificate. - */ - clientCertEngine?: string; - /** - * PEM formatted CRLs (Certificate Revocation Lists). - */ - crl?: string | Buffer | Array; - /** - * Diffie Hellman parameters, required for Perfect Forward Secrecy. Use - * openssl dhparam to create the parameters. The key length must be - * greater than or equal to 1024 bits or else an error will be thrown. - * Although 1024 bits is permissible, use 2048 bits or larger for - * stronger security. If omitted or invalid, the parameters are - * silently discarded and DHE ciphers will not be available. - */ - dhparam?: string | Buffer; - /** - * A string describing a named curve or a colon separated list of curve - * NIDs or names, for example P-521:P-384:P-256, to use for ECDH key - * agreement. Set to auto to select the curve automatically. Use - * crypto.getCurves() to obtain a list of available curve names. On - * recent releases, openssl ecparam -list_curves will also display the - * name and description of each available elliptic curve. Default: - * tls.DEFAULT_ECDH_CURVE. - */ - ecdhCurve?: string; - /** - * Attempt to use the server's cipher suite preferences instead of the - * client's. When true, causes SSL_OP_CIPHER_SERVER_PREFERENCE to be - * set in secureOptions - */ - honorCipherOrder?: boolean; - /** - * Private keys in PEM format. PEM allows the option of private keys - * being encrypted. Encrypted keys will be decrypted with - * options.passphrase. Multiple keys using different algorithms can be - * provided either as an array of unencrypted key strings or buffers, - * or an array of objects in the form {pem: [, - * passphrase: ]}. The object form can only occur in an array. - * object.passphrase is optional. Encrypted keys will be decrypted with - * object.passphrase if provided, or options.passphrase if it is not. - */ - key?: string | Buffer | Array; - /** - * Name of an OpenSSL engine to get private key from. Should be used - * together with privateKeyIdentifier. - */ - privateKeyEngine?: string; - /** - * Identifier of a private key managed by an OpenSSL engine. Should be - * used together with privateKeyEngine. Should not be set together with - * key, because both options define a private key in different ways. - */ - privateKeyIdentifier?: string; - /** - * Optionally set the maximum TLS version to allow. One - * of `'TLSv1.3'`, `'TLSv1.2'`, `'TLSv1.1'`, or `'TLSv1'`. Cannot be specified along with the - * `secureProtocol` option, use one or the other. - * **Default:** `'TLSv1.3'`, unless changed using CLI options. Using - * `--tls-max-v1.2` sets the default to `'TLSv1.2'`. Using `--tls-max-v1.3` sets the default to - * `'TLSv1.3'`. If multiple of the options are provided, the highest maximum is used. - */ - maxVersion?: SecureVersion; - /** - * Optionally set the minimum TLS version to allow. One - * of `'TLSv1.3'`, `'TLSv1.2'`, `'TLSv1.1'`, or `'TLSv1'`. Cannot be specified along with the - * `secureProtocol` option, use one or the other. It is not recommended to use - * less than TLSv1.2, but it may be required for interoperability. - * **Default:** `'TLSv1.2'`, unless changed using CLI options. Using - * `--tls-v1.0` sets the default to `'TLSv1'`. Using `--tls-v1.1` sets the default to - * `'TLSv1.1'`. Using `--tls-min-v1.3` sets the default to - * 'TLSv1.3'. If multiple of the options are provided, the lowest minimum is used. - */ - minVersion?: SecureVersion; - /** - * Shared passphrase used for a single private key and/or a PFX. - */ - passphrase?: string; - /** - * PFX or PKCS12 encoded private key and certificate chain. pfx is an - * alternative to providing key and cert individually. PFX is usually - * encrypted, if it is, passphrase will be used to decrypt it. Multiple - * PFX can be provided either as an array of unencrypted PFX buffers, - * or an array of objects in the form {buf: [, - * passphrase: ]}. The object form can only occur in an array. - * object.passphrase is optional. Encrypted PFX will be decrypted with - * object.passphrase if provided, or options.passphrase if it is not. - */ - pfx?: string | Buffer | Array; - /** - * Optionally affect the OpenSSL protocol behavior, which is not - * usually necessary. This should be used carefully if at all! Value is - * a numeric bitmask of the SSL_OP_* options from OpenSSL Options - */ - secureOptions?: number; // Value is a numeric bitmask of the `SSL_OP_*` options - /** - * Legacy mechanism to select the TLS protocol version to use, it does - * not support independent control of the minimum and maximum version, - * and does not support limiting the protocol to TLSv1.3. Use - * minVersion and maxVersion instead. The possible values are listed as - * SSL_METHODS, use the function names as strings. For example, use - * 'TLSv1_1_method' to force TLS version 1.1, or 'TLS_method' to allow - * any TLS protocol version up to TLSv1.3. It is not recommended to use - * TLS versions less than 1.2, but it may be required for - * interoperability. Default: none, see minVersion. - */ - secureProtocol?: string; - /** - * Opaque identifier used by servers to ensure session state is not - * shared between applications. Unused by clients. - */ - sessionIdContext?: string; - /** - * 48 bytes of cryptographically strong pseudo-random data. - */ - ticketKeys?: Buffer; - /** - * The number of seconds after which a TLS session created by the server - * will no longer be resumable. - */ - sessionTimeout?: number; - } - - interface SecureContext { - context: any; - } - - /* - * Verifies the certificate `cert` is issued to host `host`. - * @host The hostname to verify the certificate against - * @cert PeerCertificate representing the peer's certificate - * - * Returns Error object, populating it with the reason, host and cert on failure. On success, returns undefined. - */ - function checkServerIdentity(host: string, cert: PeerCertificate): Error | undefined; - function createServer(secureConnectionListener?: (socket: TLSSocket) => void): Server; - function createServer(options: TlsOptions, secureConnectionListener?: (socket: TLSSocket) => void): Server; - function connect(options: ConnectionOptions, secureConnectListener?: () => void): TLSSocket; - function connect(port: number, host?: string, options?: ConnectionOptions, secureConnectListener?: () => void): TLSSocket; - function connect(port: number, options?: ConnectionOptions, secureConnectListener?: () => void): TLSSocket; - /** - * @deprecated since v0.11.3 Use `tls.TLSSocket` instead. - */ - function createSecurePair(credentials?: SecureContext, isServer?: boolean, requestCert?: boolean, rejectUnauthorized?: boolean): SecurePair; - function createSecureContext(details: SecureContextOptions): SecureContext; - function getCiphers(): string[]; - - /** - * The default curve name to use for ECDH key agreement in a tls server. - * The default value is 'auto'. See tls.createSecureContext() for further - * information. - */ - let DEFAULT_ECDH_CURVE: string; - /** - * The default value of the maxVersion option of - * tls.createSecureContext(). It can be assigned any of the supported TLS - * protocol versions, 'TLSv1.3', 'TLSv1.2', 'TLSv1.1', or 'TLSv1'. Default: - * 'TLSv1.3', unless changed using CLI options. Using --tls-max-v1.2 sets - * the default to 'TLSv1.2'. Using --tls-max-v1.3 sets the default to - * 'TLSv1.3'. If multiple of the options are provided, the highest maximum - * is used. - */ - let DEFAULT_MAX_VERSION: SecureVersion; - /** - * The default value of the minVersion option of tls.createSecureContext(). - * It can be assigned any of the supported TLS protocol versions, - * 'TLSv1.3', 'TLSv1.2', 'TLSv1.1', or 'TLSv1'. Default: 'TLSv1.2', unless - * changed using CLI options. Using --tls-min-v1.0 sets the default to - * 'TLSv1'. Using --tls-min-v1.1 sets the default to 'TLSv1.1'. Using - * --tls-min-v1.3 sets the default to 'TLSv1.3'. If multiple of the options - * are provided, the lowest minimum is used. - */ - let DEFAULT_MIN_VERSION: SecureVersion; - - /** - * An immutable array of strings representing the root certificates (in PEM - * format) used for verifying peer certificates. This is the default value - * of the ca option to tls.createSecureContext(). - */ - const rootCertificates: ReadonlyArray; -} diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/node/trace_events.d.ts b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/node/trace_events.d.ts deleted file mode 100644 index 1f3a89c482..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/node/trace_events.d.ts +++ /dev/null @@ -1,61 +0,0 @@ -declare module "trace_events" { - /** - * The `Tracing` object is used to enable or disable tracing for sets of - * categories. Instances are created using the - * `trace_events.createTracing()` method. - * - * When created, the `Tracing` object is disabled. Calling the - * `tracing.enable()` method adds the categories to the set of enabled trace - * event categories. Calling `tracing.disable()` will remove the categories - * from the set of enabled trace event categories. - */ - interface Tracing { - /** - * A comma-separated list of the trace event categories covered by this - * `Tracing` object. - */ - readonly categories: string; - - /** - * Disables this `Tracing` object. - * - * Only trace event categories _not_ covered by other enabled `Tracing` - * objects and _not_ specified by the `--trace-event-categories` flag - * will be disabled. - */ - disable(): void; - - /** - * Enables this `Tracing` object for the set of categories covered by - * the `Tracing` object. - */ - enable(): void; - - /** - * `true` only if the `Tracing` object has been enabled. - */ - readonly enabled: boolean; - } - - interface CreateTracingOptions { - /** - * An array of trace category names. Values included in the array are - * coerced to a string when possible. An error will be thrown if the - * value cannot be coerced. - */ - categories: string[]; - } - - /** - * Creates and returns a Tracing object for the given set of categories. - */ - function createTracing(options: CreateTracingOptions): Tracing; - - /** - * Returns a comma-separated list of all currently-enabled trace event - * categories. The current set of enabled trace event categories is - * determined by the union of all currently-enabled `Tracing` objects and - * any categories enabled using the `--trace-event-categories` flag. - */ - function getEnabledCategories(): string | undefined; -} diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/node/ts3.4/assert.d.ts b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/node/ts3.4/assert.d.ts deleted file mode 100644 index 68b189ceba..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/node/ts3.4/assert.d.ts +++ /dev/null @@ -1,74 +0,0 @@ -declare module 'assert' { - function assert(value: any, message?: string | Error): void; - namespace assert { - class AssertionError implements Error { - name: string; - message: string; - actual: any; - expected: any; - operator: string; - generatedMessage: boolean; - code: 'ERR_ASSERTION'; - - constructor(options?: { - message?: string; - actual?: any; - expected?: any; - operator?: string; - stackStartFn?: Function; - }); - } - - type AssertPredicate = RegExp | (new () => object) | ((thrown: any) => boolean) | object | Error; - - function fail(message?: string | Error): never; - /** @deprecated since v10.0.0 - use `fail([message])` or other assert functions instead. */ - function fail( - actual: any, - expected: any, - message?: string | Error, - operator?: string, - stackStartFn?: Function, - ): never; - function ok(value: any, message?: string | Error): void; - /** @deprecated since v9.9.0 - use `strictEqual()` instead. */ - function equal(actual: any, expected: any, message?: string | Error): void; - /** @deprecated since v9.9.0 - use `notStrictEqual()` instead. */ - function notEqual(actual: any, expected: any, message?: string | Error): void; - /** @deprecated since v9.9.0 - use `deepStrictEqual()` instead. */ - function deepEqual(actual: any, expected: any, message?: string | Error): void; - /** @deprecated since v9.9.0 - use `notDeepStrictEqual()` instead. */ - function notDeepEqual(actual: any, expected: any, message?: string | Error): void; - function strictEqual(actual: any, expected: any, message?: string | Error): void; - function notStrictEqual(actual: any, expected: any, message?: string | Error): void; - function deepStrictEqual(actual: any, expected: any, message?: string | Error): void; - function notDeepStrictEqual(actual: any, expected: any, message?: string | Error): void; - - function throws(block: () => any, message?: string | Error): void; - function throws(block: () => any, error: AssertPredicate, message?: string | Error): void; - function doesNotThrow(block: () => any, message?: string | Error): void; - function doesNotThrow(block: () => any, error: RegExp | Function, message?: string | Error): void; - - function ifError(value: any): void; - - function rejects(block: (() => Promise) | Promise, message?: string | Error): Promise; - function rejects( - block: (() => Promise) | Promise, - error: AssertPredicate, - message?: string | Error, - ): Promise; - function doesNotReject(block: (() => Promise) | Promise, message?: string | Error): Promise; - function doesNotReject( - block: (() => Promise) | Promise, - error: RegExp | Function, - message?: string | Error, - ): Promise; - - function match(value: string, regExp: RegExp, message?: string | Error): void; - function doesNotMatch(value: string, regExp: RegExp, message?: string | Error): void; - - const strict: typeof assert; - } - - export = assert; -} diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/node/ts3.4/base.d.ts b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/node/ts3.4/base.d.ts deleted file mode 100644 index 2ea04f58fc..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/node/ts3.4/base.d.ts +++ /dev/null @@ -1,56 +0,0 @@ -// NOTE: These definitions support NodeJS and TypeScript 3.2 - 3.4. - -// NOTE: TypeScript version-specific augmentations can be found in the following paths: -// - ~/base.d.ts - Shared definitions common to all TypeScript versions -// - ~/index.d.ts - Definitions specific to TypeScript 2.1 -// - ~/ts3.2/base.d.ts - Definitions specific to TypeScript 3.2 -// - ~/ts3.2/index.d.ts - Definitions specific to TypeScript 3.2 with global and assert pulled in - -// Reference required types from the default lib: -/// -/// -/// -/// - -// Base definitions for all NodeJS modules that are not specific to any version of TypeScript: - -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/node/ts3.4/globals.global.d.ts b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/node/ts3.4/globals.global.d.ts deleted file mode 100644 index 8e854665ac..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/node/ts3.4/globals.global.d.ts +++ /dev/null @@ -1 +0,0 @@ -declare var global: NodeJS.Global; diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/node/ts3.4/index.d.ts b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/node/ts3.4/index.d.ts deleted file mode 100644 index 506b32a598..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/node/ts3.4/index.d.ts +++ /dev/null @@ -1,8 +0,0 @@ -// NOTE: These definitions support NodeJS and TypeScript 3.2 - 3.4. -// This is required to enable globalThis support for global in ts3.5 without causing errors -// This is required to enable typing assert in ts3.7 without causing errors -// Typically type modifiations should be made in base.d.ts instead of here - -/// -/// -/// diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/node/ts3.6/base.d.ts b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/node/ts3.6/base.d.ts deleted file mode 100644 index 081a535fac..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/node/ts3.6/base.d.ts +++ /dev/null @@ -1,23 +0,0 @@ -// NOTE: These definitions support NodeJS and TypeScript 3.5. - -// NOTE: TypeScript version-specific augmentations can be found in the following paths: -// - ~/base.d.ts - Shared definitions common to all TypeScript versions -// - ~/index.d.ts - Definitions specific to TypeScript 2.1 -// - ~/ts3.5/base.d.ts - Definitions specific to TypeScript 3.5 -// - ~/ts3.5/index.d.ts - Definitions specific to TypeScript 3.5 with assert pulled in - -// Reference required types from the default lib: -/// -/// -/// -/// - -// Base definitions for all NodeJS modules that are not specific to any version of TypeScript: -// tslint:disable-next-line:no-bad-reference -/// - -// TypeScript 3.5-specific augmentations: -/// - -// TypeScript 3.5-specific augmentations: -/// diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/node/ts3.6/index.d.ts b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/node/ts3.6/index.d.ts deleted file mode 100644 index 23b9a61dde..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/node/ts3.6/index.d.ts +++ /dev/null @@ -1,8 +0,0 @@ -// NOTE: These definitions support NodeJS and TypeScript 3.5 - 3.6. -// This is required to enable typing assert in ts3.7 without causing errors -// Typically type modifications should be made in base.d.ts instead of here - -/// - -// tslint:disable-next-line:no-bad-reference -/// diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/node/tty.d.ts b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/node/tty.d.ts deleted file mode 100644 index 7854366339..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/node/tty.d.ts +++ /dev/null @@ -1,66 +0,0 @@ -declare module "tty" { - import * as net from "net"; - - function isatty(fd: number): boolean; - class ReadStream extends net.Socket { - constructor(fd: number, options?: net.SocketConstructorOpts); - isRaw: boolean; - setRawMode(mode: boolean): this; - isTTY: boolean; - } - /** - * -1 - to the left from cursor - * 0 - the entire line - * 1 - to the right from cursor - */ - type Direction = -1 | 0 | 1; - class WriteStream extends net.Socket { - constructor(fd: number); - addListener(event: string, listener: (...args: any[]) => void): this; - addListener(event: "resize", listener: () => void): this; - - emit(event: string | symbol, ...args: any[]): boolean; - emit(event: "resize"): boolean; - - on(event: string, listener: (...args: any[]) => void): this; - on(event: "resize", listener: () => void): this; - - once(event: string, listener: (...args: any[]) => void): this; - once(event: "resize", listener: () => void): this; - - prependListener(event: string, listener: (...args: any[]) => void): this; - prependListener(event: "resize", listener: () => void): this; - - prependOnceListener(event: string, listener: (...args: any[]) => void): this; - prependOnceListener(event: "resize", listener: () => void): this; - - /** - * Clears the current line of this WriteStream in a direction identified by `dir`. - */ - clearLine(dir: Direction, callback?: () => void): boolean; - /** - * Clears this `WriteStream` from the current cursor down. - */ - clearScreenDown(callback?: () => void): boolean; - /** - * Moves this WriteStream's cursor to the specified position. - */ - cursorTo(x: number, y?: number, callback?: () => void): boolean; - cursorTo(x: number, callback: () => void): boolean; - /** - * Moves this WriteStream's cursor relative to its current position. - */ - moveCursor(dx: number, dy: number, callback?: () => void): boolean; - /** - * @default `process.env` - */ - getColorDepth(env?: {}): number; - hasColors(depth?: number): boolean; - hasColors(env?: {}): boolean; - hasColors(depth: number, env?: {}): boolean; - getWindowSize(): [number, number]; - columns: number; - rows: number; - isTTY: boolean; - } -} diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/node/url.d.ts b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/node/url.d.ts deleted file mode 100644 index 2490c352d0..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/node/url.d.ts +++ /dev/null @@ -1,110 +0,0 @@ -declare module "url" { - import { ParsedUrlQuery, ParsedUrlQueryInput } from 'querystring'; - - // Input to `url.format` - interface UrlObject { - auth?: string | null; - hash?: string | null; - host?: string | null; - hostname?: string | null; - href?: string | null; - pathname?: string | null; - protocol?: string | null; - search?: string | null; - slashes?: boolean | null; - port?: string | number | null; - query?: string | null | ParsedUrlQueryInput; - } - - // Output of `url.parse` - interface Url { - auth: string | null; - hash: string | null; - host: string | null; - hostname: string | null; - href: string; - path: string | null; - pathname: string | null; - protocol: string | null; - search: string | null; - slashes: boolean | null; - port: string | null; - query: string | null | ParsedUrlQuery; - } - - interface UrlWithParsedQuery extends Url { - query: ParsedUrlQuery; - } - - interface UrlWithStringQuery extends Url { - query: string | null; - } - - function parse(urlStr: string): UrlWithStringQuery; - function parse(urlStr: string, parseQueryString: false | undefined, slashesDenoteHost?: boolean): UrlWithStringQuery; - function parse(urlStr: string, parseQueryString: true, slashesDenoteHost?: boolean): UrlWithParsedQuery; - function parse(urlStr: string, parseQueryString: boolean, slashesDenoteHost?: boolean): Url; - - function format(URL: URL, options?: URLFormatOptions): string; - function format(urlObject: UrlObject | string): string; - function resolve(from: string, to: string): string; - - function domainToASCII(domain: string): string; - function domainToUnicode(domain: string): string; - - /** - * This function ensures the correct decodings of percent-encoded characters as - * well as ensuring a cross-platform valid absolute path string. - * @param url The file URL string or URL object to convert to a path. - */ - function fileURLToPath(url: string | URL): string; - - /** - * This function ensures that path is resolved absolutely, and that the URL - * control characters are correctly encoded when converting into a File URL. - * @param url The path to convert to a File URL. - */ - function pathToFileURL(url: string): URL; - - interface URLFormatOptions { - auth?: boolean; - fragment?: boolean; - search?: boolean; - unicode?: boolean; - } - - class URL { - constructor(input: string, base?: string | URL); - hash: string; - host: string; - hostname: string; - href: string; - readonly origin: string; - password: string; - pathname: string; - port: string; - protocol: string; - search: string; - readonly searchParams: URLSearchParams; - username: string; - toString(): string; - toJSON(): string; - } - - class URLSearchParams implements Iterable<[string, string]> { - constructor(init?: URLSearchParams | string | NodeJS.Dict> | Iterable<[string, string]> | ReadonlyArray<[string, string]>); - append(name: string, value: string): void; - delete(name: string): void; - entries(): IterableIterator<[string, string]>; - forEach(callback: (value: string, name: string, searchParams: this) => void): void; - get(name: string): string | null; - getAll(name: string): string[]; - has(name: string): boolean; - keys(): IterableIterator; - set(name: string, value: string): void; - sort(): void; - toString(): string; - values(): IterableIterator; - [Symbol.iterator](): IterableIterator<[string, string]>; - } -} diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/node/util.d.ts b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/node/util.d.ts deleted file mode 100644 index f4d1bda167..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/node/util.d.ts +++ /dev/null @@ -1,196 +0,0 @@ -declare module "util" { - interface InspectOptions extends NodeJS.InspectOptions { } - type Style = 'special' | 'number' | 'bigint' | 'boolean' | 'undefined' | 'null' | 'string' | 'symbol' | 'date' | 'regexp' | 'module'; - type CustomInspectFunction = (depth: number, options: InspectOptionsStylized) => string; - interface InspectOptionsStylized extends InspectOptions { - stylize(text: string, styleType: Style): string; - } - function format(format: any, ...param: any[]): string; - function formatWithOptions(inspectOptions: InspectOptions, format: string, ...param: any[]): string; - /** @deprecated since v0.11.3 - use a third party module instead. */ - function log(string: string): void; - function inspect(object: any, showHidden?: boolean, depth?: number | null, color?: boolean): string; - function inspect(object: any, options: InspectOptions): string; - namespace inspect { - let colors: NodeJS.Dict<[number, number]>; - let styles: { - [K in Style]: string - }; - let defaultOptions: InspectOptions; - /** - * Allows changing inspect settings from the repl. - */ - let replDefaults: InspectOptions; - const custom: unique symbol; - } - /** @deprecated since v4.0.0 - use `Array.isArray()` instead. */ - function isArray(object: any): object is any[]; - /** @deprecated since v4.0.0 - use `util.types.isRegExp()` instead. */ - function isRegExp(object: any): object is RegExp; - /** @deprecated since v4.0.0 - use `util.types.isDate()` instead. */ - function isDate(object: any): object is Date; - /** @deprecated since v4.0.0 - use `util.types.isNativeError()` instead. */ - function isError(object: any): object is Error; - function inherits(constructor: any, superConstructor: any): void; - function debuglog(key: string): (msg: string, ...param: any[]) => void; - /** @deprecated since v4.0.0 - use `typeof value === 'boolean'` instead. */ - function isBoolean(object: any): object is boolean; - /** @deprecated since v4.0.0 - use `Buffer.isBuffer()` instead. */ - function isBuffer(object: any): object is Buffer; - /** @deprecated since v4.0.0 - use `typeof value === 'function'` instead. */ - function isFunction(object: any): boolean; - /** @deprecated since v4.0.0 - use `value === null` instead. */ - function isNull(object: any): object is null; - /** @deprecated since v4.0.0 - use `value === null || value === undefined` instead. */ - function isNullOrUndefined(object: any): object is null | undefined; - /** @deprecated since v4.0.0 - use `typeof value === 'number'` instead. */ - function isNumber(object: any): object is number; - /** @deprecated since v4.0.0 - use `value !== null && typeof value === 'object'` instead. */ - function isObject(object: any): boolean; - /** @deprecated since v4.0.0 - use `(typeof value !== 'object' && typeof value !== 'function') || value === null` instead. */ - function isPrimitive(object: any): boolean; - /** @deprecated since v4.0.0 - use `typeof value === 'string'` instead. */ - function isString(object: any): object is string; - /** @deprecated since v4.0.0 - use `typeof value === 'symbol'` instead. */ - function isSymbol(object: any): object is symbol; - /** @deprecated since v4.0.0 - use `value === undefined` instead. */ - function isUndefined(object: any): object is undefined; - function deprecate(fn: T, message: string, code?: string): T; - function isDeepStrictEqual(val1: any, val2: any): boolean; - - function callbackify(fn: () => Promise): (callback: (err: NodeJS.ErrnoException) => void) => void; - function callbackify(fn: () => Promise): (callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void; - function callbackify(fn: (arg1: T1) => Promise): (arg1: T1, callback: (err: NodeJS.ErrnoException) => void) => void; - function callbackify(fn: (arg1: T1) => Promise): (arg1: T1, callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void; - function callbackify(fn: (arg1: T1, arg2: T2) => Promise): (arg1: T1, arg2: T2, callback: (err: NodeJS.ErrnoException) => void) => void; - function callbackify(fn: (arg1: T1, arg2: T2) => Promise): (arg1: T1, arg2: T2, callback: (err: NodeJS.ErrnoException | null, result: TResult) => void) => void; - function callbackify(fn: (arg1: T1, arg2: T2, arg3: T3) => Promise): (arg1: T1, arg2: T2, arg3: T3, callback: (err: NodeJS.ErrnoException) => void) => void; - function callbackify( - fn: (arg1: T1, arg2: T2, arg3: T3) => Promise): (arg1: T1, arg2: T2, arg3: T3, callback: (err: NodeJS.ErrnoException | null, result: TResult) => void) => void; - function callbackify( - fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err: NodeJS.ErrnoException) => void) => void; - function callbackify( - fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err: NodeJS.ErrnoException | null, result: TResult) => void) => void; - function callbackify( - fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err: NodeJS.ErrnoException) => void) => void; - function callbackify( - fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise, - ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err: NodeJS.ErrnoException | null, result: TResult) => void) => void; - function callbackify( - fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6) => Promise, - ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6, callback: (err: NodeJS.ErrnoException) => void) => void; - function callbackify( - fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6) => Promise - ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6, callback: (err: NodeJS.ErrnoException | null, result: TResult) => void) => void; - - interface CustomPromisifyLegacy extends Function { - __promisify__: TCustom; - } - - interface CustomPromisifySymbol extends Function { - [promisify.custom]: TCustom; - } - - type CustomPromisify = CustomPromisifySymbol | CustomPromisifyLegacy; - - function promisify(fn: CustomPromisify): TCustom; - function promisify(fn: (callback: (err: any, result: TResult) => void) => void): () => Promise; - function promisify(fn: (callback: (err?: any) => void) => void): () => Promise; - function promisify(fn: (arg1: T1, callback: (err: any, result: TResult) => void) => void): (arg1: T1) => Promise; - function promisify(fn: (arg1: T1, callback: (err?: any) => void) => void): (arg1: T1) => Promise; - function promisify(fn: (arg1: T1, arg2: T2, callback: (err: any, result: TResult) => void) => void): (arg1: T1, arg2: T2) => Promise; - function promisify(fn: (arg1: T1, arg2: T2, callback: (err?: any) => void) => void): (arg1: T1, arg2: T2) => Promise; - function promisify(fn: (arg1: T1, arg2: T2, arg3: T3, callback: (err: any, result: TResult) => void) => void): - (arg1: T1, arg2: T2, arg3: T3) => Promise; - function promisify(fn: (arg1: T1, arg2: T2, arg3: T3, callback: (err?: any) => void) => void): (arg1: T1, arg2: T2, arg3: T3) => Promise; - function promisify( - fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err: any, result: TResult) => void) => void, - ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise; - function promisify(fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err?: any) => void) => void): - (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise; - function promisify( - fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err: any, result: TResult) => void) => void, - ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise; - function promisify( - fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err?: any) => void) => void, - ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise; - function promisify(fn: Function): Function; - namespace promisify { - const custom: unique symbol; - } - - namespace types { - function isAnyArrayBuffer(object: any): boolean; - function isArgumentsObject(object: any): object is IArguments; - function isArrayBuffer(object: any): object is ArrayBuffer; - function isArrayBufferView(object: any): object is ArrayBufferView; - function isAsyncFunction(object: any): boolean; - function isBigInt64Array(value: any): value is BigInt64Array; - function isBigUint64Array(value: any): value is BigUint64Array; - function isBooleanObject(object: any): object is Boolean; - function isBoxedPrimitive(object: any): object is (Number | Boolean | String | Symbol /* | Object(BigInt) | Object(Symbol) */); - function isDataView(object: any): object is DataView; - function isDate(object: any): object is Date; - function isExternal(object: any): boolean; - function isFloat32Array(object: any): object is Float32Array; - function isFloat64Array(object: any): object is Float64Array; - function isGeneratorFunction(object: any): boolean; - function isGeneratorObject(object: any): boolean; - function isInt8Array(object: any): object is Int8Array; - function isInt16Array(object: any): object is Int16Array; - function isInt32Array(object: any): object is Int32Array; - function isMap(object: any): boolean; - function isMapIterator(object: any): boolean; - function isModuleNamespaceObject(value: any): boolean; - function isNativeError(object: any): object is Error; - function isNumberObject(object: any): object is Number; - function isPromise(object: any): boolean; - function isProxy(object: any): boolean; - function isRegExp(object: any): object is RegExp; - function isSet(object: any): boolean; - function isSetIterator(object: any): boolean; - function isSharedArrayBuffer(object: any): boolean; - function isStringObject(object: any): boolean; - function isSymbolObject(object: any): boolean; - function isTypedArray(object: any): object is NodeJS.TypedArray; - function isUint8Array(object: any): object is Uint8Array; - function isUint8ClampedArray(object: any): object is Uint8ClampedArray; - function isUint16Array(object: any): object is Uint16Array; - function isUint32Array(object: any): object is Uint32Array; - function isWeakMap(object: any): boolean; - function isWeakSet(object: any): boolean; - function isWebAssemblyCompiledModule(object: any): boolean; - } - - class TextDecoder { - readonly encoding: string; - readonly fatal: boolean; - readonly ignoreBOM: boolean; - constructor( - encoding?: string, - options?: { fatal?: boolean; ignoreBOM?: boolean } - ); - decode( - input?: NodeJS.ArrayBufferView | ArrayBuffer | null, - options?: { stream?: boolean } - ): string; - } - - interface EncodeIntoResult { - /** - * The read Unicode code units of input. - */ - - read: number; - /** - * The written UTF-8 bytes of output. - */ - written: number; - } - - class TextEncoder { - readonly encoding: string; - encode(input?: string): Uint8Array; - encodeInto(input: string, output: Uint8Array): EncodeIntoResult; - } -} diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/node/v8.d.ts b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/node/v8.d.ts deleted file mode 100644 index 7d950824f3..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/node/v8.d.ts +++ /dev/null @@ -1,187 +0,0 @@ -declare module "v8" { - import { Readable } from "stream"; - - interface HeapSpaceInfo { - space_name: string; - space_size: number; - space_used_size: number; - space_available_size: number; - physical_space_size: number; - } - - // ** Signifies if the --zap_code_space option is enabled or not. 1 == enabled, 0 == disabled. */ - type DoesZapCodeSpaceFlag = 0 | 1; - - interface HeapInfo { - total_heap_size: number; - total_heap_size_executable: number; - total_physical_size: number; - total_available_size: number; - used_heap_size: number; - heap_size_limit: number; - malloced_memory: number; - peak_malloced_memory: number; - does_zap_garbage: DoesZapCodeSpaceFlag; - number_of_native_contexts: number; - number_of_detached_contexts: number; - } - - interface HeapCodeStatistics { - code_and_metadata_size: number; - bytecode_and_metadata_size: number; - external_script_source_size: number; - } - - /** - * Returns an integer representing a "version tag" derived from the V8 version, command line flags and detected CPU features. - * This is useful for determining whether a vm.Script cachedData buffer is compatible with this instance of V8. - */ - function cachedDataVersionTag(): number; - - function getHeapStatistics(): HeapInfo; - function getHeapSpaceStatistics(): HeapSpaceInfo[]; - function setFlagsFromString(flags: string): void; - /** - * Generates a snapshot of the current V8 heap and returns a Readable - * Stream that may be used to read the JSON serialized representation. - * This conversation was marked as resolved by joyeecheung - * This JSON stream format is intended to be used with tools such as - * Chrome DevTools. The JSON schema is undocumented and specific to the - * V8 engine, and may change from one version of V8 to the next. - */ - function getHeapSnapshot(): Readable; - - /** - * - * @param fileName The file path where the V8 heap snapshot is to be - * saved. If not specified, a file name with the pattern - * `'Heap-${yyyymmdd}-${hhmmss}-${pid}-${thread_id}.heapsnapshot'` will be - * generated, where `{pid}` will be the PID of the Node.js process, - * `{thread_id}` will be `0` when `writeHeapSnapshot()` is called from - * the main Node.js thread or the id of a worker thread. - */ - function writeHeapSnapshot(fileName?: string): string; - - function getHeapCodeStatistics(): HeapCodeStatistics; - - class Serializer { - /** - * Writes out a header, which includes the serialization format version. - */ - writeHeader(): void; - - /** - * Serializes a JavaScript value and adds the serialized representation to the internal buffer. - * This throws an error if value cannot be serialized. - */ - writeValue(val: any): boolean; - - /** - * Returns the stored internal buffer. - * This serializer should not be used once the buffer is released. - * Calling this method results in undefined behavior if a previous write has failed. - */ - releaseBuffer(): Buffer; - - /** - * Marks an ArrayBuffer as having its contents transferred out of band.\ - * Pass the corresponding ArrayBuffer in the deserializing context to deserializer.transferArrayBuffer(). - */ - transferArrayBuffer(id: number, arrayBuffer: ArrayBuffer): void; - - /** - * Write a raw 32-bit unsigned integer. - */ - writeUint32(value: number): void; - - /** - * Write a raw 64-bit unsigned integer, split into high and low 32-bit parts. - */ - writeUint64(hi: number, lo: number): void; - - /** - * Write a JS number value. - */ - writeDouble(value: number): void; - - /** - * Write raw bytes into the serializer’s internal buffer. - * The deserializer will require a way to compute the length of the buffer. - */ - writeRawBytes(buffer: NodeJS.TypedArray): void; - } - - /** - * A subclass of `Serializer` that serializes `TypedArray` (in particular `Buffer`) and `DataView` objects as host objects, - * and only stores the part of their underlying `ArrayBuffers` that they are referring to. - */ - class DefaultSerializer extends Serializer { - } - - class Deserializer { - constructor(data: NodeJS.TypedArray); - /** - * Reads and validates a header (including the format version). - * May, for example, reject an invalid or unsupported wire format. - * In that case, an Error is thrown. - */ - readHeader(): boolean; - - /** - * Deserializes a JavaScript value from the buffer and returns it. - */ - readValue(): any; - - /** - * Marks an ArrayBuffer as having its contents transferred out of band. - * Pass the corresponding `ArrayBuffer` in the serializing context to serializer.transferArrayBuffer() - * (or return the id from serializer._getSharedArrayBufferId() in the case of SharedArrayBuffers). - */ - transferArrayBuffer(id: number, arrayBuffer: ArrayBuffer): void; - - /** - * Reads the underlying wire format version. - * Likely mostly to be useful to legacy code reading old wire format versions. - * May not be called before .readHeader(). - */ - getWireFormatVersion(): number; - - /** - * Read a raw 32-bit unsigned integer and return it. - */ - readUint32(): number; - - /** - * Read a raw 64-bit unsigned integer and return it as an array [hi, lo] with two 32-bit unsigned integer entries. - */ - readUint64(): [number, number]; - - /** - * Read a JS number value. - */ - readDouble(): number; - - /** - * Read raw bytes from the deserializer’s internal buffer. - * The length parameter must correspond to the length of the buffer that was passed to serializer.writeRawBytes(). - */ - readRawBytes(length: number): Buffer; - } - - /** - * A subclass of `Serializer` that serializes `TypedArray` (in particular `Buffer`) and `DataView` objects as host objects, - * and only stores the part of their underlying `ArrayBuffers` that they are referring to. - */ - class DefaultDeserializer extends Deserializer { - } - - /** - * Uses a `DefaultSerializer` to serialize value into a buffer. - */ - function serialize(value: any): Buffer; - - /** - * Uses a `DefaultDeserializer` with default options to read a JS value from a buffer. - */ - function deserialize(data: NodeJS.TypedArray): any; -} diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/node/vm.d.ts b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/node/vm.d.ts deleted file mode 100644 index 399c2a6a11..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/node/vm.d.ts +++ /dev/null @@ -1,146 +0,0 @@ -declare module "vm" { - interface Context extends NodeJS.Dict { } - interface BaseOptions { - /** - * Specifies the filename used in stack traces produced by this script. - * Default: `''`. - */ - filename?: string; - /** - * Specifies the line number offset that is displayed in stack traces produced by this script. - * Default: `0`. - */ - lineOffset?: number; - /** - * Specifies the column number offset that is displayed in stack traces produced by this script. - * Default: `0` - */ - columnOffset?: number; - } - interface ScriptOptions extends BaseOptions { - displayErrors?: boolean; - timeout?: number; - cachedData?: Buffer; - produceCachedData?: boolean; - } - interface RunningScriptOptions extends BaseOptions { - /** - * When `true`, if an `Error` occurs while compiling the `code`, the line of code causing the error is attached to the stack trace. - * Default: `true`. - */ - displayErrors?: boolean; - /** - * Specifies the number of milliseconds to execute code before terminating execution. - * If execution is terminated, an `Error` will be thrown. This value must be a strictly positive integer. - */ - timeout?: number; - /** - * If `true`, the execution will be terminated when `SIGINT` (Ctrl+C) is received. - * Existing handlers for the event that have been attached via `process.on('SIGINT')` will be disabled during script execution, but will continue to work after that. - * If execution is terminated, an `Error` will be thrown. - * Default: `false`. - */ - breakOnSigint?: boolean; - /** - * If set to `afterEvaluate`, microtasks will be run immediately after the script has run. - */ - microtaskMode?: 'afterEvaluate'; - } - interface CompileFunctionOptions extends BaseOptions { - /** - * Provides an optional data with V8's code cache data for the supplied source. - */ - cachedData?: Buffer; - /** - * Specifies whether to produce new cache data. - * Default: `false`, - */ - produceCachedData?: boolean; - /** - * The sandbox/context in which the said function should be compiled in. - */ - parsingContext?: Context; - - /** - * An array containing a collection of context extensions (objects wrapping the current scope) to be applied while compiling - */ - contextExtensions?: Object[]; - } - - interface CreateContextOptions { - /** - * Human-readable name of the newly created context. - * @default 'VM Context i' Where i is an ascending numerical index of the created context. - */ - name?: string; - /** - * Corresponds to the newly created context for display purposes. - * The origin should be formatted like a `URL`, but with only the scheme, host, and port (if necessary), - * like the value of the `url.origin` property of a URL object. - * Most notably, this string should omit the trailing slash, as that denotes a path. - * @default '' - */ - origin?: string; - codeGeneration?: { - /** - * If set to false any calls to eval or function constructors (Function, GeneratorFunction, etc) - * will throw an EvalError. - * @default true - */ - strings?: boolean; - /** - * If set to false any attempt to compile a WebAssembly module will throw a WebAssembly.CompileError. - * @default true - */ - wasm?: boolean; - }; - } - - type MeasureMemoryMode = 'summary' | 'detailed'; - - interface MeasureMemoryOptions { - /** - * @default 'summary' - */ - mode?: MeasureMemoryMode; - context?: Context; - } - - interface MemoryMeasurement { - total: { - jsMemoryEstimate: number; - jsMemoryRange: [number, number]; - }; - } - - class Script { - constructor(code: string, options?: ScriptOptions); - runInContext(contextifiedSandbox: Context, options?: RunningScriptOptions): any; - runInNewContext(sandbox?: Context, options?: RunningScriptOptions): any; - runInThisContext(options?: RunningScriptOptions): any; - createCachedData(): Buffer; - } - function createContext(sandbox?: Context, options?: CreateContextOptions): Context; - function isContext(sandbox: Context): boolean; - function runInContext(code: string, contextifiedSandbox: Context, options?: RunningScriptOptions | string): any; - function runInNewContext(code: string, sandbox?: Context, options?: RunningScriptOptions | string): any; - function runInThisContext(code: string, options?: RunningScriptOptions | string): any; - function compileFunction(code: string, params?: ReadonlyArray, options?: CompileFunctionOptions): Function; - - /** - * Measure the memory known to V8 and used by the current execution context or a specified context. - * - * The format of the object that the returned Promise may resolve with is - * specific to the V8 engine and may change from one version of V8 to the next. - * - * The returned result is different from the statistics returned by - * `v8.getHeapSpaceStatistics()` in that `vm.measureMemory()` measures - * the memory reachable by V8 from a specific context, while - * `v8.getHeapSpaceStatistics()` measures the memory used by an instance - * of V8 engine, which can switch among multiple contexts that reference - * objects in the heap of one engine. - * - * @experimental - */ - function measureMemory(options?: MeasureMemoryOptions): Promise; -} diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/node/wasi.d.ts b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/node/wasi.d.ts deleted file mode 100644 index fe2b2aab8e..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/node/wasi.d.ts +++ /dev/null @@ -1,86 +0,0 @@ -declare module 'wasi' { - interface WASIOptions { - /** - * An array of strings that the WebAssembly application will - * see as command line arguments. The first argument is the virtual path to the - * WASI command itself. - */ - args?: string[]; - - /** - * An object similar to `process.env` that the WebAssembly - * application will see as its environment. - */ - env?: object; - - /** - * This object represents the WebAssembly application's - * sandbox directory structure. The string keys of `preopens` are treated as - * directories within the sandbox. The corresponding values in `preopens` are - * the real paths to those directories on the host machine. - */ - preopens?: NodeJS.Dict; - - /** - * By default, WASI applications terminate the Node.js - * process via the `__wasi_proc_exit()` function. Setting this option to `true` - * causes `wasi.start()` to return the exit code rather than terminate the - * process. - * @default false - */ - returnOnExit?: boolean; - - /** - * The file descriptor used as standard input in the WebAssembly application. - * @default 0 - */ - stdin?: number; - - /** - * The file descriptor used as standard output in the WebAssembly application. - * @default 1 - */ - stdout?: number; - - /** - * The file descriptor used as standard error in the WebAssembly application. - * @default 2 - */ - stderr?: number; - } - - class WASI { - constructor(options?: WASIOptions); - /** - * - * Attempt to begin execution of `instance` by invoking its `_start()` export. - * If `instance` does not contain a `_start()` export, then `start()` attempts to - * invoke the `__wasi_unstable_reactor_start()` export. If neither of those exports - * is present on `instance`, then `start()` does nothing. - * - * `start()` requires that `instance` exports a [`WebAssembly.Memory`][] named - * `memory`. If `instance` does not have a `memory` export an exception is thrown. - * - * If `start()` is called more than once, an exception is thrown. - */ - start(instance: object): void; // TODO: avoid DOM dependency until WASM moved to own lib. - - /** - * Attempt to initialize `instance` as a WASI reactor by invoking its `_initialize()` export, if it is present. - * If `instance` contains a `_start()` export, then an exception is thrown. - * - * `start()` requires that `instance` exports a [`WebAssembly.Memory`][] named - * `memory`. If `instance` does not have a `memory` export an exception is thrown. - * - * If `initialize()` is called more than once, an exception is thrown. - */ - initialize(instance: object): void; // TODO: avoid DOM dependency until WASM moved to own lib. - - /** - * Is an object that implements the WASI system call API. This object - * should be passed as the `wasi_snapshot_preview1` import during the instantiation of a - * [`WebAssembly.Instance`][]. - */ - readonly wasiImport: NodeJS.Dict; // TODO: Narrow to DOM types - } -} diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/node/worker_threads.d.ts b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/node/worker_threads.d.ts deleted file mode 100644 index 3a8881e6ad..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/node/worker_threads.d.ts +++ /dev/null @@ -1,238 +0,0 @@ -declare module "worker_threads" { - import { Context } from "vm"; - import { EventEmitter } from "events"; - import { Readable, Writable } from "stream"; - import { URL } from "url"; - import { FileHandle } from "fs/promises"; - - const isMainThread: boolean; - const parentPort: null | MessagePort; - const resourceLimits: ResourceLimits; - const SHARE_ENV: unique symbol; - const threadId: number; - const workerData: any; - - class MessageChannel { - readonly port1: MessagePort; - readonly port2: MessagePort; - } - - type TransferListItem = ArrayBuffer | MessagePort | FileHandle; - - class MessagePort extends EventEmitter { - close(): void; - postMessage(value: any, transferList?: ReadonlyArray): void; - ref(): void; - unref(): void; - start(): void; - - addListener(event: "close", listener: () => void): this; - addListener(event: "message", listener: (value: any) => void): this; - addListener(event: "messageerror", listener: (error: Error) => void): this; - addListener(event: string | symbol, listener: (...args: any[]) => void): this; - - emit(event: "close"): boolean; - emit(event: "message", value: any): boolean; - emit(event: "messageerror", error: Error): boolean; - emit(event: string | symbol, ...args: any[]): boolean; - - on(event: "close", listener: () => void): this; - on(event: "message", listener: (value: any) => void): this; - on(event: "messageerror", listener: (error: Error) => void): this; - on(event: string | symbol, listener: (...args: any[]) => void): this; - - once(event: "close", listener: () => void): this; - once(event: "message", listener: (value: any) => void): this; - once(event: "messageerror", listener: (error: Error) => void): this; - once(event: string | symbol, listener: (...args: any[]) => void): this; - - prependListener(event: "close", listener: () => void): this; - prependListener(event: "message", listener: (value: any) => void): this; - prependListener(event: "messageerror", listener: (error: Error) => void): this; - prependListener(event: string | symbol, listener: (...args: any[]) => void): this; - - prependOnceListener(event: "close", listener: () => void): this; - prependOnceListener(event: "message", listener: (value: any) => void): this; - prependOnceListener(event: "messageerror", listener: (error: Error) => void): this; - prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; - - removeListener(event: "close", listener: () => void): this; - removeListener(event: "message", listener: (value: any) => void): this; - removeListener(event: "messageerror", listener: (error: Error) => void): this; - removeListener(event: string | symbol, listener: (...args: any[]) => void): this; - - off(event: "close", listener: () => void): this; - off(event: "message", listener: (value: any) => void): this; - off(event: "messageerror", listener: (error: Error) => void): this; - off(event: string | symbol, listener: (...args: any[]) => void): this; - } - - interface WorkerOptions { - /** - * List of arguments which would be stringified and appended to - * `process.argv` in the worker. This is mostly similar to the `workerData` - * but the values will be available on the global `process.argv` as if they - * were passed as CLI options to the script. - */ - argv?: any[]; - env?: NodeJS.Dict | typeof SHARE_ENV; - eval?: boolean; - workerData?: any; - stdin?: boolean; - stdout?: boolean; - stderr?: boolean; - execArgv?: string[]; - resourceLimits?: ResourceLimits; - /** - * Additional data to send in the first worker message. - */ - transferList?: TransferListItem[]; - trackUnmanagedFds?: boolean; - } - - interface ResourceLimits { - /** - * The maximum size of a heap space for recently created objects. - */ - maxYoungGenerationSizeMb?: number; - /** - * The maximum size of the main heap in MB. - */ - maxOldGenerationSizeMb?: number; - /** - * The size of a pre-allocated memory range used for generated code. - */ - codeRangeSizeMb?: number; - /** - * The default maximum stack size for the thread. Small values may lead to unusable Worker instances. - * @default 4 - */ - stackSizeMb?: number; - } - - class Worker extends EventEmitter { - readonly stdin: Writable | null; - readonly stdout: Readable; - readonly stderr: Readable; - readonly threadId: number; - readonly resourceLimits?: ResourceLimits; - - /** - * @param filename The path to the Worker’s main script or module. - * Must be either an absolute path or a relative path (i.e. relative to the current working directory) starting with ./ or ../, - * or a WHATWG URL object using file: protocol. If options.eval is true, this is a string containing JavaScript code rather than a path. - */ - constructor(filename: string | URL, options?: WorkerOptions); - - postMessage(value: any, transferList?: ReadonlyArray): void; - ref(): void; - unref(): void; - /** - * Stop all JavaScript execution in the worker thread as soon as possible. - * Returns a Promise for the exit code that is fulfilled when the `exit` event is emitted. - */ - terminate(): Promise; - - /** - * Returns a readable stream for a V8 snapshot of the current state of the Worker. - * See [`v8.getHeapSnapshot()`][] for more details. - * - * If the Worker thread is no longer running, which may occur before the - * [`'exit'` event][] is emitted, the returned `Promise` will be rejected - * immediately with an [`ERR_WORKER_NOT_RUNNING`][] error - */ - getHeapSnapshot(): Promise; - - addListener(event: "error", listener: (err: Error) => void): this; - addListener(event: "exit", listener: (exitCode: number) => void): this; - addListener(event: "message", listener: (value: any) => void): this; - addListener(event: "messageerror", listener: (error: Error) => void): this; - addListener(event: "online", listener: () => void): this; - addListener(event: string | symbol, listener: (...args: any[]) => void): this; - - emit(event: "error", err: Error): boolean; - emit(event: "exit", exitCode: number): boolean; - emit(event: "message", value: any): boolean; - emit(event: "messageerror", error: Error): boolean; - emit(event: "online"): boolean; - emit(event: string | symbol, ...args: any[]): boolean; - - on(event: "error", listener: (err: Error) => void): this; - on(event: "exit", listener: (exitCode: number) => void): this; - on(event: "message", listener: (value: any) => void): this; - on(event: "messageerror", listener: (error: Error) => void): this; - on(event: "online", listener: () => void): this; - on(event: string | symbol, listener: (...args: any[]) => void): this; - - once(event: "error", listener: (err: Error) => void): this; - once(event: "exit", listener: (exitCode: number) => void): this; - once(event: "message", listener: (value: any) => void): this; - once(event: "messageerror", listener: (error: Error) => void): this; - once(event: "online", listener: () => void): this; - once(event: string | symbol, listener: (...args: any[]) => void): this; - - prependListener(event: "error", listener: (err: Error) => void): this; - prependListener(event: "exit", listener: (exitCode: number) => void): this; - prependListener(event: "message", listener: (value: any) => void): this; - prependListener(event: "messageerror", listener: (error: Error) => void): this; - prependListener(event: "online", listener: () => void): this; - prependListener(event: string | symbol, listener: (...args: any[]) => void): this; - - prependOnceListener(event: "error", listener: (err: Error) => void): this; - prependOnceListener(event: "exit", listener: (exitCode: number) => void): this; - prependOnceListener(event: "message", listener: (value: any) => void): this; - prependOnceListener(event: "messageerror", listener: (error: Error) => void): this; - prependOnceListener(event: "online", listener: () => void): this; - prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; - - removeListener(event: "error", listener: (err: Error) => void): this; - removeListener(event: "exit", listener: (exitCode: number) => void): this; - removeListener(event: "message", listener: (value: any) => void): this; - removeListener(event: "messageerror", listener: (error: Error) => void): this; - removeListener(event: "online", listener: () => void): this; - removeListener(event: string | symbol, listener: (...args: any[]) => void): this; - - off(event: "error", listener: (err: Error) => void): this; - off(event: "exit", listener: (exitCode: number) => void): this; - off(event: "message", listener: (value: any) => void): this; - off(event: "messageerror", listener: (error: Error) => void): this; - off(event: "online", listener: () => void): this; - off(event: string | symbol, listener: (...args: any[]) => void): this; - } - - /** - * Mark an object as not transferable. - * If `object` occurs in the transfer list of a `port.postMessage()` call, it will be ignored. - * - * In particular, this makes sense for objects that can be cloned, rather than transferred, - * and which are used by other objects on the sending side. For example, Node.js marks - * the `ArrayBuffer`s it uses for its Buffer pool with this. - * - * This operation cannot be undone. - */ - function markAsUntransferable(object: object): void; - - /** - * Transfer a `MessagePort` to a different `vm` Context. The original `port` - * object will be rendered unusable, and the returned `MessagePort` instance will - * take its place. - * - * The returned `MessagePort` will be an object in the target context, and will - * inherit from its global `Object` class. Objects passed to the - * `port.onmessage()` listener will also be created in the target context - * and inherit from its global `Object` class. - * - * However, the created `MessagePort` will no longer inherit from - * `EventEmitter`, and only `port.onmessage()` can be used to receive - * events using it. - */ - function moveMessagePortToContext(port: MessagePort, context: Context): MessagePort; - - /** - * Receive a single message from a given `MessagePort`. If no message is available, - * `undefined` is returned, otherwise an object with a single `message` property - * that contains the message payload, corresponding to the oldest message in the - * `MessagePort`’s queue. - */ - function receiveMessageOnPort(port: MessagePort): { message: any } | undefined; -} diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/node/zlib.d.ts b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/node/zlib.d.ts deleted file mode 100644 index 5ed1a0c807..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/@types/node/zlib.d.ts +++ /dev/null @@ -1,392 +0,0 @@ -declare module "zlib" { - import * as stream from "stream"; - - interface ZlibOptions { - /** - * @default constants.Z_NO_FLUSH - */ - flush?: number; - /** - * @default constants.Z_FINISH - */ - finishFlush?: number; - /** - * @default 16*1024 - */ - chunkSize?: number; - windowBits?: number; - level?: number; // compression only - memLevel?: number; // compression only - strategy?: number; // compression only - dictionary?: NodeJS.ArrayBufferView | ArrayBuffer; // deflate/inflate only, empty dictionary by default - info?: boolean; - maxOutputLength?: number; - } - - interface BrotliOptions { - /** - * @default constants.BROTLI_OPERATION_PROCESS - */ - flush?: number; - /** - * @default constants.BROTLI_OPERATION_FINISH - */ - finishFlush?: number; - /** - * @default 16*1024 - */ - chunkSize?: number; - params?: { - /** - * Each key is a `constants.BROTLI_*` constant. - */ - [key: number]: boolean | number; - }; - maxOutputLength?: number; - } - - interface Zlib { - /** @deprecated Use bytesWritten instead. */ - readonly bytesRead: number; - readonly bytesWritten: number; - shell?: boolean | string; - close(callback?: () => void): void; - flush(kind?: number | (() => void), callback?: () => void): void; - } - - interface ZlibParams { - params(level: number, strategy: number, callback: () => void): void; - } - - interface ZlibReset { - reset(): void; - } - - interface BrotliCompress extends stream.Transform, Zlib { } - interface BrotliDecompress extends stream.Transform, Zlib { } - interface Gzip extends stream.Transform, Zlib { } - interface Gunzip extends stream.Transform, Zlib { } - interface Deflate extends stream.Transform, Zlib, ZlibReset, ZlibParams { } - interface Inflate extends stream.Transform, Zlib, ZlibReset { } - interface DeflateRaw extends stream.Transform, Zlib, ZlibReset, ZlibParams { } - interface InflateRaw extends stream.Transform, Zlib, ZlibReset { } - interface Unzip extends stream.Transform, Zlib { } - - function createBrotliCompress(options?: BrotliOptions): BrotliCompress; - function createBrotliDecompress(options?: BrotliOptions): BrotliDecompress; - function createGzip(options?: ZlibOptions): Gzip; - function createGunzip(options?: ZlibOptions): Gunzip; - function createDeflate(options?: ZlibOptions): Deflate; - function createInflate(options?: ZlibOptions): Inflate; - function createDeflateRaw(options?: ZlibOptions): DeflateRaw; - function createInflateRaw(options?: ZlibOptions): InflateRaw; - function createUnzip(options?: ZlibOptions): Unzip; - - type InputType = string | ArrayBuffer | NodeJS.ArrayBufferView; - - type CompressCallback = (error: Error | null, result: Buffer) => void; - - function brotliCompress(buf: InputType, options: BrotliOptions, callback: CompressCallback): void; - function brotliCompress(buf: InputType, callback: CompressCallback): void; - function brotliCompressSync(buf: InputType, options?: BrotliOptions): Buffer; - function brotliDecompress(buf: InputType, options: BrotliOptions, callback: CompressCallback): void; - function brotliDecompress(buf: InputType, callback: CompressCallback): void; - function brotliDecompressSync(buf: InputType, options?: BrotliOptions): Buffer; - function deflate(buf: InputType, callback: CompressCallback): void; - function deflate(buf: InputType, options: ZlibOptions, callback: CompressCallback): void; - function deflateSync(buf: InputType, options?: ZlibOptions): Buffer; - function deflateRaw(buf: InputType, callback: CompressCallback): void; - function deflateRaw(buf: InputType, options: ZlibOptions, callback: CompressCallback): void; - function deflateRawSync(buf: InputType, options?: ZlibOptions): Buffer; - function gzip(buf: InputType, callback: CompressCallback): void; - function gzip(buf: InputType, options: ZlibOptions, callback: CompressCallback): void; - function gzipSync(buf: InputType, options?: ZlibOptions): Buffer; - function gunzip(buf: InputType, callback: CompressCallback): void; - function gunzip(buf: InputType, options: ZlibOptions, callback: CompressCallback): void; - function gunzipSync(buf: InputType, options?: ZlibOptions): Buffer; - function inflate(buf: InputType, callback: CompressCallback): void; - function inflate(buf: InputType, options: ZlibOptions, callback: CompressCallback): void; - function inflateSync(buf: InputType, options?: ZlibOptions): Buffer; - function inflateRaw(buf: InputType, callback: CompressCallback): void; - function inflateRaw(buf: InputType, options: ZlibOptions, callback: CompressCallback): void; - function inflateRawSync(buf: InputType, options?: ZlibOptions): Buffer; - function unzip(buf: InputType, callback: CompressCallback): void; - function unzip(buf: InputType, options: ZlibOptions, callback: CompressCallback): void; - function unzipSync(buf: InputType, options?: ZlibOptions): Buffer; - - namespace brotliCompress { - function __promisify__(buffer: InputType, options: BrotliOptions): Promise; - function __promisify__(buffer: InputType): Promise; - } - namespace brotliDecompress { - function __promisify__(buffer: InputType, options: BrotliOptions): Promise; - function __promisify__(buffer: InputType): Promise; - } - namespace deflate { - function __promisify__(buffer: InputType): Promise; - function __promisify__(buffer: InputType, options: ZlibOptions): Promise; - } - namespace deflateRaw { - function __promisify__(buffer: InputType): Promise; - function __promisify__(buffer: InputType, options: ZlibOptions): Promise; - } - namespace gzip { - function __promisify__(buffer: InputType): Promise; - function __promisify__(buffer: InputType, options: ZlibOptions): Promise; - } - namespace gunzip { - function __promisify__(buffer: InputType): Promise; - function __promisify__(buffer: InputType, options: ZlibOptions): Promise; - } - namespace inflate { - function __promisify__(buffer: InputType): Promise; - function __promisify__(buffer: InputType, options: ZlibOptions): Promise; - } - namespace inflateRaw { - function __promisify__(buffer: InputType): Promise; - function __promisify__(buffer: InputType, options: ZlibOptions): Promise; - } - namespace unzip { - function __promisify__(buffer: InputType): Promise; - function __promisify__(buffer: InputType, options: ZlibOptions): Promise; - } - - namespace constants { - const BROTLI_DECODE: number; - const BROTLI_DECODER_ERROR_ALLOC_BLOCK_TYPE_TREES: number; - const BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MAP: number; - const BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MODES: number; - const BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_1: number; - const BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_2: number; - const BROTLI_DECODER_ERROR_ALLOC_TREE_GROUPS: number; - const BROTLI_DECODER_ERROR_DICTIONARY_NOT_SET: number; - const BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_1: number; - const BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_2: number; - const BROTLI_DECODER_ERROR_FORMAT_CL_SPACE: number; - const BROTLI_DECODER_ERROR_FORMAT_CONTEXT_MAP_REPEAT: number; - const BROTLI_DECODER_ERROR_FORMAT_DICTIONARY: number; - const BROTLI_DECODER_ERROR_FORMAT_DISTANCE: number; - const BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_META_NIBBLE: number; - const BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_NIBBLE: number; - const BROTLI_DECODER_ERROR_FORMAT_HUFFMAN_SPACE: number; - const BROTLI_DECODER_ERROR_FORMAT_PADDING_1: number; - const BROTLI_DECODER_ERROR_FORMAT_PADDING_2: number; - const BROTLI_DECODER_ERROR_FORMAT_RESERVED: number; - const BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_ALPHABET: number; - const BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_SAME: number; - const BROTLI_DECODER_ERROR_FORMAT_TRANSFORM: number; - const BROTLI_DECODER_ERROR_FORMAT_WINDOW_BITS: number; - const BROTLI_DECODER_ERROR_INVALID_ARGUMENTS: number; - const BROTLI_DECODER_ERROR_UNREACHABLE: number; - const BROTLI_DECODER_NEEDS_MORE_INPUT: number; - const BROTLI_DECODER_NEEDS_MORE_OUTPUT: number; - const BROTLI_DECODER_NO_ERROR: number; - const BROTLI_DECODER_PARAM_DISABLE_RING_BUFFER_REALLOCATION: number; - const BROTLI_DECODER_PARAM_LARGE_WINDOW: number; - const BROTLI_DECODER_RESULT_ERROR: number; - const BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT: number; - const BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT: number; - const BROTLI_DECODER_RESULT_SUCCESS: number; - const BROTLI_DECODER_SUCCESS: number; - - const BROTLI_DEFAULT_MODE: number; - const BROTLI_DEFAULT_QUALITY: number; - const BROTLI_DEFAULT_WINDOW: number; - const BROTLI_ENCODE: number; - const BROTLI_LARGE_MAX_WINDOW_BITS: number; - const BROTLI_MAX_INPUT_BLOCK_BITS: number; - const BROTLI_MAX_QUALITY: number; - const BROTLI_MAX_WINDOW_BITS: number; - const BROTLI_MIN_INPUT_BLOCK_BITS: number; - const BROTLI_MIN_QUALITY: number; - const BROTLI_MIN_WINDOW_BITS: number; - - const BROTLI_MODE_FONT: number; - const BROTLI_MODE_GENERIC: number; - const BROTLI_MODE_TEXT: number; - - const BROTLI_OPERATION_EMIT_METADATA: number; - const BROTLI_OPERATION_FINISH: number; - const BROTLI_OPERATION_FLUSH: number; - const BROTLI_OPERATION_PROCESS: number; - - const BROTLI_PARAM_DISABLE_LITERAL_CONTEXT_MODELING: number; - const BROTLI_PARAM_LARGE_WINDOW: number; - const BROTLI_PARAM_LGBLOCK: number; - const BROTLI_PARAM_LGWIN: number; - const BROTLI_PARAM_MODE: number; - const BROTLI_PARAM_NDIRECT: number; - const BROTLI_PARAM_NPOSTFIX: number; - const BROTLI_PARAM_QUALITY: number; - const BROTLI_PARAM_SIZE_HINT: number; - - const DEFLATE: number; - const DEFLATERAW: number; - const GUNZIP: number; - const GZIP: number; - const INFLATE: number; - const INFLATERAW: number; - const UNZIP: number; - - const Z_BEST_COMPRESSION: number; - const Z_BEST_SPEED: number; - const Z_BLOCK: number; - const Z_BUF_ERROR: number; - const Z_DATA_ERROR: number; - - const Z_DEFAULT_CHUNK: number; - const Z_DEFAULT_COMPRESSION: number; - const Z_DEFAULT_LEVEL: number; - const Z_DEFAULT_MEMLEVEL: number; - const Z_DEFAULT_STRATEGY: number; - const Z_DEFAULT_WINDOWBITS: number; - - const Z_ERRNO: number; - const Z_FILTERED: number; - const Z_FINISH: number; - const Z_FIXED: number; - const Z_FULL_FLUSH: number; - const Z_HUFFMAN_ONLY: number; - const Z_MAX_CHUNK: number; - const Z_MAX_LEVEL: number; - const Z_MAX_MEMLEVEL: number; - const Z_MAX_WINDOWBITS: number; - const Z_MEM_ERROR: number; - const Z_MIN_CHUNK: number; - const Z_MIN_LEVEL: number; - const Z_MIN_MEMLEVEL: number; - const Z_MIN_WINDOWBITS: number; - const Z_NEED_DICT: number; - const Z_NO_COMPRESSION: number; - const Z_NO_FLUSH: number; - const Z_OK: number; - const Z_PARTIAL_FLUSH: number; - const Z_RLE: number; - const Z_STREAM_END: number; - const Z_STREAM_ERROR: number; - const Z_SYNC_FLUSH: number; - const Z_VERSION_ERROR: number; - const ZLIB_VERNUM: number; - } - - /** - * @deprecated - */ - const Z_NO_FLUSH: number; - /** - * @deprecated - */ - const Z_PARTIAL_FLUSH: number; - /** - * @deprecated - */ - const Z_SYNC_FLUSH: number; - /** - * @deprecated - */ - const Z_FULL_FLUSH: number; - /** - * @deprecated - */ - const Z_FINISH: number; - /** - * @deprecated - */ - const Z_BLOCK: number; - /** - * @deprecated - */ - const Z_TREES: number; - /** - * @deprecated - */ - const Z_OK: number; - /** - * @deprecated - */ - const Z_STREAM_END: number; - /** - * @deprecated - */ - const Z_NEED_DICT: number; - /** - * @deprecated - */ - const Z_ERRNO: number; - /** - * @deprecated - */ - const Z_STREAM_ERROR: number; - /** - * @deprecated - */ - const Z_DATA_ERROR: number; - /** - * @deprecated - */ - const Z_MEM_ERROR: number; - /** - * @deprecated - */ - const Z_BUF_ERROR: number; - /** - * @deprecated - */ - const Z_VERSION_ERROR: number; - /** - * @deprecated - */ - const Z_NO_COMPRESSION: number; - /** - * @deprecated - */ - const Z_BEST_SPEED: number; - /** - * @deprecated - */ - const Z_BEST_COMPRESSION: number; - /** - * @deprecated - */ - const Z_DEFAULT_COMPRESSION: number; - /** - * @deprecated - */ - const Z_FILTERED: number; - /** - * @deprecated - */ - const Z_HUFFMAN_ONLY: number; - /** - * @deprecated - */ - const Z_RLE: number; - /** - * @deprecated - */ - const Z_FIXED: number; - /** - * @deprecated - */ - const Z_DEFAULT_STRATEGY: number; - /** - * @deprecated - */ - const Z_BINARY: number; - /** - * @deprecated - */ - const Z_TEXT: number; - /** - * @deprecated - */ - const Z_ASCII: number; - /** - * @deprecated - */ - const Z_UNKNOWN: number; - /** - * @deprecated - */ - const Z_DEFLATED: number; -} diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/accepts/HISTORY.md b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/accepts/HISTORY.md deleted file mode 100644 index 0bf041781d..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/accepts/HISTORY.md +++ /dev/null @@ -1,236 +0,0 @@ -1.3.7 / 2019-04-29 -================== - - * deps: negotiator@0.6.2 - - Fix sorting charset, encoding, and language with extra parameters - -1.3.6 / 2019-04-28 -================== - - * deps: mime-types@~2.1.24 - - deps: mime-db@~1.40.0 - -1.3.5 / 2018-02-28 -================== - - * deps: mime-types@~2.1.18 - - deps: mime-db@~1.33.0 - -1.3.4 / 2017-08-22 -================== - - * deps: mime-types@~2.1.16 - - deps: mime-db@~1.29.0 - -1.3.3 / 2016-05-02 -================== - - * deps: mime-types@~2.1.11 - - deps: mime-db@~1.23.0 - * deps: negotiator@0.6.1 - - perf: improve `Accept` parsing speed - - perf: improve `Accept-Charset` parsing speed - - perf: improve `Accept-Encoding` parsing speed - - perf: improve `Accept-Language` parsing speed - -1.3.2 / 2016-03-08 -================== - - * deps: mime-types@~2.1.10 - - Fix extension of `application/dash+xml` - - Update primary extension for `audio/mp4` - - deps: mime-db@~1.22.0 - -1.3.1 / 2016-01-19 -================== - - * deps: mime-types@~2.1.9 - - deps: mime-db@~1.21.0 - -1.3.0 / 2015-09-29 -================== - - * deps: mime-types@~2.1.7 - - deps: mime-db@~1.19.0 - * deps: negotiator@0.6.0 - - Fix including type extensions in parameters in `Accept` parsing - - Fix parsing `Accept` parameters with quoted equals - - Fix parsing `Accept` parameters with quoted semicolons - - Lazy-load modules from main entry point - - perf: delay type concatenation until needed - - perf: enable strict mode - - perf: hoist regular expressions - - perf: remove closures getting spec properties - - perf: remove a closure from media type parsing - - perf: remove property delete from media type parsing - -1.2.13 / 2015-09-06 -=================== - - * deps: mime-types@~2.1.6 - - deps: mime-db@~1.18.0 - -1.2.12 / 2015-07-30 -=================== - - * deps: mime-types@~2.1.4 - - deps: mime-db@~1.16.0 - -1.2.11 / 2015-07-16 -=================== - - * deps: mime-types@~2.1.3 - - deps: mime-db@~1.15.0 - -1.2.10 / 2015-07-01 -=================== - - * deps: mime-types@~2.1.2 - - deps: mime-db@~1.14.0 - -1.2.9 / 2015-06-08 -================== - - * deps: mime-types@~2.1.1 - - perf: fix deopt during mapping - -1.2.8 / 2015-06-07 -================== - - * deps: mime-types@~2.1.0 - - deps: mime-db@~1.13.0 - * perf: avoid argument reassignment & argument slice - * perf: avoid negotiator recursive construction - * perf: enable strict mode - * perf: remove unnecessary bitwise operator - -1.2.7 / 2015-05-10 -================== - - * deps: negotiator@0.5.3 - - Fix media type parameter matching to be case-insensitive - -1.2.6 / 2015-05-07 -================== - - * deps: mime-types@~2.0.11 - - deps: mime-db@~1.9.1 - * deps: negotiator@0.5.2 - - Fix comparing media types with quoted values - - Fix splitting media types with quoted commas - -1.2.5 / 2015-03-13 -================== - - * deps: mime-types@~2.0.10 - - deps: mime-db@~1.8.0 - -1.2.4 / 2015-02-14 -================== - - * Support Node.js 0.6 - * deps: mime-types@~2.0.9 - - deps: mime-db@~1.7.0 - * deps: negotiator@0.5.1 - - Fix preference sorting to be stable for long acceptable lists - -1.2.3 / 2015-01-31 -================== - - * deps: mime-types@~2.0.8 - - deps: mime-db@~1.6.0 - -1.2.2 / 2014-12-30 -================== - - * deps: mime-types@~2.0.7 - - deps: mime-db@~1.5.0 - -1.2.1 / 2014-12-30 -================== - - * deps: mime-types@~2.0.5 - - deps: mime-db@~1.3.1 - -1.2.0 / 2014-12-19 -================== - - * deps: negotiator@0.5.0 - - Fix list return order when large accepted list - - Fix missing identity encoding when q=0 exists - - Remove dynamic building of Negotiator class - -1.1.4 / 2014-12-10 -================== - - * deps: mime-types@~2.0.4 - - deps: mime-db@~1.3.0 - -1.1.3 / 2014-11-09 -================== - - * deps: mime-types@~2.0.3 - - deps: mime-db@~1.2.0 - -1.1.2 / 2014-10-14 -================== - - * deps: negotiator@0.4.9 - - Fix error when media type has invalid parameter - -1.1.1 / 2014-09-28 -================== - - * deps: mime-types@~2.0.2 - - deps: mime-db@~1.1.0 - * deps: negotiator@0.4.8 - - Fix all negotiations to be case-insensitive - - Stable sort preferences of same quality according to client order - -1.1.0 / 2014-09-02 -================== - - * update `mime-types` - -1.0.7 / 2014-07-04 -================== - - * Fix wrong type returned from `type` when match after unknown extension - -1.0.6 / 2014-06-24 -================== - - * deps: negotiator@0.4.7 - -1.0.5 / 2014-06-20 -================== - - * fix crash when unknown extension given - -1.0.4 / 2014-06-19 -================== - - * use `mime-types` - -1.0.3 / 2014-06-11 -================== - - * deps: negotiator@0.4.6 - - Order by specificity when quality is the same - -1.0.2 / 2014-05-29 -================== - - * Fix interpretation when header not in request - * deps: pin negotiator@0.4.5 - -1.0.1 / 2014-01-18 -================== - - * Identity encoding isn't always acceptable - * deps: negotiator@~0.4.0 - -1.0.0 / 2013-12-27 -================== - - * Genesis diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/accepts/LICENSE b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/accepts/LICENSE deleted file mode 100644 index 06166077be..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/accepts/LICENSE +++ /dev/null @@ -1,23 +0,0 @@ -(The MIT License) - -Copyright (c) 2014 Jonathan Ong -Copyright (c) 2015 Douglas Christopher Wilson - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -'Software'), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/accepts/README.md b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/accepts/README.md deleted file mode 100644 index 66a2f5400f..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/accepts/README.md +++ /dev/null @@ -1,142 +0,0 @@ -# accepts - -[![NPM Version][npm-version-image]][npm-url] -[![NPM Downloads][npm-downloads-image]][npm-url] -[![Node.js Version][node-version-image]][node-version-url] -[![Build Status][travis-image]][travis-url] -[![Test Coverage][coveralls-image]][coveralls-url] - -Higher level content negotiation based on [negotiator](https://www.npmjs.com/package/negotiator). -Extracted from [koa](https://www.npmjs.com/package/koa) for general use. - -In addition to negotiator, it allows: - -- Allows types as an array or arguments list, ie `(['text/html', 'application/json'])` - as well as `('text/html', 'application/json')`. -- Allows type shorthands such as `json`. -- Returns `false` when no types match -- Treats non-existent headers as `*` - -## Installation - -This is a [Node.js](https://nodejs.org/en/) module available through the -[npm registry](https://www.npmjs.com/). Installation is done using the -[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): - -```sh -$ npm install accepts -``` - -## API - - - -```js -var accepts = require('accepts') -``` - -### accepts(req) - -Create a new `Accepts` object for the given `req`. - -#### .charset(charsets) - -Return the first accepted charset. If nothing in `charsets` is accepted, -then `false` is returned. - -#### .charsets() - -Return the charsets that the request accepts, in the order of the client's -preference (most preferred first). - -#### .encoding(encodings) - -Return the first accepted encoding. If nothing in `encodings` is accepted, -then `false` is returned. - -#### .encodings() - -Return the encodings that the request accepts, in the order of the client's -preference (most preferred first). - -#### .language(languages) - -Return the first accepted language. If nothing in `languages` is accepted, -then `false` is returned. - -#### .languages() - -Return the languages that the request accepts, in the order of the client's -preference (most preferred first). - -#### .type(types) - -Return the first accepted type (and it is returned as the same text as what -appears in the `types` array). If nothing in `types` is accepted, then `false` -is returned. - -The `types` array can contain full MIME types or file extensions. Any value -that is not a full MIME types is passed to `require('mime-types').lookup`. - -#### .types() - -Return the types that the request accepts, in the order of the client's -preference (most preferred first). - -## Examples - -### Simple type negotiation - -This simple example shows how to use `accepts` to return a different typed -respond body based on what the client wants to accept. The server lists it's -preferences in order and will get back the best match between the client and -server. - -```js -var accepts = require('accepts') -var http = require('http') - -function app (req, res) { - var accept = accepts(req) - - // the order of this list is significant; should be server preferred order - switch (accept.type(['json', 'html'])) { - case 'json': - res.setHeader('Content-Type', 'application/json') - res.write('{"hello":"world!"}') - break - case 'html': - res.setHeader('Content-Type', 'text/html') - res.write('hello, world!') - break - default: - // the fallback is text/plain, so no need to specify it above - res.setHeader('Content-Type', 'text/plain') - res.write('hello, world!') - break - } - - res.end() -} - -http.createServer(app).listen(3000) -``` - -You can test this out with the cURL program: -```sh -curl -I -H'Accept: text/html' http://localhost:3000/ -``` - -## License - -[MIT](LICENSE) - -[coveralls-image]: https://badgen.net/coveralls/c/github/jshttp/accepts/master -[coveralls-url]: https://coveralls.io/r/jshttp/accepts?branch=master -[node-version-image]: https://badgen.net/npm/node/accepts -[node-version-url]: https://nodejs.org/en/download -[npm-downloads-image]: https://badgen.net/npm/dm/accepts -[npm-url]: https://npmjs.org/package/accepts -[npm-version-image]: https://badgen.net/npm/v/accepts -[travis-image]: https://badgen.net/travis/jshttp/accepts/master -[travis-url]: https://travis-ci.org/jshttp/accepts diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/accepts/index.js b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/accepts/index.js deleted file mode 100644 index e9b2f63fb1..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/accepts/index.js +++ /dev/null @@ -1,238 +0,0 @@ -/*! - * accepts - * Copyright(c) 2014 Jonathan Ong - * Copyright(c) 2015 Douglas Christopher Wilson - * MIT Licensed - */ - -'use strict' - -/** - * Module dependencies. - * @private - */ - -var Negotiator = require('negotiator') -var mime = require('mime-types') - -/** - * Module exports. - * @public - */ - -module.exports = Accepts - -/** - * Create a new Accepts object for the given req. - * - * @param {object} req - * @public - */ - -function Accepts (req) { - if (!(this instanceof Accepts)) { - return new Accepts(req) - } - - this.headers = req.headers - this.negotiator = new Negotiator(req) -} - -/** - * Check if the given `type(s)` is acceptable, returning - * the best match when true, otherwise `undefined`, in which - * case you should respond with 406 "Not Acceptable". - * - * The `type` value may be a single mime type string - * such as "application/json", the extension name - * such as "json" or an array `["json", "html", "text/plain"]`. When a list - * or array is given the _best_ match, if any is returned. - * - * Examples: - * - * // Accept: text/html - * this.types('html'); - * // => "html" - * - * // Accept: text/*, application/json - * this.types('html'); - * // => "html" - * this.types('text/html'); - * // => "text/html" - * this.types('json', 'text'); - * // => "json" - * this.types('application/json'); - * // => "application/json" - * - * // Accept: text/*, application/json - * this.types('image/png'); - * this.types('png'); - * // => undefined - * - * // Accept: text/*;q=.5, application/json - * this.types(['html', 'json']); - * this.types('html', 'json'); - * // => "json" - * - * @param {String|Array} types... - * @return {String|Array|Boolean} - * @public - */ - -Accepts.prototype.type = -Accepts.prototype.types = function (types_) { - var types = types_ - - // support flattened arguments - if (types && !Array.isArray(types)) { - types = new Array(arguments.length) - for (var i = 0; i < types.length; i++) { - types[i] = arguments[i] - } - } - - // no types, return all requested types - if (!types || types.length === 0) { - return this.negotiator.mediaTypes() - } - - // no accept header, return first given type - if (!this.headers.accept) { - return types[0] - } - - var mimes = types.map(extToMime) - var accepts = this.negotiator.mediaTypes(mimes.filter(validMime)) - var first = accepts[0] - - return first - ? types[mimes.indexOf(first)] - : false -} - -/** - * Return accepted encodings or best fit based on `encodings`. - * - * Given `Accept-Encoding: gzip, deflate` - * an array sorted by quality is returned: - * - * ['gzip', 'deflate'] - * - * @param {String|Array} encodings... - * @return {String|Array} - * @public - */ - -Accepts.prototype.encoding = -Accepts.prototype.encodings = function (encodings_) { - var encodings = encodings_ - - // support flattened arguments - if (encodings && !Array.isArray(encodings)) { - encodings = new Array(arguments.length) - for (var i = 0; i < encodings.length; i++) { - encodings[i] = arguments[i] - } - } - - // no encodings, return all requested encodings - if (!encodings || encodings.length === 0) { - return this.negotiator.encodings() - } - - return this.negotiator.encodings(encodings)[0] || false -} - -/** - * Return accepted charsets or best fit based on `charsets`. - * - * Given `Accept-Charset: utf-8, iso-8859-1;q=0.2, utf-7;q=0.5` - * an array sorted by quality is returned: - * - * ['utf-8', 'utf-7', 'iso-8859-1'] - * - * @param {String|Array} charsets... - * @return {String|Array} - * @public - */ - -Accepts.prototype.charset = -Accepts.prototype.charsets = function (charsets_) { - var charsets = charsets_ - - // support flattened arguments - if (charsets && !Array.isArray(charsets)) { - charsets = new Array(arguments.length) - for (var i = 0; i < charsets.length; i++) { - charsets[i] = arguments[i] - } - } - - // no charsets, return all requested charsets - if (!charsets || charsets.length === 0) { - return this.negotiator.charsets() - } - - return this.negotiator.charsets(charsets)[0] || false -} - -/** - * Return accepted languages or best fit based on `langs`. - * - * Given `Accept-Language: en;q=0.8, es, pt` - * an array sorted by quality is returned: - * - * ['es', 'pt', 'en'] - * - * @param {String|Array} langs... - * @return {Array|String} - * @public - */ - -Accepts.prototype.lang = -Accepts.prototype.langs = -Accepts.prototype.language = -Accepts.prototype.languages = function (languages_) { - var languages = languages_ - - // support flattened arguments - if (languages && !Array.isArray(languages)) { - languages = new Array(arguments.length) - for (var i = 0; i < languages.length; i++) { - languages[i] = arguments[i] - } - } - - // no languages, return all requested languages - if (!languages || languages.length === 0) { - return this.negotiator.languages() - } - - return this.negotiator.languages(languages)[0] || false -} - -/** - * Convert extnames to mime. - * - * @param {String} type - * @return {String} - * @private - */ - -function extToMime (type) { - return type.indexOf('/') === -1 - ? mime.lookup(type) - : type -} - -/** - * Check if mime is valid. - * - * @param {String} type - * @return {String} - * @private - */ - -function validMime (type) { - return typeof type === 'string' -} diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/accepts/package.json b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/accepts/package.json deleted file mode 100644 index f36a7f3c5f..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/accepts/package.json +++ /dev/null @@ -1,86 +0,0 @@ -{ - "_from": "accepts@~1.3.7", - "_id": "accepts@1.3.7", - "_inBundle": false, - "_integrity": "sha512-Il80Qs2WjYlJIBNzNkK6KYqlVMTbZLXgHx2oT0pU/fjRHyEp+PEfEPY0R3WCwAGVOtauxh1hOxNgIf5bv7dQpA==", - "_location": "/accepts", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "accepts@~1.3.7", - "name": "accepts", - "escapedName": "accepts", - "rawSpec": "~1.3.7", - "saveSpec": null, - "fetchSpec": "~1.3.7" - }, - "_requiredBy": [ - "/express" - ], - "_resolved": "https://registry.npmjs.org/accepts/-/accepts-1.3.7.tgz", - "_shasum": "531bc726517a3b2b41f850021c6cc15eaab507cd", - "_spec": "accepts@~1.3.7", - "_where": "/home/jan/Documents/skweb/node_modules/express", - "bugs": { - "url": "https://github.com/jshttp/accepts/issues" - }, - "bundleDependencies": false, - "contributors": [ - { - "name": "Douglas Christopher Wilson", - "email": "doug@somethingdoug.com" - }, - { - "name": "Jonathan Ong", - "email": "me@jongleberry.com", - "url": "http://jongleberry.com" - } - ], - "dependencies": { - "mime-types": "~2.1.24", - "negotiator": "0.6.2" - }, - "deprecated": false, - "description": "Higher-level content negotiation", - "devDependencies": { - "deep-equal": "1.0.1", - "eslint": "5.16.0", - "eslint-config-standard": "12.0.0", - "eslint-plugin-import": "2.17.2", - "eslint-plugin-markdown": "1.0.0", - "eslint-plugin-node": "8.0.1", - "eslint-plugin-promise": "4.1.1", - "eslint-plugin-standard": "4.0.0", - "mocha": "6.1.4", - "nyc": "14.0.0" - }, - "engines": { - "node": ">= 0.6" - }, - "files": [ - "LICENSE", - "HISTORY.md", - "index.js" - ], - "homepage": "https://github.com/jshttp/accepts#readme", - "keywords": [ - "content", - "negotiation", - "accept", - "accepts" - ], - "license": "MIT", - "name": "accepts", - "repository": { - "type": "git", - "url": "git+https://github.com/jshttp/accepts.git" - }, - "scripts": { - "lint": "eslint --plugin markdown --ext js,md .", - "test": "mocha --reporter spec --check-leaks --bail test/", - "test-cov": "nyc --reporter=html --reporter=text npm test", - "test-travis": "nyc --reporter=text npm test" - }, - "version": "1.3.7" -} diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/adm-zip/LICENSE b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/adm-zip/LICENSE deleted file mode 100644 index ea38ade97d..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/adm-zip/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -Copyright (c) 2012 Another-D-Mention Software and other contributors, -http://www.another-d-mention.ro/ - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -"Software"), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/adm-zip/README.md b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/adm-zip/README.md deleted file mode 100644 index 172b911191..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/adm-zip/README.md +++ /dev/null @@ -1,65 +0,0 @@ -# ADM-ZIP for NodeJS with added support for electron original-fs - -ADM-ZIP is a pure JavaScript implementation for zip data compression for [NodeJS](https://nodejs.org/). - -# Installation - -With [npm](https://www.npmjs.com/) do: - - $ npm install adm-zip - -## What is it good for? -The library allows you to: - -* decompress zip files directly to disk or in memory buffers -* compress files and store them to disk in .zip format or in compressed buffers -* update content of/add new/delete files from an existing .zip - -# Dependencies -There are no other nodeJS libraries that ADM-ZIP is dependent of - -# Examples - -## Basic usage -```javascript - - var AdmZip = require('adm-zip'); - - // reading archives - var zip = new AdmZip("./my_file.zip"); - var zipEntries = zip.getEntries(); // an array of ZipEntry records - - zipEntries.forEach(function(zipEntry) { - console.log(zipEntry.toString()); // outputs zip entries information - if (zipEntry.entryName == "my_file.txt") { - console.log(zipEntry.getData().toString('utf8')); - } - }); - // outputs the content of some_folder/my_file.txt - console.log(zip.readAsText("some_folder/my_file.txt")); - // extracts the specified file to the specified location - zip.extractEntryTo(/*entry name*/"some_folder/my_file.txt", /*target path*/"/home/me/tempfolder", /*maintainEntryPath*/false, /*overwrite*/true); - // extracts everything - zip.extractAllTo(/*target path*/"/home/me/zipcontent/", /*overwrite*/true); - - - // creating archives - var zip = new AdmZip(); - - // add file directly - var content = "inner content of the file"; - zip.addFile("test.txt", Buffer.alloc(content.length, content), "entry comment goes here"); - // add local file - zip.addLocalFile("/home/me/some_picture.png"); - // get everything as a buffer - var willSendthis = zip.toBuffer(); - // or write everything to disk - zip.writeZip(/*target file name*/"/home/me/files.zip"); - - - // ... more examples in the wiki -``` - -For more detailed information please check out the [wiki](https://github.com/cthackers/adm-zip/wiki). - -[![Build Status](https://travis-ci.org/cthackers/adm-zip.svg?branch=master)](https://travis-ci.org/cthackers/adm-zip) diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/adm-zip/adm-zip.js b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/adm-zip/adm-zip.js deleted file mode 100644 index 619544db07..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/adm-zip/adm-zip.js +++ /dev/null @@ -1,639 +0,0 @@ -var Utils = require("./util"); -var fs = Utils.FileSystem.require(), - pth = require("path"); - -fs.existsSync = fs.existsSync || pth.existsSync; - -var ZipEntry = require("./zipEntry"), - ZipFile = require("./zipFile"); - -var isWin = /^win/.test(process.platform); - - -module.exports = function (/**String*/input) { - var _zip = undefined, - _filename = ""; - - if (input && typeof input === "string") { // load zip file - if (fs.existsSync(input)) { - _filename = input; - _zip = new ZipFile(input, Utils.Constants.FILE); - } else { - throw new Error(Utils.Errors.INVALID_FILENAME); - } - } else if (input && Buffer.isBuffer(input)) { // load buffer - _zip = new ZipFile(input, Utils.Constants.BUFFER); - } else { // create new zip file - _zip = new ZipFile(null, Utils.Constants.NONE); - } - - function sanitize(prefix, name) { - prefix = pth.resolve(pth.normalize(prefix)); - var parts = name.split('/'); - for (var i = 0, l = parts.length; i < l; i++) { - var path = pth.normalize(pth.join(prefix, parts.slice(i, l).join(pth.sep))); - if (path.indexOf(prefix) === 0) { - return path; - } - } - return pth.normalize(pth.join(prefix, pth.basename(name))); - } - - function getEntry(/**Object*/entry) { - if (entry && _zip) { - var item; - // If entry was given as a file name - if (typeof entry === "string") - item = _zip.getEntry(entry); - // if entry was given as a ZipEntry object - if (typeof entry === "object" && typeof entry.entryName !== "undefined" && typeof entry.header !== "undefined") - item = _zip.getEntry(entry.entryName); - - if (item) { - return item; - } - } - return null; - } - - return { - /** - * Extracts the given entry from the archive and returns the content as a Buffer object - * @param entry ZipEntry object or String with the full path of the entry - * - * @return Buffer or Null in case of error - */ - readFile: function (/**Object*/entry) { - var item = getEntry(entry); - return item && item.getData() || null; - }, - - /** - * Asynchronous readFile - * @param entry ZipEntry object or String with the full path of the entry - * @param callback - * - * @return Buffer or Null in case of error - */ - readFileAsync: function (/**Object*/entry, /**Function*/callback) { - var item = getEntry(entry); - if (item) { - item.getDataAsync(callback); - } else { - callback(null, "getEntry failed for:" + entry) - } - }, - - /** - * Extracts the given entry from the archive and returns the content as plain text in the given encoding - * @param entry ZipEntry object or String with the full path of the entry - * @param encoding Optional. If no encoding is specified utf8 is used - * - * @return String - */ - readAsText: function (/**Object*/entry, /**String=*/encoding) { - var item = getEntry(entry); - if (item) { - var data = item.getData(); - if (data && data.length) { - return data.toString(encoding || "utf8"); - } - } - return ""; - }, - - /** - * Asynchronous readAsText - * @param entry ZipEntry object or String with the full path of the entry - * @param callback - * @param encoding Optional. If no encoding is specified utf8 is used - * - * @return String - */ - readAsTextAsync: function (/**Object*/entry, /**Function*/callback, /**String=*/encoding) { - var item = getEntry(entry); - if (item) { - item.getDataAsync(function (data, err) { - if (err) { - callback(data, err); - return; - } - - if (data && data.length) { - callback(data.toString(encoding || "utf8")); - } else { - callback(""); - } - }) - } else { - callback(""); - } - }, - - /** - * Remove the entry from the file or the entry and all it's nested directories and files if the given entry is a directory - * - * @param entry - */ - deleteFile: function (/**Object*/entry) { // @TODO: test deleteFile - var item = getEntry(entry); - if (item) { - _zip.deleteEntry(item.entryName); - } - }, - - /** - * Adds a comment to the zip. The zip must be rewritten after adding the comment. - * - * @param comment - */ - addZipComment: function (/**String*/comment) { // @TODO: test addZipComment - _zip.comment = comment; - }, - - /** - * Returns the zip comment - * - * @return String - */ - getZipComment: function () { - return _zip.comment || ''; - }, - - /** - * Adds a comment to a specified zipEntry. The zip must be rewritten after adding the comment - * The comment cannot exceed 65535 characters in length - * - * @param entry - * @param comment - */ - addZipEntryComment: function (/**Object*/entry, /**String*/comment) { - var item = getEntry(entry); - if (item) { - item.comment = comment; - } - }, - - /** - * Returns the comment of the specified entry - * - * @param entry - * @return String - */ - getZipEntryComment: function (/**Object*/entry) { - var item = getEntry(entry); - if (item) { - return item.comment || ''; - } - return '' - }, - - /** - * Updates the content of an existing entry inside the archive. The zip must be rewritten after updating the content - * - * @param entry - * @param content - */ - updateFile: function (/**Object*/entry, /**Buffer*/content) { - var item = getEntry(entry); - if (item) { - item.setData(content); - } - }, - - /** - * Adds a file from the disk to the archive - * - * @param localPath File to add to zip - * @param zipPath Optional path inside the zip - * @param zipName Optional name for the file - */ - addLocalFile: function (/**String*/localPath, /**String=*/zipPath, /**String=*/zipName) { - if (fs.existsSync(localPath)) { - if (zipPath) { - zipPath = zipPath.split("\\").join("/"); - if (zipPath.charAt(zipPath.length - 1) !== "/") { - zipPath += "/"; - } - } else { - zipPath = ""; - } - var p = localPath.split("\\").join("/").split("/").pop(); - - if (zipName) { - this.addFile(zipPath + zipName, fs.readFileSync(localPath), "", 0) - } else { - this.addFile(zipPath + p, fs.readFileSync(localPath), "", 0) - } - } else { - throw new Error(Utils.Errors.FILE_NOT_FOUND.replace("%s", localPath)); - } - }, - - /** - * Adds a local directory and all its nested files and directories to the archive - * - * @param localPath - * @param zipPath optional path inside zip - * @param filter optional RegExp or Function if files match will - * be included. - */ - addLocalFolder: function (/**String*/localPath, /**String=*/zipPath, /**=RegExp|Function*/filter) { - if (filter === undefined) { - filter = function () { - return true; - }; - } else if (filter instanceof RegExp) { - filter = function (filter) { - return function (filename) { - return filter.test(filename); - } - }(filter); - } - - if (zipPath) { - zipPath = zipPath.split("\\").join("/"); - if (zipPath.charAt(zipPath.length - 1) !== "/") { - zipPath += "/"; - } - } else { - zipPath = ""; - } - // normalize the path first - localPath = pth.normalize(localPath); - localPath = localPath.split("\\").join("/"); //windows fix - if (localPath.charAt(localPath.length - 1) !== "/") - localPath += "/"; - - if (fs.existsSync(localPath)) { - - var items = Utils.findFiles(localPath), - self = this; - - if (items.length) { - items.forEach(function (path) { - var p = path.split("\\").join("/").replace(new RegExp(localPath.replace(/(\(|\)|\$)/g, '\\$1'), 'i'), ""); //windows fix - if (filter(p)) { - if (p.charAt(p.length - 1) !== "/") { - self.addFile(zipPath + p, fs.readFileSync(path), "", 0) - } else { - self.addFile(zipPath + p, Buffer.alloc(0), "", 0) - } - } - }); - } - } else { - throw new Error(Utils.Errors.FILE_NOT_FOUND.replace("%s", localPath)); - } - }, - - /** - * Asynchronous addLocalFile - * @param localPath - * @param callback - * @param zipPath optional path inside zip - * @param filter optional RegExp or Function if files match will - * be included. - */ - addLocalFolderAsync: function (/*String*/localPath, /*Function*/callback, /*String*/zipPath, /*RegExp|Function*/filter) { - if (filter === undefined) { - filter = function () { - return true; - }; - } else if (filter instanceof RegExp) { - filter = function (filter) { - return function (filename) { - return filter.test(filename); - } - }(filter); - } - - if (zipPath) { - zipPath = zipPath.split("\\").join("/"); - if (zipPath.charAt(zipPath.length - 1) !== "/") { - zipPath += "/"; - } - } else { - zipPath = ""; - } - // normalize the path first - localPath = pth.normalize(localPath); - localPath = localPath.split("\\").join("/"); //windows fix - if (localPath.charAt(localPath.length - 1) !== "/") - localPath += "/"; - - var self = this; - fs.open(localPath, 'r', function (err, fd) { - if (err && err.code === 'ENOENT') { - callback(undefined, Utils.Errors.FILE_NOT_FOUND.replace("%s", localPath)); - } else if (err) { - callback(undefined, err); - } else { - var items = Utils.findFiles(localPath); - var i = -1; - - var next = function () { - i += 1; - if (i < items.length) { - var p = items[i].split("\\").join("/").replace(new RegExp(localPath.replace(/(\(|\))/g, '\\$1'), 'i'), ""); //windows fix - p = p.normalize('NFD').replace(/[\u0300-\u036f]/g, '').replace(/[^\x20-\x7E]/g, '') // accent fix - if (filter(p)) { - if (p.charAt(p.length - 1) !== "/") { - fs.readFile(items[i], function (err, data) { - if (err) { - callback(undefined, err); - } else { - self.addFile(zipPath + p, data, '', 0); - next(); - } - }) - } else { - self.addFile(zipPath + p, Buffer.alloc(0), "", 0); - next(); - } - } else { - next(); - } - - } else { - callback(true, undefined); - } - } - - next(); - } - }); - }, - - /** - * Allows you to create a entry (file or directory) in the zip file. - * If you want to create a directory the entryName must end in / and a null buffer should be provided. - * Comment and attributes are optional - * - * @param entryName - * @param content - * @param comment - * @param attr - */ - addFile: function (/**String*/entryName, /**Buffer*/content, /**String*/comment, /**Number*/attr) { - var entry = new ZipEntry(); - entry.entryName = entryName; - entry.comment = comment || ""; - - if (!attr) { - if (entry.isDirectory) { - attr = (0o40755 << 16) | 0x10; // (permissions drwxr-xr-x) + (MS-DOS directory flag) - } else { - attr = 0o644 << 16; // permissions -r-wr--r-- - } - } - - entry.attr = attr; - - entry.setData(content); - _zip.setEntry(entry); - }, - - /** - * Returns an array of ZipEntry objects representing the files and folders inside the archive - * - * @return Array - */ - getEntries: function () { - if (_zip) { - return _zip.entries; - } else { - return []; - } - }, - - /** - * Returns a ZipEntry object representing the file or folder specified by ``name``. - * - * @param name - * @return ZipEntry - */ - getEntry: function (/**String*/name) { - return getEntry(name); - }, - - getEntryCount: function() { - return _zip.getEntryCount(); - }, - - forEach: function(callback) { - return _zip.forEach(callback); - }, - - /** - * Extracts the given entry to the given targetPath - * If the entry is a directory inside the archive, the entire directory and it's subdirectories will be extracted - * - * @param entry ZipEntry object or String with the full path of the entry - * @param targetPath Target folder where to write the file - * @param maintainEntryPath If maintainEntryPath is true and the entry is inside a folder, the entry folder - * will be created in targetPath as well. Default is TRUE - * @param overwrite If the file already exists at the target path, the file will be overwriten if this is true. - * Default is FALSE - * - * @return Boolean - */ - extractEntryTo: function (/**Object*/entry, /**String*/targetPath, /**Boolean*/maintainEntryPath, /**Boolean*/overwrite) { - overwrite = overwrite || false; - maintainEntryPath = typeof maintainEntryPath === "undefined" ? true : maintainEntryPath; - - var item = getEntry(entry); - if (!item) { - throw new Error(Utils.Errors.NO_ENTRY); - } - - var entryName = item.entryName; - - var target = sanitize(targetPath, maintainEntryPath ? entryName : pth.basename(entryName)); - - if (item.isDirectory) { - target = pth.resolve(target, ".."); - var children = _zip.getEntryChildren(item); - children.forEach(function (child) { - if (child.isDirectory) return; - var content = child.getData(); - if (!content) { - throw new Error(Utils.Errors.CANT_EXTRACT_FILE); - } - var childName = sanitize(targetPath, maintainEntryPath ? child.entryName : pth.basename(child.entryName)); - - Utils.writeFileTo(childName, content, overwrite); - }); - return true; - } - - var content = item.getData(); - if (!content) throw new Error(Utils.Errors.CANT_EXTRACT_FILE); - - if (fs.existsSync(target) && !overwrite) { - throw new Error(Utils.Errors.CANT_OVERRIDE); - } - Utils.writeFileTo(target, content, overwrite); - - return true; - }, - - /** - * Test the archive - * - */ - test: function () { - if (!_zip) { - return false; - } - - for (var entry in _zip.entries) { - try { - if (entry.isDirectory) { - continue; - } - var content = _zip.entries[entry].getData(); - if (!content) { - return false; - } - } catch (err) { - return false; - } - } - return true; - }, - - /** - * Extracts the entire archive to the given location - * - * @param targetPath Target location - * @param overwrite If the file already exists at the target path, the file will be overwriten if this is true. - * Default is FALSE - */ - extractAllTo: function (/**String*/targetPath, /**Boolean*/overwrite) { - overwrite = overwrite || false; - if (!_zip) { - throw new Error(Utils.Errors.NO_ZIP); - } - _zip.entries.forEach(function (entry) { - var entryName = sanitize(targetPath, entry.entryName.toString()); - if (entry.isDirectory) { - Utils.makeDir(entryName); - return; - } - var content = entry.getData(); - if (!content) { - throw new Error(Utils.Errors.CANT_EXTRACT_FILE); - } - Utils.writeFileTo(entryName, content, overwrite); - try { - fs.utimesSync(entryName, entry.header.time, entry.header.time) - } catch (err) { - throw new Error(Utils.Errors.CANT_EXTRACT_FILE); - } - }) - }, - - /** - * Asynchronous extractAllTo - * - * @param targetPath Target location - * @param overwrite If the file already exists at the target path, the file will be overwriten if this is true. - * Default is FALSE - * @param callback - */ - extractAllToAsync: function (/**String*/targetPath, /**Boolean*/overwrite, /**Function*/callback) { - if (!callback) { - callback = function() {} - } - overwrite = overwrite || false; - if (!_zip) { - callback(new Error(Utils.Errors.NO_ZIP)); - return; - } - - var entries = _zip.entries; - var i = entries.length; - entries.forEach(function (entry) { - if (i <= 0) return; // Had an error already - - var entryName = pth.normalize(entry.entryName.toString()); - - if (entry.isDirectory) { - Utils.makeDir(sanitize(targetPath, entryName)); - if (--i === 0) - callback(undefined); - return; - } - entry.getDataAsync(function (content, err) { - if (i <= 0) return; - if (err) { - callback(new Error(err)); - return; - } - if (!content) { - i = 0; - callback(new Error(Utils.Errors.CANT_EXTRACT_FILE)); - return; - } - - Utils.writeFileToAsync(sanitize(targetPath, entryName), content, overwrite, function (succ) { - try { - fs.utimesSync(pth.resolve(targetPath, entryName), entry.header.time, entry.header.time); - } catch (err) { - callback(new Error('Unable to set utimes')); - } - if (i <= 0) return; - if (!succ) { - i = 0; - callback(new Error('Unable to write')); - return; - } - if (--i === 0) - callback(undefined); - }); - }); - }) - }, - - /** - * Writes the newly created zip file to disk at the specified location or if a zip was opened and no ``targetFileName`` is provided, it will overwrite the opened zip - * - * @param targetFileName - * @param callback - */ - writeZip: function (/**String*/targetFileName, /**Function*/callback) { - if (arguments.length === 1) { - if (typeof targetFileName === "function") { - callback = targetFileName; - targetFileName = ""; - } - } - - if (!targetFileName && _filename) { - targetFileName = _filename; - } - if (!targetFileName) return; - - var zipData = _zip.compressToBuffer(); - if (zipData) { - var ok = Utils.writeFileTo(targetFileName, zipData, true); - if (typeof callback === 'function') callback(!ok ? new Error("failed") : null, ""); - } - }, - - /** - * Returns the content of the entire zip file as a Buffer object - * - * @return Buffer - */ - toBuffer: function (/**Function=*/onSuccess, /**Function=*/onFail, /**Function=*/onItemStart, /**Function=*/onItemEnd) { - this.valueOf = 2; - if (typeof onSuccess === "function") { - _zip.toAsyncBuffer(onSuccess, onFail, onItemStart, onItemEnd); - return null; - } - return _zip.compressToBuffer() - } - } -}; diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/adm-zip/headers/entryHeader.js b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/adm-zip/headers/entryHeader.js deleted file mode 100644 index 29cfaf9b5d..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/adm-zip/headers/entryHeader.js +++ /dev/null @@ -1,261 +0,0 @@ -var Utils = require("../util"), - Constants = Utils.Constants; - -/* The central directory file header */ -module.exports = function () { - var _verMade = 0x0A, - _version = 0x0A, - _flags = 0, - _method = 0, - _time = 0, - _crc = 0, - _compressedSize = 0, - _size = 0, - _fnameLen = 0, - _extraLen = 0, - - _comLen = 0, - _diskStart = 0, - _inattr = 0, - _attr = 0, - _offset = 0; - - var _dataHeader = {}; - - function setTime(val) { - val = new Date(val); - _time = (val.getFullYear() - 1980 & 0x7f) << 25 // b09-16 years from 1980 - | (val.getMonth() + 1) << 21 // b05-08 month - | val.getDate() << 16 // b00-04 hour - - // 2 bytes time - | val.getHours() << 11 // b11-15 hour - | val.getMinutes() << 5 // b05-10 minute - | val.getSeconds() >> 1; // b00-04 seconds divided by 2 - } - - setTime(+new Date()); - - return { - get made () { return _verMade; }, - set made (val) { _verMade = val; }, - - get version () { return _version; }, - set version (val) { _version = val }, - - get flags () { return _flags }, - set flags (val) { _flags = val; }, - - get method () { return _method; }, - set method (val) { _method = val; }, - - get time () { return new Date( - ((_time >> 25) & 0x7f) + 1980, - ((_time >> 21) & 0x0f) - 1, - (_time >> 16) & 0x1f, - (_time >> 11) & 0x1f, - (_time >> 5) & 0x3f, - (_time & 0x1f) << 1 - ); - }, - set time (val) { - setTime(val); - }, - - get crc () { return _crc; }, - set crc (val) { _crc = val; }, - - get compressedSize () { return _compressedSize; }, - set compressedSize (val) { _compressedSize = val; }, - - get size () { return _size; }, - set size (val) { _size = val; }, - - get fileNameLength () { return _fnameLen; }, - set fileNameLength (val) { _fnameLen = val; }, - - get extraLength () { return _extraLen }, - set extraLength (val) { _extraLen = val; }, - - get commentLength () { return _comLen }, - set commentLength (val) { _comLen = val }, - - get diskNumStart () { return _diskStart }, - set diskNumStart (val) { _diskStart = val }, - - get inAttr () { return _inattr }, - set inAttr (val) { _inattr = val }, - - get attr () { return _attr }, - set attr (val) { _attr = val }, - - get offset () { return _offset }, - set offset (val) { _offset = val }, - - get encripted () { return (_flags & 1) === 1 }, - - get entryHeaderSize () { - return Constants.CENHDR + _fnameLen + _extraLen + _comLen; - }, - - get realDataOffset () { - return _offset + Constants.LOCHDR + _dataHeader.fnameLen + _dataHeader.extraLen; - }, - - get dataHeader () { - return _dataHeader; - }, - - loadDataHeaderFromBinary : function(/*Buffer*/input) { - var data = input.slice(_offset, _offset + Constants.LOCHDR); - // 30 bytes and should start with "PK\003\004" - if (data.readUInt32LE(0) !== Constants.LOCSIG) { - throw new Error(Utils.Errors.INVALID_LOC); - } - _dataHeader = { - // version needed to extract - version : data.readUInt16LE(Constants.LOCVER), - // general purpose bit flag - flags : data.readUInt16LE(Constants.LOCFLG), - // compression method - method : data.readUInt16LE(Constants.LOCHOW), - // modification time (2 bytes time, 2 bytes date) - time : data.readUInt32LE(Constants.LOCTIM), - // uncompressed file crc-32 value - crc : data.readUInt32LE(Constants.LOCCRC), - // compressed size - compressedSize : data.readUInt32LE(Constants.LOCSIZ), - // uncompressed size - size : data.readUInt32LE(Constants.LOCLEN), - // filename length - fnameLen : data.readUInt16LE(Constants.LOCNAM), - // extra field length - extraLen : data.readUInt16LE(Constants.LOCEXT) - } - }, - - loadFromBinary : function(/*Buffer*/data) { - // data should be 46 bytes and start with "PK 01 02" - if (data.length !== Constants.CENHDR || data.readUInt32LE(0) !== Constants.CENSIG) { - throw new Error(Utils.Errors.INVALID_CEN); - } - // version made by - _verMade = data.readUInt16LE(Constants.CENVEM); - // version needed to extract - _version = data.readUInt16LE(Constants.CENVER); - // encrypt, decrypt flags - _flags = data.readUInt16LE(Constants.CENFLG); - // compression method - _method = data.readUInt16LE(Constants.CENHOW); - // modification time (2 bytes time, 2 bytes date) - _time = data.readUInt32LE(Constants.CENTIM); - // uncompressed file crc-32 value - _crc = data.readUInt32LE(Constants.CENCRC); - // compressed size - _compressedSize = data.readUInt32LE(Constants.CENSIZ); - // uncompressed size - _size = data.readUInt32LE(Constants.CENLEN); - // filename length - _fnameLen = data.readUInt16LE(Constants.CENNAM); - // extra field length - _extraLen = data.readUInt16LE(Constants.CENEXT); - // file comment length - _comLen = data.readUInt16LE(Constants.CENCOM); - // volume number start - _diskStart = data.readUInt16LE(Constants.CENDSK); - // internal file attributes - _inattr = data.readUInt16LE(Constants.CENATT); - // external file attributes - _attr = data.readUInt32LE(Constants.CENATX); - // LOC header offset - _offset = data.readUInt32LE(Constants.CENOFF); - }, - - dataHeaderToBinary : function() { - // LOC header size (30 bytes) - var data = Buffer.alloc(Constants.LOCHDR); - // "PK\003\004" - data.writeUInt32LE(Constants.LOCSIG, 0); - // version needed to extract - data.writeUInt16LE(_version, Constants.LOCVER); - // general purpose bit flag - data.writeUInt16LE(_flags, Constants.LOCFLG); - // compression method - data.writeUInt16LE(_method, Constants.LOCHOW); - // modification time (2 bytes time, 2 bytes date) - data.writeUInt32LE(_time, Constants.LOCTIM); - // uncompressed file crc-32 value - data.writeUInt32LE(_crc, Constants.LOCCRC); - // compressed size - data.writeUInt32LE(_compressedSize, Constants.LOCSIZ); - // uncompressed size - data.writeUInt32LE(_size, Constants.LOCLEN); - // filename length - data.writeUInt16LE(_fnameLen, Constants.LOCNAM); - // extra field length - data.writeUInt16LE(_extraLen, Constants.LOCEXT); - return data; - }, - - entryHeaderToBinary : function() { - // CEN header size (46 bytes) - var data = Buffer.alloc(Constants.CENHDR + _fnameLen + _extraLen + _comLen); - // "PK\001\002" - data.writeUInt32LE(Constants.CENSIG, 0); - // version made by - data.writeUInt16LE(_verMade, Constants.CENVEM); - // version needed to extract - data.writeUInt16LE(_version, Constants.CENVER); - // encrypt, decrypt flags - data.writeUInt16LE(_flags, Constants.CENFLG); - // compression method - data.writeUInt16LE(_method, Constants.CENHOW); - // modification time (2 bytes time, 2 bytes date) - data.writeUInt32LE(_time, Constants.CENTIM); - // uncompressed file crc-32 value - data.writeUInt32LE(_crc, Constants.CENCRC); - // compressed size - data.writeUInt32LE(_compressedSize, Constants.CENSIZ); - // uncompressed size - data.writeUInt32LE(_size, Constants.CENLEN); - // filename length - data.writeUInt16LE(_fnameLen, Constants.CENNAM); - // extra field length - data.writeUInt16LE(_extraLen, Constants.CENEXT); - // file comment length - data.writeUInt16LE(_comLen, Constants.CENCOM); - // volume number start - data.writeUInt16LE(_diskStart, Constants.CENDSK); - // internal file attributes - data.writeUInt16LE(_inattr, Constants.CENATT); - // external file attributes - data.writeUInt32LE(_attr, Constants.CENATX); - // LOC header offset - data.writeUInt32LE(_offset, Constants.CENOFF); - // fill all with - data.fill(0x00, Constants.CENHDR); - return data; - }, - - toString : function() { - return '{\n' + - '\t"made" : ' + _verMade + ",\n" + - '\t"version" : ' + _version + ",\n" + - '\t"flags" : ' + _flags + ",\n" + - '\t"method" : ' + Utils.methodToString(_method) + ",\n" + - '\t"time" : ' + this.time + ",\n" + - '\t"crc" : 0x' + _crc.toString(16).toUpperCase() + ",\n" + - '\t"compressedSize" : ' + _compressedSize + " bytes,\n" + - '\t"size" : ' + _size + " bytes,\n" + - '\t"fileNameLength" : ' + _fnameLen + ",\n" + - '\t"extraLength" : ' + _extraLen + " bytes,\n" + - '\t"commentLength" : ' + _comLen + " bytes,\n" + - '\t"diskNumStart" : ' + _diskStart + ",\n" + - '\t"inAttr" : ' + _inattr + ",\n" + - '\t"attr" : ' + _attr + ",\n" + - '\t"offset" : ' + _offset + ",\n" + - '\t"entryHeaderSize" : ' + (Constants.CENHDR + _fnameLen + _extraLen + _comLen) + " bytes\n" + - '}'; - } - } -}; diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/adm-zip/headers/index.js b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/adm-zip/headers/index.js deleted file mode 100644 index b8c67b96f6..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/adm-zip/headers/index.js +++ /dev/null @@ -1,2 +0,0 @@ -exports.EntryHeader = require("./entryHeader"); -exports.MainHeader = require("./mainHeader"); diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/adm-zip/headers/mainHeader.js b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/adm-zip/headers/mainHeader.js deleted file mode 100644 index 195f597b32..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/adm-zip/headers/mainHeader.js +++ /dev/null @@ -1,98 +0,0 @@ -var Utils = require("../util"), - Constants = Utils.Constants; - -/* The entries in the end of central directory */ -module.exports = function () { - var _volumeEntries = 0, - _totalEntries = 0, - _size = 0, - _offset = 0, - _commentLength = 0; - - return { - get diskEntries () { return _volumeEntries }, - set diskEntries (/*Number*/val) { _volumeEntries = _totalEntries = val; }, - - get totalEntries () { return _totalEntries }, - set totalEntries (/*Number*/val) { _totalEntries = _volumeEntries = val; }, - - get size () { return _size }, - set size (/*Number*/val) { _size = val; }, - - get offset () { return _offset }, - set offset (/*Number*/val) { _offset = val; }, - - get commentLength () { return _commentLength }, - set commentLength (/*Number*/val) { _commentLength = val; }, - - get mainHeaderSize () { - return Constants.ENDHDR + _commentLength; - }, - - loadFromBinary : function(/*Buffer*/data) { - // data should be 22 bytes and start with "PK 05 06" - // or be 56+ bytes and start with "PK 06 06" for Zip64 - if ((data.length !== Constants.ENDHDR || data.readUInt32LE(0) !== Constants.ENDSIG) && - (data.length < Constants.ZIP64HDR || data.readUInt32LE(0) !== Constants.ZIP64SIG)) { - - throw new Error(Utils.Errors.INVALID_END); - } - - if (data.readUInt32LE(0) === Constants.ENDSIG) { - // number of entries on this volume - _volumeEntries = data.readUInt16LE(Constants.ENDSUB); - // total number of entries - _totalEntries = data.readUInt16LE(Constants.ENDTOT); - // central directory size in bytes - _size = data.readUInt32LE(Constants.ENDSIZ); - // offset of first CEN header - _offset = data.readUInt32LE(Constants.ENDOFF); - // zip file comment length - _commentLength = data.readUInt16LE(Constants.ENDCOM); - } else { - // number of entries on this volume - _volumeEntries = Utils.readBigUInt64LE(data, Constants.ZIP64SUB); - // total number of entries - _totalEntries = Utils.readBigUInt64LE(data, Constants.ZIP64TOT); - // central directory size in bytes - _size = Utils.readBigUInt64LE(data, Constants.ZIP64SIZ); - // offset of first CEN header - _offset = Utils.readBigUInt64LE(data, Constants.ZIP64OFF); - - _commentLength = 0; - } - - }, - - toBinary : function() { - var b = Buffer.alloc(Constants.ENDHDR + _commentLength); - // "PK 05 06" signature - b.writeUInt32LE(Constants.ENDSIG, 0); - b.writeUInt32LE(0, 4); - // number of entries on this volume - b.writeUInt16LE(_volumeEntries, Constants.ENDSUB); - // total number of entries - b.writeUInt16LE(_totalEntries, Constants.ENDTOT); - // central directory size in bytes - b.writeUInt32LE(_size, Constants.ENDSIZ); - // offset of first CEN header - b.writeUInt32LE(_offset, Constants.ENDOFF); - // zip file comment length - b.writeUInt16LE(_commentLength, Constants.ENDCOM); - // fill comment memory with spaces so no garbage is left there - b.fill(" ", Constants.ENDHDR); - - return b; - }, - - toString : function() { - return '{\n' + - '\t"diskEntries" : ' + _volumeEntries + ",\n" + - '\t"totalEntries" : ' + _totalEntries + ",\n" + - '\t"size" : ' + _size + " bytes,\n" + - '\t"offset" : 0x' + _offset.toString(16).toUpperCase() + ",\n" + - '\t"commentLength" : 0x' + _commentLength + "\n" + - '}'; - } - } -}; \ No newline at end of file diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/adm-zip/methods/deflater.js b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/adm-zip/methods/deflater.js deleted file mode 100644 index 1208639288..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/adm-zip/methods/deflater.js +++ /dev/null @@ -1,31 +0,0 @@ -module.exports = function (/*Buffer*/inbuf) { - - var zlib = require("zlib"); - - var opts = {chunkSize: (parseInt(inbuf.length / 1024) + 1) * 1024}; - - return { - deflate: function () { - return zlib.deflateRawSync(inbuf, opts); - }, - - deflateAsync: function (/*Function*/callback) { - var tmp = zlib.createDeflateRaw(opts), parts = [], total = 0; - tmp.on('data', function (data) { - parts.push(data); - total += data.length; - }); - tmp.on('end', function () { - var buf = Buffer.alloc(total), written = 0; - buf.fill(0); - for (var i = 0; i < parts.length; i++) { - var part = parts[i]; - part.copy(buf, written); - written += part.length; - } - callback && callback(buf); - }); - tmp.end(inbuf); - } - } -}; diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/adm-zip/methods/index.js b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/adm-zip/methods/index.js deleted file mode 100644 index ddcbba6002..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/adm-zip/methods/index.js +++ /dev/null @@ -1,2 +0,0 @@ -exports.Deflater = require("./deflater"); -exports.Inflater = require("./inflater"); \ No newline at end of file diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/adm-zip/methods/inflater.js b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/adm-zip/methods/inflater.js deleted file mode 100644 index 2978110f57..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/adm-zip/methods/inflater.js +++ /dev/null @@ -1,29 +0,0 @@ -module.exports = function (/*Buffer*/inbuf) { - - var zlib = require("zlib"); - - return { - inflate: function () { - return zlib.inflateRawSync(inbuf); - }, - - inflateAsync: function (/*Function*/callback) { - var tmp = zlib.createInflateRaw(), parts = [], total = 0; - tmp.on('data', function (data) { - parts.push(data); - total += data.length; - }); - tmp.on('end', function () { - var buf = Buffer.alloc(total), written = 0; - buf.fill(0); - for (var i = 0; i < parts.length; i++) { - var part = parts[i]; - part.copy(buf, written); - written += part.length; - } - callback && callback(buf); - }); - tmp.end(inbuf); - } - } -}; diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/adm-zip/package.json b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/adm-zip/package.json deleted file mode 100644 index dd9c88ee56..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/adm-zip/package.json +++ /dev/null @@ -1,72 +0,0 @@ -{ - "_from": "adm-zip@^0.4.13", - "_id": "adm-zip@0.4.16", - "_inBundle": false, - "_integrity": "sha512-TFi4HBKSGfIKsK5YCkKaaFG2m4PEDyViZmEwof3MTIgzimHLto6muaHVpbrljdIvIrFZzEq/p4nafOeLcYegrg==", - "_location": "/adm-zip", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "adm-zip@^0.4.13", - "name": "adm-zip", - "escapedName": "adm-zip", - "rawSpec": "^0.4.13", - "saveSpec": null, - "fetchSpec": "^0.4.13" - }, - "_requiredBy": [ - "/cassandra-driver" - ], - "_resolved": "https://registry.npmjs.org/adm-zip/-/adm-zip-0.4.16.tgz", - "_shasum": "cf4c508fdffab02c269cbc7f471a875f05570365", - "_spec": "adm-zip@^0.4.13", - "_where": "/home/jan/Documents/skweb/node_modules/cassandra-driver", - "author": { - "name": "Nasca Iacob", - "email": "sy@another-d-mention.ro", - "url": "https://github.com/cthackers" - }, - "bugs": { - "url": "https://github.com/cthackers/adm-zip/issues", - "email": "sy@another-d-mention.ro" - }, - "bundleDependencies": false, - "deprecated": false, - "description": "Javascript implementation of zip for nodejs with support for electron original-fs. Allows user to create or extract zip files both in memory or to/from disk", - "devDependencies": { - "chai": "^4.1.2", - "mocha": "^8.0.1", - "rimraf": "^2.6.2" - }, - "engines": { - "node": ">=0.3.0" - }, - "files": [ - "adm-zip.js", - "headers", - "methods", - "util", - "zipEntry.js", - "zipFile.js", - "MIT-LICENSE.txt" - ], - "homepage": "https://github.com/cthackers/adm-zip", - "keywords": [ - "zip", - "methods", - "archive", - "unzip" - ], - "license": "MIT", - "main": "adm-zip.js", - "name": "adm-zip", - "repository": { - "type": "git", - "url": "git+https://github.com/cthackers/adm-zip.git" - }, - "scripts": { - "test": "mocha test/mocha.js test/crc/index.js" - }, - "version": "0.4.16" -} diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/adm-zip/util/constants.js b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/adm-zip/util/constants.js deleted file mode 100644 index 96a914d582..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/adm-zip/util/constants.js +++ /dev/null @@ -1,135 +0,0 @@ -module.exports = { - /* The local file header */ - LOCHDR : 30, // LOC header size - LOCSIG : 0x04034b50, // "PK\003\004" - LOCVER : 4, // version needed to extract - LOCFLG : 6, // general purpose bit flag - LOCHOW : 8, // compression method - LOCTIM : 10, // modification time (2 bytes time, 2 bytes date) - LOCCRC : 14, // uncompressed file crc-32 value - LOCSIZ : 18, // compressed size - LOCLEN : 22, // uncompressed size - LOCNAM : 26, // filename length - LOCEXT : 28, // extra field length - - /* The Data descriptor */ - EXTSIG : 0x08074b50, // "PK\007\008" - EXTHDR : 16, // EXT header size - EXTCRC : 4, // uncompressed file crc-32 value - EXTSIZ : 8, // compressed size - EXTLEN : 12, // uncompressed size - - /* The central directory file header */ - CENHDR : 46, // CEN header size - CENSIG : 0x02014b50, // "PK\001\002" - CENVEM : 4, // version made by - CENVER : 6, // version needed to extract - CENFLG : 8, // encrypt, decrypt flags - CENHOW : 10, // compression method - CENTIM : 12, // modification time (2 bytes time, 2 bytes date) - CENCRC : 16, // uncompressed file crc-32 value - CENSIZ : 20, // compressed size - CENLEN : 24, // uncompressed size - CENNAM : 28, // filename length - CENEXT : 30, // extra field length - CENCOM : 32, // file comment length - CENDSK : 34, // volume number start - CENATT : 36, // internal file attributes - CENATX : 38, // external file attributes (host system dependent) - CENOFF : 42, // LOC header offset - - /* The entries in the end of central directory */ - ENDHDR : 22, // END header size - ENDSIG : 0x06054b50, // "PK\005\006" - ENDSUB : 8, // number of entries on this disk - ENDTOT : 10, // total number of entries - ENDSIZ : 12, // central directory size in bytes - ENDOFF : 16, // offset of first CEN header - ENDCOM : 20, // zip file comment length - - END64HDR : 20, // zip64 END header size - END64SIG : 0x07064b50, // zip64 Locator signature, "PK\006\007" - END64START : 4, // number of the disk with the start of the zip64 - END64OFF : 8, // relative offset of the zip64 end of central directory - END64NUMDISKS : 16, // total number of disks - - ZIP64SIG : 0x06064b50, // zip64 signature, "PK\006\006" - ZIP64HDR : 56, // zip64 record minimum size - ZIP64LEAD : 12, // leading bytes at the start of the record, not counted by the value stored in ZIP64SIZE - ZIP64SIZE : 4, // zip64 size of the central directory record - ZIP64VEM : 12, // zip64 version made by - ZIP64VER : 14, // zip64 version needed to extract - ZIP64DSK : 16, // zip64 number of this disk - ZIP64DSKDIR : 20, // number of the disk with the start of the record directory - ZIP64SUB : 24, // number of entries on this disk - ZIP64TOT : 32, // total number of entries - ZIP64SIZB : 40, // zip64 central directory size in bytes - ZIP64OFF : 48, // offset of start of central directory with respect to the starting disk number - ZIP64EXTRA : 56, // extensible data sector - - /* Compression methods */ - STORED : 0, // no compression - SHRUNK : 1, // shrunk - REDUCED1 : 2, // reduced with compression factor 1 - REDUCED2 : 3, // reduced with compression factor 2 - REDUCED3 : 4, // reduced with compression factor 3 - REDUCED4 : 5, // reduced with compression factor 4 - IMPLODED : 6, // imploded - // 7 reserved - DEFLATED : 8, // deflated - ENHANCED_DEFLATED: 9, // enhanced deflated - PKWARE : 10,// PKWare DCL imploded - // 11 reserved - BZIP2 : 12, // compressed using BZIP2 - // 13 reserved - LZMA : 14, // LZMA - // 15-17 reserved - IBM_TERSE : 18, // compressed using IBM TERSE - IBM_LZ77 : 19, //IBM LZ77 z - - /* General purpose bit flag */ - FLG_ENC : 0, // encripted file - FLG_COMP1 : 1, // compression option - FLG_COMP2 : 2, // compression option - FLG_DESC : 4, // data descriptor - FLG_ENH : 8, // enhanced deflation - FLG_STR : 16, // strong encryption - FLG_LNG : 1024, // language encoding - FLG_MSK : 4096, // mask header values - - /* Load type */ - FILE : 0, - BUFFER : 1, - NONE : 2, - - /* 4.5 Extensible data fields */ - EF_ID : 0, - EF_SIZE : 2, - - /* Header IDs */ - ID_ZIP64 : 0x0001, - ID_AVINFO : 0x0007, - ID_PFS : 0x0008, - ID_OS2 : 0x0009, - ID_NTFS : 0x000a, - ID_OPENVMS : 0x000c, - ID_UNIX : 0x000d, - ID_FORK : 0x000e, - ID_PATCH : 0x000f, - ID_X509_PKCS7 : 0x0014, - ID_X509_CERTID_F : 0x0015, - ID_X509_CERTID_C : 0x0016, - ID_STRONGENC : 0x0017, - ID_RECORD_MGT : 0x0018, - ID_X509_PKCS7_RL : 0x0019, - ID_IBM1 : 0x0065, - ID_IBM2 : 0x0066, - ID_POSZIP : 0x4690, - - EF_ZIP64_OR_32 : 0xffffffff, - EF_ZIP64_OR_16 : 0xffff, - EF_ZIP64_SUNCOMP : 0, - EF_ZIP64_SCOMP : 8, - EF_ZIP64_RHO : 16, - EF_ZIP64_DSN : 24 -}; diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/adm-zip/util/errors.js b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/adm-zip/util/errors.js deleted file mode 100644 index db5d69e9a8..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/adm-zip/util/errors.js +++ /dev/null @@ -1,35 +0,0 @@ -module.exports = { - /* Header error messages */ - "INVALID_LOC" : "Invalid LOC header (bad signature)", - "INVALID_CEN" : "Invalid CEN header (bad signature)", - "INVALID_END" : "Invalid END header (bad signature)", - - /* ZipEntry error messages*/ - "NO_DATA" : "Nothing to decompress", - "BAD_CRC" : "CRC32 checksum failed", - "FILE_IN_THE_WAY" : "There is a file in the way: %s", - "UNKNOWN_METHOD" : "Invalid/unsupported compression method", - - /* Inflater error messages */ - "AVAIL_DATA" : "inflate::Available inflate data did not terminate", - "INVALID_DISTANCE" : "inflate::Invalid literal/length or distance code in fixed or dynamic block", - "TO_MANY_CODES" : "inflate::Dynamic block code description: too many length or distance codes", - "INVALID_REPEAT_LEN" : "inflate::Dynamic block code description: repeat more than specified lengths", - "INVALID_REPEAT_FIRST" : "inflate::Dynamic block code description: repeat lengths with no first length", - "INCOMPLETE_CODES" : "inflate::Dynamic block code description: code lengths codes incomplete", - "INVALID_DYN_DISTANCE": "inflate::Dynamic block code description: invalid distance code lengths", - "INVALID_CODES_LEN": "inflate::Dynamic block code description: invalid literal/length code lengths", - "INVALID_STORE_BLOCK" : "inflate::Stored block length did not match one's complement", - "INVALID_BLOCK_TYPE" : "inflate::Invalid block type (type == 3)", - - /* ADM-ZIP error messages */ - "CANT_EXTRACT_FILE" : "Could not extract the file", - "CANT_OVERRIDE" : "Target file already exists", - "NO_ZIP" : "No zip file was loaded", - "NO_ENTRY" : "Entry doesn't exist", - "DIRECTORY_CONTENT_ERROR" : "A directory cannot have content", - "FILE_NOT_FOUND" : "File not found: %s", - "NOT_IMPLEMENTED" : "Not implemented", - "INVALID_FILENAME" : "Invalid filename", - "INVALID_FORMAT" : "Invalid or unsupported zip format. No END header found" -}; \ No newline at end of file diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/adm-zip/util/fattr.js b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/adm-zip/util/fattr.js deleted file mode 100644 index b56fbd79a6..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/adm-zip/util/fattr.js +++ /dev/null @@ -1,84 +0,0 @@ -var fs = require("./fileSystem").require(), - pth = require("path"); - -fs.existsSync = fs.existsSync || pth.existsSync; - -module.exports = function(/*String*/path) { - - var _path = path || "", - _permissions = 0, - _obj = newAttr(), - _stat = null; - - function newAttr() { - return { - directory : false, - readonly : false, - hidden : false, - executable : false, - mtime : 0, - atime : 0 - } - } - - if (_path && fs.existsSync(_path)) { - _stat = fs.statSync(_path); - _obj.directory = _stat.isDirectory(); - _obj.mtime = _stat.mtime; - _obj.atime = _stat.atime; - _obj.executable = !!(1 & parseInt ((_stat.mode & parseInt ("777", 8)).toString (8)[0])); - _obj.readonly = !!(2 & parseInt ((_stat.mode & parseInt ("777", 8)).toString (8)[0])); - _obj.hidden = pth.basename(_path)[0] === "."; - } else { - console.warn("Invalid path: " + _path) - } - - return { - - get directory () { - return _obj.directory; - }, - - get readOnly () { - return _obj.readonly; - }, - - get hidden () { - return _obj.hidden; - }, - - get mtime () { - return _obj.mtime; - }, - - get atime () { - return _obj.atime; - }, - - - get executable () { - return _obj.executable; - }, - - decodeAttributes : function(val) { - - }, - - encodeAttributes : function (val) { - - }, - - toString : function() { - return '{\n' + - '\t"path" : "' + _path + ",\n" + - '\t"isDirectory" : ' + _obj.directory + ",\n" + - '\t"isReadOnly" : ' + _obj.readonly + ",\n" + - '\t"isHidden" : ' + _obj.hidden + ",\n" + - '\t"isExecutable" : ' + _obj.executable + ",\n" + - '\t"mTime" : ' + _obj.mtime + "\n" + - '\t"aTime" : ' + _obj.atime + "\n" + - '}'; - } - } - -}; diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/adm-zip/util/fileSystem.js b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/adm-zip/util/fileSystem.js deleted file mode 100644 index 801ebffd0c..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/adm-zip/util/fileSystem.js +++ /dev/null @@ -1,12 +0,0 @@ -exports.require = function() { - var fs = require("fs"); - if (process.versions['electron']) { - try { - originalFs = require("original-fs"); - if (Object.keys(originalFs).length > 0) { - fs = originalFs; - } - } catch (e) {} - } - return fs -}; diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/adm-zip/util/index.js b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/adm-zip/util/index.js deleted file mode 100644 index 70528f62de..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/adm-zip/util/index.js +++ /dev/null @@ -1,5 +0,0 @@ -module.exports = require("./utils"); -module.exports.FileSystem = require("./fileSystem"); -module.exports.Constants = require("./constants"); -module.exports.Errors = require("./errors"); -module.exports.FileAttr = require("./fattr"); \ No newline at end of file diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/adm-zip/util/utils.js b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/adm-zip/util/utils.js deleted file mode 100644 index a1c1b5c251..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/adm-zip/util/utils.js +++ /dev/null @@ -1,218 +0,0 @@ -var fs = require("./fileSystem").require(), - pth = require('path'); - -fs.existsSync = fs.existsSync || pth.existsSync; - -module.exports = (function() { - - var crcTable = [], - Constants = require('./constants'), - Errors = require('./errors'), - - PATH_SEPARATOR = pth.sep; - - - function mkdirSync(/*String*/path) { - var resolvedPath = path.split(PATH_SEPARATOR)[0]; - path.split(PATH_SEPARATOR).forEach(function(name) { - if (!name || name.substr(-1,1) === ":") return; - resolvedPath += PATH_SEPARATOR + name; - var stat; - try { - stat = fs.statSync(resolvedPath); - } catch (e) { - fs.mkdirSync(resolvedPath); - } - if (stat && stat.isFile()) - throw Errors.FILE_IN_THE_WAY.replace("%s", resolvedPath); - }); - } - - function findSync(/*String*/dir, /*RegExp*/pattern, /*Boolean*/recoursive) { - if (typeof pattern === 'boolean') { - recoursive = pattern; - pattern = undefined; - } - var files = []; - fs.readdirSync(dir).forEach(function(file) { - var path = pth.join(dir, file); - - if (fs.statSync(path).isDirectory() && recoursive) - files = files.concat(findSync(path, pattern, recoursive)); - - if (!pattern || pattern.test(path)) { - files.push(pth.normalize(path) + (fs.statSync(path).isDirectory() ? PATH_SEPARATOR : "")); - } - - }); - return files; - } - - function readBigUInt64LE(/*Buffer*/buffer, /*int*/index) { - var slice = Buffer.from(buffer.slice(index, index + 8)); - slice.swap64(); - - return parseInt(`0x${ slice.toString('hex') }`); - } - - return { - makeDir : function(/*String*/path) { - mkdirSync(path); - }, - - crc32 : function(buf) { - if (typeof buf === 'string') { - buf = Buffer.alloc(buf.length, buf); - } - var b = Buffer.alloc(4); - if (!crcTable.length) { - for (var n = 0; n < 256; n++) { - var c = n; - for (var k = 8; --k >= 0;) // - if ((c & 1) !== 0) { c = 0xedb88320 ^ (c >>> 1); } else { c = c >>> 1; } - if (c < 0) { - b.writeInt32LE(c, 0); - c = b.readUInt32LE(0); - } - crcTable[n] = c; - } - } - var crc = 0, off = 0, len = buf.length, c1 = ~crc; - while(--len >= 0) c1 = crcTable[(c1 ^ buf[off++]) & 0xff] ^ (c1 >>> 8); - crc = ~c1; - b.writeInt32LE(crc & 0xffffffff, 0); - return b.readUInt32LE(0); - }, - - methodToString : function(/*Number*/method) { - switch (method) { - case Constants.STORED: - return 'STORED (' + method + ')'; - case Constants.DEFLATED: - return 'DEFLATED (' + method + ')'; - default: - return 'UNSUPPORTED (' + method + ')'; - } - - }, - - writeFileTo : function(/*String*/path, /*Buffer*/content, /*Boolean*/overwrite, /*Number*/attr) { - if (fs.existsSync(path)) { - if (!overwrite) - return false; // cannot overwrite - - var stat = fs.statSync(path); - if (stat.isDirectory()) { - return false; - } - } - var folder = pth.dirname(path); - if (!fs.existsSync(folder)) { - mkdirSync(folder); - } - - var fd; - try { - fd = fs.openSync(path, 'w', 438); // 0666 - } catch(e) { - fs.chmodSync(path, 438); - fd = fs.openSync(path, 'w', 438); - } - if (fd) { - try { - fs.writeSync(fd, content, 0, content.length, 0); - } - catch (e){ - throw e; - } - finally { - fs.closeSync(fd); - } - } - fs.chmodSync(path, attr || 438); - return true; - }, - - writeFileToAsync : function(/*String*/path, /*Buffer*/content, /*Boolean*/overwrite, /*Number*/attr, /*Function*/callback) { - if(typeof attr === 'function') { - callback = attr; - attr = undefined; - } - - fs.exists(path, function(exists) { - if(exists && !overwrite) - return callback(false); - - fs.stat(path, function(err, stat) { - if(exists &&stat.isDirectory()) { - return callback(false); - } - - var folder = pth.dirname(path); - fs.exists(folder, function(exists) { - if(!exists) - mkdirSync(folder); - - fs.open(path, 'w', 438, function(err, fd) { - if(err) { - fs.chmod(path, 438, function() { - fs.open(path, 'w', 438, function(err, fd) { - fs.write(fd, content, 0, content.length, 0, function() { - fs.close(fd, function() { - fs.chmod(path, attr || 438, function() { - callback(true); - }) - }); - }); - }); - }) - } else { - if(fd) { - fs.write(fd, content, 0, content.length, 0, function() { - fs.close(fd, function() { - fs.chmod(path, attr || 438, function() { - callback(true); - }) - }); - }); - } else { - fs.chmod(path, attr || 438, function() { - callback(true); - }) - } - } - }); - }) - }) - }) - }, - - findFiles : function(/*String*/path) { - return findSync(path, true); - }, - - getAttributes : function(/*String*/path) { - - }, - - setAttributes : function(/*String*/path) { - - }, - - toBuffer : function(input) { - if (Buffer.isBuffer(input)) { - return input; - } else { - if (input.length === 0) { - return Buffer.alloc(0) - } - return Buffer.from(input, 'utf8'); - } - }, - - readBigUInt64LE, - - Constants : Constants, - Errors : Errors - } -})(); diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/adm-zip/zipEntry.js b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/adm-zip/zipEntry.js deleted file mode 100644 index 979f125639..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/adm-zip/zipEntry.js +++ /dev/null @@ -1,291 +0,0 @@ -var Utils = require("./util"), - Headers = require("./headers"), - Constants = Utils.Constants, - Methods = require("./methods"); - -module.exports = function (/*Buffer*/input) { - - var _entryHeader = new Headers.EntryHeader(), - _entryName = Buffer.alloc(0), - _comment = Buffer.alloc(0), - _isDirectory = false, - uncompressedData = null, - _extra = Buffer.alloc(0); - - function getCompressedDataFromZip() { - if (!input || !Buffer.isBuffer(input)) { - return Buffer.alloc(0); - } - _entryHeader.loadDataHeaderFromBinary(input); - return input.slice(_entryHeader.realDataOffset, _entryHeader.realDataOffset + _entryHeader.compressedSize) - } - - function crc32OK(data) { - // if bit 3 (0x08) of the general-purpose flags field is set, then the CRC-32 and file sizes are not known when the header is written - if ((_entryHeader.flags & 0x8) !== 0x8) { - if (Utils.crc32(data) !== _entryHeader.dataHeader.crc) { - return false; - } - } else { - // @TODO: load and check data descriptor header - // The fields in the local header are filled with zero, and the CRC-32 and size are appended in a 12-byte structure - // (optionally preceded by a 4-byte signature) immediately after the compressed data: - } - return true; - } - - function decompress(/*Boolean*/async, /*Function*/callback, /*String*/pass) { - if(typeof callback === 'undefined' && typeof async === 'string') { - pass=async; - async=void 0; - } - if (_isDirectory) { - if (async && callback) { - callback(Buffer.alloc(0), Utils.Errors.DIRECTORY_CONTENT_ERROR); //si added error. - } - return Buffer.alloc(0); - } - - var compressedData = getCompressedDataFromZip(); - - if (compressedData.length === 0) { - // File is empty, nothing to decompress. - if (async && callback) callback(compressedData); - return compressedData; - } - - var data = Buffer.alloc(_entryHeader.size); - - switch (_entryHeader.method) { - case Utils.Constants.STORED: - compressedData.copy(data); - if (!crc32OK(data)) { - if (async && callback) callback(data, Utils.Errors.BAD_CRC);//si added error - throw new Error(Utils.Errors.BAD_CRC); - } else {//si added otherwise did not seem to return data. - if (async && callback) callback(data); - return data; - } - case Utils.Constants.DEFLATED: - var inflater = new Methods.Inflater(compressedData); - if (!async) { - var result = inflater.inflate(data); - result.copy(data, 0); - if (!crc32OK(data)) { - throw new Error(Utils.Errors.BAD_CRC + " " + _entryName.toString()); - } - return data; - } else { - inflater.inflateAsync(function(result) { - result.copy(data, 0); - if (!crc32OK(data)) { - if (callback) callback(data, Utils.Errors.BAD_CRC); //si added error - } else { //si added otherwise did not seem to return data. - if (callback) callback(data); - } - }) - } - break; - default: - if (async && callback) callback(Buffer.alloc(0), Utils.Errors.UNKNOWN_METHOD); - throw new Error(Utils.Errors.UNKNOWN_METHOD); - } - } - - function compress(/*Boolean*/async, /*Function*/callback) { - if ((!uncompressedData || !uncompressedData.length) && Buffer.isBuffer(input)) { - // no data set or the data wasn't changed to require recompression - if (async && callback) callback(getCompressedDataFromZip()); - return getCompressedDataFromZip(); - } - - if (uncompressedData.length && !_isDirectory) { - var compressedData; - // Local file header - switch (_entryHeader.method) { - case Utils.Constants.STORED: - _entryHeader.compressedSize = _entryHeader.size; - - compressedData = Buffer.alloc(uncompressedData.length); - uncompressedData.copy(compressedData); - - if (async && callback) callback(compressedData); - return compressedData; - default: - case Utils.Constants.DEFLATED: - - var deflater = new Methods.Deflater(uncompressedData); - if (!async) { - var deflated = deflater.deflate(); - _entryHeader.compressedSize = deflated.length; - return deflated; - } else { - deflater.deflateAsync(function(data) { - compressedData = Buffer.alloc(data.length); - _entryHeader.compressedSize = data.length; - data.copy(compressedData); - callback && callback(compressedData); - }) - } - deflater = null; - break; - } - } else { - if (async && callback) { - callback(Buffer.alloc(0)); - } else { - return Buffer.alloc(0); - } - } - } - - function readUInt64LE(buffer, offset) { - return (buffer.readUInt32LE(offset + 4) << 4) + buffer.readUInt32LE(offset); - } - - function parseExtra(data) { - var offset = 0; - var signature, size, part; - while(offset= Constants.EF_ZIP64_SCOMP) { - size = readUInt64LE(data, Constants.EF_ZIP64_SUNCOMP); - if(_entryHeader.size === Constants.EF_ZIP64_OR_32) { - _entryHeader.size = size; - } - } - if(data.length >= Constants.EF_ZIP64_RHO) { - compressedSize = readUInt64LE(data, Constants.EF_ZIP64_SCOMP); - if(_entryHeader.compressedSize === Constants.EF_ZIP64_OR_32) { - _entryHeader.compressedSize = compressedSize; - } - } - if(data.length >= Constants.EF_ZIP64_DSN) { - offset = readUInt64LE(data, Constants.EF_ZIP64_RHO); - if(_entryHeader.offset === Constants.EF_ZIP64_OR_32) { - _entryHeader.offset = offset; - } - } - if(data.length >= Constants.EF_ZIP64_DSN+4) { - diskNumStart = data.readUInt32LE(Constants.EF_ZIP64_DSN); - if(_entryHeader.diskNumStart === Constants.EF_ZIP64_OR_16) { - _entryHeader.diskNumStart = diskNumStart; - } - } - } - - - return { - get entryName () { return _entryName.toString(); }, - get rawEntryName() { return _entryName; }, - set entryName (val) { - _entryName = Utils.toBuffer(val); - var lastChar = _entryName[_entryName.length - 1]; - _isDirectory = (lastChar === 47) || (lastChar === 92); - _entryHeader.fileNameLength = _entryName.length; - }, - - get extra () { return _extra; }, - set extra (val) { - _extra = val; - _entryHeader.extraLength = val.length; - parseExtra(val); - }, - - get comment () { return _comment.toString(); }, - set comment (val) { - _comment = Utils.toBuffer(val); - _entryHeader.commentLength = _comment.length; - }, - - get name () { var n = _entryName.toString(); return _isDirectory ? n.substr(n.length - 1).split("/").pop() : n.split("/").pop(); }, - get isDirectory () { return _isDirectory }, - - getCompressedData : function() { - return compress(false, null) - }, - - getCompressedDataAsync : function(/*Function*/callback) { - compress(true, callback) - }, - - setData : function(value) { - uncompressedData = Utils.toBuffer(value); - if (!_isDirectory && uncompressedData.length) { - _entryHeader.size = uncompressedData.length; - _entryHeader.method = Utils.Constants.DEFLATED; - _entryHeader.crc = Utils.crc32(value); - _entryHeader.changed = true; - } else { // folders and blank files should be stored - _entryHeader.method = Utils.Constants.STORED; - } - }, - - getData : function(pass) { - if (_entryHeader.changed) { - return uncompressedData; - } else { - return decompress(false, null, pass); - } - }, - - getDataAsync : function(/*Function*/callback, pass) { - if (_entryHeader.changed) { - callback(uncompressedData) - } else { - decompress(true, callback, pass) - } - }, - - set attr(attr) { _entryHeader.attr = attr; }, - get attr() { return _entryHeader.attr; }, - - set header(/*Buffer*/data) { - _entryHeader.loadFromBinary(data); - }, - - get header() { - return _entryHeader; - }, - - packHeader : function() { - var header = _entryHeader.entryHeaderToBinary(); - // add - _entryName.copy(header, Utils.Constants.CENHDR); - if (_entryHeader.extraLength) { - _extra.copy(header, Utils.Constants.CENHDR + _entryName.length) - } - if (_entryHeader.commentLength) { - _comment.copy(header, Utils.Constants.CENHDR + _entryName.length + _entryHeader.extraLength, _comment.length); - } - return header; - }, - - toString : function() { - return '{\n' + - '\t"entryName" : "' + _entryName.toString() + "\",\n" + - '\t"name" : "' + (_isDirectory ? _entryName.toString().replace(/\/$/, '').split("/").pop() : _entryName.toString().split("/").pop()) + "\",\n" + - '\t"comment" : "' + _comment.toString() + "\",\n" + - '\t"isDirectory" : ' + _isDirectory + ",\n" + - '\t"header" : ' + _entryHeader.toString().replace(/\t/mg, "\t\t").replace(/}/mg, "\t}") + ",\n" + - '\t"compressedData" : <' + (input && input.length + " bytes buffer" || "null") + ">\n" + - '\t"data" : <' + (uncompressedData && uncompressedData.length + " bytes buffer" || "null") + ">\n" + - '}'; - } - } -}; diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/adm-zip/zipFile.js b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/adm-zip/zipFile.js deleted file mode 100644 index e4d1058b82..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/adm-zip/zipFile.js +++ /dev/null @@ -1,408 +0,0 @@ -var ZipEntry = require("./zipEntry"), - Headers = require("./headers"), - Utils = require("./util"); - -module.exports = function (/*String|Buffer*/input, /*Number*/inputType) { - var entryList = [], - entryTable = {}, - _comment = Buffer.alloc(0), - filename = "", - fs = Utils.FileSystem.require(), - inBuffer = null, - mainHeader = new Headers.MainHeader(), - loadedEntries = false; - - if (inputType === Utils.Constants.FILE) { - // is a filename - filename = input; - inBuffer = fs.readFileSync(filename); - readMainHeader(); - } else if (inputType === Utils.Constants.BUFFER) { - // is a memory buffer - inBuffer = input; - readMainHeader(); - } else { - // none. is a new file - loadedEntries = true; - } - - function iterateEntries(callback) { - const totalEntries = mainHeader.diskEntries; // total number of entries - let index = mainHeader.offset; // offset of first CEN header - - for (let i = 0; i < totalEntries; i++) { - let tmp = index; - const entry = new ZipEntry(inBuffer); - - entry.header = inBuffer.slice(tmp, tmp += Utils.Constants.CENHDR); - entry.entryName = inBuffer.slice(tmp, tmp += entry.header.fileNameLength); - - index += entry.header.entryHeaderSize; - - callback(entry); - } - } - - function readEntries() { - loadedEntries = true; - entryTable = {}; - entryList = new Array(mainHeader.diskEntries); // total number of entries - var index = mainHeader.offset; // offset of first CEN header - for (var i = 0; i < entryList.length; i++) { - - var tmp = index, - entry = new ZipEntry(inBuffer); - entry.header = inBuffer.slice(tmp, tmp += Utils.Constants.CENHDR); - - entry.entryName = inBuffer.slice(tmp, tmp += entry.header.fileNameLength); - - if (entry.header.extraLength) { - entry.extra = inBuffer.slice(tmp, tmp += entry.header.extraLength); - } - - if (entry.header.commentLength) - entry.comment = inBuffer.slice(tmp, tmp + entry.header.commentLength); - - index += entry.header.entryHeaderSize; - - entryList[i] = entry; - entryTable[entry.entryName] = entry; - } - } - - function readMainHeader() { - var i = inBuffer.length - Utils.Constants.ENDHDR, // END header size - max = Math.max(0, i - 0xFFFF), // 0xFFFF is the max zip file comment length - n = max, - endStart = inBuffer.length, - endOffset = -1, // Start offset of the END header - commentEnd = 0; - - for (i; i >= n; i--) { - if (inBuffer[i] !== 0x50) continue; // quick check that the byte is 'P' - if (inBuffer.readUInt32LE(i) === Utils.Constants.ENDSIG) { // "PK\005\006" - endOffset = i; - commentEnd = i; - endStart = i + Utils.Constants.ENDHDR; - // We already found a regular signature, let's look just a bit further to check if there's any zip64 signature - n = i - Utils.Constants.END64HDR; - continue; - } - - if (inBuffer.readUInt32LE(i) === Utils.Constants.END64SIG) { - // Found a zip64 signature, let's continue reading the whole zip64 record - n = max; - continue; - } - - if (inBuffer.readUInt32LE(i) == Utils.Constants.ZIP64SIG) { - // Found the zip64 record, let's determine it's size - endOffset = i; - endStart = i + Utils.readBigUInt64LE(inBuffer, i + Utils.Constants.ZIP64SIZE) + Utils.Constants.ZIP64LEAD; - break; - } - } - - if (!~endOffset) - throw new Error(Utils.Errors.INVALID_FORMAT); - - mainHeader.loadFromBinary(inBuffer.slice(endOffset, endStart)); - if (mainHeader.commentLength) { - _comment = inBuffer.slice(commentEnd + Utils.Constants.ENDHDR); - } - // readEntries(); - } - - return { - /** - * Returns an array of ZipEntry objects existent in the current opened archive - * @return Array - */ - get entries() { - if (!loadedEntries) { - readEntries(); - } - return entryList; - }, - - /** - * Archive comment - * @return {String} - */ - get comment() { - return _comment.toString(); - }, - set comment(val) { - mainHeader.commentLength = val.length; - _comment = val; - }, - - getEntryCount: function() { - if (!loadedEntries) { - return mainHeader.diskEntries; - } - - return entryList.length; - }, - - forEach: function(callback) { - if (!loadedEntries) { - iterateEntries(callback); - return; - } - - entryList.forEach(callback); - }, - - /** - * Returns a reference to the entry with the given name or null if entry is inexistent - * - * @param entryName - * @return ZipEntry - */ - getEntry: function (/*String*/entryName) { - if (!loadedEntries) { - readEntries(); - } - return entryTable[entryName] || null; - }, - - /** - * Adds the given entry to the entry list - * - * @param entry - */ - setEntry: function (/*ZipEntry*/entry) { - if (!loadedEntries) { - readEntries(); - } - entryList.push(entry); - entryTable[entry.entryName] = entry; - mainHeader.totalEntries = entryList.length; - }, - - /** - * Removes the entry with the given name from the entry list. - * - * If the entry is a directory, then all nested files and directories will be removed - * @param entryName - */ - deleteEntry: function (/*String*/entryName) { - if (!loadedEntries) { - readEntries(); - } - var entry = entryTable[entryName]; - if (entry && entry.isDirectory) { - var _self = this; - this.getEntryChildren(entry).forEach(function (child) { - if (child.entryName !== entryName) { - _self.deleteEntry(child.entryName) - } - }) - } - entryList.splice(entryList.indexOf(entry), 1); - delete(entryTable[entryName]); - mainHeader.totalEntries = entryList.length; - }, - - /** - * Iterates and returns all nested files and directories of the given entry - * - * @param entry - * @return Array - */ - getEntryChildren: function (/*ZipEntry*/entry) { - if (!loadedEntries) { - readEntries(); - } - if (entry.isDirectory) { - var list = [], - name = entry.entryName, - len = name.length; - - entryList.forEach(function (zipEntry) { - if (zipEntry.entryName.substr(0, len) === name) { - list.push(zipEntry); - } - }); - return list; - } - return [] - }, - - /** - * Returns the zip file - * - * @return Buffer - */ - compressToBuffer: function () { - if (!loadedEntries) { - readEntries(); - } - if (entryList.length > 1) { - entryList.sort(function (a, b) { - var nameA = a.entryName.toLowerCase(); - var nameB = b.entryName.toLowerCase(); - if (nameA < nameB) { - return -1 - } - if (nameA > nameB) { - return 1 - } - return 0; - }); - } - - var totalSize = 0, - dataBlock = [], - entryHeaders = [], - dindex = 0; - - mainHeader.size = 0; - mainHeader.offset = 0; - - entryList.forEach(function (entry) { - // compress data and set local and entry header accordingly. Reason why is called first - var compressedData = entry.getCompressedData(); - // data header - entry.header.offset = dindex; - var dataHeader = entry.header.dataHeaderToBinary(); - var entryNameLen = entry.rawEntryName.length; - var extra = entry.extra.toString(); - var postHeader = Buffer.alloc(entryNameLen + extra.length); - entry.rawEntryName.copy(postHeader, 0); - postHeader.fill(extra, entryNameLen); - - var dataLength = dataHeader.length + postHeader.length + compressedData.length; - - dindex += dataLength; - - dataBlock.push(dataHeader); - dataBlock.push(postHeader); - dataBlock.push(compressedData); - - var entryHeader = entry.packHeader(); - entryHeaders.push(entryHeader); - mainHeader.size += entryHeader.length; - totalSize += (dataLength + entryHeader.length); - }); - - totalSize += mainHeader.mainHeaderSize; // also includes zip file comment length - // point to end of data and beginning of central directory first record - mainHeader.offset = dindex; - - dindex = 0; - var outBuffer = Buffer.alloc(totalSize); - dataBlock.forEach(function (content) { - content.copy(outBuffer, dindex); // write data blocks - dindex += content.length; - }); - entryHeaders.forEach(function (content) { - content.copy(outBuffer, dindex); // write central directory entries - dindex += content.length; - }); - - var mh = mainHeader.toBinary(); - if (_comment) { - Buffer.from(_comment).copy(mh, Utils.Constants.ENDHDR); // add zip file comment - } - - mh.copy(outBuffer, dindex); // write main header - - return outBuffer - }, - - toAsyncBuffer: function (/*Function*/onSuccess, /*Function*/onFail, /*Function*/onItemStart, /*Function*/onItemEnd) { - if (!loadedEntries) { - readEntries(); - } - if (entryList.length > 1) { - entryList.sort(function (a, b) { - var nameA = a.entryName.toLowerCase(); - var nameB = b.entryName.toLowerCase(); - if (nameA > nameB) { - return -1 - } - if (nameA < nameB) { - return 1 - } - return 0; - }); - } - - var totalSize = 0, - dataBlock = [], - entryHeaders = [], - dindex = 0; - - mainHeader.size = 0; - mainHeader.offset = 0; - - var compress = function (entryList) { - var self = arguments.callee; - if (entryList.length) { - var entry = entryList.pop(); - var name = entry.entryName + entry.extra.toString(); - if (onItemStart) onItemStart(name); - entry.getCompressedDataAsync(function (compressedData) { - if (onItemEnd) onItemEnd(name); - - entry.header.offset = dindex; - // data header - var dataHeader = entry.header.dataHeaderToBinary(); - var postHeader; - try { - postHeader = Buffer.alloc(name.length, name); // using alloc will work on node 5.x+ - } catch(e){ - postHeader = new Buffer(name); // use deprecated method if alloc fails... - } - var dataLength = dataHeader.length + postHeader.length + compressedData.length; - - dindex += dataLength; - - dataBlock.push(dataHeader); - dataBlock.push(postHeader); - dataBlock.push(compressedData); - - var entryHeader = entry.packHeader(); - entryHeaders.push(entryHeader); - mainHeader.size += entryHeader.length; - totalSize += (dataLength + entryHeader.length); - - if (entryList.length) { - self(entryList); - } else { - - - totalSize += mainHeader.mainHeaderSize; // also includes zip file comment length - // point to end of data and beginning of central directory first record - mainHeader.offset = dindex; - - dindex = 0; - var outBuffer = Buffer.alloc(totalSize); - dataBlock.forEach(function (content) { - content.copy(outBuffer, dindex); // write data blocks - dindex += content.length; - }); - entryHeaders.forEach(function (content) { - content.copy(outBuffer, dindex); // write central directory entries - dindex += content.length; - }); - - var mh = mainHeader.toBinary(); - if (_comment) { - _comment.copy(mh, Utils.Constants.ENDHDR); // add zip file comment - } - - mh.copy(outBuffer, dindex); // write main header - - onSuccess(outBuffer); - } - }); - } - }; - - compress(entryList); - } - } -}; diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/agentkeepalive/History.md b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/agentkeepalive/History.md deleted file mode 100644 index d5d14d8b4c..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/agentkeepalive/History.md +++ /dev/null @@ -1,170 +0,0 @@ - -3.5.2 / 2018-10-19 -================== - -**fixes** - * [[`5751fc1`](http://github.com/node-modules/agentkeepalive/commit/5751fc1180ed6544602c681ffbd08ca66a0cb12c)] - fix: sockLen being miscalculated when removing sockets (#60) (Ehden Sinai <>) - -3.5.1 / 2018-07-31 -================== - -**fixes** - * [[`495f1ab`](http://github.com/node-modules/agentkeepalive/commit/495f1ab625d43945d72f68096b97db723d4f0657)] - fix: add the lost npm files (#66) (Henry Zhuang <>) - -3.5.0 / 2018-07-31 -================== - -**features** - * [[`16f5aea`](http://github.com/node-modules/agentkeepalive/commit/16f5aeadfda57f1c602652f1472a63cc83cd05bf)] - feat: add typing define. (#65) (Henry Zhuang <>) - -**others** - * [[`28fa062`](http://github.com/node-modules/agentkeepalive/commit/28fa06246fb5103f88ebeeb8563757a9078b8157)] - docs: add "per host" to description of maxFreeSockets (tony-gutierrez <>) - * [[`7df2577`](http://github.com/node-modules/agentkeepalive/commit/7df25774f00a1031ca4daad2878a17e0539072a2)] - test: run test on node 10 (#63) (fengmk2 <>) - -3.4.1 / 2018-03-08 -================== - -**fixes** - * [[`4d3a3b1`](http://github.com/node-modules/agentkeepalive/commit/4d3a3b1f7b16595febbbd39eeed72b2663549014)] - fix: Handle ipv6 addresses in host-header correctly with TLS (#53) (Mattias Holmlund <>) - -**others** - * [[`55a7a5c`](http://github.com/node-modules/agentkeepalive/commit/55a7a5cd33e97f9a8370083dcb041c5552f10ac9)] - test: stop timer after test end (fengmk2 <>) - -3.4.0 / 2018-02-27 -================== - -**features** - * [[`bc7cadb`](http://github.com/node-modules/agentkeepalive/commit/bc7cadb30ecd2071e2b341ac53ae1a2b8155c43d)] - feat: use socket custom freeSocketKeepAliveTimeout first (#59) (fengmk2 <>) - -**others** - * [[`138eda8`](http://github.com/node-modules/agentkeepalive/commit/138eda81e10b632aaa87bea0cb66d8667124c4e8)] - doc: fix `keepAliveMsecs` params description (#55) (Hongcai Deng <>) - -3.3.0 / 2017-06-20 -================== - - * feat: add statusChanged getter (#51) - * chore: format License - -3.2.0 / 2017-06-10 -================== - - * feat: add expiring active sockets - * test: add node 8 (#49) - -3.1.0 / 2017-02-20 -================== - - * feat: timeout support humanize ms (#48) - -3.0.0 / 2016-12-20 -================== - - * fix: emit agent socket close event - * test: add remove excess calls to removeSocket - * test: use egg-ci - * test: refactor test with eslint rules - * feat: merge _http_agent.js from 7.2.1 - -2.2.0 / 2016-06-26 -================== - - * feat: Add browser shim (noop) for isomorphic use. (#39) - * chore: add security check badge - -2.1.1 / 2016-04-06 -================== - - * https: fix ssl socket leak when keepalive is used - * chore: remove circle ci image - -2.1.0 / 2016-04-02 -================== - - * fix: opened sockets number overflow maxSockets - -2.0.5 / 2016-03-16 -================== - - * fix: pick _evictSession to httpsAgent - -2.0.4 / 2016-03-13 -================== - - * test: add Circle ci - * test: add appveyor ci build - * refactor: make sure only one error listener - * chore: use codecov - * fix: handle idle socket error - * test: run on more node versions - -2.0.3 / 2015-08-03 -================== - - * fix: add default error handler to avoid Unhandled error event throw - -2.0.2 / 2015-04-25 -================== - - * fix: remove socket from freeSockets on 'timeout' (@pmalouin) - -2.0.1 / 2015-04-19 -================== - - * fix: add timeoutSocketCount to getCurrentStatus() - * feat(getCurrentStatus): add getCurrentStatus - -2.0.0 / 2015-04-01 -================== - - * fix: socket.destroyed always be undefined on 0.10.x - * Make it compatible with node v0.10.x (@lattmann) - -1.2.1 / 2015-03-23 -================== - - * patch from iojs: don't overwrite servername option - * patch commits from joyent/node - * add max sockets test case - * add nagle algorithm delayed link - -1.2.0 / 2014-09-02 -================== - - * allow set keepAliveTimeout = 0 - * support timeout on working socket. fixed #6 - -1.1.0 / 2014-08-28 -================== - - * add some socket counter for deep monitor - -1.0.0 / 2014-08-13 -================== - - * update _http_agent, only support 0.11+, only support node 0.11.0+ - -0.2.2 / 2013-11-19 -================== - - * support node 0.8 and node 0.10 - -0.2.1 / 2013-11-08 -================== - - * fix socket does not timeout bug, it will hang on life, must use 0.2.x on node 0.11 - -0.2.0 / 2013-11-06 -================== - - * use keepalive agent on node 0.11+ impl - -0.1.5 / 2013-06-24 -================== - - * support coveralls - * add node 0.10 test - * add 0.8.22 original https.js - * add original http.js module to diff - * update jscover - * mv pem to fixtures - * add https agent usage diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/agentkeepalive/README.md b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/agentkeepalive/README.md deleted file mode 100644 index 823145821b..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/agentkeepalive/README.md +++ /dev/null @@ -1,248 +0,0 @@ -# agentkeepalive - -[![NPM version][npm-image]][npm-url] -[![build status][travis-image]][travis-url] -[![Appveyor status][appveyor-image]][appveyor-url] -[![Test coverage][codecov-image]][codecov-url] -[![David deps][david-image]][david-url] -[![Known Vulnerabilities][snyk-image]][snyk-url] -[![npm download][download-image]][download-url] - -[npm-image]: https://img.shields.io/npm/v/agentkeepalive.svg?style=flat -[npm-url]: https://npmjs.org/package/agentkeepalive -[travis-image]: https://img.shields.io/travis/node-modules/agentkeepalive.svg?style=flat -[travis-url]: https://travis-ci.org/node-modules/agentkeepalive -[appveyor-image]: https://ci.appveyor.com/api/projects/status/k7ct4s47di6m5uy2?svg=true -[appveyor-url]: https://ci.appveyor.com/project/fengmk2/agentkeepalive -[codecov-image]: https://codecov.io/gh/node-modules/agentkeepalive/branch/master/graph/badge.svg -[codecov-url]: https://codecov.io/gh/node-modules/agentkeepalive -[david-image]: https://img.shields.io/david/node-modules/agentkeepalive.svg?style=flat -[david-url]: https://david-dm.org/node-modules/agentkeepalive -[snyk-image]: https://snyk.io/test/npm/agentkeepalive/badge.svg?style=flat-square -[snyk-url]: https://snyk.io/test/npm/agentkeepalive -[download-image]: https://img.shields.io/npm/dm/agentkeepalive.svg?style=flat-square -[download-url]: https://npmjs.org/package/agentkeepalive - -The Node.js's missing `keep alive` `http.Agent`. Support `http` and `https`. - -## What's different from original `http.Agent`? - -- `keepAlive=true` by default -- Disable Nagle's algorithm: `socket.setNoDelay(true)` -- Add free socket timeout: avoid long time inactivity socket leak in the free-sockets queue. -- Add active socket timeout: avoid long time inactivity socket leak in the active-sockets queue. - -## Install - -```bash -$ npm install agentkeepalive --save -``` - -## new Agent([options]) - -* `options` {Object} Set of configurable options to set on the agent. - Can have the following fields: - * `keepAlive` {Boolean} Keep sockets around in a pool to be used by - other requests in the future. Default = `true`. - * `keepAliveMsecs` {Number} When using the keepAlive option, specifies the initial delay - for TCP Keep-Alive packets. Ignored when the keepAlive option is false or undefined. Defaults to 1000. - Default = `1000`. Only relevant if `keepAlive` is set to `true`. - * `freeSocketKeepAliveTimeout`: {Number} Sets the free socket to timeout - after `freeSocketKeepAliveTimeout` milliseconds of inactivity on the free socket. - Default is `15000`. - Only relevant if `keepAlive` is set to `true`. - * `timeout`: {Number} Sets the working socket to timeout - after `timeout` milliseconds of inactivity on the working socket. - Default is `freeSocketKeepAliveTimeout * 2`. - * `maxSockets` {Number} Maximum number of sockets to allow per - host. Default = `Infinity`. - * `maxFreeSockets` {Number} Maximum number of sockets (per host) to leave open - in a free state. Only relevant if `keepAlive` is set to `true`. - Default = `256`. - * `socketActiveTTL` {Number} Sets the socket active time to live, even if it's in use. - If not setted the behaviour continues the same (the socket will be released only when free) - Default = `null`. - -## Usage - -```js -const http = require('http'); -const Agent = require('agentkeepalive'); - -const keepaliveAgent = new Agent({ - maxSockets: 100, - maxFreeSockets: 10, - timeout: 60000, - freeSocketKeepAliveTimeout: 30000, // free socket keepalive for 30 seconds -}); - -const options = { - host: 'cnodejs.org', - port: 80, - path: '/', - method: 'GET', - agent: keepaliveAgent, -}; - -const req = http.request(options, res => { - console.log('STATUS: ' + res.statusCode); - console.log('HEADERS: ' + JSON.stringify(res.headers)); - res.setEncoding('utf8'); - res.on('data', function (chunk) { - console.log('BODY: ' + chunk); - }); -}); -req.on('error', e => { - console.log('problem with request: ' + e.message); -}); -req.end(); - -setTimeout(() => { - if (keepaliveAgent.statusChanged) { - console.log('[%s] agent status changed: %j', Date(), keepaliveAgent.getCurrentStatus()); - } -}, 2000); - -``` - -### `getter agent.statusChanged` - -counters have change or not after last checkpoint. - -### `agent.getCurrentStatus()` - -`agent.getCurrentStatus()` will return a object to show the status of this agent: - -```js -{ - createSocketCount: 10, - closeSocketCount: 5, - timeoutSocketCount: 0, - requestCount: 5, - freeSockets: { 'localhost:57479:': 3 }, - sockets: { 'localhost:57479:': 5 }, - requests: {} -} -``` - -### Support `https` - -```js -const https = require('https'); -const HttpsAgent = require('agentkeepalive').HttpsAgent; - -const keepaliveAgent = new HttpsAgent(); -// https://www.google.com/search?q=nodejs&sugexp=chrome,mod=12&sourceid=chrome&ie=UTF-8 -const options = { - host: 'www.google.com', - port: 443, - path: '/search?q=nodejs&sugexp=chrome,mod=12&sourceid=chrome&ie=UTF-8', - method: 'GET', - agent: keepaliveAgent, -}; - -const req = https.request(options, res => { - console.log('STATUS: ' + res.statusCode); - console.log('HEADERS: ' + JSON.stringify(res.headers)); - res.setEncoding('utf8'); - res.on('data', chunk => { - console.log('BODY: ' + chunk); - }); -}); - -req.on('error', e => { - console.log('problem with request: ' + e.message); -}); -req.end(); - -setTimeout(() => { - console.log('agent status: %j', keepaliveAgent.getCurrentStatus()); -}, 2000); -``` - -## [Benchmark](https://github.com/node-modules/agentkeepalive/tree/master/benchmark) - -run the benchmark: - -```bash -cd benchmark -sh start.sh -``` - -Intel(R) Core(TM)2 Duo CPU P8600 @ 2.40GHz - -node@v0.8.9 - -50 maxSockets, 60 concurrent, 1000 requests per concurrent, 5ms delay - -Keep alive agent (30 seconds): - -```js -Transactions: 60000 hits -Availability: 100.00 % -Elapsed time: 29.70 secs -Data transferred: 14.88 MB -Response time: 0.03 secs -Transaction rate: 2020.20 trans/sec -Throughput: 0.50 MB/sec -Concurrency: 59.84 -Successful transactions: 60000 -Failed transactions: 0 -Longest transaction: 0.15 -Shortest transaction: 0.01 -``` - -Normal agent: - -```js -Transactions: 60000 hits -Availability: 100.00 % -Elapsed time: 46.53 secs -Data transferred: 14.88 MB -Response time: 0.05 secs -Transaction rate: 1289.49 trans/sec -Throughput: 0.32 MB/sec -Concurrency: 59.81 -Successful transactions: 60000 -Failed transactions: 0 -Longest transaction: 0.45 -Shortest transaction: 0.00 -``` - -Socket created: - -``` -[proxy.js:120000] keepalive, 50 created, 60000 requestFinished, 1200 req/socket, 0 requests, 0 sockets, 0 unusedSockets, 50 timeout -{" <10ms":662," <15ms":17825," <20ms":20552," <30ms":17646," <40ms":2315," <50ms":567," <100ms":377," <150ms":56," <200ms":0," >=200ms+":0} ----------------------------------------------------------------- -[proxy.js:120000] normal , 53866 created, 84260 requestFinished, 1.56 req/socket, 0 requests, 0 sockets -{" <10ms":75," <15ms":1112," <20ms":10947," <30ms":32130," <40ms":8228," <50ms":3002," <100ms":4274," <150ms":181," <200ms":18," >=200ms+":33} -``` - -## License - -``` -(The MIT License) - -Copyright(c) node-modules and other contributors. -Copyright(c) 2012 - 2015 fengmk2 - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -'Software'), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -``` diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/agentkeepalive/browser.js b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/agentkeepalive/browser.js deleted file mode 100644 index 29c9398aa5..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/agentkeepalive/browser.js +++ /dev/null @@ -1,5 +0,0 @@ -module.exports = noop; -module.exports.HttpsAgent = noop; - -// Noop function for browser since native api's don't use agents. -function noop () {} diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/agentkeepalive/index.d.ts b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/agentkeepalive/index.d.ts deleted file mode 100644 index c11636f7ca..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/agentkeepalive/index.d.ts +++ /dev/null @@ -1,43 +0,0 @@ -declare module "agentkeepalive" { - import * as http from 'http'; - import * as https from 'https'; - - interface AgentStatus { - createSocketCount: number, - createSocketErrorCount: number, - closeSocketCount: number, - errorSocketCount: number, - timeoutSocketCount: number, - requestCount: number, - freeSockets: object, - sockets: object, - requests: object, - } - - interface HttpOptions extends http.AgentOptions { - freeSocketKeepAliveTimeout?: number; - timeout?: number; - socketActiveTTL?: number; - } - - interface HttpsOptions extends https.AgentOptions { - freeSocketKeepAliveTimeout?: number; - timeout?: number; - socketActiveTTL?: number; - } - - class internal extends http.Agent { - constructor(opts?: HttpOptions); - readonly statusChanged: boolean; - createSocket(req: http.IncomingMessage, options: http.RequestOptions, cb: Function): void; - getCurrentStatus(): AgentStatus; - } - - namespace internal { - export class HttpsAgent extends internal { - constructor(opts?: HttpsOptions); - } - } - - export = internal; -} diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/agentkeepalive/index.js b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/agentkeepalive/index.js deleted file mode 100644 index 6138131a9b..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/agentkeepalive/index.js +++ /dev/null @@ -1,4 +0,0 @@ -'use strict'; - -module.exports = require('./lib/agent'); -module.exports.HttpsAgent = require('./lib/https_agent'); diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/agentkeepalive/lib/_http_agent.js b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/agentkeepalive/lib/_http_agent.js deleted file mode 100644 index c324b7f875..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/agentkeepalive/lib/_http_agent.js +++ /dev/null @@ -1,416 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -// patch from https://github.com/nodejs/node/blob/v7.2.1/lib/_http_agent.js - -'use strict'; - -const net = require('net'); -const util = require('util'); -const EventEmitter = require('events'); -const debug = util.debuglog('http'); - -// New Agent code. - -// The largest departure from the previous implementation is that -// an Agent instance holds connections for a variable number of host:ports. -// Surprisingly, this is still API compatible as far as third parties are -// concerned. The only code that really notices the difference is the -// request object. - -// Another departure is that all code related to HTTP parsing is in -// ClientRequest.onSocket(). The Agent is now *strictly* -// concerned with managing a connection pool. - -function Agent(options) { - if (!(this instanceof Agent)) - return new Agent(options); - - EventEmitter.call(this); - - var self = this; - - self.defaultPort = 80; - self.protocol = 'http:'; - - self.options = util._extend({}, options); - - // don't confuse net and make it think that we're connecting to a pipe - self.options.path = null; - self.requests = {}; - self.sockets = {}; - self.freeSockets = {}; - self.keepAliveMsecs = self.options.keepAliveMsecs || 1000; - self.keepAlive = self.options.keepAlive || false; - self.maxSockets = self.options.maxSockets || Agent.defaultMaxSockets; - self.maxFreeSockets = self.options.maxFreeSockets || 256; - - // [patch start] - // free keep-alive socket timeout. By default free socket do not have a timeout. - self.freeSocketKeepAliveTimeout = self.options.freeSocketKeepAliveTimeout || 0; - // working socket timeout. By default working socket do not have a timeout. - self.timeout = self.options.timeout || 0; - // the socket active time to live, even if it's in use - this.socketActiveTTL = this.options.socketActiveTTL || null; - // [patch end] - - self.on('free', function(socket, options) { - var name = self.getName(options); - debug('agent.on(free)', name); - - if (socket.writable && - self.requests[name] && self.requests[name].length) { - // [patch start] - debug('continue handle next request'); - // [patch end] - self.requests[name].shift().onSocket(socket); - if (self.requests[name].length === 0) { - // don't leak - delete self.requests[name]; - } - } else { - // If there are no pending requests, then put it in - // the freeSockets pool, but only if we're allowed to do so. - var req = socket._httpMessage; - if (req && - req.shouldKeepAlive && - socket.writable && - self.keepAlive) { - var freeSockets = self.freeSockets[name]; - var freeLen = freeSockets ? freeSockets.length : 0; - var count = freeLen; - if (self.sockets[name]) - count += self.sockets[name].length; - - if (count > self.maxSockets || freeLen >= self.maxFreeSockets) { - socket.destroy(); - } else { - freeSockets = freeSockets || []; - self.freeSockets[name] = freeSockets; - socket.setKeepAlive(true, self.keepAliveMsecs); - socket.unref(); - socket._httpMessage = null; - self.removeSocket(socket, options); - freeSockets.push(socket); - - // [patch start] - // Add a default error handler to avoid Unhandled 'error' event throw on idle socket - // https://github.com/node-modules/agentkeepalive/issues/25 - // https://github.com/nodejs/node/pull/4482 (fixed in >= 4.4.0 and >= 5.4.0) - if (socket.listeners('error').length === 0) { - socket.once('error', freeSocketErrorListener); - } - // set free keepalive timer - // try to use socket custom freeSocketKeepAliveTimeout first - const freeSocketKeepAliveTimeout = socket.freeSocketKeepAliveTimeout || self.freeSocketKeepAliveTimeout; - socket.setTimeout(freeSocketKeepAliveTimeout); - debug(`push to free socket queue and wait for ${freeSocketKeepAliveTimeout}ms`); - // [patch end] - } - } else { - socket.destroy(); - } - } - }); -} - -util.inherits(Agent, EventEmitter); -exports.Agent = Agent; - -// [patch start] -function freeSocketErrorListener(err) { - var socket = this; - debug('SOCKET ERROR on FREE socket:', err.message, err.stack); - socket.destroy(); - socket.emit('agentRemove'); -} -// [patch end] - -Agent.defaultMaxSockets = Infinity; - -Agent.prototype.createConnection = net.createConnection; - -// Get the key for a given set of request options -Agent.prototype.getName = function getName(options) { - var name = options.host || 'localhost'; - - name += ':'; - if (options.port) - name += options.port; - - name += ':'; - if (options.localAddress) - name += options.localAddress; - - // Pacify parallel/test-http-agent-getname by only appending - // the ':' when options.family is set. - if (options.family === 4 || options.family === 6) - name += ':' + options.family; - - return name; -}; - -// [patch start] -function handleSocketCreation(req) { - return function(err, newSocket) { - if (err) { - process.nextTick(function() { - req.emit('error', err); - }); - return; - } - req.onSocket(newSocket); - } -} -// [patch end] - -Agent.prototype.addRequest = function addRequest(req, options, port/*legacy*/, - localAddress/*legacy*/) { - // Legacy API: addRequest(req, host, port, localAddress) - if (typeof options === 'string') { - options = { - host: options, - port, - localAddress - }; - } - - options = util._extend({}, options); - options = util._extend(options, this.options); - - if (!options.servername) - options.servername = calculateServerName(options, req); - - var name = this.getName(options); - if (!this.sockets[name]) { - this.sockets[name] = []; - } - - var freeLen = this.freeSockets[name] ? this.freeSockets[name].length : 0; - var sockLen = freeLen + this.sockets[name].length; - - if (freeLen) { - // we have a free socket, so use that. - var socket = this.freeSockets[name].shift(); - debug('have free socket'); - - // [patch start] - // remove free socket error event handler - socket.removeListener('error', freeSocketErrorListener); - // restart the default timer - socket.setTimeout(this.timeout); - - if (this.socketActiveTTL && Date.now() - socket.createdTime > this.socketActiveTTL) { - debug(`socket ${socket.createdTime} expired`); - socket.destroy(); - return this.createSocket(req, options, handleSocketCreation(req)); - } - // [patch end] - - // don't leak - if (!this.freeSockets[name].length) - delete this.freeSockets[name]; - - socket.ref(); - req.onSocket(socket); - this.sockets[name].push(socket); - } else if (sockLen < this.maxSockets) { - debug('call onSocket', sockLen, freeLen); - // If we are under maxSockets create a new one. - // [patch start] - this.createSocket(req, options, handleSocketCreation(req)); - // [patch end] - } else { - debug('wait for socket'); - // We are over limit so we'll add it to the queue. - if (!this.requests[name]) { - this.requests[name] = []; - } - this.requests[name].push(req); - } -}; - -Agent.prototype.createSocket = function createSocket(req, options, cb) { - var self = this; - options = util._extend({}, options); - options = util._extend(options, self.options); - - if (!options.servername) - options.servername = calculateServerName(options, req); - - var name = self.getName(options); - options._agentKey = name; - - debug('createConnection', name, options); - options.encoding = null; - var called = false; - const newSocket = self.createConnection(options, oncreate); - // [patch start] - if (newSocket) { - oncreate(null, Object.assign(newSocket, { createdTime: Date.now() })); - } - // [patch end] - function oncreate(err, s) { - if (called) - return; - called = true; - if (err) - return cb(err); - if (!self.sockets[name]) { - self.sockets[name] = []; - } - self.sockets[name].push(s); - debug('sockets', name, self.sockets[name].length); - - function onFree() { - self.emit('free', s, options); - } - s.on('free', onFree); - - function onClose(err) { - debug('CLIENT socket onClose'); - // This is the only place where sockets get removed from the Agent. - // If you want to remove a socket from the pool, just close it. - // All socket errors end in a close event anyway. - self.removeSocket(s, options); - - // [patch start] - self.emit('close'); - // [patch end] - } - s.on('close', onClose); - - // [patch start] - // start socket timeout handler - function onTimeout() { - debug('CLIENT socket onTimeout'); - s.destroy(); - // Remove it from freeSockets immediately to prevent new requests from being sent through this socket. - self.removeSocket(s, options); - self.emit('timeout'); - } - s.on('timeout', onTimeout); - // set the default timer - s.setTimeout(self.timeout); - // [patch end] - - function onRemove() { - // We need this function for cases like HTTP 'upgrade' - // (defined by WebSockets) where we need to remove a socket from the - // pool because it'll be locked up indefinitely - debug('CLIENT socket onRemove'); - self.removeSocket(s, options); - s.removeListener('close', onClose); - s.removeListener('free', onFree); - s.removeListener('agentRemove', onRemove); - - // [patch start] - // remove socket timeout handler - s.setTimeout(0, onTimeout); - // [patch end] - } - s.on('agentRemove', onRemove); - cb(null, s); - } -}; - -function calculateServerName(options, req) { - let servername = options.host; - const hostHeader = req.getHeader('host'); - if (hostHeader) { - // abc => abc - // abc:123 => abc - // [::1] => ::1 - // [::1]:123 => ::1 - if (hostHeader.startsWith('[')) { - const index = hostHeader.indexOf(']'); - if (index === -1) { - // Leading '[', but no ']'. Need to do something... - servername = hostHeader; - } else { - servername = hostHeader.substr(1, index - 1); - } - } else { - servername = hostHeader.split(':', 1)[0]; - } - } - return servername; -} - -Agent.prototype.removeSocket = function removeSocket(s, options) { - var name = this.getName(options); - debug('removeSocket', name, 'writable:', s.writable); - var sets = [this.sockets]; - - // If the socket was destroyed, remove it from the free buffers too. - if (!s.writable) - sets.push(this.freeSockets); - - for (var sk = 0; sk < sets.length; sk++) { - var sockets = sets[sk]; - - if (sockets[name]) { - var index = sockets[name].indexOf(s); - if (index !== -1) { - sockets[name].splice(index, 1); - // Don't leak - if (sockets[name].length === 0) - delete sockets[name]; - } - } - } - - // [patch start] - var freeLen = this.freeSockets[name] ? this.freeSockets[name].length : 0; - var sockLen = freeLen + (this.sockets[name] ? this.sockets[name].length : 0); - // [patch end] - - if (this.requests[name] && this.requests[name].length && sockLen < this.maxSockets) { - debug('removeSocket, have a request, make a socket'); - var req = this.requests[name][0]; - // If we have pending requests and a socket gets closed make a new one - this.createSocket(req, options, function(err, newSocket) { - if (err) { - process.nextTick(function() { - req.emit('error', err); - }); - return; - } - newSocket.emit('free'); - }); - } -}; - -Agent.prototype.destroy = function destroy() { - var sets = [this.freeSockets, this.sockets]; - for (var s = 0; s < sets.length; s++) { - var set = sets[s]; - var keys = Object.keys(set); - for (var v = 0; v < keys.length; v++) { - var setName = set[keys[v]]; - for (var n = 0; n < setName.length; n++) { - setName[n].destroy(); - } - } - } -}; - -exports.globalAgent = new Agent(); diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/agentkeepalive/lib/agent.js b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/agentkeepalive/lib/agent.js deleted file mode 100644 index a51ad597bc..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/agentkeepalive/lib/agent.js +++ /dev/null @@ -1,133 +0,0 @@ -/** - * refer: - * * @atimb "Real keep-alive HTTP agent": https://gist.github.com/2963672 - * * https://github.com/joyent/node/blob/master/lib/http.js - * * https://github.com/joyent/node/blob/master/lib/https.js - * * https://github.com/joyent/node/blob/master/lib/_http_agent.js - */ - -'use strict'; - -const OriginalAgent = require('./_http_agent').Agent; -const ms = require('humanize-ms'); - -class Agent extends OriginalAgent { - constructor(options) { - options = options || {}; - options.keepAlive = options.keepAlive !== false; - // default is keep-alive and 15s free socket timeout - if (options.freeSocketKeepAliveTimeout === undefined) { - options.freeSocketKeepAliveTimeout = 15000; - } - // Legacy API: keepAliveTimeout should be rename to `freeSocketKeepAliveTimeout` - if (options.keepAliveTimeout) { - options.freeSocketKeepAliveTimeout = options.keepAliveTimeout; - } - options.freeSocketKeepAliveTimeout = ms(options.freeSocketKeepAliveTimeout); - - // Sets the socket to timeout after timeout milliseconds of inactivity on the socket. - // By default is double free socket keepalive timeout. - if (options.timeout === undefined) { - options.timeout = options.freeSocketKeepAliveTimeout * 2; - // make sure socket default inactivity timeout >= 30s - if (options.timeout < 30000) { - options.timeout = 30000; - } - } - options.timeout = ms(options.timeout); - - super(options); - - this.createSocketCount = 0; - this.createSocketCountLastCheck = 0; - - this.createSocketErrorCount = 0; - this.createSocketErrorCountLastCheck = 0; - - this.closeSocketCount = 0; - this.closeSocketCountLastCheck = 0; - - // socket error event count - this.errorSocketCount = 0; - this.errorSocketCountLastCheck = 0; - - this.requestCount = 0; - this.requestCountLastCheck = 0; - - this.timeoutSocketCount = 0; - this.timeoutSocketCountLastCheck = 0; - - this.on('free', s => { - this.requestCount++; - // last enter free queue timestamp - s.lastFreeTime = Date.now(); - }); - this.on('timeout', () => { - this.timeoutSocketCount++; - }); - this.on('close', () => { - this.closeSocketCount++; - }); - this.on('error', () => { - this.errorSocketCount++; - }); - } - - createSocket(req, options, cb) { - super.createSocket(req, options, (err, socket) => { - if (err) { - this.createSocketErrorCount++; - return cb(err); - } - if (this.keepAlive) { - // Disable Nagle's algorithm: http://blog.caustik.com/2012/04/08/scaling-node-js-to-100k-concurrent-connections/ - // https://fengmk2.com/benchmark/nagle-algorithm-delayed-ack-mock.html - socket.setNoDelay(true); - } - this.createSocketCount++; - cb(null, socket); - }); - } - - get statusChanged() { - const changed = this.createSocketCount !== this.createSocketCountLastCheck || - this.createSocketErrorCount !== this.createSocketErrorCountLastCheck || - this.closeSocketCount !== this.closeSocketCountLastCheck || - this.errorSocketCount !== this.errorSocketCountLastCheck || - this.timeoutSocketCount !== this.timeoutSocketCountLastCheck || - this.requestCount !== this.requestCountLastCheck; - if (changed) { - this.createSocketCountLastCheck = this.createSocketCount; - this.createSocketErrorCountLastCheck = this.createSocketErrorCount; - this.closeSocketCountLastCheck = this.closeSocketCount; - this.errorSocketCountLastCheck = this.errorSocketCount; - this.timeoutSocketCountLastCheck = this.timeoutSocketCount; - this.requestCountLastCheck = this.requestCount; - } - return changed; - } - - getCurrentStatus() { - return { - createSocketCount: this.createSocketCount, - createSocketErrorCount: this.createSocketErrorCount, - closeSocketCount: this.closeSocketCount, - errorSocketCount: this.errorSocketCount, - timeoutSocketCount: this.timeoutSocketCount, - requestCount: this.requestCount, - freeSockets: inspect(this.freeSockets), - sockets: inspect(this.sockets), - requests: inspect(this.requests), - }; - } -} - -module.exports = Agent; - -function inspect(obj) { - const res = {}; - for (const key in obj) { - res[key] = obj[key].length; - } - return res; -} diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/agentkeepalive/lib/https_agent.js b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/agentkeepalive/lib/https_agent.js deleted file mode 100644 index e6d58a3df9..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/agentkeepalive/lib/https_agent.js +++ /dev/null @@ -1,42 +0,0 @@ -/** - * Https Agent base on custom http agent - */ - -'use strict'; - -const https = require('https'); -const HttpAgent = require('./agent'); -const OriginalHttpsAgent = https.Agent; - -class HttpsAgent extends HttpAgent { - constructor(options) { - super(options); - - this.defaultPort = 443; - this.protocol = 'https:'; - this.maxCachedSessions = this.options.maxCachedSessions; - if (this.maxCachedSessions === undefined) { - this.maxCachedSessions = 100; - } - - this._sessionCache = { - map: {}, - list: [], - }; - } -} - -[ - 'createConnection', - 'getName', - '_getSession', - '_cacheSession', - // https://github.com/nodejs/node/pull/4982 - '_evictSession', -].forEach(function(method) { - if (typeof OriginalHttpsAgent.prototype[method] === 'function') { - HttpsAgent.prototype[method] = OriginalHttpsAgent.prototype[method]; - } -}); - -module.exports = HttpsAgent; diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/agentkeepalive/package.json b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/agentkeepalive/package.json deleted file mode 100644 index c81dc9c399..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/agentkeepalive/package.json +++ /dev/null @@ -1,83 +0,0 @@ -{ - "_from": "agentkeepalive@^3.4.1", - "_id": "agentkeepalive@3.5.2", - "_inBundle": false, - "_integrity": "sha512-e0L/HNe6qkQ7H19kTlRRqUibEAwDK5AFk6y3PtMsuut2VAH6+Q4xZml1tNDJD7kSAyqmbG/K08K5WEJYtUrSlQ==", - "_location": "/agentkeepalive", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "agentkeepalive@^3.4.1", - "name": "agentkeepalive", - "escapedName": "agentkeepalive", - "rawSpec": "^3.4.1", - "saveSpec": null, - "fetchSpec": "^3.4.1" - }, - "_requiredBy": [ - "/elasticsearch" - ], - "_resolved": "https://registry.npmjs.org/agentkeepalive/-/agentkeepalive-3.5.2.tgz", - "_shasum": "a113924dd3fa24a0bc3b78108c450c2abee00f67", - "_spec": "agentkeepalive@^3.4.1", - "_where": "/home/jan/Documents/skweb/node_modules/elasticsearch", - "author": { - "name": "fengmk2", - "email": "fengmk2@gmail.com", - "url": "https://fengmk2.com" - }, - "browser": "browser.js", - "bugs": { - "url": "https://github.com/node-modules/agentkeepalive/issues" - }, - "bundleDependencies": false, - "ci": { - "version": "4, 6, 8, 10" - }, - "dependencies": { - "humanize-ms": "^1.2.1" - }, - "deprecated": false, - "description": "Missing keepalive http.Agent", - "devDependencies": { - "autod": "^3.0.1", - "egg-bin": "^1.11.1", - "egg-ci": "^1.8.0", - "eslint": "^4.19.1", - "eslint-config-egg": "^6.0.0", - "pedding": "^1.1.0" - }, - "engines": { - "node": ">= 4.0.0" - }, - "files": [ - "index.js", - "index.d.ts", - "browser.js", - "lib" - ], - "homepage": "https://github.com/node-modules/agentkeepalive#readme", - "keywords": [ - "http", - "https", - "agent", - "keepalive", - "agentkeepalive" - ], - "license": "MIT", - "main": "index.js", - "name": "agentkeepalive", - "repository": { - "type": "git", - "url": "git://github.com/node-modules/agentkeepalive.git" - }, - "scripts": { - "autod": "autod", - "ci": "npm run lint && npm run cov", - "cov": "egg-bin cov", - "lint": "eslint lib test index.js", - "test": "egg-bin test" - }, - "version": "3.5.2" -} diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/ansi-regex/index.js b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/ansi-regex/index.js deleted file mode 100644 index b9574ed7e8..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/ansi-regex/index.js +++ /dev/null @@ -1,4 +0,0 @@ -'use strict'; -module.exports = function () { - return /[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-PRZcf-nqry=><]/g; -}; diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/ansi-regex/license b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/ansi-regex/license deleted file mode 100644 index 654d0bfe94..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/ansi-regex/license +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) Sindre Sorhus (sindresorhus.com) - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/ansi-regex/package.json b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/ansi-regex/package.json deleted file mode 100644 index 98b701423e..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/ansi-regex/package.json +++ /dev/null @@ -1,109 +0,0 @@ -{ - "_from": "ansi-regex@^2.0.0", - "_id": "ansi-regex@2.1.1", - "_inBundle": false, - "_integrity": "sha1-w7M6te42DYbg5ijwRorn7yfWVN8=", - "_location": "/ansi-regex", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "ansi-regex@^2.0.0", - "name": "ansi-regex", - "escapedName": "ansi-regex", - "rawSpec": "^2.0.0", - "saveSpec": null, - "fetchSpec": "^2.0.0" - }, - "_requiredBy": [ - "/has-ansi", - "/strip-ansi" - ], - "_resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-2.1.1.tgz", - "_shasum": "c3b33ab5ee360d86e0e628f0468ae7ef27d654df", - "_spec": "ansi-regex@^2.0.0", - "_where": "/home/jan/Documents/skweb/node_modules/has-ansi", - "author": { - "name": "Sindre Sorhus", - "email": "sindresorhus@gmail.com", - "url": "sindresorhus.com" - }, - "bugs": { - "url": "https://github.com/chalk/ansi-regex/issues" - }, - "bundleDependencies": false, - "deprecated": false, - "description": "Regular expression for matching ANSI escape codes", - "devDependencies": { - "ava": "0.17.0", - "xo": "0.16.0" - }, - "engines": { - "node": ">=0.10.0" - }, - "files": [ - "index.js" - ], - "homepage": "https://github.com/chalk/ansi-regex#readme", - "keywords": [ - "ansi", - "styles", - "color", - "colour", - "colors", - "terminal", - "console", - "cli", - "string", - "tty", - "escape", - "formatting", - "rgb", - "256", - "shell", - "xterm", - "command-line", - "text", - "regex", - "regexp", - "re", - "match", - "test", - "find", - "pattern" - ], - "license": "MIT", - "maintainers": [ - { - "name": "Sindre Sorhus", - "email": "sindresorhus@gmail.com", - "url": "sindresorhus.com" - }, - { - "name": "Joshua Appelman", - "email": "jappelman@xebia.com", - "url": "jbnicolai.com" - }, - { - "name": "JD Ballard", - "email": "i.am.qix@gmail.com", - "url": "github.com/qix-" - } - ], - "name": "ansi-regex", - "repository": { - "type": "git", - "url": "git+https://github.com/chalk/ansi-regex.git" - }, - "scripts": { - "test": "xo && ava --verbose", - "view-supported": "node fixtures/view-codes.js" - }, - "version": "2.1.1", - "xo": { - "rules": { - "guard-for-in": 0, - "no-loop-func": 0 - } - } -} diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/ansi-regex/readme.md b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/ansi-regex/readme.md deleted file mode 100644 index 6a928edf0f..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/ansi-regex/readme.md +++ /dev/null @@ -1,39 +0,0 @@ -# ansi-regex [![Build Status](https://travis-ci.org/chalk/ansi-regex.svg?branch=master)](https://travis-ci.org/chalk/ansi-regex) - -> Regular expression for matching [ANSI escape codes](http://en.wikipedia.org/wiki/ANSI_escape_code) - - -## Install - -``` -$ npm install --save ansi-regex -``` - - -## Usage - -```js -const ansiRegex = require('ansi-regex'); - -ansiRegex().test('\u001b[4mcake\u001b[0m'); -//=> true - -ansiRegex().test('cake'); -//=> false - -'\u001b[4mcake\u001b[0m'.match(ansiRegex()); -//=> ['\u001b[4m', '\u001b[0m'] -``` - -## FAQ - -### Why do you test for codes not in the ECMA 48 standard? - -Some of the codes we run as a test are codes that we acquired finding various lists of non-standard or manufacturer specific codes. If I recall correctly, we test for both standard and non-standard codes, as most of them follow the same or similar format and can be safely matched in strings without the risk of removing actual string content. There are a few non-standard control codes that do not follow the traditional format (i.e. they end in numbers) thus forcing us to exclude them from the test because we cannot reliably match them. - -On the historical side, those ECMA standards were established in the early 90's whereas the VT100, for example, was designed in the mid/late 70's. At that point in time, control codes were still pretty ungoverned and engineers used them for a multitude of things, namely to activate hardware ports that may have been proprietary. Somewhere else you see a similar 'anarchy' of codes is in the x86 architecture for processors; there are a ton of "interrupts" that can mean different things on certain brands of processors, most of which have been phased out. - - -## License - -MIT © [Sindre Sorhus](http://sindresorhus.com) diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/ansi-styles/index.js b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/ansi-styles/index.js deleted file mode 100644 index 78945278f7..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/ansi-styles/index.js +++ /dev/null @@ -1,65 +0,0 @@ -'use strict'; - -function assembleStyles () { - var styles = { - modifiers: { - reset: [0, 0], - bold: [1, 22], // 21 isn't widely supported and 22 does the same thing - dim: [2, 22], - italic: [3, 23], - underline: [4, 24], - inverse: [7, 27], - hidden: [8, 28], - strikethrough: [9, 29] - }, - colors: { - black: [30, 39], - red: [31, 39], - green: [32, 39], - yellow: [33, 39], - blue: [34, 39], - magenta: [35, 39], - cyan: [36, 39], - white: [37, 39], - gray: [90, 39] - }, - bgColors: { - bgBlack: [40, 49], - bgRed: [41, 49], - bgGreen: [42, 49], - bgYellow: [43, 49], - bgBlue: [44, 49], - bgMagenta: [45, 49], - bgCyan: [46, 49], - bgWhite: [47, 49] - } - }; - - // fix humans - styles.colors.grey = styles.colors.gray; - - Object.keys(styles).forEach(function (groupName) { - var group = styles[groupName]; - - Object.keys(group).forEach(function (styleName) { - var style = group[styleName]; - - styles[styleName] = group[styleName] = { - open: '\u001b[' + style[0] + 'm', - close: '\u001b[' + style[1] + 'm' - }; - }); - - Object.defineProperty(styles, groupName, { - value: group, - enumerable: false - }); - }); - - return styles; -} - -Object.defineProperty(module, 'exports', { - enumerable: true, - get: assembleStyles -}); diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/ansi-styles/license b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/ansi-styles/license deleted file mode 100644 index 654d0bfe94..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/ansi-styles/license +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) Sindre Sorhus (sindresorhus.com) - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/ansi-styles/package.json b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/ansi-styles/package.json deleted file mode 100644 index 4083a72ac2..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/ansi-styles/package.json +++ /dev/null @@ -1,90 +0,0 @@ -{ - "_from": "ansi-styles@^2.2.1", - "_id": "ansi-styles@2.2.1", - "_inBundle": false, - "_integrity": "sha1-tDLdM1i2NM914eRmQ2gkBTPB3b4=", - "_location": "/ansi-styles", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "ansi-styles@^2.2.1", - "name": "ansi-styles", - "escapedName": "ansi-styles", - "rawSpec": "^2.2.1", - "saveSpec": null, - "fetchSpec": "^2.2.1" - }, - "_requiredBy": [ - "/chalk" - ], - "_resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-2.2.1.tgz", - "_shasum": "b432dd3358b634cf75e1e4664368240533c1ddbe", - "_spec": "ansi-styles@^2.2.1", - "_where": "/home/jan/Documents/skweb/node_modules/chalk", - "author": { - "name": "Sindre Sorhus", - "email": "sindresorhus@gmail.com", - "url": "sindresorhus.com" - }, - "bugs": { - "url": "https://github.com/chalk/ansi-styles/issues" - }, - "bundleDependencies": false, - "deprecated": false, - "description": "ANSI escape codes for styling strings in the terminal", - "devDependencies": { - "mocha": "*" - }, - "engines": { - "node": ">=0.10.0" - }, - "files": [ - "index.js" - ], - "homepage": "https://github.com/chalk/ansi-styles#readme", - "keywords": [ - "ansi", - "styles", - "color", - "colour", - "colors", - "terminal", - "console", - "cli", - "string", - "tty", - "escape", - "formatting", - "rgb", - "256", - "shell", - "xterm", - "log", - "logging", - "command-line", - "text" - ], - "license": "MIT", - "maintainers": [ - { - "name": "Sindre Sorhus", - "email": "sindresorhus@gmail.com", - "url": "sindresorhus.com" - }, - { - "name": "Joshua Appelman", - "email": "jappelman@xebia.com", - "url": "jbnicolai.com" - } - ], - "name": "ansi-styles", - "repository": { - "type": "git", - "url": "git+https://github.com/chalk/ansi-styles.git" - }, - "scripts": { - "test": "mocha" - }, - "version": "2.2.1" -} diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/ansi-styles/readme.md b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/ansi-styles/readme.md deleted file mode 100644 index 3f933f6162..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/ansi-styles/readme.md +++ /dev/null @@ -1,86 +0,0 @@ -# ansi-styles [![Build Status](https://travis-ci.org/chalk/ansi-styles.svg?branch=master)](https://travis-ci.org/chalk/ansi-styles) - -> [ANSI escape codes](http://en.wikipedia.org/wiki/ANSI_escape_code#Colors_and_Styles) for styling strings in the terminal - -You probably want the higher-level [chalk](https://github.com/chalk/chalk) module for styling your strings. - -![](screenshot.png) - - -## Install - -``` -$ npm install --save ansi-styles -``` - - -## Usage - -```js -var ansi = require('ansi-styles'); - -console.log(ansi.green.open + 'Hello world!' + ansi.green.close); -``` - - -## API - -Each style has an `open` and `close` property. - - -## Styles - -### Modifiers - -- `reset` -- `bold` -- `dim` -- `italic` *(not widely supported)* -- `underline` -- `inverse` -- `hidden` -- `strikethrough` *(not widely supported)* - -### Colors - -- `black` -- `red` -- `green` -- `yellow` -- `blue` -- `magenta` -- `cyan` -- `white` -- `gray` - -### Background colors - -- `bgBlack` -- `bgRed` -- `bgGreen` -- `bgYellow` -- `bgBlue` -- `bgMagenta` -- `bgCyan` -- `bgWhite` - - -## Advanced usage - -By default you get a map of styles, but the styles are also available as groups. They are non-enumerable so they don't show up unless you access them explicitly. This makes it easier to expose only a subset in a higher-level module. - -- `ansi.modifiers` -- `ansi.colors` -- `ansi.bgColors` - - -###### Example - -```js -console.log(ansi.colors.green.open); -``` - - -## License - -MIT © [Sindre Sorhus](http://sindresorhus.com) diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/array-filter/.npmignore b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/array-filter/.npmignore deleted file mode 100644 index 3c3629e647..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/array-filter/.npmignore +++ /dev/null @@ -1 +0,0 @@ -node_modules diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/array-filter/.travis.yml b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/array-filter/.travis.yml deleted file mode 100644 index cc4dba29d9..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/array-filter/.travis.yml +++ /dev/null @@ -1,4 +0,0 @@ -language: node_js -node_js: - - "0.8" - - "0.10" diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/array-filter/README.md b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/array-filter/README.md deleted file mode 100644 index c078005248..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/array-filter/README.md +++ /dev/null @@ -1,67 +0,0 @@ - -# array-filter - -`Array#filter` for older browsers. - -[![build status](https://secure.travis-ci.org/juliangruber/array-filter.png)](http://travis-ci.org/juliangruber/array-filter) -[![downloads](https://img.shields.io/npm/dm/array-filter.svg)](https://www.npmjs.org/package/array-filter) - -[![testling badge](https://ci.testling.com/juliangruber/array-filter.png)](https://ci.testling.com/juliangruber/array-filter) - -## Usage - -```js -var filter = require('array-filter'); - -var array = [1, 2, 3]; -console.log(filter(array, function (el, i, arr) { - return false; // I throw it on the ground! -})); -// => [] -``` - -## API - -### filter(arr, fn[, self]) - -Return an array with elements of `arr` for which `fn` returns a truthy value. `fn` is called with - -* `el`: The current element -* `i`: The element's index -* `arr`: The whole array - -Optionally pass in `self` as the `this` value for `fn`. - -## Installation - -With [npm](http://npmjs.org) do - -```bash -$ npm install array-filter -``` - -Then bundle for the browser with [browserify](https://github.com/substack/browserify). - -## License - -(MIT) - -Copyright (c) 2013 Julian Gruber <julian@juliangruber.com> - -Permission is hereby granted, free of charge, to any person obtaining a copy of -this software and associated documentation files (the "Software"), to deal in -the Software without restriction, including without limitation the rights to -use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies -of the Software, and to permit persons to whom the Software is furnished to do -so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/array-filter/index.js b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/array-filter/index.js deleted file mode 100644 index 40c0133d07..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/array-filter/index.js +++ /dev/null @@ -1,25 +0,0 @@ - -/** - * Array#filter. - * - * @param {Array} arr - * @param {Function} fn - * @param {Object=} self - * @return {Array} - * @throw TypeError - */ - -module.exports = function (arr, fn, self) { - if (arr.filter) return arr.filter(fn, self); - if (void 0 === arr || null === arr) throw new TypeError; - if ('function' != typeof fn) throw new TypeError; - var ret = []; - for (var i = 0; i < arr.length; i++) { - if (!hasOwn.call(arr, i)) continue; - var val = arr[i]; - if (fn.call(self, val, i, arr)) ret.push(val); - } - return ret; -}; - -var hasOwn = Object.prototype.hasOwnProperty; diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/array-filter/package.json b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/array-filter/package.json deleted file mode 100644 index 16bbf4da01..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/array-filter/package.json +++ /dev/null @@ -1,75 +0,0 @@ -{ - "_from": "array-filter@^1.0.0", - "_id": "array-filter@1.0.0", - "_inBundle": false, - "_integrity": "sha1-uveeYubvTCpMC4MSMtr/7CUfnYM=", - "_location": "/array-filter", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "array-filter@^1.0.0", - "name": "array-filter", - "escapedName": "array-filter", - "rawSpec": "^1.0.0", - "saveSpec": null, - "fetchSpec": "^1.0.0" - }, - "_requiredBy": [ - "/available-typed-arrays" - ], - "_resolved": "https://registry.npmjs.org/array-filter/-/array-filter-1.0.0.tgz", - "_shasum": "baf79e62e6ef4c2a4c0b831232daffec251f9d83", - "_spec": "array-filter@^1.0.0", - "_where": "/home/jan/Documents/skweb/node_modules/available-typed-arrays", - "author": { - "name": "Julian Gruber", - "email": "mail@juliangruber.com", - "url": "http://juliangruber.com" - }, - "bugs": { - "url": "https://github.com/juliangruber/array-filter/issues" - }, - "bundleDependencies": false, - "dependencies": {}, - "deprecated": false, - "description": "Array#filter for older browsers.", - "devDependencies": { - "tape": "~2.3.2" - }, - "homepage": "https://github.com/juliangruber/array-filter", - "keywords": [ - "array", - "filter", - "browser", - "html", - "browserify" - ], - "license": "MIT", - "main": "index.js", - "name": "array-filter", - "repository": { - "type": "git", - "url": "git://github.com/juliangruber/array-filter.git" - }, - "scripts": { - "test": "tape test/*.js" - }, - "testling": { - "files": "test/*.js", - "browsers": [ - "ie/8..latest", - "firefox/17..latest", - "firefox/nightly", - "chrome/22..latest", - "chrome/canary", - "opera/12..latest", - "opera/next", - "safari/5.1..latest", - "ipad/6.0..latest", - "iphone/6.0..latest", - "android-browser/4.2..latest" - ] - }, - "version": "1.0.0" -} diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/array-filter/test/filter.js b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/array-filter/test/filter.js deleted file mode 100644 index 9a2a186f51..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/array-filter/test/filter.js +++ /dev/null @@ -1,12 +0,0 @@ -var filter = require('..'); -var test = require('tape'); - -test('filter', function(t) { - var arr = [1, 2, 3, 4, 5]; - arr.filter = undefined; - var even = filter(arr, function(el) { - return el % 2 == 0; - }); - t.deepEqual(even, [2, 4]); - t.end(); -}); diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/array-filter/test/holes.js b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/array-filter/test/holes.js deleted file mode 100644 index 3fbfa951f5..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/array-filter/test/holes.js +++ /dev/null @@ -1,12 +0,0 @@ -var filter = require('..'); -var test = require('tape'); - -test('skip over holes', function(t) { - var arr = new Array(5); - arr.filter = undefined; - var res = filter(arr, function(el) { - return false; - }); - t.deepEqual(res, []); - t.end(); -}); diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/array-filter/test/modify.js b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/array-filter/test/modify.js deleted file mode 100644 index 4ca62b119c..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/array-filter/test/modify.js +++ /dev/null @@ -1,13 +0,0 @@ -var filter = require('..'); -var test = require('tape'); - -test('modify', function(t) { - var arr = ['foo']; - arr.filter = undefined; - var mod = filter(arr, function(el, i, arr) { - arr[i] = 'bar'; - return true; - }); - t.deepEqual(mod, ['foo']); - t.end(); -}); diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/array-filter/test/self.js b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/array-filter/test/self.js deleted file mode 100644 index 9252530b56..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/array-filter/test/self.js +++ /dev/null @@ -1,12 +0,0 @@ -var filter = require('..'); -var test = require('tape'); - -test('self', function(t) { - var arr = [1]; - arr.filter = undefined; - var self = {}; - filter(arr, function(el) { - t.equal(this, self); - t.end(); - }, self); -}); diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/array-filter/test/this-arg.js b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/array-filter/test/this-arg.js deleted file mode 100644 index 877221a0e8..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/array-filter/test/this-arg.js +++ /dev/null @@ -1,21 +0,0 @@ -var filter = require('..'); -var test = require('tape'); - -test('thisArg', function(t) { - var self = {}; - var arr = [1]; - arr.filter = undefined; - filter(arr, function(el) { - t.equal(this, self); - t.end(); - }, self); -}); - -test('thisArg native', function(t) { - var self = {}; - var arr = [1]; - filter(arr, function(el) { - t.equal(this, self); - t.end(); - }, self); -}); diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/array-filter/test/typecheck.js b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/array-filter/test/typecheck.js deleted file mode 100644 index 61c39f9bfd..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/array-filter/test/typecheck.js +++ /dev/null @@ -1,21 +0,0 @@ -var filter = require('..'); -var test = require('tape'); - -test('typecheck', function(t) { - var arr = []; - arr.filter = undefined; - - t.throws(function() { - filter(undefined, function(){}); - }, 'arr undefined'); - - t.throws(function() { - filter(null, function(){}); - }, 'arr null'); - - t.throws(function() { - filter(arr, {}); - }, 'fn wrong type'); - - t.end(); -}); diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/array-flatten/LICENSE b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/array-flatten/LICENSE deleted file mode 100644 index 983fbe8aec..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/array-flatten/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2014 Blake Embrey (hello@blakeembrey.com) - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/array-flatten/README.md b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/array-flatten/README.md deleted file mode 100644 index 91fa5b637e..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/array-flatten/README.md +++ /dev/null @@ -1,43 +0,0 @@ -# Array Flatten - -[![NPM version][npm-image]][npm-url] -[![NPM downloads][downloads-image]][downloads-url] -[![Build status][travis-image]][travis-url] -[![Test coverage][coveralls-image]][coveralls-url] - -> Flatten an array of nested arrays into a single flat array. Accepts an optional depth. - -## Installation - -``` -npm install array-flatten --save -``` - -## Usage - -```javascript -var flatten = require('array-flatten') - -flatten([1, [2, [3, [4, [5], 6], 7], 8], 9]) -//=> [1, 2, 3, 4, 5, 6, 7, 8, 9] - -flatten([1, [2, [3, [4, [5], 6], 7], 8], 9], 2) -//=> [1, 2, 3, [4, [5], 6], 7, 8, 9] - -(function () { - flatten(arguments) //=> [1, 2, 3] -})(1, [2, 3]) -``` - -## License - -MIT - -[npm-image]: https://img.shields.io/npm/v/array-flatten.svg?style=flat -[npm-url]: https://npmjs.org/package/array-flatten -[downloads-image]: https://img.shields.io/npm/dm/array-flatten.svg?style=flat -[downloads-url]: https://npmjs.org/package/array-flatten -[travis-image]: https://img.shields.io/travis/blakeembrey/array-flatten.svg?style=flat -[travis-url]: https://travis-ci.org/blakeembrey/array-flatten -[coveralls-image]: https://img.shields.io/coveralls/blakeembrey/array-flatten.svg?style=flat -[coveralls-url]: https://coveralls.io/r/blakeembrey/array-flatten?branch=master diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/array-flatten/array-flatten.js b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/array-flatten/array-flatten.js deleted file mode 100644 index 089117b322..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/array-flatten/array-flatten.js +++ /dev/null @@ -1,64 +0,0 @@ -'use strict' - -/** - * Expose `arrayFlatten`. - */ -module.exports = arrayFlatten - -/** - * Recursive flatten function with depth. - * - * @param {Array} array - * @param {Array} result - * @param {Number} depth - * @return {Array} - */ -function flattenWithDepth (array, result, depth) { - for (var i = 0; i < array.length; i++) { - var value = array[i] - - if (depth > 0 && Array.isArray(value)) { - flattenWithDepth(value, result, depth - 1) - } else { - result.push(value) - } - } - - return result -} - -/** - * Recursive flatten function. Omitting depth is slightly faster. - * - * @param {Array} array - * @param {Array} result - * @return {Array} - */ -function flattenForever (array, result) { - for (var i = 0; i < array.length; i++) { - var value = array[i] - - if (Array.isArray(value)) { - flattenForever(value, result) - } else { - result.push(value) - } - } - - return result -} - -/** - * Flatten an array, with the ability to define a depth. - * - * @param {Array} array - * @param {Number} depth - * @return {Array} - */ -function arrayFlatten (array, depth) { - if (depth == null) { - return flattenForever(array, []) - } - - return flattenWithDepth(array, [], depth) -} diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/array-flatten/package.json b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/array-flatten/package.json deleted file mode 100644 index 0f22847fca..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/array-flatten/package.json +++ /dev/null @@ -1,64 +0,0 @@ -{ - "_from": "array-flatten@1.1.1", - "_id": "array-flatten@1.1.1", - "_inBundle": false, - "_integrity": "sha1-ml9pkFGx5wczKPKgCJaLZOopVdI=", - "_location": "/array-flatten", - "_phantomChildren": {}, - "_requested": { - "type": "version", - "registry": true, - "raw": "array-flatten@1.1.1", - "name": "array-flatten", - "escapedName": "array-flatten", - "rawSpec": "1.1.1", - "saveSpec": null, - "fetchSpec": "1.1.1" - }, - "_requiredBy": [ - "/express" - ], - "_resolved": "https://registry.npmjs.org/array-flatten/-/array-flatten-1.1.1.tgz", - "_shasum": "9a5f699051b1e7073328f2a008968b64ea2955d2", - "_spec": "array-flatten@1.1.1", - "_where": "/home/jan/Documents/skweb/node_modules/express", - "author": { - "name": "Blake Embrey", - "email": "hello@blakeembrey.com", - "url": "http://blakeembrey.me" - }, - "bugs": { - "url": "https://github.com/blakeembrey/array-flatten/issues" - }, - "bundleDependencies": false, - "deprecated": false, - "description": "Flatten an array of nested arrays into a single flat array", - "devDependencies": { - "istanbul": "^0.3.13", - "mocha": "^2.2.4", - "pre-commit": "^1.0.7", - "standard": "^3.7.3" - }, - "files": [ - "array-flatten.js", - "LICENSE" - ], - "homepage": "https://github.com/blakeembrey/array-flatten", - "keywords": [ - "array", - "flatten", - "arguments", - "depth" - ], - "license": "MIT", - "main": "array-flatten.js", - "name": "array-flatten", - "repository": { - "type": "git", - "url": "git://github.com/blakeembrey/array-flatten.git" - }, - "scripts": { - "test": "istanbul cover _mocha -- -R spec" - }, - "version": "1.1.1" -} diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/assert/CHANGELOG.md b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/assert/CHANGELOG.md deleted file mode 100644 index 807626d6c4..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/assert/CHANGELOG.md +++ /dev/null @@ -1,14 +0,0 @@ -# assert change log - -All notable changes to this project will be documented in this file. - -This project adheres to [Semantic Versioning](http://semver.org/). - -## 2.0.0 - -* Sync with Node.js master. ([@lukechilds](https://github.com/lukechilds) in [#44](https://github.com/browserify/commonjs-assert/pull/44)) - -**Note:** Support for IE9 and IE10 has been dropped. IE11 is still supported. - -## 1.5.0 -* Add strict mode APIs. ([@lukechilds](https://github.com/lukechilds) in [#41](https://github.com/browserify/commonjs-assert/pull/41)) diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/assert/LICENSE b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/assert/LICENSE deleted file mode 100644 index e3d4e695a4..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/assert/LICENSE +++ /dev/null @@ -1,18 +0,0 @@ -Copyright Joyent, Inc. and other Node contributors. All rights reserved. -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to -deal in the Software without restriction, including without limitation the -rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -sell copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -IN THE SOFTWARE. diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/assert/README.md b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/assert/README.md deleted file mode 100644 index e2cc9e154e..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/assert/README.md +++ /dev/null @@ -1,73 +0,0 @@ -# assert - -> The [`assert`](https://nodejs.org/api/assert.html) module from Node.js, for the browser. - -[![Build Status](https://travis-ci.org/browserify/commonjs-assert.svg?branch=master)](https://travis-ci.org/browserify/commonjs-assert) -[![npm](https://img.shields.io/npm/dm/assert.svg)](https://www.npmjs.com/package/assert) -[![npm](https://img.shields.io/npm/v/assert.svg)](https://www.npmjs.com/package/assert) - -With browserify, simply `require('assert')` or use the `assert` global and you will get this module. - -The goal is to provide an API that is as functionally identical to the [Node.js `assert` API](https://nodejs.org/api/assert.html) as possible. Read the [official docs](https://nodejs.org/api/assert.html) for API documentation. - -## Install - -To use this module directly (without browserify), install it as a dependency: - -``` -npm install assert -``` - -## Usage - -The goal is to provide an API that is as functionally identical to the [Node.js `assert` API](https://nodejs.org/api/assert.html) as possible. Read the [official docs](https://nodejs.org/api/assert.html) for API documentation. - -### Inconsistencies with Node.js `assert` - -Due to differences between browsers, some error properties such as `message` and `stack` will be inconsistent. However the assertion behaviour is as close as possible to Node.js and the same error `code` will always be used. - -## Contributing - -To contribute, work on the source files. Then build and run the tests against the built files. Be careful to not introduce syntax that will be transpiled down to unsupported syntax. For example, `for...of` loops will be transpiled to use `Symbol.iterator` which is unavailable in IE. - -### Build scripts - -#### `npm run build` - -Builds the project into the `build` dir. - -#### `npm run dev` - -Watches source files for changes and rebuilds them into the `build` dir. - -#### `npm run test` - -Builds the source files into the `build` dir and then runs the tests against the built project. - -#### `npm run test:nobuild` - -Runs the tests against the built project without rebuilding first. - -This is useful if you're debugging in the transpiled code and want to re-run the tests without overwriting any changes you may have made. - -#### `npm run test:source` - -Runs the tests against the unbuilt source files. - -This will only work on modern Node.js versions. - -#### `npm run test:browsers` - -Run browser tests against the all targets in the cloud. - -Requires airtap credentials to be configured on your machine. - -#### `npm run test:browsers:local` - -Run a local browser test server. No airtap configuration required. - -When paired with `npm run dev` any changes you make to the source files will be automatically transpiled and served on the next request to the test server. - -## License - -MIT © Joyent, Inc. and other Node contributors diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/assert/build/assert.js b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/assert/build/assert.js deleted file mode 100644 index a4bc0a810b..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/assert/build/assert.js +++ /dev/null @@ -1,631 +0,0 @@ -// Currently in sync with Node.js lib/assert.js -// https://github.com/nodejs/node/commit/2a51ae424a513ec9a6aa3466baa0cc1d55dd4f3b -// Originally from narwhal.js (http://narwhaljs.org) -// Copyright (c) 2009 Thomas Robinson <280north.com> -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the 'Software'), to -// deal in the Software without restriction, including without limitation the -// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -// sell copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN -// ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -'use strict'; - -function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } - -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -var _require = require('./internal/errors'), - _require$codes = _require.codes, - ERR_AMBIGUOUS_ARGUMENT = _require$codes.ERR_AMBIGUOUS_ARGUMENT, - ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE, - ERR_INVALID_ARG_VALUE = _require$codes.ERR_INVALID_ARG_VALUE, - ERR_INVALID_RETURN_VALUE = _require$codes.ERR_INVALID_RETURN_VALUE, - ERR_MISSING_ARGS = _require$codes.ERR_MISSING_ARGS; - -var AssertionError = require('./internal/assert/assertion_error'); - -var _require2 = require('util/'), - inspect = _require2.inspect; - -var _require$types = require('util/').types, - isPromise = _require$types.isPromise, - isRegExp = _require$types.isRegExp; - -var objectAssign = Object.assign ? Object.assign : require('es6-object-assign').assign; -var objectIs = Object.is ? Object.is : require('object-is'); -var errorCache = new Map(); -var isDeepEqual; -var isDeepStrictEqual; -var parseExpressionAt; -var findNodeAround; -var decoder; - -function lazyLoadComparison() { - var comparison = require('./internal/util/comparisons'); - - isDeepEqual = comparison.isDeepEqual; - isDeepStrictEqual = comparison.isDeepStrictEqual; -} // Escape control characters but not \n and \t to keep the line breaks and -// indentation intact. -// eslint-disable-next-line no-control-regex - - -var escapeSequencesRegExp = /[\x00-\x08\x0b\x0c\x0e-\x1f]/g; -var meta = ["\\u0000", "\\u0001", "\\u0002", "\\u0003", "\\u0004", "\\u0005", "\\u0006", "\\u0007", '\\b', '', '', "\\u000b", '\\f', '', "\\u000e", "\\u000f", "\\u0010", "\\u0011", "\\u0012", "\\u0013", "\\u0014", "\\u0015", "\\u0016", "\\u0017", "\\u0018", "\\u0019", "\\u001a", "\\u001b", "\\u001c", "\\u001d", "\\u001e", "\\u001f"]; - -var escapeFn = function escapeFn(str) { - return meta[str.charCodeAt(0)]; -}; - -var warned = false; // The assert module provides functions that throw -// AssertionError's when particular conditions are not met. The -// assert module must conform to the following interface. - -var assert = module.exports = ok; -var NO_EXCEPTION_SENTINEL = {}; // All of the following functions must throw an AssertionError -// when a corresponding condition is not met, with a message that -// may be undefined if not provided. All assertion methods provide -// both the actual and expected values to the assertion error for -// display purposes. - -function innerFail(obj) { - if (obj.message instanceof Error) throw obj.message; - throw new AssertionError(obj); -} - -function fail(actual, expected, message, operator, stackStartFn) { - var argsLen = arguments.length; - var internalMessage; - - if (argsLen === 0) { - internalMessage = 'Failed'; - } else if (argsLen === 1) { - message = actual; - actual = undefined; - } else { - if (warned === false) { - warned = true; - var warn = process.emitWarning ? process.emitWarning : console.warn.bind(console); - warn('assert.fail() with more than one argument is deprecated. ' + 'Please use assert.strictEqual() instead or only pass a message.', 'DeprecationWarning', 'DEP0094'); - } - - if (argsLen === 2) operator = '!='; - } - - if (message instanceof Error) throw message; - var errArgs = { - actual: actual, - expected: expected, - operator: operator === undefined ? 'fail' : operator, - stackStartFn: stackStartFn || fail - }; - - if (message !== undefined) { - errArgs.message = message; - } - - var err = new AssertionError(errArgs); - - if (internalMessage) { - err.message = internalMessage; - err.generatedMessage = true; - } - - throw err; -} - -assert.fail = fail; // The AssertionError is defined in internal/error. - -assert.AssertionError = AssertionError; - -function innerOk(fn, argLen, value, message) { - if (!value) { - var generatedMessage = false; - - if (argLen === 0) { - generatedMessage = true; - message = 'No value argument passed to `assert.ok()`'; - } else if (message instanceof Error) { - throw message; - } - - var err = new AssertionError({ - actual: value, - expected: true, - message: message, - operator: '==', - stackStartFn: fn - }); - err.generatedMessage = generatedMessage; - throw err; - } -} // Pure assertion tests whether a value is truthy, as determined -// by !!value. - - -function ok() { - for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { - args[_key] = arguments[_key]; - } - - innerOk.apply(void 0, [ok, args.length].concat(args)); -} - -assert.ok = ok; // The equality assertion tests shallow, coercive equality with ==. - -/* eslint-disable no-restricted-properties */ - -assert.equal = function equal(actual, expected, message) { - if (arguments.length < 2) { - throw new ERR_MISSING_ARGS('actual', 'expected'); - } // eslint-disable-next-line eqeqeq - - - if (actual != expected) { - innerFail({ - actual: actual, - expected: expected, - message: message, - operator: '==', - stackStartFn: equal - }); - } -}; // The non-equality assertion tests for whether two objects are not -// equal with !=. - - -assert.notEqual = function notEqual(actual, expected, message) { - if (arguments.length < 2) { - throw new ERR_MISSING_ARGS('actual', 'expected'); - } // eslint-disable-next-line eqeqeq - - - if (actual == expected) { - innerFail({ - actual: actual, - expected: expected, - message: message, - operator: '!=', - stackStartFn: notEqual - }); - } -}; // The equivalence assertion tests a deep equality relation. - - -assert.deepEqual = function deepEqual(actual, expected, message) { - if (arguments.length < 2) { - throw new ERR_MISSING_ARGS('actual', 'expected'); - } - - if (isDeepEqual === undefined) lazyLoadComparison(); - - if (!isDeepEqual(actual, expected)) { - innerFail({ - actual: actual, - expected: expected, - message: message, - operator: 'deepEqual', - stackStartFn: deepEqual - }); - } -}; // The non-equivalence assertion tests for any deep inequality. - - -assert.notDeepEqual = function notDeepEqual(actual, expected, message) { - if (arguments.length < 2) { - throw new ERR_MISSING_ARGS('actual', 'expected'); - } - - if (isDeepEqual === undefined) lazyLoadComparison(); - - if (isDeepEqual(actual, expected)) { - innerFail({ - actual: actual, - expected: expected, - message: message, - operator: 'notDeepEqual', - stackStartFn: notDeepEqual - }); - } -}; -/* eslint-enable */ - - -assert.deepStrictEqual = function deepStrictEqual(actual, expected, message) { - if (arguments.length < 2) { - throw new ERR_MISSING_ARGS('actual', 'expected'); - } - - if (isDeepEqual === undefined) lazyLoadComparison(); - - if (!isDeepStrictEqual(actual, expected)) { - innerFail({ - actual: actual, - expected: expected, - message: message, - operator: 'deepStrictEqual', - stackStartFn: deepStrictEqual - }); - } -}; - -assert.notDeepStrictEqual = notDeepStrictEqual; - -function notDeepStrictEqual(actual, expected, message) { - if (arguments.length < 2) { - throw new ERR_MISSING_ARGS('actual', 'expected'); - } - - if (isDeepEqual === undefined) lazyLoadComparison(); - - if (isDeepStrictEqual(actual, expected)) { - innerFail({ - actual: actual, - expected: expected, - message: message, - operator: 'notDeepStrictEqual', - stackStartFn: notDeepStrictEqual - }); - } -} - -assert.strictEqual = function strictEqual(actual, expected, message) { - if (arguments.length < 2) { - throw new ERR_MISSING_ARGS('actual', 'expected'); - } - - if (!objectIs(actual, expected)) { - innerFail({ - actual: actual, - expected: expected, - message: message, - operator: 'strictEqual', - stackStartFn: strictEqual - }); - } -}; - -assert.notStrictEqual = function notStrictEqual(actual, expected, message) { - if (arguments.length < 2) { - throw new ERR_MISSING_ARGS('actual', 'expected'); - } - - if (objectIs(actual, expected)) { - innerFail({ - actual: actual, - expected: expected, - message: message, - operator: 'notStrictEqual', - stackStartFn: notStrictEqual - }); - } -}; - -var Comparison = function Comparison(obj, keys, actual) { - var _this = this; - - _classCallCheck(this, Comparison); - - keys.forEach(function (key) { - if (key in obj) { - if (actual !== undefined && typeof actual[key] === 'string' && isRegExp(obj[key]) && obj[key].test(actual[key])) { - _this[key] = actual[key]; - } else { - _this[key] = obj[key]; - } - } - }); -}; - -function compareExceptionKey(actual, expected, key, message, keys, fn) { - if (!(key in actual) || !isDeepStrictEqual(actual[key], expected[key])) { - if (!message) { - // Create placeholder objects to create a nice output. - var a = new Comparison(actual, keys); - var b = new Comparison(expected, keys, actual); - var err = new AssertionError({ - actual: a, - expected: b, - operator: 'deepStrictEqual', - stackStartFn: fn - }); - err.actual = actual; - err.expected = expected; - err.operator = fn.name; - throw err; - } - - innerFail({ - actual: actual, - expected: expected, - message: message, - operator: fn.name, - stackStartFn: fn - }); - } -} - -function expectedException(actual, expected, msg, fn) { - if (typeof expected !== 'function') { - if (isRegExp(expected)) return expected.test(actual); // assert.doesNotThrow does not accept objects. - - if (arguments.length === 2) { - throw new ERR_INVALID_ARG_TYPE('expected', ['Function', 'RegExp'], expected); - } // Handle primitives properly. - - - if (_typeof(actual) !== 'object' || actual === null) { - var err = new AssertionError({ - actual: actual, - expected: expected, - message: msg, - operator: 'deepStrictEqual', - stackStartFn: fn - }); - err.operator = fn.name; - throw err; - } - - var keys = Object.keys(expected); // Special handle errors to make sure the name and the message are compared - // as well. - - if (expected instanceof Error) { - keys.push('name', 'message'); - } else if (keys.length === 0) { - throw new ERR_INVALID_ARG_VALUE('error', expected, 'may not be an empty object'); - } - - if (isDeepEqual === undefined) lazyLoadComparison(); - keys.forEach(function (key) { - if (typeof actual[key] === 'string' && isRegExp(expected[key]) && expected[key].test(actual[key])) { - return; - } - - compareExceptionKey(actual, expected, key, msg, keys, fn); - }); - return true; - } // Guard instanceof against arrow functions as they don't have a prototype. - - - if (expected.prototype !== undefined && actual instanceof expected) { - return true; - } - - if (Error.isPrototypeOf(expected)) { - return false; - } - - return expected.call({}, actual) === true; -} - -function getActual(fn) { - if (typeof fn !== 'function') { - throw new ERR_INVALID_ARG_TYPE('fn', 'Function', fn); - } - - try { - fn(); - } catch (e) { - return e; - } - - return NO_EXCEPTION_SENTINEL; -} - -function checkIsPromise(obj) { - // Accept native ES6 promises and promises that are implemented in a similar - // way. Do not accept thenables that use a function as `obj` and that have no - // `catch` handler. - // TODO: thenables are checked up until they have the correct methods, - // but according to documentation, the `then` method should receive - // the `fulfill` and `reject` arguments as well or it may be never resolved. - return isPromise(obj) || obj !== null && _typeof(obj) === 'object' && typeof obj.then === 'function' && typeof obj.catch === 'function'; -} - -function waitForActual(promiseFn) { - return Promise.resolve().then(function () { - var resultPromise; - - if (typeof promiseFn === 'function') { - // Return a rejected promise if `promiseFn` throws synchronously. - resultPromise = promiseFn(); // Fail in case no promise is returned. - - if (!checkIsPromise(resultPromise)) { - throw new ERR_INVALID_RETURN_VALUE('instance of Promise', 'promiseFn', resultPromise); - } - } else if (checkIsPromise(promiseFn)) { - resultPromise = promiseFn; - } else { - throw new ERR_INVALID_ARG_TYPE('promiseFn', ['Function', 'Promise'], promiseFn); - } - - return Promise.resolve().then(function () { - return resultPromise; - }).then(function () { - return NO_EXCEPTION_SENTINEL; - }).catch(function (e) { - return e; - }); - }); -} - -function expectsError(stackStartFn, actual, error, message) { - if (typeof error === 'string') { - if (arguments.length === 4) { - throw new ERR_INVALID_ARG_TYPE('error', ['Object', 'Error', 'Function', 'RegExp'], error); - } - - if (_typeof(actual) === 'object' && actual !== null) { - if (actual.message === error) { - throw new ERR_AMBIGUOUS_ARGUMENT('error/message', "The error message \"".concat(actual.message, "\" is identical to the message.")); - } - } else if (actual === error) { - throw new ERR_AMBIGUOUS_ARGUMENT('error/message', "The error \"".concat(actual, "\" is identical to the message.")); - } - - message = error; - error = undefined; - } else if (error != null && _typeof(error) !== 'object' && typeof error !== 'function') { - throw new ERR_INVALID_ARG_TYPE('error', ['Object', 'Error', 'Function', 'RegExp'], error); - } - - if (actual === NO_EXCEPTION_SENTINEL) { - var details = ''; - - if (error && error.name) { - details += " (".concat(error.name, ")"); - } - - details += message ? ": ".concat(message) : '.'; - var fnType = stackStartFn.name === 'rejects' ? 'rejection' : 'exception'; - innerFail({ - actual: undefined, - expected: error, - operator: stackStartFn.name, - message: "Missing expected ".concat(fnType).concat(details), - stackStartFn: stackStartFn - }); - } - - if (error && !expectedException(actual, error, message, stackStartFn)) { - throw actual; - } -} - -function expectsNoError(stackStartFn, actual, error, message) { - if (actual === NO_EXCEPTION_SENTINEL) return; - - if (typeof error === 'string') { - message = error; - error = undefined; - } - - if (!error || expectedException(actual, error)) { - var details = message ? ": ".concat(message) : '.'; - var fnType = stackStartFn.name === 'doesNotReject' ? 'rejection' : 'exception'; - innerFail({ - actual: actual, - expected: error, - operator: stackStartFn.name, - message: "Got unwanted ".concat(fnType).concat(details, "\n") + "Actual message: \"".concat(actual && actual.message, "\""), - stackStartFn: stackStartFn - }); - } - - throw actual; -} - -assert.throws = function throws(promiseFn) { - for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { - args[_key2 - 1] = arguments[_key2]; - } - - expectsError.apply(void 0, [throws, getActual(promiseFn)].concat(args)); -}; - -assert.rejects = function rejects(promiseFn) { - for (var _len3 = arguments.length, args = new Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) { - args[_key3 - 1] = arguments[_key3]; - } - - return waitForActual(promiseFn).then(function (result) { - return expectsError.apply(void 0, [rejects, result].concat(args)); - }); -}; - -assert.doesNotThrow = function doesNotThrow(fn) { - for (var _len4 = arguments.length, args = new Array(_len4 > 1 ? _len4 - 1 : 0), _key4 = 1; _key4 < _len4; _key4++) { - args[_key4 - 1] = arguments[_key4]; - } - - expectsNoError.apply(void 0, [doesNotThrow, getActual(fn)].concat(args)); -}; - -assert.doesNotReject = function doesNotReject(fn) { - for (var _len5 = arguments.length, args = new Array(_len5 > 1 ? _len5 - 1 : 0), _key5 = 1; _key5 < _len5; _key5++) { - args[_key5 - 1] = arguments[_key5]; - } - - return waitForActual(fn).then(function (result) { - return expectsNoError.apply(void 0, [doesNotReject, result].concat(args)); - }); -}; - -assert.ifError = function ifError(err) { - if (err !== null && err !== undefined) { - var message = 'ifError got unwanted exception: '; - - if (_typeof(err) === 'object' && typeof err.message === 'string') { - if (err.message.length === 0 && err.constructor) { - message += err.constructor.name; - } else { - message += err.message; - } - } else { - message += inspect(err); - } - - var newErr = new AssertionError({ - actual: err, - expected: null, - operator: 'ifError', - message: message, - stackStartFn: ifError - }); // Make sure we actually have a stack trace! - - var origStack = err.stack; - - if (typeof origStack === 'string') { - // This will remove any duplicated frames from the error frames taken - // from within `ifError` and add the original error frames to the newly - // created ones. - var tmp2 = origStack.split('\n'); - tmp2.shift(); // Filter all frames existing in err.stack. - - var tmp1 = newErr.stack.split('\n'); - - for (var i = 0; i < tmp2.length; i++) { - // Find the first occurrence of the frame. - var pos = tmp1.indexOf(tmp2[i]); - - if (pos !== -1) { - // Only keep new frames. - tmp1 = tmp1.slice(0, pos); - break; - } - } - - newErr.stack = "".concat(tmp1.join('\n'), "\n").concat(tmp2.join('\n')); - } - - throw newErr; - } -}; // Expose a strict only variant of assert - - -function strict() { - for (var _len6 = arguments.length, args = new Array(_len6), _key6 = 0; _key6 < _len6; _key6++) { - args[_key6] = arguments[_key6]; - } - - innerOk.apply(void 0, [strict, args.length].concat(args)); -} - -assert.strict = objectAssign(strict, assert, { - equal: assert.strictEqual, - deepEqual: assert.deepStrictEqual, - notEqual: assert.notStrictEqual, - notDeepEqual: assert.notDeepStrictEqual -}); -assert.strict.strict = assert.strict; \ No newline at end of file diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/assert/build/internal/assert/assertion_error.js b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/assert/build/internal/assert/assertion_error.js deleted file mode 100644 index 9295f0a283..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/assert/build/internal/assert/assertion_error.js +++ /dev/null @@ -1,501 +0,0 @@ -// Currently in sync with Node.js lib/internal/assert/assertion_error.js -// https://github.com/nodejs/node/commit/0817840f775032169ddd70c85ac059f18ffcc81c -'use strict'; - -function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === 'function') { ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function (key) { _defineProperty(target, key, source[key]); }); } return target; } - -function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } - -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } - -function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } - -function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } - -function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } - -function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } - -function _wrapNativeSuper(Class) { var _cache = typeof Map === "function" ? new Map() : undefined; _wrapNativeSuper = function _wrapNativeSuper(Class) { if (Class === null || !_isNativeFunction(Class)) return Class; if (typeof Class !== "function") { throw new TypeError("Super expression must either be null or a function"); } if (typeof _cache !== "undefined") { if (_cache.has(Class)) return _cache.get(Class); _cache.set(Class, Wrapper); } function Wrapper() { return _construct(Class, arguments, _getPrototypeOf(this).constructor); } Wrapper.prototype = Object.create(Class.prototype, { constructor: { value: Wrapper, enumerable: false, writable: true, configurable: true } }); return _setPrototypeOf(Wrapper, Class); }; return _wrapNativeSuper(Class); } - -function isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } - -function _construct(Parent, args, Class) { if (isNativeReflectConstruct()) { _construct = Reflect.construct; } else { _construct = function _construct(Parent, args, Class) { var a = [null]; a.push.apply(a, args); var Constructor = Function.bind.apply(Parent, a); var instance = new Constructor(); if (Class) _setPrototypeOf(instance, Class.prototype); return instance; }; } return _construct.apply(null, arguments); } - -function _isNativeFunction(fn) { return Function.toString.call(fn).indexOf("[native code]") !== -1; } - -function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } - -function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } - -function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } - -var _require = require('util/'), - inspect = _require.inspect; - -var _require2 = require('../errors'), - ERR_INVALID_ARG_TYPE = _require2.codes.ERR_INVALID_ARG_TYPE; // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith - - -function endsWith(str, search, this_len) { - if (this_len === undefined || this_len > str.length) { - this_len = str.length; - } - - return str.substring(this_len - search.length, this_len) === search; -} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/repeat - - -function repeat(str, count) { - count = Math.floor(count); - if (str.length == 0 || count == 0) return ''; - var maxCount = str.length * count; - count = Math.floor(Math.log(count) / Math.log(2)); - - while (count) { - str += str; - count--; - } - - str += str.substring(0, maxCount - str.length); - return str; -} - -var blue = ''; -var green = ''; -var red = ''; -var white = ''; -var kReadableOperator = { - deepStrictEqual: 'Expected values to be strictly deep-equal:', - strictEqual: 'Expected values to be strictly equal:', - strictEqualObject: 'Expected "actual" to be reference-equal to "expected":', - deepEqual: 'Expected values to be loosely deep-equal:', - equal: 'Expected values to be loosely equal:', - notDeepStrictEqual: 'Expected "actual" not to be strictly deep-equal to:', - notStrictEqual: 'Expected "actual" to be strictly unequal to:', - notStrictEqualObject: 'Expected "actual" not to be reference-equal to "expected":', - notDeepEqual: 'Expected "actual" not to be loosely deep-equal to:', - notEqual: 'Expected "actual" to be loosely unequal to:', - notIdentical: 'Values identical but not reference-equal:' -}; // Comparing short primitives should just show === / !== instead of using the -// diff. - -var kMaxShortLength = 10; - -function copyError(source) { - var keys = Object.keys(source); - var target = Object.create(Object.getPrototypeOf(source)); - keys.forEach(function (key) { - target[key] = source[key]; - }); - Object.defineProperty(target, 'message', { - value: source.message - }); - return target; -} - -function inspectValue(val) { - // The util.inspect default values could be changed. This makes sure the - // error messages contain the necessary information nevertheless. - return inspect(val, { - compact: false, - customInspect: false, - depth: 1000, - maxArrayLength: Infinity, - // Assert compares only enumerable properties (with a few exceptions). - showHidden: false, - // Having a long line as error is better than wrapping the line for - // comparison for now. - // TODO(BridgeAR): `breakLength` should be limited as soon as soon as we - // have meta information about the inspected properties (i.e., know where - // in what line the property starts and ends). - breakLength: Infinity, - // Assert does not detect proxies currently. - showProxy: false, - sorted: true, - // Inspect getters as we also check them when comparing entries. - getters: true - }); -} - -function createErrDiff(actual, expected, operator) { - var other = ''; - var res = ''; - var lastPos = 0; - var end = ''; - var skipped = false; - var actualInspected = inspectValue(actual); - var actualLines = actualInspected.split('\n'); - var expectedLines = inspectValue(expected).split('\n'); - var i = 0; - var indicator = ''; // In case both values are objects explicitly mark them as not reference equal - // for the `strictEqual` operator. - - if (operator === 'strictEqual' && _typeof(actual) === 'object' && _typeof(expected) === 'object' && actual !== null && expected !== null) { - operator = 'strictEqualObject'; - } // If "actual" and "expected" fit on a single line and they are not strictly - // equal, check further special handling. - - - if (actualLines.length === 1 && expectedLines.length === 1 && actualLines[0] !== expectedLines[0]) { - var inputLength = actualLines[0].length + expectedLines[0].length; // If the character length of "actual" and "expected" together is less than - // kMaxShortLength and if neither is an object and at least one of them is - // not `zero`, use the strict equal comparison to visualize the output. - - if (inputLength <= kMaxShortLength) { - if ((_typeof(actual) !== 'object' || actual === null) && (_typeof(expected) !== 'object' || expected === null) && (actual !== 0 || expected !== 0)) { - // -0 === +0 - return "".concat(kReadableOperator[operator], "\n\n") + "".concat(actualLines[0], " !== ").concat(expectedLines[0], "\n"); - } - } else if (operator !== 'strictEqualObject') { - // If the stderr is a tty and the input length is lower than the current - // columns per line, add a mismatch indicator below the output. If it is - // not a tty, use a default value of 80 characters. - var maxLength = process.stderr && process.stderr.isTTY ? process.stderr.columns : 80; - - if (inputLength < maxLength) { - while (actualLines[0][i] === expectedLines[0][i]) { - i++; - } // Ignore the first characters. - - - if (i > 2) { - // Add position indicator for the first mismatch in case it is a - // single line and the input length is less than the column length. - indicator = "\n ".concat(repeat(' ', i), "^"); - i = 0; - } - } - } - } // Remove all ending lines that match (this optimizes the output for - // readability by reducing the number of total changed lines). - - - var a = actualLines[actualLines.length - 1]; - var b = expectedLines[expectedLines.length - 1]; - - while (a === b) { - if (i++ < 2) { - end = "\n ".concat(a).concat(end); - } else { - other = a; - } - - actualLines.pop(); - expectedLines.pop(); - if (actualLines.length === 0 || expectedLines.length === 0) break; - a = actualLines[actualLines.length - 1]; - b = expectedLines[expectedLines.length - 1]; - } - - var maxLines = Math.max(actualLines.length, expectedLines.length); // Strict equal with identical objects that are not identical by reference. - // E.g., assert.deepStrictEqual({ a: Symbol() }, { a: Symbol() }) - - if (maxLines === 0) { - // We have to get the result again. The lines were all removed before. - var _actualLines = actualInspected.split('\n'); // Only remove lines in case it makes sense to collapse those. - // TODO: Accept env to always show the full error. - - - if (_actualLines.length > 30) { - _actualLines[26] = "".concat(blue, "...").concat(white); - - while (_actualLines.length > 27) { - _actualLines.pop(); - } - } - - return "".concat(kReadableOperator.notIdentical, "\n\n").concat(_actualLines.join('\n'), "\n"); - } - - if (i > 3) { - end = "\n".concat(blue, "...").concat(white).concat(end); - skipped = true; - } - - if (other !== '') { - end = "\n ".concat(other).concat(end); - other = ''; - } - - var printedLines = 0; - var msg = kReadableOperator[operator] + "\n".concat(green, "+ actual").concat(white, " ").concat(red, "- expected").concat(white); - var skippedMsg = " ".concat(blue, "...").concat(white, " Lines skipped"); - - for (i = 0; i < maxLines; i++) { - // Only extra expected lines exist - var cur = i - lastPos; - - if (actualLines.length < i + 1) { - // If the last diverging line is more than one line above and the - // current line is at least line three, add some of the former lines and - // also add dots to indicate skipped entries. - if (cur > 1 && i > 2) { - if (cur > 4) { - res += "\n".concat(blue, "...").concat(white); - skipped = true; - } else if (cur > 3) { - res += "\n ".concat(expectedLines[i - 2]); - printedLines++; - } - - res += "\n ".concat(expectedLines[i - 1]); - printedLines++; - } // Mark the current line as the last diverging one. - - - lastPos = i; // Add the expected line to the cache. - - other += "\n".concat(red, "-").concat(white, " ").concat(expectedLines[i]); - printedLines++; // Only extra actual lines exist - } else if (expectedLines.length < i + 1) { - // If the last diverging line is more than one line above and the - // current line is at least line three, add some of the former lines and - // also add dots to indicate skipped entries. - if (cur > 1 && i > 2) { - if (cur > 4) { - res += "\n".concat(blue, "...").concat(white); - skipped = true; - } else if (cur > 3) { - res += "\n ".concat(actualLines[i - 2]); - printedLines++; - } - - res += "\n ".concat(actualLines[i - 1]); - printedLines++; - } // Mark the current line as the last diverging one. - - - lastPos = i; // Add the actual line to the result. - - res += "\n".concat(green, "+").concat(white, " ").concat(actualLines[i]); - printedLines++; // Lines diverge - } else { - var expectedLine = expectedLines[i]; - var actualLine = actualLines[i]; // If the lines diverge, specifically check for lines that only diverge by - // a trailing comma. In that case it is actually identical and we should - // mark it as such. - - var divergingLines = actualLine !== expectedLine && (!endsWith(actualLine, ',') || actualLine.slice(0, -1) !== expectedLine); // If the expected line has a trailing comma but is otherwise identical, - // add a comma at the end of the actual line. Otherwise the output could - // look weird as in: - // - // [ - // 1 // No comma at the end! - // + 2 - // ] - // - - if (divergingLines && endsWith(expectedLine, ',') && expectedLine.slice(0, -1) === actualLine) { - divergingLines = false; - actualLine += ','; - } - - if (divergingLines) { - // If the last diverging line is more than one line above and the - // current line is at least line three, add some of the former lines and - // also add dots to indicate skipped entries. - if (cur > 1 && i > 2) { - if (cur > 4) { - res += "\n".concat(blue, "...").concat(white); - skipped = true; - } else if (cur > 3) { - res += "\n ".concat(actualLines[i - 2]); - printedLines++; - } - - res += "\n ".concat(actualLines[i - 1]); - printedLines++; - } // Mark the current line as the last diverging one. - - - lastPos = i; // Add the actual line to the result and cache the expected diverging - // line so consecutive diverging lines show up as +++--- and not +-+-+-. - - res += "\n".concat(green, "+").concat(white, " ").concat(actualLine); - other += "\n".concat(red, "-").concat(white, " ").concat(expectedLine); - printedLines += 2; // Lines are identical - } else { - // Add all cached information to the result before adding other things - // and reset the cache. - res += other; - other = ''; // If the last diverging line is exactly one line above or if it is the - // very first line, add the line to the result. - - if (cur === 1 || i === 0) { - res += "\n ".concat(actualLine); - printedLines++; - } - } - } // Inspected object to big (Show ~20 rows max) - - - if (printedLines > 20 && i < maxLines - 2) { - return "".concat(msg).concat(skippedMsg, "\n").concat(res, "\n").concat(blue, "...").concat(white).concat(other, "\n") + "".concat(blue, "...").concat(white); - } - } - - return "".concat(msg).concat(skipped ? skippedMsg : '', "\n").concat(res).concat(other).concat(end).concat(indicator); -} - -var AssertionError = -/*#__PURE__*/ -function (_Error) { - _inherits(AssertionError, _Error); - - function AssertionError(options) { - var _this; - - _classCallCheck(this, AssertionError); - - if (_typeof(options) !== 'object' || options === null) { - throw new ERR_INVALID_ARG_TYPE('options', 'Object', options); - } - - var message = options.message, - operator = options.operator, - stackStartFn = options.stackStartFn; - var actual = options.actual, - expected = options.expected; - var limit = Error.stackTraceLimit; - Error.stackTraceLimit = 0; - - if (message != null) { - _this = _possibleConstructorReturn(this, _getPrototypeOf(AssertionError).call(this, String(message))); - } else { - if (process.stderr && process.stderr.isTTY) { - // Reset on each call to make sure we handle dynamically set environment - // variables correct. - if (process.stderr && process.stderr.getColorDepth && process.stderr.getColorDepth() !== 1) { - blue = "\x1B[34m"; - green = "\x1B[32m"; - white = "\x1B[39m"; - red = "\x1B[31m"; - } else { - blue = ''; - green = ''; - white = ''; - red = ''; - } - } // Prevent the error stack from being visible by duplicating the error - // in a very close way to the original in case both sides are actually - // instances of Error. - - - if (_typeof(actual) === 'object' && actual !== null && _typeof(expected) === 'object' && expected !== null && 'stack' in actual && actual instanceof Error && 'stack' in expected && expected instanceof Error) { - actual = copyError(actual); - expected = copyError(expected); - } - - if (operator === 'deepStrictEqual' || operator === 'strictEqual') { - _this = _possibleConstructorReturn(this, _getPrototypeOf(AssertionError).call(this, createErrDiff(actual, expected, operator))); - } else if (operator === 'notDeepStrictEqual' || operator === 'notStrictEqual') { - // In case the objects are equal but the operator requires unequal, show - // the first object and say A equals B - var base = kReadableOperator[operator]; - var res = inspectValue(actual).split('\n'); // In case "actual" is an object, it should not be reference equal. - - if (operator === 'notStrictEqual' && _typeof(actual) === 'object' && actual !== null) { - base = kReadableOperator.notStrictEqualObject; - } // Only remove lines in case it makes sense to collapse those. - // TODO: Accept env to always show the full error. - - - if (res.length > 30) { - res[26] = "".concat(blue, "...").concat(white); - - while (res.length > 27) { - res.pop(); - } - } // Only print a single input. - - - if (res.length === 1) { - _this = _possibleConstructorReturn(this, _getPrototypeOf(AssertionError).call(this, "".concat(base, " ").concat(res[0]))); - } else { - _this = _possibleConstructorReturn(this, _getPrototypeOf(AssertionError).call(this, "".concat(base, "\n\n").concat(res.join('\n'), "\n"))); - } - } else { - var _res = inspectValue(actual); - - var other = ''; - var knownOperators = kReadableOperator[operator]; - - if (operator === 'notDeepEqual' || operator === 'notEqual') { - _res = "".concat(kReadableOperator[operator], "\n\n").concat(_res); - - if (_res.length > 1024) { - _res = "".concat(_res.slice(0, 1021), "..."); - } - } else { - other = "".concat(inspectValue(expected)); - - if (_res.length > 512) { - _res = "".concat(_res.slice(0, 509), "..."); - } - - if (other.length > 512) { - other = "".concat(other.slice(0, 509), "..."); - } - - if (operator === 'deepEqual' || operator === 'equal') { - _res = "".concat(knownOperators, "\n\n").concat(_res, "\n\nshould equal\n\n"); - } else { - other = " ".concat(operator, " ").concat(other); - } - } - - _this = _possibleConstructorReturn(this, _getPrototypeOf(AssertionError).call(this, "".concat(_res).concat(other))); - } - } - - Error.stackTraceLimit = limit; - _this.generatedMessage = !message; - Object.defineProperty(_assertThisInitialized(_this), 'name', { - value: 'AssertionError [ERR_ASSERTION]', - enumerable: false, - writable: true, - configurable: true - }); - _this.code = 'ERR_ASSERTION'; - _this.actual = actual; - _this.expected = expected; - _this.operator = operator; - - if (Error.captureStackTrace) { - // eslint-disable-next-line no-restricted-syntax - Error.captureStackTrace(_assertThisInitialized(_this), stackStartFn); - } // Create error message including the error code in the name. - - - _this.stack; // Reset the name. - - _this.name = 'AssertionError'; - return _possibleConstructorReturn(_this); - } - - _createClass(AssertionError, [{ - key: "toString", - value: function toString() { - return "".concat(this.name, " [").concat(this.code, "]: ").concat(this.message); - } - }, { - key: inspect.custom, - value: function value(recurseTimes, ctx) { - // This limits the `actual` and `expected` property default inspection to - // the minimum depth. Otherwise those values would be too verbose compared - // to the actual error message which contains a combined view of these two - // input values. - return inspect(this, _objectSpread({}, ctx, { - customInspect: false, - depth: 0 - })); - } - }]); - - return AssertionError; -}(_wrapNativeSuper(Error)); - -module.exports = AssertionError; \ No newline at end of file diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/assert/build/internal/errors.js b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/assert/build/internal/errors.js deleted file mode 100644 index 3f4350a2e6..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/assert/build/internal/errors.js +++ /dev/null @@ -1,195 +0,0 @@ -// Currently in sync with Node.js lib/internal/errors.js -// https://github.com/nodejs/node/commit/3b044962c48fe313905877a96b5d0894a5404f6f - -/* eslint node-core/documented-errors: "error" */ - -/* eslint node-core/alphabetize-errors: "error" */ - -/* eslint node-core/prefer-util-format-errors: "error" */ -'use strict'; // The whole point behind this internal module is to allow Node.js to no -// longer be forced to treat every error message change as a semver-major -// change. The NodeError classes here all expose a `code` property whose -// value statically and permanently identifies the error. While the error -// message may change, the code should not. - -function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } - -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } - -function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } - -function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } - -function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } - -function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } - -var codes = {}; // Lazy loaded - -var assert; -var util; - -function createErrorType(code, message, Base) { - if (!Base) { - Base = Error; - } - - function getMessage(arg1, arg2, arg3) { - if (typeof message === 'string') { - return message; - } else { - return message(arg1, arg2, arg3); - } - } - - var NodeError = - /*#__PURE__*/ - function (_Base) { - _inherits(NodeError, _Base); - - function NodeError(arg1, arg2, arg3) { - var _this; - - _classCallCheck(this, NodeError); - - _this = _possibleConstructorReturn(this, _getPrototypeOf(NodeError).call(this, getMessage(arg1, arg2, arg3))); - _this.code = code; - return _this; - } - - return NodeError; - }(Base); - - codes[code] = NodeError; -} // https://github.com/nodejs/node/blob/v10.8.0/lib/internal/errors.js - - -function oneOf(expected, thing) { - if (Array.isArray(expected)) { - var len = expected.length; - expected = expected.map(function (i) { - return String(i); - }); - - if (len > 2) { - return "one of ".concat(thing, " ").concat(expected.slice(0, len - 1).join(', '), ", or ") + expected[len - 1]; - } else if (len === 2) { - return "one of ".concat(thing, " ").concat(expected[0], " or ").concat(expected[1]); - } else { - return "of ".concat(thing, " ").concat(expected[0]); - } - } else { - return "of ".concat(thing, " ").concat(String(expected)); - } -} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith - - -function startsWith(str, search, pos) { - return str.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search; -} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith - - -function endsWith(str, search, this_len) { - if (this_len === undefined || this_len > str.length) { - this_len = str.length; - } - - return str.substring(this_len - search.length, this_len) === search; -} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes - - -function includes(str, search, start) { - if (typeof start !== 'number') { - start = 0; - } - - if (start + search.length > str.length) { - return false; - } else { - return str.indexOf(search, start) !== -1; - } -} - -createErrorType('ERR_AMBIGUOUS_ARGUMENT', 'The "%s" argument is ambiguous. %s', TypeError); -createErrorType('ERR_INVALID_ARG_TYPE', function (name, expected, actual) { - if (assert === undefined) assert = require('../assert'); - assert(typeof name === 'string', "'name' must be a string"); // determiner: 'must be' or 'must not be' - - var determiner; - - if (typeof expected === 'string' && startsWith(expected, 'not ')) { - determiner = 'must not be'; - expected = expected.replace(/^not /, ''); - } else { - determiner = 'must be'; - } - - var msg; - - if (endsWith(name, ' argument')) { - // For cases like 'first argument' - msg = "The ".concat(name, " ").concat(determiner, " ").concat(oneOf(expected, 'type')); - } else { - var type = includes(name, '.') ? 'property' : 'argument'; - msg = "The \"".concat(name, "\" ").concat(type, " ").concat(determiner, " ").concat(oneOf(expected, 'type')); - } // TODO(BridgeAR): Improve the output by showing `null` and similar. - - - msg += ". Received type ".concat(_typeof(actual)); - return msg; -}, TypeError); -createErrorType('ERR_INVALID_ARG_VALUE', function (name, value) { - var reason = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'is invalid'; - if (util === undefined) util = require('util/'); - var inspected = util.inspect(value); - - if (inspected.length > 128) { - inspected = "".concat(inspected.slice(0, 128), "..."); - } - - return "The argument '".concat(name, "' ").concat(reason, ". Received ").concat(inspected); -}, TypeError, RangeError); -createErrorType('ERR_INVALID_RETURN_VALUE', function (input, name, value) { - var type; - - if (value && value.constructor && value.constructor.name) { - type = "instance of ".concat(value.constructor.name); - } else { - type = "type ".concat(_typeof(value)); - } - - return "Expected ".concat(input, " to be returned from the \"").concat(name, "\"") + " function but got ".concat(type, "."); -}, TypeError); -createErrorType('ERR_MISSING_ARGS', function () { - for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { - args[_key] = arguments[_key]; - } - - if (assert === undefined) assert = require('../assert'); - assert(args.length > 0, 'At least one arg needs to be specified'); - var msg = 'The '; - var len = args.length; - args = args.map(function (a) { - return "\"".concat(a, "\""); - }); - - switch (len) { - case 1: - msg += "".concat(args[0], " argument"); - break; - - case 2: - msg += "".concat(args[0], " and ").concat(args[1], " arguments"); - break; - - default: - msg += args.slice(0, len - 1).join(', '); - msg += ", and ".concat(args[len - 1], " arguments"); - break; - } - - return "".concat(msg, " must be specified"); -}, TypeError); -module.exports.codes = codes; \ No newline at end of file diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/assert/build/internal/util/comparisons.js b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/assert/build/internal/util/comparisons.js deleted file mode 100644 index 31d43ffd49..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/assert/build/internal/util/comparisons.js +++ /dev/null @@ -1,688 +0,0 @@ -// Currently in sync with Node.js lib/internal/util/comparisons.js -// https://github.com/nodejs/node/commit/112cc7c27551254aa2b17098fb774867f05ed0d9 -'use strict'; - -function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); } - -function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } - -function _iterableToArrayLimit(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } - -function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } - -function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } - -var regexFlagsSupported = /a/g.flags !== undefined; - -var arrayFromSet = function arrayFromSet(set) { - var array = []; - set.forEach(function (value) { - return array.push(value); - }); - return array; -}; - -var arrayFromMap = function arrayFromMap(map) { - var array = []; - map.forEach(function (value, key) { - return array.push([key, value]); - }); - return array; -}; - -var objectIs = Object.is ? Object.is : require('object-is'); -var objectGetOwnPropertySymbols = Object.getOwnPropertySymbols ? Object.getOwnPropertySymbols : function () { - return []; -}; -var numberIsNaN = Number.isNaN ? Number.isNaN : require('is-nan'); - -function uncurryThis(f) { - return f.call.bind(f); -} - -var hasOwnProperty = uncurryThis(Object.prototype.hasOwnProperty); -var propertyIsEnumerable = uncurryThis(Object.prototype.propertyIsEnumerable); -var objectToString = uncurryThis(Object.prototype.toString); - -var _require$types = require('util/').types, - isAnyArrayBuffer = _require$types.isAnyArrayBuffer, - isArrayBufferView = _require$types.isArrayBufferView, - isDate = _require$types.isDate, - isMap = _require$types.isMap, - isRegExp = _require$types.isRegExp, - isSet = _require$types.isSet, - isNativeError = _require$types.isNativeError, - isBoxedPrimitive = _require$types.isBoxedPrimitive, - isNumberObject = _require$types.isNumberObject, - isStringObject = _require$types.isStringObject, - isBooleanObject = _require$types.isBooleanObject, - isBigIntObject = _require$types.isBigIntObject, - isSymbolObject = _require$types.isSymbolObject, - isFloat32Array = _require$types.isFloat32Array, - isFloat64Array = _require$types.isFloat64Array; - -function isNonIndex(key) { - if (key.length === 0 || key.length > 10) return true; - - for (var i = 0; i < key.length; i++) { - var code = key.charCodeAt(i); - if (code < 48 || code > 57) return true; - } // The maximum size for an array is 2 ** 32 -1. - - - return key.length === 10 && key >= Math.pow(2, 32); -} - -function getOwnNonIndexProperties(value) { - return Object.keys(value).filter(isNonIndex).concat(objectGetOwnPropertySymbols(value).filter(Object.prototype.propertyIsEnumerable.bind(value))); -} // Taken from https://github.com/feross/buffer/blob/680e9e5e488f22aac27599a57dc844a6315928dd/index.js -// original notice: - -/*! - * The buffer module from node.js, for the browser. - * - * @author Feross Aboukhadijeh - * @license MIT - */ - - -function compare(a, b) { - if (a === b) { - return 0; - } - - var x = a.length; - var y = b.length; - - for (var i = 0, len = Math.min(x, y); i < len; ++i) { - if (a[i] !== b[i]) { - x = a[i]; - y = b[i]; - break; - } - } - - if (x < y) { - return -1; - } - - if (y < x) { - return 1; - } - - return 0; -} - -var ONLY_ENUMERABLE = undefined; -var kStrict = true; -var kLoose = false; -var kNoIterator = 0; -var kIsArray = 1; -var kIsSet = 2; -var kIsMap = 3; // Check if they have the same source and flags - -function areSimilarRegExps(a, b) { - return regexFlagsSupported ? a.source === b.source && a.flags === b.flags : RegExp.prototype.toString.call(a) === RegExp.prototype.toString.call(b); -} - -function areSimilarFloatArrays(a, b) { - if (a.byteLength !== b.byteLength) { - return false; - } - - for (var offset = 0; offset < a.byteLength; offset++) { - if (a[offset] !== b[offset]) { - return false; - } - } - - return true; -} - -function areSimilarTypedArrays(a, b) { - if (a.byteLength !== b.byteLength) { - return false; - } - - return compare(new Uint8Array(a.buffer, a.byteOffset, a.byteLength), new Uint8Array(b.buffer, b.byteOffset, b.byteLength)) === 0; -} - -function areEqualArrayBuffers(buf1, buf2) { - return buf1.byteLength === buf2.byteLength && compare(new Uint8Array(buf1), new Uint8Array(buf2)) === 0; -} - -function isEqualBoxedPrimitive(val1, val2) { - if (isNumberObject(val1)) { - return isNumberObject(val2) && objectIs(Number.prototype.valueOf.call(val1), Number.prototype.valueOf.call(val2)); - } - - if (isStringObject(val1)) { - return isStringObject(val2) && String.prototype.valueOf.call(val1) === String.prototype.valueOf.call(val2); - } - - if (isBooleanObject(val1)) { - return isBooleanObject(val2) && Boolean.prototype.valueOf.call(val1) === Boolean.prototype.valueOf.call(val2); - } - - if (isBigIntObject(val1)) { - return isBigIntObject(val2) && BigInt.prototype.valueOf.call(val1) === BigInt.prototype.valueOf.call(val2); - } - - return isSymbolObject(val2) && Symbol.prototype.valueOf.call(val1) === Symbol.prototype.valueOf.call(val2); -} // Notes: Type tags are historical [[Class]] properties that can be set by -// FunctionTemplate::SetClassName() in C++ or Symbol.toStringTag in JS -// and retrieved using Object.prototype.toString.call(obj) in JS -// See https://tc39.github.io/ecma262/#sec-object.prototype.tostring -// for a list of tags pre-defined in the spec. -// There are some unspecified tags in the wild too (e.g. typed array tags). -// Since tags can be altered, they only serve fast failures -// -// Typed arrays and buffers are checked by comparing the content in their -// underlying ArrayBuffer. This optimization requires that it's -// reasonable to interpret their underlying memory in the same way, -// which is checked by comparing their type tags. -// (e.g. a Uint8Array and a Uint16Array with the same memory content -// could still be different because they will be interpreted differently). -// -// For strict comparison, objects should have -// a) The same built-in type tags -// b) The same prototypes. - - -function innerDeepEqual(val1, val2, strict, memos) { - // All identical values are equivalent, as determined by ===. - if (val1 === val2) { - if (val1 !== 0) return true; - return strict ? objectIs(val1, val2) : true; - } // Check more closely if val1 and val2 are equal. - - - if (strict) { - if (_typeof(val1) !== 'object') { - return typeof val1 === 'number' && numberIsNaN(val1) && numberIsNaN(val2); - } - - if (_typeof(val2) !== 'object' || val1 === null || val2 === null) { - return false; - } - - if (Object.getPrototypeOf(val1) !== Object.getPrototypeOf(val2)) { - return false; - } - } else { - if (val1 === null || _typeof(val1) !== 'object') { - if (val2 === null || _typeof(val2) !== 'object') { - // eslint-disable-next-line eqeqeq - return val1 == val2; - } - - return false; - } - - if (val2 === null || _typeof(val2) !== 'object') { - return false; - } - } - - var val1Tag = objectToString(val1); - var val2Tag = objectToString(val2); - - if (val1Tag !== val2Tag) { - return false; - } - - if (Array.isArray(val1)) { - // Check for sparse arrays and general fast path - if (val1.length !== val2.length) { - return false; - } - - var keys1 = getOwnNonIndexProperties(val1, ONLY_ENUMERABLE); - var keys2 = getOwnNonIndexProperties(val2, ONLY_ENUMERABLE); - - if (keys1.length !== keys2.length) { - return false; - } - - return keyCheck(val1, val2, strict, memos, kIsArray, keys1); - } // [browserify] This triggers on certain types in IE (Map/Set) so we don't - // wan't to early return out of the rest of the checks. However we can check - // if the second value is one of these values and the first isn't. - - - if (val1Tag === '[object Object]') { - // return keyCheck(val1, val2, strict, memos, kNoIterator); - if (!isMap(val1) && isMap(val2) || !isSet(val1) && isSet(val2)) { - return false; - } - } - - if (isDate(val1)) { - if (!isDate(val2) || Date.prototype.getTime.call(val1) !== Date.prototype.getTime.call(val2)) { - return false; - } - } else if (isRegExp(val1)) { - if (!isRegExp(val2) || !areSimilarRegExps(val1, val2)) { - return false; - } - } else if (isNativeError(val1) || val1 instanceof Error) { - // Do not compare the stack as it might differ even though the error itself - // is otherwise identical. - if (val1.message !== val2.message || val1.name !== val2.name) { - return false; - } - } else if (isArrayBufferView(val1)) { - if (!strict && (isFloat32Array(val1) || isFloat64Array(val1))) { - if (!areSimilarFloatArrays(val1, val2)) { - return false; - } - } else if (!areSimilarTypedArrays(val1, val2)) { - return false; - } // Buffer.compare returns true, so val1.length === val2.length. If they both - // only contain numeric keys, we don't need to exam further than checking - // the symbols. - - - var _keys = getOwnNonIndexProperties(val1, ONLY_ENUMERABLE); - - var _keys2 = getOwnNonIndexProperties(val2, ONLY_ENUMERABLE); - - if (_keys.length !== _keys2.length) { - return false; - } - - return keyCheck(val1, val2, strict, memos, kNoIterator, _keys); - } else if (isSet(val1)) { - if (!isSet(val2) || val1.size !== val2.size) { - return false; - } - - return keyCheck(val1, val2, strict, memos, kIsSet); - } else if (isMap(val1)) { - if (!isMap(val2) || val1.size !== val2.size) { - return false; - } - - return keyCheck(val1, val2, strict, memos, kIsMap); - } else if (isAnyArrayBuffer(val1)) { - if (!areEqualArrayBuffers(val1, val2)) { - return false; - } - } else if (isBoxedPrimitive(val1) && !isEqualBoxedPrimitive(val1, val2)) { - return false; - } - - return keyCheck(val1, val2, strict, memos, kNoIterator); -} - -function getEnumerables(val, keys) { - return keys.filter(function (k) { - return propertyIsEnumerable(val, k); - }); -} - -function keyCheck(val1, val2, strict, memos, iterationType, aKeys) { - // For all remaining Object pairs, including Array, objects and Maps, - // equivalence is determined by having: - // a) The same number of owned enumerable properties - // b) The same set of keys/indexes (although not necessarily the same order) - // c) Equivalent values for every corresponding key/index - // d) For Sets and Maps, equal contents - // Note: this accounts for both named and indexed properties on Arrays. - if (arguments.length === 5) { - aKeys = Object.keys(val1); - var bKeys = Object.keys(val2); // The pair must have the same number of owned properties. - - if (aKeys.length !== bKeys.length) { - return false; - } - } // Cheap key test - - - var i = 0; - - for (; i < aKeys.length; i++) { - if (!hasOwnProperty(val2, aKeys[i])) { - return false; - } - } - - if (strict && arguments.length === 5) { - var symbolKeysA = objectGetOwnPropertySymbols(val1); - - if (symbolKeysA.length !== 0) { - var count = 0; - - for (i = 0; i < symbolKeysA.length; i++) { - var key = symbolKeysA[i]; - - if (propertyIsEnumerable(val1, key)) { - if (!propertyIsEnumerable(val2, key)) { - return false; - } - - aKeys.push(key); - count++; - } else if (propertyIsEnumerable(val2, key)) { - return false; - } - } - - var symbolKeysB = objectGetOwnPropertySymbols(val2); - - if (symbolKeysA.length !== symbolKeysB.length && getEnumerables(val2, symbolKeysB).length !== count) { - return false; - } - } else { - var _symbolKeysB = objectGetOwnPropertySymbols(val2); - - if (_symbolKeysB.length !== 0 && getEnumerables(val2, _symbolKeysB).length !== 0) { - return false; - } - } - } - - if (aKeys.length === 0 && (iterationType === kNoIterator || iterationType === kIsArray && val1.length === 0 || val1.size === 0)) { - return true; - } // Use memos to handle cycles. - - - if (memos === undefined) { - memos = { - val1: new Map(), - val2: new Map(), - position: 0 - }; - } else { - // We prevent up to two map.has(x) calls by directly retrieving the value - // and checking for undefined. The map can only contain numbers, so it is - // safe to check for undefined only. - var val2MemoA = memos.val1.get(val1); - - if (val2MemoA !== undefined) { - var val2MemoB = memos.val2.get(val2); - - if (val2MemoB !== undefined) { - return val2MemoA === val2MemoB; - } - } - - memos.position++; - } - - memos.val1.set(val1, memos.position); - memos.val2.set(val2, memos.position); - var areEq = objEquiv(val1, val2, strict, aKeys, memos, iterationType); - memos.val1.delete(val1); - memos.val2.delete(val2); - return areEq; -} - -function setHasEqualElement(set, val1, strict, memo) { - // Go looking. - var setValues = arrayFromSet(set); - - for (var i = 0; i < setValues.length; i++) { - var val2 = setValues[i]; - - if (innerDeepEqual(val1, val2, strict, memo)) { - // Remove the matching element to make sure we do not check that again. - set.delete(val2); - return true; - } - } - - return false; -} // See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness#Loose_equality_using -// Sadly it is not possible to detect corresponding values properly in case the -// type is a string, number, bigint or boolean. The reason is that those values -// can match lots of different string values (e.g., 1n == '+00001'). - - -function findLooseMatchingPrimitives(prim) { - switch (_typeof(prim)) { - case 'undefined': - return null; - - case 'object': - // Only pass in null as object! - return undefined; - - case 'symbol': - return false; - - case 'string': - prim = +prim; - // Loose equal entries exist only if the string is possible to convert to - // a regular number and not NaN. - // Fall through - - case 'number': - if (numberIsNaN(prim)) { - return false; - } - - } - - return true; -} - -function setMightHaveLoosePrim(a, b, prim) { - var altValue = findLooseMatchingPrimitives(prim); - if (altValue != null) return altValue; - return b.has(altValue) && !a.has(altValue); -} - -function mapMightHaveLoosePrim(a, b, prim, item, memo) { - var altValue = findLooseMatchingPrimitives(prim); - - if (altValue != null) { - return altValue; - } - - var curB = b.get(altValue); - - if (curB === undefined && !b.has(altValue) || !innerDeepEqual(item, curB, false, memo)) { - return false; - } - - return !a.has(altValue) && innerDeepEqual(item, curB, false, memo); -} - -function setEquiv(a, b, strict, memo) { - // This is a lazily initiated Set of entries which have to be compared - // pairwise. - var set = null; - var aValues = arrayFromSet(a); - - for (var i = 0; i < aValues.length; i++) { - var val = aValues[i]; // Note: Checking for the objects first improves the performance for object - // heavy sets but it is a minor slow down for primitives. As they are fast - // to check this improves the worst case scenario instead. - - if (_typeof(val) === 'object' && val !== null) { - if (set === null) { - set = new Set(); - } // If the specified value doesn't exist in the second set its an not null - // object (or non strict only: a not matching primitive) we'll need to go - // hunting for something thats deep-(strict-)equal to it. To make this - // O(n log n) complexity we have to copy these values in a new set first. - - - set.add(val); - } else if (!b.has(val)) { - if (strict) return false; // Fast path to detect missing string, symbol, undefined and null values. - - if (!setMightHaveLoosePrim(a, b, val)) { - return false; - } - - if (set === null) { - set = new Set(); - } - - set.add(val); - } - } - - if (set !== null) { - var bValues = arrayFromSet(b); - - for (var _i = 0; _i < bValues.length; _i++) { - var _val = bValues[_i]; // We have to check if a primitive value is already - // matching and only if it's not, go hunting for it. - - if (_typeof(_val) === 'object' && _val !== null) { - if (!setHasEqualElement(set, _val, strict, memo)) return false; - } else if (!strict && !a.has(_val) && !setHasEqualElement(set, _val, strict, memo)) { - return false; - } - } - - return set.size === 0; - } - - return true; -} - -function mapHasEqualEntry(set, map, key1, item1, strict, memo) { - // To be able to handle cases like: - // Map([[{}, 'a'], [{}, 'b']]) vs Map([[{}, 'b'], [{}, 'a']]) - // ... we need to consider *all* matching keys, not just the first we find. - var setValues = arrayFromSet(set); - - for (var i = 0; i < setValues.length; i++) { - var key2 = setValues[i]; - - if (innerDeepEqual(key1, key2, strict, memo) && innerDeepEqual(item1, map.get(key2), strict, memo)) { - set.delete(key2); - return true; - } - } - - return false; -} - -function mapEquiv(a, b, strict, memo) { - var set = null; - var aEntries = arrayFromMap(a); - - for (var i = 0; i < aEntries.length; i++) { - var _aEntries$i = _slicedToArray(aEntries[i], 2), - key = _aEntries$i[0], - item1 = _aEntries$i[1]; - - if (_typeof(key) === 'object' && key !== null) { - if (set === null) { - set = new Set(); - } - - set.add(key); - } else { - // By directly retrieving the value we prevent another b.has(key) check in - // almost all possible cases. - var item2 = b.get(key); - - if (item2 === undefined && !b.has(key) || !innerDeepEqual(item1, item2, strict, memo)) { - if (strict) return false; // Fast path to detect missing string, symbol, undefined and null - // keys. - - if (!mapMightHaveLoosePrim(a, b, key, item1, memo)) return false; - - if (set === null) { - set = new Set(); - } - - set.add(key); - } - } - } - - if (set !== null) { - var bEntries = arrayFromMap(b); - - for (var _i2 = 0; _i2 < bEntries.length; _i2++) { - var _bEntries$_i = _slicedToArray(bEntries[_i2], 2), - key = _bEntries$_i[0], - item = _bEntries$_i[1]; - - if (_typeof(key) === 'object' && key !== null) { - if (!mapHasEqualEntry(set, a, key, item, strict, memo)) return false; - } else if (!strict && (!a.has(key) || !innerDeepEqual(a.get(key), item, false, memo)) && !mapHasEqualEntry(set, a, key, item, false, memo)) { - return false; - } - } - - return set.size === 0; - } - - return true; -} - -function objEquiv(a, b, strict, keys, memos, iterationType) { - // Sets and maps don't have their entries accessible via normal object - // properties. - var i = 0; - - if (iterationType === kIsSet) { - if (!setEquiv(a, b, strict, memos)) { - return false; - } - } else if (iterationType === kIsMap) { - if (!mapEquiv(a, b, strict, memos)) { - return false; - } - } else if (iterationType === kIsArray) { - for (; i < a.length; i++) { - if (hasOwnProperty(a, i)) { - if (!hasOwnProperty(b, i) || !innerDeepEqual(a[i], b[i], strict, memos)) { - return false; - } - } else if (hasOwnProperty(b, i)) { - return false; - } else { - // Array is sparse. - var keysA = Object.keys(a); - - for (; i < keysA.length; i++) { - var key = keysA[i]; - - if (!hasOwnProperty(b, key) || !innerDeepEqual(a[key], b[key], strict, memos)) { - return false; - } - } - - if (keysA.length !== Object.keys(b).length) { - return false; - } - - return true; - } - } - } // The pair must have equivalent values for every corresponding key. - // Possibly expensive deep test: - - - for (i = 0; i < keys.length; i++) { - var _key = keys[i]; - - if (!innerDeepEqual(a[_key], b[_key], strict, memos)) { - return false; - } - } - - return true; -} - -function isDeepEqual(val1, val2) { - return innerDeepEqual(val1, val2, kLoose); -} - -function isDeepStrictEqual(val1, val2) { - return innerDeepEqual(val1, val2, kStrict); -} - -module.exports = { - isDeepEqual: isDeepEqual, - isDeepStrictEqual: isDeepStrictEqual -}; \ No newline at end of file diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/assert/package.json b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/assert/package.json deleted file mode 100644 index 296973c25b..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/assert/package.json +++ /dev/null @@ -1,77 +0,0 @@ -{ - "_from": "assert", - "_id": "assert@2.0.0", - "_inBundle": false, - "_integrity": "sha512-se5Cd+js9dXJnu6Ag2JFc00t+HmHOen+8Q+L7O9zI0PqQXr20uk2J0XQqMxZEeo5U50o8Nvmmx7dZrl+Ufr35A==", - "_location": "/assert", - "_phantomChildren": {}, - "_requested": { - "type": "tag", - "registry": true, - "raw": "assert", - "name": "assert", - "escapedName": "assert", - "rawSpec": "", - "saveSpec": null, - "fetchSpec": "latest" - }, - "_requiredBy": [ - "#USER", - "/" - ], - "_resolved": "https://registry.npmjs.org/assert/-/assert-2.0.0.tgz", - "_shasum": "95fc1c616d48713510680f2eaf2d10dd22e02d32", - "_spec": "assert", - "_where": "/home/jan/Documents/skweb", - "bugs": { - "url": "https://github.com/browserify/commonjs-assert/issues" - }, - "bundleDependencies": false, - "dependencies": { - "es6-object-assign": "^1.1.0", - "is-nan": "^1.2.1", - "object-is": "^1.0.1", - "util": "^0.12.0" - }, - "deprecated": false, - "description": "The assert module from Node.js, for the browser.", - "devDependencies": { - "@babel/cli": "^7.4.4", - "@babel/core": "^7.4.4", - "@babel/preset-env": "^7.4.4", - "airtap": "^2.0.2", - "array-fill": "^1.2.0", - "core-js": "^3.0.1", - "cross-env": "^5.2.0", - "object.entries": "^1.1.0", - "object.getownpropertydescriptors": "^2.0.3", - "tape": "^4.10.1" - }, - "files": [ - "build/assert.js", - "build/internal" - ], - "homepage": "https://github.com/browserify/commonjs-assert", - "keywords": [ - "assert", - "browser" - ], - "license": "MIT", - "main": "build/assert.js", - "name": "assert", - "repository": { - "type": "git", - "url": "git+https://github.com/browserify/commonjs-assert.git" - }, - "scripts": { - "build": "babel assert.js test.js --out-dir build && babel internal --out-dir build/internal && babel test --out-dir build/test", - "dev": "babel assert.js test.js --watch --out-dir build & babel internal --watch --out-dir build/internal & babel test --watch --out-dir build/test", - "prepare": "npm run build", - "test": "npm run build && npm run test:nobuild", - "test:browsers": "airtap build/test.js", - "test:browsers:local": "npm run test:browsers -- --local", - "test:nobuild": "node build/test.js", - "test:source": "node test.js" - }, - "version": "2.0.0" -} diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/available-typed-arrays/.eslintrc b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/available-typed-arrays/.eslintrc deleted file mode 100644 index 3b5d9e90ec..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/available-typed-arrays/.eslintrc +++ /dev/null @@ -1,5 +0,0 @@ -{ - "root": true, - - "extends": "@ljharb", -} diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/available-typed-arrays/.github/workflows/rebase.yml b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/available-typed-arrays/.github/workflows/rebase.yml deleted file mode 100644 index 436cb79dca..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/available-typed-arrays/.github/workflows/rebase.yml +++ /dev/null @@ -1,15 +0,0 @@ -name: Automatic Rebase - -on: [pull_request] - -jobs: - _: - name: "Automatic Rebase" - - runs-on: ubuntu-latest - - steps: - - uses: actions/checkout@v1 - - uses: ljharb/rebase@master - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/available-typed-arrays/.travis.yml b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/available-typed-arrays/.travis.yml deleted file mode 100644 index 5ed0fa52f9..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/available-typed-arrays/.travis.yml +++ /dev/null @@ -1,8 +0,0 @@ -version: ~> 1.0 -language: node_js -os: - - linux -import: - - ljharb/travis-ci:node/all.yml - - ljharb/travis-ci:node/pretest.yml - - ljharb/travis-ci:node/posttest.yml diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/available-typed-arrays/CHANGELOG.md b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/available-typed-arrays/CHANGELOG.md deleted file mode 100644 index 63db1e230e..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/available-typed-arrays/CHANGELOG.md +++ /dev/null @@ -1,38 +0,0 @@ -# Changelog - -All notable changes to this project will be documented in this file. - -The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) -and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). - -Generated by [`auto-changelog`](https://github.com/CookPete/auto-changelog). - -## [v1.0.2](https://github.com/inspect-js/available-typed-arrays/compare/v1.0.1...v1.0.2) - 2020-01-26 - -### Commits - -- [actions] add automatic rebasing / merge commit blocking [`3229a74`](https://github.com/inspect-js/available-typed-arrays/commit/3229a74bda60f24e2257efc40ddff9a3ce98de76) -- [Dev Deps] update `@ljharb/eslint-config` [`9579abe`](https://github.com/inspect-js/available-typed-arrays/commit/9579abecc196088561d3aedf27cad45b56f8e18b) -- [Fix] remove `require` condition to avoid experimental warning [`2cade6b`](https://github.com/inspect-js/available-typed-arrays/commit/2cade6b56d6a508a950c7da27d038bee496e716b) - -## [v1.0.1](https://github.com/inspect-js/available-typed-arrays/compare/v1.0.0...v1.0.1) - 2020-01-24 - -### Commits - -- [meta] add "exports" [`5942917`](https://github.com/inspect-js/available-typed-arrays/commit/5942917aafb56c6bce80f01b7ae6a9b46bc72c69) - -## v1.0.0 - 2020-01-24 - -### Commits - -- Initial commit [`2bc5144`](https://github.com/inspect-js/available-typed-arrays/commit/2bc514459c9f65756adfbd9964abf433183d78f6) -- readme [`31e4796`](https://github.com/inspect-js/available-typed-arrays/commit/31e4796379eba4a16d3c6a8e9baf6eb3f39e33d1) -- npm init [`9194266`](https://github.com/inspect-js/available-typed-arrays/commit/9194266b471a2a2dd5e6969bc40358ceb346e21e) -- Tests [`b539830`](https://github.com/inspect-js/available-typed-arrays/commit/b539830c3213f90de42b4d6e62803f52daf61a6d) -- Implementation [`6577df2`](https://github.com/inspect-js/available-typed-arrays/commit/6577df244ea146ef5ec16858044c8955e0fc445c) -- [meta] add `auto-changelog` [`7b43310`](https://github.com/inspect-js/available-typed-arrays/commit/7b43310be76f00fe60b74a2fd6d0e46ac1d01f3e) -- [Tests] add `npm run lint` [`dedfbc1`](https://github.com/inspect-js/available-typed-arrays/commit/dedfbc1592f86ac1636267d3965f2345df43815b) -- [Tests] use shared travis-ci configs [`c459d78`](https://github.com/inspect-js/available-typed-arrays/commit/c459d78bf2efa9d777f88599ae71a796dbfcb70f) -- Only apps should have lockfiles [`d294668`](https://github.com/inspect-js/available-typed-arrays/commit/d294668422cf35f5e7716a85bfd204e62b01c056) -- [meta] add `funding` field [`6e70bc1`](https://github.com/inspect-js/available-typed-arrays/commit/6e70bc1fb199c7898165aaf05c25bb49f4062e53) -- [meta] add `safe-publish-latest` [`dd89ca2`](https://github.com/inspect-js/available-typed-arrays/commit/dd89ca2c6842f0f3e82958df2b2bd0fc0c929c51) diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/available-typed-arrays/LICENSE b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/available-typed-arrays/LICENSE deleted file mode 100644 index 707437b575..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/available-typed-arrays/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2020 Inspect JS - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/available-typed-arrays/README.md b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/available-typed-arrays/README.md deleted file mode 100644 index 1dd2778364..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/available-typed-arrays/README.md +++ /dev/null @@ -1,49 +0,0 @@ -# available-typed-arrays [![Version Badge][2]][1] - -[![Build Status][3]][4] -[![dependency status][5]][6] -[![dev dependency status][7]][8] -[![License][license-image]][license-url] -[![Downloads][downloads-image]][downloads-url] - -[![npm badge][11]][1] - -Returns an array of Typed Array names that are available in the current environment. - -## Example - -```js -var availableTypedArrays = require('available-typed-arrays'); -var assert = require('assert'); - -assert.deepStrictEqual(availableTypedArrays(), [ - 'Int8Array', - 'Uint8Array', - 'Uint8ClampedArray', - 'Int16Array', - 'Uint16Array', - 'Int32Array', - 'Uint32Array', - 'Float32Array', - 'Float64Array', - 'BigInt64Array', - 'BigUint64Array' -].sort()); -``` - -## Tests -Simply clone the repo, `npm install`, and run `npm test` - -[1]: https://npmjs.org/package/available-typed-arrays -[2]: http://versionbadg.es/inspect-js/available-typed-arrays.svg -[3]: https://travis-ci.org/inspect-js/available-typed-arrays.svg -[4]: https://travis-ci.org/inspect-js/available-typed-arrays -[5]: https://david-dm.org/inspect-js/available-typed-arrays.svg -[6]: https://david-dm.org/inspect-js/available-typed-arrays -[7]: https://david-dm.org/inspect-js/available-typed-arrays/dev-status.svg -[8]: https://david-dm.org/inspect-js/available-typed-arrays#info=devDependencies -[11]: https://nodei.co/npm/available-typed-arrays.png?downloads=true&stars=true -[license-image]: http://img.shields.io/npm/l/available-typed-arrays.svg -[license-url]: LICENSE -[downloads-image]: http://img.shields.io/npm/dm/available-typed-arrays.svg -[downloads-url]: http://npm-stat.com/charts.html?package=available-typed-arrays diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/available-typed-arrays/index.js b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/available-typed-arrays/index.js deleted file mode 100644 index 665dbe9e2a..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/available-typed-arrays/index.js +++ /dev/null @@ -1,21 +0,0 @@ -'use strict'; - -var filter = require('array-filter'); - -module.exports = function availableTypedArrays() { - return filter([ - 'BigInt64Array', - 'BigUint64Array', - 'Float32Array', - 'Float64Array', - 'Int16Array', - 'Int32Array', - 'Int8Array', - 'Uint16Array', - 'Uint32Array', - 'Uint8Array', - 'Uint8ClampedArray' - ], function (typedArray) { - return typeof global[typedArray] === 'function'; - }); -}; diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/available-typed-arrays/package.json b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/available-typed-arrays/package.json deleted file mode 100644 index 54746e7bb2..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/available-typed-arrays/package.json +++ /dev/null @@ -1,108 +0,0 @@ -{ - "_from": "available-typed-arrays@^1.0.0", - "_id": "available-typed-arrays@1.0.2", - "_inBundle": false, - "_integrity": "sha512-XWX3OX8Onv97LMk/ftVyBibpGwY5a8SmuxZPzeOxqmuEqUCOM9ZE+uIaD1VNJ5QnvU2UQusvmKbuM1FR8QWGfQ==", - "_location": "/available-typed-arrays", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "available-typed-arrays@^1.0.0", - "name": "available-typed-arrays", - "escapedName": "available-typed-arrays", - "rawSpec": "^1.0.0", - "saveSpec": null, - "fetchSpec": "^1.0.0" - }, - "_requiredBy": [ - "/is-typed-array", - "/which-typed-array" - ], - "_resolved": "https://registry.npmjs.org/available-typed-arrays/-/available-typed-arrays-1.0.2.tgz", - "_shasum": "6b098ca9d8039079ee3f77f7b783c4480ba513f5", - "_spec": "available-typed-arrays@^1.0.0", - "_where": "/home/jan/Documents/skweb/node_modules/is-typed-array", - "author": { - "name": "Jordan Harband", - "email": "ljharb@gmail.com" - }, - "auto-changelog": { - "output": "CHANGELOG.md", - "template": "keepachangelog", - "unreleased": false, - "commitLimit": false, - "backfillLimit": false - }, - "bugs": { - "url": "https://github.com/inspect-js/available-typed-arrays/issues" - }, - "bundleDependencies": false, - "dependencies": { - "array-filter": "^1.0.0" - }, - "deprecated": false, - "description": "Returns an array of Typed Array names that are available in the current environment", - "devDependencies": { - "@ljharb/eslint-config": "^16.0.0", - "array.prototype.every": "^1.1.0", - "auto-changelog": "^1.16.2", - "eslint": "^6.8.0", - "evalmd": "^0.0.19", - "isarray": "^2.0.5", - "safe-publish-latest": "^1.1.4", - "tape": "^5.0.0-next.4" - }, - "engines": { - "node": ">= 0.4" - }, - "exports": { - ".": [ - { - "default": "./index.js" - }, - "./index.js" - ], - "./package": "./package.json", - "./package.json": "./package.json" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - }, - "homepage": "https://github.com/inspect-js/available-typed-arrays#readme", - "keywords": [ - "typed", - "arrays", - "Float32Array", - "Float64Array", - "Int8Array", - "Int16Array", - "Int32Array", - "Uint8Array", - "Uint8ClampedArray", - "Uint16Array", - "Uint32Array", - "BigInt64Array", - "BigUint64Array" - ], - "license": "MIT", - "main": "index.js", - "name": "available-typed-arrays", - "repository": { - "type": "git", - "url": "git+https://github.com/inspect-js/available-typed-arrays.git" - }, - "scripts": { - "lint": "eslint .", - "posttest": "npx aud", - "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"", - "prelint": "evalmd README.md", - "prepublish": "safe-publish-latest", - "pretest": "npm run lint", - "test": "npm run tests-only", - "tests-only": "node test", - "version": "auto-changelog && git add CHANGELOG.md" - }, - "type": "commonjs", - "version": "1.0.2" -} diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/available-typed-arrays/test/index.js b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/available-typed-arrays/test/index.js deleted file mode 100644 index 21c986dc8e..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/available-typed-arrays/test/index.js +++ /dev/null @@ -1,18 +0,0 @@ -'use strict'; - -var test = require('tape'); -var isArray = require('isarray'); -var every = require('array.prototype.every'); - -var availableTypedArrays = require('../'); - -test('available typed arrays', function (t) { - t.equal(typeof availableTypedArrays, 'function', 'is a function'); - - var arrays = availableTypedArrays(); - t.equal(isArray(arrays), true, 'returns an array'); - - t.equal(every(arrays, function (array) { return typeof array === 'string'; }), true, 'contains only strings'); - - t.end(); -}); diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/body-parser/HISTORY.md b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/body-parser/HISTORY.md deleted file mode 100644 index a1d3fbfbb9..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/body-parser/HISTORY.md +++ /dev/null @@ -1,609 +0,0 @@ -1.19.0 / 2019-04-25 -=================== - - * deps: bytes@3.1.0 - - Add petabyte (`pb`) support - * deps: http-errors@1.7.2 - - Set constructor name when possible - - deps: setprototypeof@1.1.1 - - deps: statuses@'>= 1.5.0 < 2' - * deps: iconv-lite@0.4.24 - - Added encoding MIK - * deps: qs@6.7.0 - - Fix parsing array brackets after index - * deps: raw-body@2.4.0 - - deps: bytes@3.1.0 - - deps: http-errors@1.7.2 - - deps: iconv-lite@0.4.24 - * deps: type-is@~1.6.17 - - deps: mime-types@~2.1.24 - - perf: prevent internal `throw` on invalid type - -1.18.3 / 2018-05-14 -=================== - - * Fix stack trace for strict json parse error - * deps: depd@~1.1.2 - - perf: remove argument reassignment - * deps: http-errors@~1.6.3 - - deps: depd@~1.1.2 - - deps: setprototypeof@1.1.0 - - deps: statuses@'>= 1.3.1 < 2' - * deps: iconv-lite@0.4.23 - - Fix loading encoding with year appended - - Fix deprecation warnings on Node.js 10+ - * deps: qs@6.5.2 - * deps: raw-body@2.3.3 - - deps: http-errors@1.6.3 - - deps: iconv-lite@0.4.23 - * deps: type-is@~1.6.16 - - deps: mime-types@~2.1.18 - -1.18.2 / 2017-09-22 -=================== - - * deps: debug@2.6.9 - * perf: remove argument reassignment - -1.18.1 / 2017-09-12 -=================== - - * deps: content-type@~1.0.4 - - perf: remove argument reassignment - - perf: skip parameter parsing when no parameters - * deps: iconv-lite@0.4.19 - - Fix ISO-8859-1 regression - - Update Windows-1255 - * deps: qs@6.5.1 - - Fix parsing & compacting very deep objects - * deps: raw-body@2.3.2 - - deps: iconv-lite@0.4.19 - -1.18.0 / 2017-09-08 -=================== - - * Fix JSON strict violation error to match native parse error - * Include the `body` property on verify errors - * Include the `type` property on all generated errors - * Use `http-errors` to set status code on errors - * deps: bytes@3.0.0 - * deps: debug@2.6.8 - * deps: depd@~1.1.1 - - Remove unnecessary `Buffer` loading - * deps: http-errors@~1.6.2 - - deps: depd@1.1.1 - * deps: iconv-lite@0.4.18 - - Add support for React Native - - Add a warning if not loaded as utf-8 - - Fix CESU-8 decoding in Node.js 8 - - Improve speed of ISO-8859-1 encoding - * deps: qs@6.5.0 - * deps: raw-body@2.3.1 - - Use `http-errors` for standard emitted errors - - deps: bytes@3.0.0 - - deps: iconv-lite@0.4.18 - - perf: skip buffer decoding on overage chunk - * perf: prevent internal `throw` when missing charset - -1.17.2 / 2017-05-17 -=================== - - * deps: debug@2.6.7 - - Fix `DEBUG_MAX_ARRAY_LENGTH` - - deps: ms@2.0.0 - * deps: type-is@~1.6.15 - - deps: mime-types@~2.1.15 - -1.17.1 / 2017-03-06 -=================== - - * deps: qs@6.4.0 - - Fix regression parsing keys starting with `[` - -1.17.0 / 2017-03-01 -=================== - - * deps: http-errors@~1.6.1 - - Make `message` property enumerable for `HttpError`s - - deps: setprototypeof@1.0.3 - * deps: qs@6.3.1 - - Fix compacting nested arrays - -1.16.1 / 2017-02-10 -=================== - - * deps: debug@2.6.1 - - Fix deprecation messages in WebStorm and other editors - - Undeprecate `DEBUG_FD` set to `1` or `2` - -1.16.0 / 2017-01-17 -=================== - - * deps: debug@2.6.0 - - Allow colors in workers - - Deprecated `DEBUG_FD` environment variable - - Fix error when running under React Native - - Use same color for same namespace - - deps: ms@0.7.2 - * deps: http-errors@~1.5.1 - - deps: inherits@2.0.3 - - deps: setprototypeof@1.0.2 - - deps: statuses@'>= 1.3.1 < 2' - * deps: iconv-lite@0.4.15 - - Added encoding MS-31J - - Added encoding MS-932 - - Added encoding MS-936 - - Added encoding MS-949 - - Added encoding MS-950 - - Fix GBK/GB18030 handling of Euro character - * deps: qs@6.2.1 - - Fix array parsing from skipping empty values - * deps: raw-body@~2.2.0 - - deps: iconv-lite@0.4.15 - * deps: type-is@~1.6.14 - - deps: mime-types@~2.1.13 - -1.15.2 / 2016-06-19 -=================== - - * deps: bytes@2.4.0 - * deps: content-type@~1.0.2 - - perf: enable strict mode - * deps: http-errors@~1.5.0 - - Use `setprototypeof` module to replace `__proto__` setting - - deps: statuses@'>= 1.3.0 < 2' - - perf: enable strict mode - * deps: qs@6.2.0 - * deps: raw-body@~2.1.7 - - deps: bytes@2.4.0 - - perf: remove double-cleanup on happy path - * deps: type-is@~1.6.13 - - deps: mime-types@~2.1.11 - -1.15.1 / 2016-05-05 -=================== - - * deps: bytes@2.3.0 - - Drop partial bytes on all parsed units - - Fix parsing byte string that looks like hex - * deps: raw-body@~2.1.6 - - deps: bytes@2.3.0 - * deps: type-is@~1.6.12 - - deps: mime-types@~2.1.10 - -1.15.0 / 2016-02-10 -=================== - - * deps: http-errors@~1.4.0 - - Add `HttpError` export, for `err instanceof createError.HttpError` - - deps: inherits@2.0.1 - - deps: statuses@'>= 1.2.1 < 2' - * deps: qs@6.1.0 - * deps: type-is@~1.6.11 - - deps: mime-types@~2.1.9 - -1.14.2 / 2015-12-16 -=================== - - * deps: bytes@2.2.0 - * deps: iconv-lite@0.4.13 - * deps: qs@5.2.0 - * deps: raw-body@~2.1.5 - - deps: bytes@2.2.0 - - deps: iconv-lite@0.4.13 - * deps: type-is@~1.6.10 - - deps: mime-types@~2.1.8 - -1.14.1 / 2015-09-27 -=================== - - * Fix issue where invalid charset results in 400 when `verify` used - * deps: iconv-lite@0.4.12 - - Fix CESU-8 decoding in Node.js 4.x - * deps: raw-body@~2.1.4 - - Fix masking critical errors from `iconv-lite` - - deps: iconv-lite@0.4.12 - * deps: type-is@~1.6.9 - - deps: mime-types@~2.1.7 - -1.14.0 / 2015-09-16 -=================== - - * Fix JSON strict parse error to match syntax errors - * Provide static `require` analysis in `urlencoded` parser - * deps: depd@~1.1.0 - - Support web browser loading - * deps: qs@5.1.0 - * deps: raw-body@~2.1.3 - - Fix sync callback when attaching data listener causes sync read - * deps: type-is@~1.6.8 - - Fix type error when given invalid type to match against - - deps: mime-types@~2.1.6 - -1.13.3 / 2015-07-31 -=================== - - * deps: type-is@~1.6.6 - - deps: mime-types@~2.1.4 - -1.13.2 / 2015-07-05 -=================== - - * deps: iconv-lite@0.4.11 - * deps: qs@4.0.0 - - Fix dropping parameters like `hasOwnProperty` - - Fix user-visible incompatibilities from 3.1.0 - - Fix various parsing edge cases - * deps: raw-body@~2.1.2 - - Fix error stack traces to skip `makeError` - - deps: iconv-lite@0.4.11 - * deps: type-is@~1.6.4 - - deps: mime-types@~2.1.2 - - perf: enable strict mode - - perf: remove argument reassignment - -1.13.1 / 2015-06-16 -=================== - - * deps: qs@2.4.2 - - Downgraded from 3.1.0 because of user-visible incompatibilities - -1.13.0 / 2015-06-14 -=================== - - * Add `statusCode` property on `Error`s, in addition to `status` - * Change `type` default to `application/json` for JSON parser - * Change `type` default to `application/x-www-form-urlencoded` for urlencoded parser - * Provide static `require` analysis - * Use the `http-errors` module to generate errors - * deps: bytes@2.1.0 - - Slight optimizations - * deps: iconv-lite@0.4.10 - - The encoding UTF-16 without BOM now defaults to UTF-16LE when detection fails - - Leading BOM is now removed when decoding - * deps: on-finished@~2.3.0 - - Add defined behavior for HTTP `CONNECT` requests - - Add defined behavior for HTTP `Upgrade` requests - - deps: ee-first@1.1.1 - * deps: qs@3.1.0 - - Fix dropping parameters like `hasOwnProperty` - - Fix various parsing edge cases - - Parsed object now has `null` prototype - * deps: raw-body@~2.1.1 - - Use `unpipe` module for unpiping requests - - deps: iconv-lite@0.4.10 - * deps: type-is@~1.6.3 - - deps: mime-types@~2.1.1 - - perf: reduce try block size - - perf: remove bitwise operations - * perf: enable strict mode - * perf: remove argument reassignment - * perf: remove delete call - -1.12.4 / 2015-05-10 -=================== - - * deps: debug@~2.2.0 - * deps: qs@2.4.2 - - Fix allowing parameters like `constructor` - * deps: on-finished@~2.2.1 - * deps: raw-body@~2.0.1 - - Fix a false-positive when unpiping in Node.js 0.8 - - deps: bytes@2.0.1 - * deps: type-is@~1.6.2 - - deps: mime-types@~2.0.11 - -1.12.3 / 2015-04-15 -=================== - - * Slight efficiency improvement when not debugging - * deps: depd@~1.0.1 - * deps: iconv-lite@0.4.8 - - Add encoding alias UNICODE-1-1-UTF-7 - * deps: raw-body@1.3.4 - - Fix hanging callback if request aborts during read - - deps: iconv-lite@0.4.8 - -1.12.2 / 2015-03-16 -=================== - - * deps: qs@2.4.1 - - Fix error when parameter `hasOwnProperty` is present - -1.12.1 / 2015-03-15 -=================== - - * deps: debug@~2.1.3 - - Fix high intensity foreground color for bold - - deps: ms@0.7.0 - * deps: type-is@~1.6.1 - - deps: mime-types@~2.0.10 - -1.12.0 / 2015-02-13 -=================== - - * add `debug` messages - * accept a function for the `type` option - * use `content-type` to parse `Content-Type` headers - * deps: iconv-lite@0.4.7 - - Gracefully support enumerables on `Object.prototype` - * deps: raw-body@1.3.3 - - deps: iconv-lite@0.4.7 - * deps: type-is@~1.6.0 - - fix argument reassignment - - fix false-positives in `hasBody` `Transfer-Encoding` check - - support wildcard for both type and subtype (`*/*`) - - deps: mime-types@~2.0.9 - -1.11.0 / 2015-01-30 -=================== - - * make internal `extended: true` depth limit infinity - * deps: type-is@~1.5.6 - - deps: mime-types@~2.0.8 - -1.10.2 / 2015-01-20 -=================== - - * deps: iconv-lite@0.4.6 - - Fix rare aliases of single-byte encodings - * deps: raw-body@1.3.2 - - deps: iconv-lite@0.4.6 - -1.10.1 / 2015-01-01 -=================== - - * deps: on-finished@~2.2.0 - * deps: type-is@~1.5.5 - - deps: mime-types@~2.0.7 - -1.10.0 / 2014-12-02 -=================== - - * make internal `extended: true` array limit dynamic - -1.9.3 / 2014-11-21 -================== - - * deps: iconv-lite@0.4.5 - - Fix Windows-31J and X-SJIS encoding support - * deps: qs@2.3.3 - - Fix `arrayLimit` behavior - * deps: raw-body@1.3.1 - - deps: iconv-lite@0.4.5 - * deps: type-is@~1.5.3 - - deps: mime-types@~2.0.3 - -1.9.2 / 2014-10-27 -================== - - * deps: qs@2.3.2 - - Fix parsing of mixed objects and values - -1.9.1 / 2014-10-22 -================== - - * deps: on-finished@~2.1.1 - - Fix handling of pipelined requests - * deps: qs@2.3.0 - - Fix parsing of mixed implicit and explicit arrays - * deps: type-is@~1.5.2 - - deps: mime-types@~2.0.2 - -1.9.0 / 2014-09-24 -================== - - * include the charset in "unsupported charset" error message - * include the encoding in "unsupported content encoding" error message - * deps: depd@~1.0.0 - -1.8.4 / 2014-09-23 -================== - - * fix content encoding to be case-insensitive - -1.8.3 / 2014-09-19 -================== - - * deps: qs@2.2.4 - - Fix issue with object keys starting with numbers truncated - -1.8.2 / 2014-09-15 -================== - - * deps: depd@0.4.5 - -1.8.1 / 2014-09-07 -================== - - * deps: media-typer@0.3.0 - * deps: type-is@~1.5.1 - -1.8.0 / 2014-09-05 -================== - - * make empty-body-handling consistent between chunked requests - - empty `json` produces `{}` - - empty `raw` produces `new Buffer(0)` - - empty `text` produces `''` - - empty `urlencoded` produces `{}` - * deps: qs@2.2.3 - - Fix issue where first empty value in array is discarded - * deps: type-is@~1.5.0 - - fix `hasbody` to be true for `content-length: 0` - -1.7.0 / 2014-09-01 -================== - - * add `parameterLimit` option to `urlencoded` parser - * change `urlencoded` extended array limit to 100 - * respond with 413 when over `parameterLimit` in `urlencoded` - -1.6.7 / 2014-08-29 -================== - - * deps: qs@2.2.2 - - Remove unnecessary cloning - -1.6.6 / 2014-08-27 -================== - - * deps: qs@2.2.0 - - Array parsing fix - - Performance improvements - -1.6.5 / 2014-08-16 -================== - - * deps: on-finished@2.1.0 - -1.6.4 / 2014-08-14 -================== - - * deps: qs@1.2.2 - -1.6.3 / 2014-08-10 -================== - - * deps: qs@1.2.1 - -1.6.2 / 2014-08-07 -================== - - * deps: qs@1.2.0 - - Fix parsing array of objects - -1.6.1 / 2014-08-06 -================== - - * deps: qs@1.1.0 - - Accept urlencoded square brackets - - Accept empty values in implicit array notation - -1.6.0 / 2014-08-05 -================== - - * deps: qs@1.0.2 - - Complete rewrite - - Limits array length to 20 - - Limits object depth to 5 - - Limits parameters to 1,000 - -1.5.2 / 2014-07-27 -================== - - * deps: depd@0.4.4 - - Work-around v8 generating empty stack traces - -1.5.1 / 2014-07-26 -================== - - * deps: depd@0.4.3 - - Fix exception when global `Error.stackTraceLimit` is too low - -1.5.0 / 2014-07-20 -================== - - * deps: depd@0.4.2 - - Add `TRACE_DEPRECATION` environment variable - - Remove non-standard grey color from color output - - Support `--no-deprecation` argument - - Support `--trace-deprecation` argument - * deps: iconv-lite@0.4.4 - - Added encoding UTF-7 - * deps: raw-body@1.3.0 - - deps: iconv-lite@0.4.4 - - Added encoding UTF-7 - - Fix `Cannot switch to old mode now` error on Node.js 0.10+ - * deps: type-is@~1.3.2 - -1.4.3 / 2014-06-19 -================== - - * deps: type-is@1.3.1 - - fix global variable leak - -1.4.2 / 2014-06-19 -================== - - * deps: type-is@1.3.0 - - improve type parsing - -1.4.1 / 2014-06-19 -================== - - * fix urlencoded extended deprecation message - -1.4.0 / 2014-06-19 -================== - - * add `text` parser - * add `raw` parser - * check accepted charset in content-type (accepts utf-8) - * check accepted encoding in content-encoding (accepts identity) - * deprecate `bodyParser()` middleware; use `.json()` and `.urlencoded()` as needed - * deprecate `urlencoded()` without provided `extended` option - * lazy-load urlencoded parsers - * parsers split into files for reduced mem usage - * support gzip and deflate bodies - - set `inflate: false` to turn off - * deps: raw-body@1.2.2 - - Support all encodings from `iconv-lite` - -1.3.1 / 2014-06-11 -================== - - * deps: type-is@1.2.1 - - Switch dependency from mime to mime-types@1.0.0 - -1.3.0 / 2014-05-31 -================== - - * add `extended` option to urlencoded parser - -1.2.2 / 2014-05-27 -================== - - * deps: raw-body@1.1.6 - - assert stream encoding on node.js 0.8 - - assert stream encoding on node.js < 0.10.6 - - deps: bytes@1 - -1.2.1 / 2014-05-26 -================== - - * invoke `next(err)` after request fully read - - prevents hung responses and socket hang ups - -1.2.0 / 2014-05-11 -================== - - * add `verify` option - * deps: type-is@1.2.0 - - support suffix matching - -1.1.2 / 2014-05-11 -================== - - * improve json parser speed - -1.1.1 / 2014-05-11 -================== - - * fix repeated limit parsing with every request - -1.1.0 / 2014-05-10 -================== - - * add `type` option - * deps: pin for safety and consistency - -1.0.2 / 2014-04-14 -================== - - * use `type-is` module - -1.0.1 / 2014-03-20 -================== - - * lower default limits to 100kb diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/body-parser/LICENSE b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/body-parser/LICENSE deleted file mode 100644 index 386b7b6946..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/body-parser/LICENSE +++ /dev/null @@ -1,23 +0,0 @@ -(The MIT License) - -Copyright (c) 2014 Jonathan Ong -Copyright (c) 2014-2015 Douglas Christopher Wilson - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -'Software'), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/body-parser/README.md b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/body-parser/README.md deleted file mode 100644 index aba6297a84..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/body-parser/README.md +++ /dev/null @@ -1,443 +0,0 @@ -# body-parser - -[![NPM Version][npm-image]][npm-url] -[![NPM Downloads][downloads-image]][downloads-url] -[![Build Status][travis-image]][travis-url] -[![Test Coverage][coveralls-image]][coveralls-url] - -Node.js body parsing middleware. - -Parse incoming request bodies in a middleware before your handlers, available -under the `req.body` property. - -**Note** As `req.body`'s shape is based on user-controlled input, all -properties and values in this object are untrusted and should be validated -before trusting. For example, `req.body.foo.toString()` may fail in multiple -ways, for example the `foo` property may not be there or may not be a string, -and `toString` may not be a function and instead a string or other user input. - -[Learn about the anatomy of an HTTP transaction in Node.js](https://nodejs.org/en/docs/guides/anatomy-of-an-http-transaction/). - -_This does not handle multipart bodies_, due to their complex and typically -large nature. For multipart bodies, you may be interested in the following -modules: - - * [busboy](https://www.npmjs.org/package/busboy#readme) and - [connect-busboy](https://www.npmjs.org/package/connect-busboy#readme) - * [multiparty](https://www.npmjs.org/package/multiparty#readme) and - [connect-multiparty](https://www.npmjs.org/package/connect-multiparty#readme) - * [formidable](https://www.npmjs.org/package/formidable#readme) - * [multer](https://www.npmjs.org/package/multer#readme) - -This module provides the following parsers: - - * [JSON body parser](#bodyparserjsonoptions) - * [Raw body parser](#bodyparserrawoptions) - * [Text body parser](#bodyparsertextoptions) - * [URL-encoded form body parser](#bodyparserurlencodedoptions) - -Other body parsers you might be interested in: - -- [body](https://www.npmjs.org/package/body#readme) -- [co-body](https://www.npmjs.org/package/co-body#readme) - -## Installation - -```sh -$ npm install body-parser -``` - -## API - - - -```js -var bodyParser = require('body-parser') -``` - -The `bodyParser` object exposes various factories to create middlewares. All -middlewares will populate the `req.body` property with the parsed body when -the `Content-Type` request header matches the `type` option, or an empty -object (`{}`) if there was no body to parse, the `Content-Type` was not matched, -or an error occurred. - -The various errors returned by this module are described in the -[errors section](#errors). - -### bodyParser.json([options]) - -Returns middleware that only parses `json` and only looks at requests where -the `Content-Type` header matches the `type` option. This parser accepts any -Unicode encoding of the body and supports automatic inflation of `gzip` and -`deflate` encodings. - -A new `body` object containing the parsed data is populated on the `request` -object after the middleware (i.e. `req.body`). - -#### Options - -The `json` function takes an optional `options` object that may contain any of -the following keys: - -##### inflate - -When set to `true`, then deflated (compressed) bodies will be inflated; when -`false`, deflated bodies are rejected. Defaults to `true`. - -##### limit - -Controls the maximum request body size. If this is a number, then the value -specifies the number of bytes; if it is a string, the value is passed to the -[bytes](https://www.npmjs.com/package/bytes) library for parsing. Defaults -to `'100kb'`. - -##### reviver - -The `reviver` option is passed directly to `JSON.parse` as the second -argument. You can find more information on this argument -[in the MDN documentation about JSON.parse](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse#Example.3A_Using_the_reviver_parameter). - -##### strict - -When set to `true`, will only accept arrays and objects; when `false` will -accept anything `JSON.parse` accepts. Defaults to `true`. - -##### type - -The `type` option is used to determine what media type the middleware will -parse. This option can be a string, array of strings, or a function. If not a -function, `type` option is passed directly to the -[type-is](https://www.npmjs.org/package/type-is#readme) library and this can -be an extension name (like `json`), a mime type (like `application/json`), or -a mime type with a wildcard (like `*/*` or `*/json`). If a function, the `type` -option is called as `fn(req)` and the request is parsed if it returns a truthy -value. Defaults to `application/json`. - -##### verify - -The `verify` option, if supplied, is called as `verify(req, res, buf, encoding)`, -where `buf` is a `Buffer` of the raw request body and `encoding` is the -encoding of the request. The parsing can be aborted by throwing an error. - -### bodyParser.raw([options]) - -Returns middleware that parses all bodies as a `Buffer` and only looks at -requests where the `Content-Type` header matches the `type` option. This -parser supports automatic inflation of `gzip` and `deflate` encodings. - -A new `body` object containing the parsed data is populated on the `request` -object after the middleware (i.e. `req.body`). This will be a `Buffer` object -of the body. - -#### Options - -The `raw` function takes an optional `options` object that may contain any of -the following keys: - -##### inflate - -When set to `true`, then deflated (compressed) bodies will be inflated; when -`false`, deflated bodies are rejected. Defaults to `true`. - -##### limit - -Controls the maximum request body size. If this is a number, then the value -specifies the number of bytes; if it is a string, the value is passed to the -[bytes](https://www.npmjs.com/package/bytes) library for parsing. Defaults -to `'100kb'`. - -##### type - -The `type` option is used to determine what media type the middleware will -parse. This option can be a string, array of strings, or a function. -If not a function, `type` option is passed directly to the -[type-is](https://www.npmjs.org/package/type-is#readme) library and this -can be an extension name (like `bin`), a mime type (like -`application/octet-stream`), or a mime type with a wildcard (like `*/*` or -`application/*`). If a function, the `type` option is called as `fn(req)` -and the request is parsed if it returns a truthy value. Defaults to -`application/octet-stream`. - -##### verify - -The `verify` option, if supplied, is called as `verify(req, res, buf, encoding)`, -where `buf` is a `Buffer` of the raw request body and `encoding` is the -encoding of the request. The parsing can be aborted by throwing an error. - -### bodyParser.text([options]) - -Returns middleware that parses all bodies as a string and only looks at -requests where the `Content-Type` header matches the `type` option. This -parser supports automatic inflation of `gzip` and `deflate` encodings. - -A new `body` string containing the parsed data is populated on the `request` -object after the middleware (i.e. `req.body`). This will be a string of the -body. - -#### Options - -The `text` function takes an optional `options` object that may contain any of -the following keys: - -##### defaultCharset - -Specify the default character set for the text content if the charset is not -specified in the `Content-Type` header of the request. Defaults to `utf-8`. - -##### inflate - -When set to `true`, then deflated (compressed) bodies will be inflated; when -`false`, deflated bodies are rejected. Defaults to `true`. - -##### limit - -Controls the maximum request body size. If this is a number, then the value -specifies the number of bytes; if it is a string, the value is passed to the -[bytes](https://www.npmjs.com/package/bytes) library for parsing. Defaults -to `'100kb'`. - -##### type - -The `type` option is used to determine what media type the middleware will -parse. This option can be a string, array of strings, or a function. If not -a function, `type` option is passed directly to the -[type-is](https://www.npmjs.org/package/type-is#readme) library and this can -be an extension name (like `txt`), a mime type (like `text/plain`), or a mime -type with a wildcard (like `*/*` or `text/*`). If a function, the `type` -option is called as `fn(req)` and the request is parsed if it returns a -truthy value. Defaults to `text/plain`. - -##### verify - -The `verify` option, if supplied, is called as `verify(req, res, buf, encoding)`, -where `buf` is a `Buffer` of the raw request body and `encoding` is the -encoding of the request. The parsing can be aborted by throwing an error. - -### bodyParser.urlencoded([options]) - -Returns middleware that only parses `urlencoded` bodies and only looks at -requests where the `Content-Type` header matches the `type` option. This -parser accepts only UTF-8 encoding of the body and supports automatic -inflation of `gzip` and `deflate` encodings. - -A new `body` object containing the parsed data is populated on the `request` -object after the middleware (i.e. `req.body`). This object will contain -key-value pairs, where the value can be a string or array (when `extended` is -`false`), or any type (when `extended` is `true`). - -#### Options - -The `urlencoded` function takes an optional `options` object that may contain -any of the following keys: - -##### extended - -The `extended` option allows to choose between parsing the URL-encoded data -with the `querystring` library (when `false`) or the `qs` library (when -`true`). The "extended" syntax allows for rich objects and arrays to be -encoded into the URL-encoded format, allowing for a JSON-like experience -with URL-encoded. For more information, please -[see the qs library](https://www.npmjs.org/package/qs#readme). - -Defaults to `true`, but using the default has been deprecated. Please -research into the difference between `qs` and `querystring` and choose the -appropriate setting. - -##### inflate - -When set to `true`, then deflated (compressed) bodies will be inflated; when -`false`, deflated bodies are rejected. Defaults to `true`. - -##### limit - -Controls the maximum request body size. If this is a number, then the value -specifies the number of bytes; if it is a string, the value is passed to the -[bytes](https://www.npmjs.com/package/bytes) library for parsing. Defaults -to `'100kb'`. - -##### parameterLimit - -The `parameterLimit` option controls the maximum number of parameters that -are allowed in the URL-encoded data. If a request contains more parameters -than this value, a 413 will be returned to the client. Defaults to `1000`. - -##### type - -The `type` option is used to determine what media type the middleware will -parse. This option can be a string, array of strings, or a function. If not -a function, `type` option is passed directly to the -[type-is](https://www.npmjs.org/package/type-is#readme) library and this can -be an extension name (like `urlencoded`), a mime type (like -`application/x-www-form-urlencoded`), or a mime type with a wildcard (like -`*/x-www-form-urlencoded`). If a function, the `type` option is called as -`fn(req)` and the request is parsed if it returns a truthy value. Defaults -to `application/x-www-form-urlencoded`. - -##### verify - -The `verify` option, if supplied, is called as `verify(req, res, buf, encoding)`, -where `buf` is a `Buffer` of the raw request body and `encoding` is the -encoding of the request. The parsing can be aborted by throwing an error. - -## Errors - -The middlewares provided by this module create errors depending on the error -condition during parsing. The errors will typically have a `status`/`statusCode` -property that contains the suggested HTTP response code, an `expose` property -to determine if the `message` property should be displayed to the client, a -`type` property to determine the type of error without matching against the -`message`, and a `body` property containing the read body, if available. - -The following are the common errors emitted, though any error can come through -for various reasons. - -### content encoding unsupported - -This error will occur when the request had a `Content-Encoding` header that -contained an encoding but the "inflation" option was set to `false`. The -`status` property is set to `415`, the `type` property is set to -`'encoding.unsupported'`, and the `charset` property will be set to the -encoding that is unsupported. - -### request aborted - -This error will occur when the request is aborted by the client before reading -the body has finished. The `received` property will be set to the number of -bytes received before the request was aborted and the `expected` property is -set to the number of expected bytes. The `status` property is set to `400` -and `type` property is set to `'request.aborted'`. - -### request entity too large - -This error will occur when the request body's size is larger than the "limit" -option. The `limit` property will be set to the byte limit and the `length` -property will be set to the request body's length. The `status` property is -set to `413` and the `type` property is set to `'entity.too.large'`. - -### request size did not match content length - -This error will occur when the request's length did not match the length from -the `Content-Length` header. This typically occurs when the request is malformed, -typically when the `Content-Length` header was calculated based on characters -instead of bytes. The `status` property is set to `400` and the `type` property -is set to `'request.size.invalid'`. - -### stream encoding should not be set - -This error will occur when something called the `req.setEncoding` method prior -to this middleware. This module operates directly on bytes only and you cannot -call `req.setEncoding` when using this module. The `status` property is set to -`500` and the `type` property is set to `'stream.encoding.set'`. - -### too many parameters - -This error will occur when the content of the request exceeds the configured -`parameterLimit` for the `urlencoded` parser. The `status` property is set to -`413` and the `type` property is set to `'parameters.too.many'`. - -### unsupported charset "BOGUS" - -This error will occur when the request had a charset parameter in the -`Content-Type` header, but the `iconv-lite` module does not support it OR the -parser does not support it. The charset is contained in the message as well -as in the `charset` property. The `status` property is set to `415`, the -`type` property is set to `'charset.unsupported'`, and the `charset` property -is set to the charset that is unsupported. - -### unsupported content encoding "bogus" - -This error will occur when the request had a `Content-Encoding` header that -contained an unsupported encoding. The encoding is contained in the message -as well as in the `encoding` property. The `status` property is set to `415`, -the `type` property is set to `'encoding.unsupported'`, and the `encoding` -property is set to the encoding that is unsupported. - -## Examples - -### Express/Connect top-level generic - -This example demonstrates adding a generic JSON and URL-encoded parser as a -top-level middleware, which will parse the bodies of all incoming requests. -This is the simplest setup. - -```js -var express = require('express') -var bodyParser = require('body-parser') - -var app = express() - -// parse application/x-www-form-urlencoded -app.use(bodyParser.urlencoded({ extended: false })) - -// parse application/json -app.use(bodyParser.json()) - -app.use(function (req, res) { - res.setHeader('Content-Type', 'text/plain') - res.write('you posted:\n') - res.end(JSON.stringify(req.body, null, 2)) -}) -``` - -### Express route-specific - -This example demonstrates adding body parsers specifically to the routes that -need them. In general, this is the most recommended way to use body-parser with -Express. - -```js -var express = require('express') -var bodyParser = require('body-parser') - -var app = express() - -// create application/json parser -var jsonParser = bodyParser.json() - -// create application/x-www-form-urlencoded parser -var urlencodedParser = bodyParser.urlencoded({ extended: false }) - -// POST /login gets urlencoded bodies -app.post('/login', urlencodedParser, function (req, res) { - res.send('welcome, ' + req.body.username) -}) - -// POST /api/users gets JSON bodies -app.post('/api/users', jsonParser, function (req, res) { - // create user in req.body -}) -``` - -### Change accepted type for parsers - -All the parsers accept a `type` option which allows you to change the -`Content-Type` that the middleware will parse. - -```js -var express = require('express') -var bodyParser = require('body-parser') - -var app = express() - -// parse various different custom JSON types as JSON -app.use(bodyParser.json({ type: 'application/*+json' })) - -// parse some custom thing into a Buffer -app.use(bodyParser.raw({ type: 'application/vnd.custom-type' })) - -// parse an HTML body into a string -app.use(bodyParser.text({ type: 'text/html' })) -``` - -## License - -[MIT](LICENSE) - -[npm-image]: https://img.shields.io/npm/v/body-parser.svg -[npm-url]: https://npmjs.org/package/body-parser -[travis-image]: https://img.shields.io/travis/expressjs/body-parser/master.svg -[travis-url]: https://travis-ci.org/expressjs/body-parser -[coveralls-image]: https://img.shields.io/coveralls/expressjs/body-parser/master.svg -[coveralls-url]: https://coveralls.io/r/expressjs/body-parser?branch=master -[downloads-image]: https://img.shields.io/npm/dm/body-parser.svg -[downloads-url]: https://npmjs.org/package/body-parser diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/body-parser/index.js b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/body-parser/index.js deleted file mode 100644 index 93c3a1fffa..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/body-parser/index.js +++ /dev/null @@ -1,157 +0,0 @@ -/*! - * body-parser - * Copyright(c) 2014-2015 Douglas Christopher Wilson - * MIT Licensed - */ - -'use strict' - -/** - * Module dependencies. - * @private - */ - -var deprecate = require('depd')('body-parser') - -/** - * Cache of loaded parsers. - * @private - */ - -var parsers = Object.create(null) - -/** - * @typedef Parsers - * @type {function} - * @property {function} json - * @property {function} raw - * @property {function} text - * @property {function} urlencoded - */ - -/** - * Module exports. - * @type {Parsers} - */ - -exports = module.exports = deprecate.function(bodyParser, - 'bodyParser: use individual json/urlencoded middlewares') - -/** - * JSON parser. - * @public - */ - -Object.defineProperty(exports, 'json', { - configurable: true, - enumerable: true, - get: createParserGetter('json') -}) - -/** - * Raw parser. - * @public - */ - -Object.defineProperty(exports, 'raw', { - configurable: true, - enumerable: true, - get: createParserGetter('raw') -}) - -/** - * Text parser. - * @public - */ - -Object.defineProperty(exports, 'text', { - configurable: true, - enumerable: true, - get: createParserGetter('text') -}) - -/** - * URL-encoded parser. - * @public - */ - -Object.defineProperty(exports, 'urlencoded', { - configurable: true, - enumerable: true, - get: createParserGetter('urlencoded') -}) - -/** - * Create a middleware to parse json and urlencoded bodies. - * - * @param {object} [options] - * @return {function} - * @deprecated - * @public - */ - -function bodyParser (options) { - var opts = {} - - // exclude type option - if (options) { - for (var prop in options) { - if (prop !== 'type') { - opts[prop] = options[prop] - } - } - } - - var _urlencoded = exports.urlencoded(opts) - var _json = exports.json(opts) - - return function bodyParser (req, res, next) { - _json(req, res, function (err) { - if (err) return next(err) - _urlencoded(req, res, next) - }) - } -} - -/** - * Create a getter for loading a parser. - * @private - */ - -function createParserGetter (name) { - return function get () { - return loadParser(name) - } -} - -/** - * Load a parser module. - * @private - */ - -function loadParser (parserName) { - var parser = parsers[parserName] - - if (parser !== undefined) { - return parser - } - - // this uses a switch for static require analysis - switch (parserName) { - case 'json': - parser = require('./lib/types/json') - break - case 'raw': - parser = require('./lib/types/raw') - break - case 'text': - parser = require('./lib/types/text') - break - case 'urlencoded': - parser = require('./lib/types/urlencoded') - break - } - - // store to prevent invoking require() - return (parsers[parserName] = parser) -} diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/body-parser/lib/read.js b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/body-parser/lib/read.js deleted file mode 100644 index c10260958f..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/body-parser/lib/read.js +++ /dev/null @@ -1,181 +0,0 @@ -/*! - * body-parser - * Copyright(c) 2014-2015 Douglas Christopher Wilson - * MIT Licensed - */ - -'use strict' - -/** - * Module dependencies. - * @private - */ - -var createError = require('http-errors') -var getBody = require('raw-body') -var iconv = require('iconv-lite') -var onFinished = require('on-finished') -var zlib = require('zlib') - -/** - * Module exports. - */ - -module.exports = read - -/** - * Read a request into a buffer and parse. - * - * @param {object} req - * @param {object} res - * @param {function} next - * @param {function} parse - * @param {function} debug - * @param {object} options - * @private - */ - -function read (req, res, next, parse, debug, options) { - var length - var opts = options - var stream - - // flag as parsed - req._body = true - - // read options - var encoding = opts.encoding !== null - ? opts.encoding - : null - var verify = opts.verify - - try { - // get the content stream - stream = contentstream(req, debug, opts.inflate) - length = stream.length - stream.length = undefined - } catch (err) { - return next(err) - } - - // set raw-body options - opts.length = length - opts.encoding = verify - ? null - : encoding - - // assert charset is supported - if (opts.encoding === null && encoding !== null && !iconv.encodingExists(encoding)) { - return next(createError(415, 'unsupported charset "' + encoding.toUpperCase() + '"', { - charset: encoding.toLowerCase(), - type: 'charset.unsupported' - })) - } - - // read body - debug('read body') - getBody(stream, opts, function (error, body) { - if (error) { - var _error - - if (error.type === 'encoding.unsupported') { - // echo back charset - _error = createError(415, 'unsupported charset "' + encoding.toUpperCase() + '"', { - charset: encoding.toLowerCase(), - type: 'charset.unsupported' - }) - } else { - // set status code on error - _error = createError(400, error) - } - - // read off entire request - stream.resume() - onFinished(req, function onfinished () { - next(createError(400, _error)) - }) - return - } - - // verify - if (verify) { - try { - debug('verify body') - verify(req, res, body, encoding) - } catch (err) { - next(createError(403, err, { - body: body, - type: err.type || 'entity.verify.failed' - })) - return - } - } - - // parse - var str = body - try { - debug('parse body') - str = typeof body !== 'string' && encoding !== null - ? iconv.decode(body, encoding) - : body - req.body = parse(str) - } catch (err) { - next(createError(400, err, { - body: str, - type: err.type || 'entity.parse.failed' - })) - return - } - - next() - }) -} - -/** - * Get the content stream of the request. - * - * @param {object} req - * @param {function} debug - * @param {boolean} [inflate=true] - * @return {object} - * @api private - */ - -function contentstream (req, debug, inflate) { - var encoding = (req.headers['content-encoding'] || 'identity').toLowerCase() - var length = req.headers['content-length'] - var stream - - debug('content-encoding "%s"', encoding) - - if (inflate === false && encoding !== 'identity') { - throw createError(415, 'content encoding unsupported', { - encoding: encoding, - type: 'encoding.unsupported' - }) - } - - switch (encoding) { - case 'deflate': - stream = zlib.createInflate() - debug('inflate body') - req.pipe(stream) - break - case 'gzip': - stream = zlib.createGunzip() - debug('gunzip body') - req.pipe(stream) - break - case 'identity': - stream = req - stream.length = length - break - default: - throw createError(415, 'unsupported content encoding "' + encoding + '"', { - encoding: encoding, - type: 'encoding.unsupported' - }) - } - - return stream -} diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/body-parser/lib/types/json.js b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/body-parser/lib/types/json.js deleted file mode 100644 index 2971dc14d9..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/body-parser/lib/types/json.js +++ /dev/null @@ -1,230 +0,0 @@ -/*! - * body-parser - * Copyright(c) 2014 Jonathan Ong - * Copyright(c) 2014-2015 Douglas Christopher Wilson - * MIT Licensed - */ - -'use strict' - -/** - * Module dependencies. - * @private - */ - -var bytes = require('bytes') -var contentType = require('content-type') -var createError = require('http-errors') -var debug = require('debug')('body-parser:json') -var read = require('../read') -var typeis = require('type-is') - -/** - * Module exports. - */ - -module.exports = json - -/** - * RegExp to match the first non-space in a string. - * - * Allowed whitespace is defined in RFC 7159: - * - * ws = *( - * %x20 / ; Space - * %x09 / ; Horizontal tab - * %x0A / ; Line feed or New line - * %x0D ) ; Carriage return - */ - -var FIRST_CHAR_REGEXP = /^[\x20\x09\x0a\x0d]*(.)/ // eslint-disable-line no-control-regex - -/** - * Create a middleware to parse JSON bodies. - * - * @param {object} [options] - * @return {function} - * @public - */ - -function json (options) { - var opts = options || {} - - var limit = typeof opts.limit !== 'number' - ? bytes.parse(opts.limit || '100kb') - : opts.limit - var inflate = opts.inflate !== false - var reviver = opts.reviver - var strict = opts.strict !== false - var type = opts.type || 'application/json' - var verify = opts.verify || false - - if (verify !== false && typeof verify !== 'function') { - throw new TypeError('option verify must be function') - } - - // create the appropriate type checking function - var shouldParse = typeof type !== 'function' - ? typeChecker(type) - : type - - function parse (body) { - if (body.length === 0) { - // special-case empty json body, as it's a common client-side mistake - // TODO: maybe make this configurable or part of "strict" option - return {} - } - - if (strict) { - var first = firstchar(body) - - if (first !== '{' && first !== '[') { - debug('strict violation') - throw createStrictSyntaxError(body, first) - } - } - - try { - debug('parse json') - return JSON.parse(body, reviver) - } catch (e) { - throw normalizeJsonSyntaxError(e, { - message: e.message, - stack: e.stack - }) - } - } - - return function jsonParser (req, res, next) { - if (req._body) { - debug('body already parsed') - next() - return - } - - req.body = req.body || {} - - // skip requests without bodies - if (!typeis.hasBody(req)) { - debug('skip empty body') - next() - return - } - - debug('content-type %j', req.headers['content-type']) - - // determine if request should be parsed - if (!shouldParse(req)) { - debug('skip parsing') - next() - return - } - - // assert charset per RFC 7159 sec 8.1 - var charset = getCharset(req) || 'utf-8' - if (charset.substr(0, 4) !== 'utf-') { - debug('invalid charset') - next(createError(415, 'unsupported charset "' + charset.toUpperCase() + '"', { - charset: charset, - type: 'charset.unsupported' - })) - return - } - - // read - read(req, res, next, parse, debug, { - encoding: charset, - inflate: inflate, - limit: limit, - verify: verify - }) - } -} - -/** - * Create strict violation syntax error matching native error. - * - * @param {string} str - * @param {string} char - * @return {Error} - * @private - */ - -function createStrictSyntaxError (str, char) { - var index = str.indexOf(char) - var partial = str.substring(0, index) + '#' - - try { - JSON.parse(partial); /* istanbul ignore next */ throw new SyntaxError('strict violation') - } catch (e) { - return normalizeJsonSyntaxError(e, { - message: e.message.replace('#', char), - stack: e.stack - }) - } -} - -/** - * Get the first non-whitespace character in a string. - * - * @param {string} str - * @return {function} - * @private - */ - -function firstchar (str) { - return FIRST_CHAR_REGEXP.exec(str)[1] -} - -/** - * Get the charset of a request. - * - * @param {object} req - * @api private - */ - -function getCharset (req) { - try { - return (contentType.parse(req).parameters.charset || '').toLowerCase() - } catch (e) { - return undefined - } -} - -/** - * Normalize a SyntaxError for JSON.parse. - * - * @param {SyntaxError} error - * @param {object} obj - * @return {SyntaxError} - */ - -function normalizeJsonSyntaxError (error, obj) { - var keys = Object.getOwnPropertyNames(error) - - for (var i = 0; i < keys.length; i++) { - var key = keys[i] - if (key !== 'stack' && key !== 'message') { - delete error[key] - } - } - - // replace stack before message for Node.js 0.10 and below - error.stack = obj.stack.replace(error.message, obj.message) - error.message = obj.message - - return error -} - -/** - * Get the simple type checker. - * - * @param {string} type - * @return {function} - */ - -function typeChecker (type) { - return function checkType (req) { - return Boolean(typeis(req, type)) - } -} diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/body-parser/lib/types/raw.js b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/body-parser/lib/types/raw.js deleted file mode 100644 index f5d1b67475..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/body-parser/lib/types/raw.js +++ /dev/null @@ -1,101 +0,0 @@ -/*! - * body-parser - * Copyright(c) 2014-2015 Douglas Christopher Wilson - * MIT Licensed - */ - -'use strict' - -/** - * Module dependencies. - */ - -var bytes = require('bytes') -var debug = require('debug')('body-parser:raw') -var read = require('../read') -var typeis = require('type-is') - -/** - * Module exports. - */ - -module.exports = raw - -/** - * Create a middleware to parse raw bodies. - * - * @param {object} [options] - * @return {function} - * @api public - */ - -function raw (options) { - var opts = options || {} - - var inflate = opts.inflate !== false - var limit = typeof opts.limit !== 'number' - ? bytes.parse(opts.limit || '100kb') - : opts.limit - var type = opts.type || 'application/octet-stream' - var verify = opts.verify || false - - if (verify !== false && typeof verify !== 'function') { - throw new TypeError('option verify must be function') - } - - // create the appropriate type checking function - var shouldParse = typeof type !== 'function' - ? typeChecker(type) - : type - - function parse (buf) { - return buf - } - - return function rawParser (req, res, next) { - if (req._body) { - debug('body already parsed') - next() - return - } - - req.body = req.body || {} - - // skip requests without bodies - if (!typeis.hasBody(req)) { - debug('skip empty body') - next() - return - } - - debug('content-type %j', req.headers['content-type']) - - // determine if request should be parsed - if (!shouldParse(req)) { - debug('skip parsing') - next() - return - } - - // read - read(req, res, next, parse, debug, { - encoding: null, - inflate: inflate, - limit: limit, - verify: verify - }) - } -} - -/** - * Get the simple type checker. - * - * @param {string} type - * @return {function} - */ - -function typeChecker (type) { - return function checkType (req) { - return Boolean(typeis(req, type)) - } -} diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/body-parser/lib/types/text.js b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/body-parser/lib/types/text.js deleted file mode 100644 index 083a00908a..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/body-parser/lib/types/text.js +++ /dev/null @@ -1,121 +0,0 @@ -/*! - * body-parser - * Copyright(c) 2014-2015 Douglas Christopher Wilson - * MIT Licensed - */ - -'use strict' - -/** - * Module dependencies. - */ - -var bytes = require('bytes') -var contentType = require('content-type') -var debug = require('debug')('body-parser:text') -var read = require('../read') -var typeis = require('type-is') - -/** - * Module exports. - */ - -module.exports = text - -/** - * Create a middleware to parse text bodies. - * - * @param {object} [options] - * @return {function} - * @api public - */ - -function text (options) { - var opts = options || {} - - var defaultCharset = opts.defaultCharset || 'utf-8' - var inflate = opts.inflate !== false - var limit = typeof opts.limit !== 'number' - ? bytes.parse(opts.limit || '100kb') - : opts.limit - var type = opts.type || 'text/plain' - var verify = opts.verify || false - - if (verify !== false && typeof verify !== 'function') { - throw new TypeError('option verify must be function') - } - - // create the appropriate type checking function - var shouldParse = typeof type !== 'function' - ? typeChecker(type) - : type - - function parse (buf) { - return buf - } - - return function textParser (req, res, next) { - if (req._body) { - debug('body already parsed') - next() - return - } - - req.body = req.body || {} - - // skip requests without bodies - if (!typeis.hasBody(req)) { - debug('skip empty body') - next() - return - } - - debug('content-type %j', req.headers['content-type']) - - // determine if request should be parsed - if (!shouldParse(req)) { - debug('skip parsing') - next() - return - } - - // get charset - var charset = getCharset(req) || defaultCharset - - // read - read(req, res, next, parse, debug, { - encoding: charset, - inflate: inflate, - limit: limit, - verify: verify - }) - } -} - -/** - * Get the charset of a request. - * - * @param {object} req - * @api private - */ - -function getCharset (req) { - try { - return (contentType.parse(req).parameters.charset || '').toLowerCase() - } catch (e) { - return undefined - } -} - -/** - * Get the simple type checker. - * - * @param {string} type - * @return {function} - */ - -function typeChecker (type) { - return function checkType (req) { - return Boolean(typeis(req, type)) - } -} diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/body-parser/lib/types/urlencoded.js b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/body-parser/lib/types/urlencoded.js deleted file mode 100644 index b2ca8f16d0..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/body-parser/lib/types/urlencoded.js +++ /dev/null @@ -1,284 +0,0 @@ -/*! - * body-parser - * Copyright(c) 2014 Jonathan Ong - * Copyright(c) 2014-2015 Douglas Christopher Wilson - * MIT Licensed - */ - -'use strict' - -/** - * Module dependencies. - * @private - */ - -var bytes = require('bytes') -var contentType = require('content-type') -var createError = require('http-errors') -var debug = require('debug')('body-parser:urlencoded') -var deprecate = require('depd')('body-parser') -var read = require('../read') -var typeis = require('type-is') - -/** - * Module exports. - */ - -module.exports = urlencoded - -/** - * Cache of parser modules. - */ - -var parsers = Object.create(null) - -/** - * Create a middleware to parse urlencoded bodies. - * - * @param {object} [options] - * @return {function} - * @public - */ - -function urlencoded (options) { - var opts = options || {} - - // notice because option default will flip in next major - if (opts.extended === undefined) { - deprecate('undefined extended: provide extended option') - } - - var extended = opts.extended !== false - var inflate = opts.inflate !== false - var limit = typeof opts.limit !== 'number' - ? bytes.parse(opts.limit || '100kb') - : opts.limit - var type = opts.type || 'application/x-www-form-urlencoded' - var verify = opts.verify || false - - if (verify !== false && typeof verify !== 'function') { - throw new TypeError('option verify must be function') - } - - // create the appropriate query parser - var queryparse = extended - ? extendedparser(opts) - : simpleparser(opts) - - // create the appropriate type checking function - var shouldParse = typeof type !== 'function' - ? typeChecker(type) - : type - - function parse (body) { - return body.length - ? queryparse(body) - : {} - } - - return function urlencodedParser (req, res, next) { - if (req._body) { - debug('body already parsed') - next() - return - } - - req.body = req.body || {} - - // skip requests without bodies - if (!typeis.hasBody(req)) { - debug('skip empty body') - next() - return - } - - debug('content-type %j', req.headers['content-type']) - - // determine if request should be parsed - if (!shouldParse(req)) { - debug('skip parsing') - next() - return - } - - // assert charset - var charset = getCharset(req) || 'utf-8' - if (charset !== 'utf-8') { - debug('invalid charset') - next(createError(415, 'unsupported charset "' + charset.toUpperCase() + '"', { - charset: charset, - type: 'charset.unsupported' - })) - return - } - - // read - read(req, res, next, parse, debug, { - debug: debug, - encoding: charset, - inflate: inflate, - limit: limit, - verify: verify - }) - } -} - -/** - * Get the extended query parser. - * - * @param {object} options - */ - -function extendedparser (options) { - var parameterLimit = options.parameterLimit !== undefined - ? options.parameterLimit - : 1000 - var parse = parser('qs') - - if (isNaN(parameterLimit) || parameterLimit < 1) { - throw new TypeError('option parameterLimit must be a positive number') - } - - if (isFinite(parameterLimit)) { - parameterLimit = parameterLimit | 0 - } - - return function queryparse (body) { - var paramCount = parameterCount(body, parameterLimit) - - if (paramCount === undefined) { - debug('too many parameters') - throw createError(413, 'too many parameters', { - type: 'parameters.too.many' - }) - } - - var arrayLimit = Math.max(100, paramCount) - - debug('parse extended urlencoding') - return parse(body, { - allowPrototypes: true, - arrayLimit: arrayLimit, - depth: Infinity, - parameterLimit: parameterLimit - }) - } -} - -/** - * Get the charset of a request. - * - * @param {object} req - * @api private - */ - -function getCharset (req) { - try { - return (contentType.parse(req).parameters.charset || '').toLowerCase() - } catch (e) { - return undefined - } -} - -/** - * Count the number of parameters, stopping once limit reached - * - * @param {string} body - * @param {number} limit - * @api private - */ - -function parameterCount (body, limit) { - var count = 0 - var index = 0 - - while ((index = body.indexOf('&', index)) !== -1) { - count++ - index++ - - if (count === limit) { - return undefined - } - } - - return count -} - -/** - * Get parser for module name dynamically. - * - * @param {string} name - * @return {function} - * @api private - */ - -function parser (name) { - var mod = parsers[name] - - if (mod !== undefined) { - return mod.parse - } - - // this uses a switch for static require analysis - switch (name) { - case 'qs': - mod = require('qs') - break - case 'querystring': - mod = require('querystring') - break - } - - // store to prevent invoking require() - parsers[name] = mod - - return mod.parse -} - -/** - * Get the simple query parser. - * - * @param {object} options - */ - -function simpleparser (options) { - var parameterLimit = options.parameterLimit !== undefined - ? options.parameterLimit - : 1000 - var parse = parser('querystring') - - if (isNaN(parameterLimit) || parameterLimit < 1) { - throw new TypeError('option parameterLimit must be a positive number') - } - - if (isFinite(parameterLimit)) { - parameterLimit = parameterLimit | 0 - } - - return function queryparse (body) { - var paramCount = parameterCount(body, parameterLimit) - - if (paramCount === undefined) { - debug('too many parameters') - throw createError(413, 'too many parameters', { - type: 'parameters.too.many' - }) - } - - debug('parse urlencoding') - return parse(body, undefined, undefined, { maxKeys: parameterLimit }) - } -} - -/** - * Get the simple type checker. - * - * @param {string} type - * @return {function} - */ - -function typeChecker (type) { - return function checkType (req) { - return Boolean(typeis(req, type)) - } -} diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/body-parser/package.json b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/body-parser/package.json deleted file mode 100644 index 0b79e6b271..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/body-parser/package.json +++ /dev/null @@ -1,93 +0,0 @@ -{ - "_from": "body-parser@^1.19.0", - "_id": "body-parser@1.19.0", - "_inBundle": false, - "_integrity": "sha512-dhEPs72UPbDnAQJ9ZKMNTP6ptJaionhP5cBb541nXPlW60Jepo9RV/a4fX4XWW9CuFNK22krhrj1+rgzifNCsw==", - "_location": "/body-parser", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "body-parser@^1.19.0", - "name": "body-parser", - "escapedName": "body-parser", - "rawSpec": "^1.19.0", - "saveSpec": null, - "fetchSpec": "^1.19.0" - }, - "_requiredBy": [ - "#USER", - "/", - "/express" - ], - "_resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.19.0.tgz", - "_shasum": "96b2709e57c9c4e09a6fd66a8fd979844f69f08a", - "_spec": "body-parser@^1.19.0", - "_where": "/home/jan/Documents/skweb", - "bugs": { - "url": "https://github.com/expressjs/body-parser/issues" - }, - "bundleDependencies": false, - "contributors": [ - { - "name": "Douglas Christopher Wilson", - "email": "doug@somethingdoug.com" - }, - { - "name": "Jonathan Ong", - "email": "me@jongleberry.com", - "url": "http://jongleberry.com" - } - ], - "dependencies": { - "bytes": "3.1.0", - "content-type": "~1.0.4", - "debug": "2.6.9", - "depd": "~1.1.2", - "http-errors": "1.7.2", - "iconv-lite": "0.4.24", - "on-finished": "~2.3.0", - "qs": "6.7.0", - "raw-body": "2.4.0", - "type-is": "~1.6.17" - }, - "deprecated": false, - "description": "Node.js body parsing middleware", - "devDependencies": { - "eslint": "5.16.0", - "eslint-config-standard": "12.0.0", - "eslint-plugin-import": "2.17.2", - "eslint-plugin-markdown": "1.0.0", - "eslint-plugin-node": "8.0.1", - "eslint-plugin-promise": "4.1.1", - "eslint-plugin-standard": "4.0.0", - "istanbul": "0.4.5", - "methods": "1.1.2", - "mocha": "6.1.4", - "safe-buffer": "5.1.2", - "supertest": "4.0.2" - }, - "engines": { - "node": ">= 0.8" - }, - "files": [ - "lib/", - "LICENSE", - "HISTORY.md", - "index.js" - ], - "homepage": "https://github.com/expressjs/body-parser#readme", - "license": "MIT", - "name": "body-parser", - "repository": { - "type": "git", - "url": "git+https://github.com/expressjs/body-parser.git" - }, - "scripts": { - "lint": "eslint --plugin markdown --ext js,md .", - "test": "mocha --require test/support/env --reporter spec --check-leaks --bail test/", - "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --require test/support/env --reporter dot --check-leaks test/", - "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --require test/support/env --reporter spec --check-leaks test/" - }, - "version": "1.19.0" -} diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/bytes/History.md b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/bytes/History.md deleted file mode 100644 index cf6a5bb9cf..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/bytes/History.md +++ /dev/null @@ -1,87 +0,0 @@ -3.1.0 / 2019-01-22 -================== - - * Add petabyte (`pb`) support - -3.0.0 / 2017-08-31 -================== - - * Change "kB" to "KB" in format output - * Remove support for Node.js 0.6 - * Remove support for ComponentJS - -2.5.0 / 2017-03-24 -================== - - * Add option "unit" - -2.4.0 / 2016-06-01 -================== - - * Add option "unitSeparator" - -2.3.0 / 2016-02-15 -================== - - * Drop partial bytes on all parsed units - * Fix non-finite numbers to `.format` to return `null` - * Fix parsing byte string that looks like hex - * perf: hoist regular expressions - -2.2.0 / 2015-11-13 -================== - - * add option "decimalPlaces" - * add option "fixedDecimals" - -2.1.0 / 2015-05-21 -================== - - * add `.format` export - * add `.parse` export - -2.0.2 / 2015-05-20 -================== - - * remove map recreation - * remove unnecessary object construction - -2.0.1 / 2015-05-07 -================== - - * fix browserify require - * remove node.extend dependency - -2.0.0 / 2015-04-12 -================== - - * add option "case" - * add option "thousandsSeparator" - * return "null" on invalid parse input - * support proper round-trip: bytes(bytes(num)) === num - * units no longer case sensitive when parsing - -1.0.0 / 2014-05-05 -================== - - * add negative support. fixes #6 - -0.3.0 / 2014-03-19 -================== - - * added terabyte support - -0.2.1 / 2013-04-01 -================== - - * add .component - -0.2.0 / 2012-10-28 -================== - - * bytes(200).should.eql('200b') - -0.1.0 / 2012-07-04 -================== - - * add bytes to string conversion [yields] diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/bytes/LICENSE b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/bytes/LICENSE deleted file mode 100644 index 63e95a9633..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/bytes/LICENSE +++ /dev/null @@ -1,23 +0,0 @@ -(The MIT License) - -Copyright (c) 2012-2014 TJ Holowaychuk -Copyright (c) 2015 Jed Watson - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -'Software'), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/bytes/Readme.md b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/bytes/Readme.md deleted file mode 100644 index 6ad1ec6e2a..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/bytes/Readme.md +++ /dev/null @@ -1,126 +0,0 @@ -# Bytes utility - -[![NPM Version][npm-image]][npm-url] -[![NPM Downloads][downloads-image]][downloads-url] -[![Build Status][travis-image]][travis-url] -[![Test Coverage][coveralls-image]][coveralls-url] - -Utility to parse a string bytes (ex: `1TB`) to bytes (`1099511627776`) and vice-versa. - -## Installation - -This is a [Node.js](https://nodejs.org/en/) module available through the -[npm registry](https://www.npmjs.com/). Installation is done using the -[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): - -```bash -$ npm install bytes -``` - -## Usage - -```js -var bytes = require('bytes'); -``` - -#### bytes.format(number value, [options]): string|null - -Format the given value in bytes into a string. If the value is negative, it is kept as such. If it is a float, it is - rounded. - -**Arguments** - -| Name | Type | Description | -|---------|----------|--------------------| -| value | `number` | Value in bytes | -| options | `Object` | Conversion options | - -**Options** - -| Property | Type | Description | -|-------------------|--------|-----------------------------------------------------------------------------------------| -| decimalPlaces | `number`|`null` | Maximum number of decimal places to include in output. Default value to `2`. | -| fixedDecimals | `boolean`|`null` | Whether to always display the maximum number of decimal places. Default value to `false` | -| thousandsSeparator | `string`|`null` | Example of values: `' '`, `','` and `.`... Default value to `''`. | -| unit | `string`|`null` | The unit in which the result will be returned (B/KB/MB/GB/TB). Default value to `''` (which means auto detect). | -| unitSeparator | `string`|`null` | Separator to use between number and unit. Default value to `''`. | - -**Returns** - -| Name | Type | Description | -|---------|------------------|-------------------------------------------------| -| results | `string`|`null` | Return null upon error. String value otherwise. | - -**Example** - -```js -bytes(1024); -// output: '1KB' - -bytes(1000); -// output: '1000B' - -bytes(1000, {thousandsSeparator: ' '}); -// output: '1 000B' - -bytes(1024 * 1.7, {decimalPlaces: 0}); -// output: '2KB' - -bytes(1024, {unitSeparator: ' '}); -// output: '1 KB' - -``` - -#### bytes.parse(string|number value): number|null - -Parse the string value into an integer in bytes. If no unit is given, or `value` -is a number, it is assumed the value is in bytes. - -Supported units and abbreviations are as follows and are case-insensitive: - - * `b` for bytes - * `kb` for kilobytes - * `mb` for megabytes - * `gb` for gigabytes - * `tb` for terabytes - * `pb` for petabytes - -The units are in powers of two, not ten. This means 1kb = 1024b according to this parser. - -**Arguments** - -| Name | Type | Description | -|---------------|--------|--------------------| -| value | `string`|`number` | String to parse, or number in bytes. | - -**Returns** - -| Name | Type | Description | -|---------|-------------|-------------------------| -| results | `number`|`null` | Return null upon error. Value in bytes otherwise. | - -**Example** - -```js -bytes('1KB'); -// output: 1024 - -bytes('1024'); -// output: 1024 - -bytes(1024); -// output: 1KB -``` - -## License - -[MIT](LICENSE) - -[coveralls-image]: https://badgen.net/coveralls/c/github/visionmedia/bytes.js/master -[coveralls-url]: https://coveralls.io/r/visionmedia/bytes.js?branch=master -[downloads-image]: https://badgen.net/npm/dm/bytes -[downloads-url]: https://npmjs.org/package/bytes -[npm-image]: https://badgen.net/npm/node/bytes -[npm-url]: https://npmjs.org/package/bytes -[travis-image]: https://badgen.net/travis/visionmedia/bytes.js/master -[travis-url]: https://travis-ci.org/visionmedia/bytes.js diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/bytes/index.js b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/bytes/index.js deleted file mode 100644 index 4975bfb0c9..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/bytes/index.js +++ /dev/null @@ -1,162 +0,0 @@ -/*! - * bytes - * Copyright(c) 2012-2014 TJ Holowaychuk - * Copyright(c) 2015 Jed Watson - * MIT Licensed - */ - -'use strict'; - -/** - * Module exports. - * @public - */ - -module.exports = bytes; -module.exports.format = format; -module.exports.parse = parse; - -/** - * Module variables. - * @private - */ - -var formatThousandsRegExp = /\B(?=(\d{3})+(?!\d))/g; - -var formatDecimalsRegExp = /(?:\.0*|(\.[^0]+)0+)$/; - -var map = { - b: 1, - kb: 1 << 10, - mb: 1 << 20, - gb: 1 << 30, - tb: Math.pow(1024, 4), - pb: Math.pow(1024, 5), -}; - -var parseRegExp = /^((-|\+)?(\d+(?:\.\d+)?)) *(kb|mb|gb|tb|pb)$/i; - -/** - * Convert the given value in bytes into a string or parse to string to an integer in bytes. - * - * @param {string|number} value - * @param {{ - * case: [string], - * decimalPlaces: [number] - * fixedDecimals: [boolean] - * thousandsSeparator: [string] - * unitSeparator: [string] - * }} [options] bytes options. - * - * @returns {string|number|null} - */ - -function bytes(value, options) { - if (typeof value === 'string') { - return parse(value); - } - - if (typeof value === 'number') { - return format(value, options); - } - - return null; -} - -/** - * Format the given value in bytes into a string. - * - * If the value is negative, it is kept as such. If it is a float, - * it is rounded. - * - * @param {number} value - * @param {object} [options] - * @param {number} [options.decimalPlaces=2] - * @param {number} [options.fixedDecimals=false] - * @param {string} [options.thousandsSeparator=] - * @param {string} [options.unit=] - * @param {string} [options.unitSeparator=] - * - * @returns {string|null} - * @public - */ - -function format(value, options) { - if (!Number.isFinite(value)) { - return null; - } - - var mag = Math.abs(value); - var thousandsSeparator = (options && options.thousandsSeparator) || ''; - var unitSeparator = (options && options.unitSeparator) || ''; - var decimalPlaces = (options && options.decimalPlaces !== undefined) ? options.decimalPlaces : 2; - var fixedDecimals = Boolean(options && options.fixedDecimals); - var unit = (options && options.unit) || ''; - - if (!unit || !map[unit.toLowerCase()]) { - if (mag >= map.pb) { - unit = 'PB'; - } else if (mag >= map.tb) { - unit = 'TB'; - } else if (mag >= map.gb) { - unit = 'GB'; - } else if (mag >= map.mb) { - unit = 'MB'; - } else if (mag >= map.kb) { - unit = 'KB'; - } else { - unit = 'B'; - } - } - - var val = value / map[unit.toLowerCase()]; - var str = val.toFixed(decimalPlaces); - - if (!fixedDecimals) { - str = str.replace(formatDecimalsRegExp, '$1'); - } - - if (thousandsSeparator) { - str = str.replace(formatThousandsRegExp, thousandsSeparator); - } - - return str + unitSeparator + unit; -} - -/** - * Parse the string value into an integer in bytes. - * - * If no unit is given, it is assumed the value is in bytes. - * - * @param {number|string} val - * - * @returns {number|null} - * @public - */ - -function parse(val) { - if (typeof val === 'number' && !isNaN(val)) { - return val; - } - - if (typeof val !== 'string') { - return null; - } - - // Test if the string passed is valid - var results = parseRegExp.exec(val); - var floatValue; - var unit = 'b'; - - if (!results) { - // Nothing could be extracted from the given string - floatValue = parseInt(val, 10); - unit = 'b' - } else { - // Retrieve the value and the unit - floatValue = parseFloat(results[1]); - unit = results[4].toLowerCase(); - } - - return Math.floor(map[unit] * floatValue); -} diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/bytes/package.json b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/bytes/package.json deleted file mode 100644 index 0c4b66bb40..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/bytes/package.json +++ /dev/null @@ -1,84 +0,0 @@ -{ - "_from": "bytes@3.1.0", - "_id": "bytes@3.1.0", - "_inBundle": false, - "_integrity": "sha512-zauLjrfCG+xvoyaqLoV8bLVXXNGC4JqlxFCutSDWA6fJrTo2ZuvLYTqZ7aHBLZSMOopbzwv8f+wZcVzfVTI2Dg==", - "_location": "/bytes", - "_phantomChildren": {}, - "_requested": { - "type": "version", - "registry": true, - "raw": "bytes@3.1.0", - "name": "bytes", - "escapedName": "bytes", - "rawSpec": "3.1.0", - "saveSpec": null, - "fetchSpec": "3.1.0" - }, - "_requiredBy": [ - "/body-parser", - "/raw-body" - ], - "_resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.0.tgz", - "_shasum": "f6cf7933a360e0588fa9fde85651cdc7f805d1f6", - "_spec": "bytes@3.1.0", - "_where": "/home/jan/Documents/skweb/node_modules/body-parser", - "author": { - "name": "TJ Holowaychuk", - "email": "tj@vision-media.ca", - "url": "http://tjholowaychuk.com" - }, - "bugs": { - "url": "https://github.com/visionmedia/bytes.js/issues" - }, - "bundleDependencies": false, - "contributors": [ - { - "name": "Jed Watson", - "email": "jed.watson@me.com" - }, - { - "name": "Théo FIDRY", - "email": "theo.fidry@gmail.com" - } - ], - "deprecated": false, - "description": "Utility to parse a string bytes to bytes and vice-versa", - "devDependencies": { - "eslint": "5.12.1", - "mocha": "5.2.0", - "nyc": "13.1.0" - }, - "engines": { - "node": ">= 0.8" - }, - "files": [ - "History.md", - "LICENSE", - "Readme.md", - "index.js" - ], - "homepage": "https://github.com/visionmedia/bytes.js#readme", - "keywords": [ - "byte", - "bytes", - "utility", - "parse", - "parser", - "convert", - "converter" - ], - "license": "MIT", - "name": "bytes", - "repository": { - "type": "git", - "url": "git+https://github.com/visionmedia/bytes.js.git" - }, - "scripts": { - "lint": "eslint .", - "test": "mocha --check-leaks --reporter spec", - "test-ci": "nyc --reporter=text npm test", - "test-cov": "nyc --reporter=html --reporter=text npm test" - }, - "version": "3.1.0" -} diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/.eslintignore b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/.eslintignore deleted file mode 100644 index d1d2071283..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/.eslintignore +++ /dev/null @@ -1,8 +0,0 @@ -# TypeScript: js files are generated using tsc transpiler -/test/unit/typescript/*.js - -# Integer is part of the Closure Library -/lib/types/integer.js - -# TinkerPop-based files -/lib/datastax/graph/type-serializers.js \ No newline at end of file diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/.travis.yml b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/.travis.yml deleted file mode 100644 index c3de682b8e..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/.travis.yml +++ /dev/null @@ -1,44 +0,0 @@ -language: node_js -sudo: false -cache: - directories: - - node_modules - -jobs: - include: - - stage: "tests" - name: "Run eslint" - script: "npm install -g eslint@4; npm run eslint;" - node_js: "10" - - name: "TypeScript 2.9 generation and compilation tests" - node_js: "10" - script: - - npm install -g typescript@2.9; - - pushd test/unit/typescript/ - - tsc -p . - - node -e "require('./api-generation-test').generate()" > generated.ts - - tsc generated.ts - - name: "Unit tests - Node.js 12" - node_js: "12" - script: "npm test" - - name: "Unit tests w/ latest dependencies - Node.js 12" - node_js: "12" - script: - - rm package-lock.json - - rm -rf node_modules - - npm install - - npm test - - name: "Unit tests - Node.js 10" - node_js: "10" - script: "npm test" - - name: "Unit tests - Node.js 8" - node_js: "8" - script: "npm test" - - name: "TypeScript (latest) generation and compilation tests" - node_js: "10" - script: - - npm install -g typescript; - - pushd test/unit/typescript/ - - tsc -p . - - node -e "require('./api-generation-test').generate()" > generated.ts - - tsc generated.ts diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/CHANGELOG.md b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/CHANGELOG.md deleted file mode 100644 index 4494bb0f7d..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/CHANGELOG.md +++ /dev/null @@ -1,575 +0,0 @@ -# ChangeLog - DataStax Node.js Driver - -## 4.6.0 - -2020-08-11 - -### Features - -- [NODEJS-587] - Mapper: Add ability to provide a encoding/decoding functions to ModelOptions.columns -- [NODEJS-607] - Mapper: Add clear error messages when the model can not be found -- [NODEJS-611] - Use "allow list" terminology instead of whitelist - -### Bug fixes - -- [NODEJS-609] - NodeJS driver doesn't support transitional authentication -- [NODEJS-610] - TypeScript error on Type 'ResultSet' must have a '[Symbol.asyncIterator]()' method that returns an - async iterator. - -## 4.5.2 - -2020-05-07 - -### Bug fixes - -- [NODEJS-606] - Graph: Direction serializer does not serialize direction elements - -## 4.5.1 - -2020-04-14 - -### Bug fixes - -- [NODEJS-605] - Graph: TSerializer does not deserialize T elements correctly - -## 4.5.0 - -2020-03-26 - -### Features - -- [NODEJS-489] - Initial DS Graph 6.8 Support -- [NODEJS-482] - Remove unnecessary allocations during GraphExecutionOptions creation -- [NODEJS-564] - Include available dcs in all localDataCenter errors -- [NODEJS-571] - Astra: Validate server certificate CN against the proxy host name -- [NODEJS-573] - Expose a method to build the default load balancing policy with the data center name - -### Bug fixes - -- [NODEJS-594] - Cloud support uses fs.promises which is marked as experimental in Node.js - -## 4.4.0 - -2020-01-15 - -### Features - -- [NODEJS-549] - Unified driver: merge core and DSE drivers into a single package -- [NODEJS-574] - Refactor Driver Internals: modernize codebase and use async functions internally -- [NODEJS-563] - Support paging with async iterator -- [NODEJS-585] - Implement TCP flow control -- [NODEJS-516] - Drop support for Node.js 4 and 6 runtime - -### Bug fixes - -- [NODEJS-583] - Default load balancing policy local hosts cache might exclude hosts that were down -- [NODEJS-584] - Exclude down hosts when preparing on all hosts -- [NODEJS-586] - Encode Date as BigInt when useBigIntAsLong is true - -## 4.3.1 - -2019-11-06 - -### Bug fixes - -- [NODEJS-541] - Deprecated IdempotencyAwareRetryPolicy checks for options resulting in error -- [NODEJS-572] - TypeScript: ExecutionProfile parameters should be marked as optional -- [NODEJS-576] - MutableLong multiplication can cause infinite recursion - -## 4.3.0 - -2019-10-21 - -### Features - -- [NODEJS-503] - DataStax Astra Support -- [NODEJS-562] - TypeScript: Add generics to Mapper - -### Bug fixes - -- [NODEJS-556] - TypeScript: Client.stream typedef has incorrect return type -- [NODEJS-557] - TypeScript: DataCollection speculateRetry should be speculativeRetry -- [NODEJS-559] - TypeScript: DataCollection object|map types -- [NODEJS-561] - TypeScript: Missing credentials in ClientOptions - -## 4.2.0 - -2019-09-23 - -### Features - -- [NODEJS-464] - Include TypeScript declaration files on the package -- [NODEJS-512] - Mapper: support selecting the table or view using clustering keys from "order by" -- [NODEJS-514] - Support string input for all numeric types -- [NODEJS-515] - Mapper: support static column updates with only the partition key -- [NODEJS-545] - Introduce 'credentials' client option - -### Bug fixes - -- [NODEJS-509] - Mapper: batch items promise usage can lead to unhandled rejections -- [NODEJS-524] - "RangeError: Index out of range" when fetching tuples -- [NODEJS-527] - Mapper: select query cache key uses order by portion incorrectly -- [NODEJS-529] - Tuple constructor incorrectly handles single element values -- [NODEJS-538] - Mapper query generation error: USING clause is misplaced -- [NODEJS-546] - Mapper result throws when inspected and result is not ROWS - -## 4.1.0 - -2019-04-25 - -### Features - -- [NODEJS-180] - Expose API for parallel execution -- [NODEJS-100] - Provide a way to stream data in -- [NODEJS-491] - Send driver name and driver version in the STARTUP message -- [NODEJS-497] - Add jitter to ExponentialReconnectionPolicy -- [NODEJS-500] - ControlConnection init: Defer host map creation until system tables have been queried -- [NODEJS-501] - Include host_id in host metadata - -### Bug fixes - -- [NODEJS-475] - Buffer out of bounds error when reading empty byte buffers -- [NODEJS-477] - Logged message when preparing times out does not contain host address -- [NODEJS-492] - RequestLogger: Object parameter is not stringified before using substr -- [NODEJS-506] - ControlConnection queries during shutdown can leave active handles - -## 4.0.0 - -2018-12-17 - -### Features - -- [NODEJS-144] - Object Mapper -- [NODEJS-104] - Randomize contact points to prevent hotspots -- [NODEJS-192] - Allow raw bytes to be input for all types -- [NODEJS-220] - Slow Query Logger -- [NODEJS-300] - Expose metrics API -- [NODEJS-331] - Bypass retry logic when query is marked as non-idempotent -- [NODEJS-345] - Expose Metadata.checkSchemaAgreement() and ExecutionInfo.isSchemaInAgreement() -- [NODEJS-366] - Latency tracker interface -- [NODEJS-379] - DCAwareRoundRobinPolicy: Throw when local datacenter is not specified -- [NODEJS-387] - Expose optional callbacks in TimeUuid.now() and TimeUuid.fromDate() as an async overload -- [NODEJS-449] - Support new JavaScript primitive type bigint -- [NODEJS-450] - Introduce a wrapper around QueryOptions -- [NODEJS-485] - Remove usedHostsPerRemoteDc from DCAwareRoundRobinPolicy -- [NODEJS-462] - Remove the experimental flag to the Execution Profiles - -### Bug fixes - -- [NODEJS-473] - Zero-length map values: Fix RangeError on empty buffer in Encoder - -## 3.6.0 - -2018-12-04 - -### Features - -- [NODEJS-442] - Parse Virtual Keyspace Metadata -- [NODEJS-443] - Provide a means of sending query to a specific node to facilitate virtual table queries -- [NODEJS-459] - Support for Virtual Tables/System views -- [NODEJS-487] - Deprecate DCAwareRoundRobinPolicy parameter for inter-DC failover - -### Bug fixes - -- [NODEJS-465] - Table metadata fetch fails when using ES2015 Set and C* 3.0+ -- [NODEJS-472] - Connections attempts are made when a new node is bootstrapped even if its marked as "ignored" -- [NODEJS-474] - Retry on current host should be made on a different connection - -## 3.5.0 - -2018-04-17 - -### Features - -- [NODEJS-407] - Add NO\_COMPACT option -- [NODEJS-426] - Log driver version on Client.connect -- [NODEJS-431] - Consider using OPTIONS for heartbeats instead of 'select key from system.local' - -### Bug fixes - -- [NODEJS-412] - Methods to retrieve schema metadata should reject promise when not connected -- [NODEJS-418] - Add jsdoc for each response error code -- [NODEJS-428] - Connection associated with reconnect is not fully closed when STARTUP times out on node that is unresponsive -- #271 - Use all columns from peers in ControlConnection -- #276 - Remove buffers `noAssert` argument - - -## 3.4.1 - -2018-02-20 - -### Bug Fixes - -- [NODEJS-429] - Additional validation needed in Encoder.setRoutingKeyFromUser to ensure provided routing key is valid -- [NODEJS-430] - Unexpected error when query execution doesn't include parameters which are part of the partition key - -## 3.4.0 - -2018-02-05 - -### Features - -- [NODEJS-95] - Expose node token and range information -- [NODEJS-335] - Avoid using Object.defineProperty() for type representations -- [NODEJS-344] - Verbose logging on Connection overhead -- [NODEJS-363] - Drop support for Node.js v0.10 and v0.12 -- [NODEJS-378] - DCAwareRoundRobinPolicy: Warn when the local datacenter is not specified -- [NODEJS-388] - Drop support for domains -- [NODEJS-400] - Modify the message for batch log write failures -- [NODEJS-402] - Batch: Use routing key from first statement -- [NODEJS-404] - Use pooling.warmup to true as default -- [NODEJS-405] - Use system.peers in protocol negotiation -- [NODEJS-406] - Use ES2015 - Modernize codebase -- [NODEJS-409] - alreadyExists error does not include keyspace and table attributes -- [NODEJS-417] - Handle network stream backpressure when writing and limit write queue - -### Bug Fixes - -- [NODEJS-390] - Buffer.from() fails in older versions of Node.js v4 (lower than v4.5) -- [NODEJS-403] - NoHostAvailableError does not call super DriverError constructor -- [NODEJS-415] - Incorrect Murmur3 hashing of tokens which byte length satisfy length & 15 >= 12 -- [NODEJS-419] - Token to Replica map can omit replicas for vnodes - - -## 3.3.0 - -2017-09-19 - -### Features - -- [NODEJS-82] - Speculative query retries -- [NODEJS-287] - Provide metrics on the state of connections to Cassandra -- [NODEJS-308] - Add CDC to TableOptionsMetadata and TableOptions for Cassandra 3.8+ -- [NODEJS-309] - Allow prepared statements to be prepared on all nodes -- [NODEJS-339] - Avoid using deprecated Buffer constructors -- [NODEJS-343] - Improve performance of Murmur 3 partitioner -- [NODEJS-359] - Add 'applied' to ResultSet, similar to java-drivers ResultSet.wasApplied() -- [NODEJS-375] - Expose optional callbacks Uuid.random() as async overload -- [NODEJS-376] - Stringify tokens once to simplify computations when building token map - -### Bug Fixes - -- [NODEJS-365] - Routing key component length is encoded as int16 instead of uint16 -- [NODEJS-370] - Consistency of trace queries is not configurable -- [NODEJS-373] - Empty string in a map field returned as null on query - -## 3.2.2 - -2017-06-05 - -### Bug Fixes - -- [NODEJS-346] - Shutdown doesn't work if error occurs after control connection initialization -- [NODEJS-347] - Metadata: Schema parser fails to handle index_options null values -- [NODEJS-355] - Domain without dots will not connect -- [NODEJS-358] - TokenAwarePolicy does not take statement keyspace into account -- [NODEJS-360] - ControlConnection: when any of the queries to refresh topology fail it will not attempt to reconnect -- [NODEJS-362] - Driver fails to encode Duration's with large values - -## 3.2.1 - -2017-04-24 - -### Features - -- [NODEJS-332] - Support Duration Type -- [NODEJS-338] - Make protocol negotiation more resilient - -## 3.2.0 - -2017-01-17 - -### Notable Changes - -- Promise support ([#194](https://github.com/datastax/nodejs-driver/pull/194)). -- Timestamp generation: client-side timestamps are generated and sent in the request by default when the -server supports it ([#195](https://github.com/datastax/nodejs-driver/pull/195)). -- Added `isIdempotent` query option which is set to `false` by default: future versions of the driver will use this - value to consider whether an execution should be retried or directly rethrown to the consumer without using the retry - policy ([#197](https://github.com/datastax/nodejs-driver/pull/197)). - -### Features - -- [NODEJS-322] - Timestamp Generator Support for providing Client Timestamps Improvement -- [NODEJS-189] - Support promises -- [NODEJS-230] - Expose ResultSet `@@iterator` -- [NODEJS-325] - Add explicit idempotency setting in the query options - -## 3.1.6 - -2016-11-14 - -### Bug Fixes - -- [NODEJS-294] - TokenAwarePolicy: Avoid yielding the primary replica first - -## 3.1.5 - -2016-10-07 - -### Bug Fixes - -- [NODEJS-313] - Client-to-node encryption: mark request as written before invoking socket.write() - -## 3.1.4 - -2016-09-21 - -### Bug Fixes - -- [NODEJS-310] - Reading streaming frames with flags can result in uncaught error - -## 3.1.3 - -2016-08-31 - -### Bug Fixes - -- [NODEJS-303] - Protocol version downgrade fails on OSX and Windows. - -## 3.1.2 - -2016-08-30 - -### Bug Fixes - -- [NODEJS-283] - Possible connection leak if pool is shutting down while core connections are being created. -- [NODEJS-288] - Callback never executed in error on subsequent Client.execute with Client configured with keyspace -that doesn't exist. -- [NODEJS-293] - When client.connect() return error - client.shutdown() not work properly. -- [NODEJS-296] - Cannot read property 'consistency' of null, TypeError: Cannot read property 'consistency' of null -- [NODEJS-297] - DCAwareRoundRobinPolicy should make a local reference to host arrays -- [NODEJS-301] - 'Trying to access beyond buffer length' error if Warnings, Custom Payload, or Trace Id present in -non-RESULT response Improvement -- [NODEJS-265] - Remove connection from host pool when closed by server side - -## 3.1.1 - -2016-06-30 - -### Bug Fixes - -- [NODEJS-284] - Driver fails to resolve host names in the local hosts file - -## 3.1.0 - -2016-06-28 - -### Notable Changes - -- Introduced experimental Execution Profiles API ([#156](https://github.com/datastax/nodejs-driver/pull/156)) -- Removed dependency to [async](https://github.com/caolan/async) package ( -[#138](https://github.com/datastax/nodejs-driver/pull/138)). -- Enhanced retry policies: handle client timeouts, connection closed and other errors. New retry decision: try next -host ([#143](https://github.com/datastax/nodejs-driver/pull/143)). - -### Features - -- [NODEJS-261] - Execution profiles -- [NODEJS-105] - New Retry Policy Decision - try next host -- [NODEJS-106] - Don't mark host down while one connection is active -- [NODEJS-107] - Prevent duplicate metadata fetches from control connection and allow disabling schema metadata fetching -- [NODEJS-247] - Schedule idleTimeout before descheduling the previous -- [NODEJS-177] - Use A-record with multiple IPs for contact points -- [NODEJS-201] - Avoid dynamically copying query options properties into users query options -- [NODEJS-236] - Handle empty map values gracefully -- [NODEJS-240] - Replace async dependency -- [NODEJS-242] - Expose default policies and default options -- [NODEJS-248] - Optimize query plan hosts iteration -- [NODEJS-249] - Avoid using Object.defineProperty() in ResultSet constructor -- [NODEJS-251] - Expose onRequestError() method in the RetryPolicy prototype - -### Bug Fixes - -- [NODEJS-246] - InetAddress validation improperly flags IPv4-mapped IPv6 -- [NODEJS-250] - Timeout duration reported in OperationTimedOutError does not consider statement-level options. -- [NODEJS-252] - Prepared statement metadata does not use logged keyspace -- [NODEJS-255] - InetAddress.toString() improperly truncates last group if preceding bytes are 0 for ipv6 addresses -- [NODEJS-257] - Connection wrongly parses IPv6 from Host address -- [NODEJS-273] - readTimeout set to 0 in queryOptions is not used. - -## 3.0.2 - -2016-04-05 - -### Features - -- [NODEJS-228] - Allow setting read timeout at statement level - -### Bug Fixes - -- [NODEJS-159] - Metadata.getTokenToReplicaNetworkMapper does not account for multiple racks in a DC -- [NODEJS-235] - Decoding error can result in callback not executed -- [NODEJS-237] - Timeuuid generation sub-millisecond portion is not guaranteed to be increasing -- [NODEJS-238] - eachRow() retry attempts after read timeout don't execute rowCallback - -## 3.0.1 - -2016-02-08 - -### Features - -- [NODEJS-211] - Pass the authenticator name from the server to the auth provider - -### Bug Fixes - -- [NODEJS-216] - Inet with alpha character is converting the character to 0 - -## 3.0.0 - -2015-12-14 - -### Notable Changes - -- Default consistency changed back to `LOCAL_ONE`. - -### Features - -- [NODEJS-155] - Schedule reconnections using Timers -- [NODEJS-195] - Expose encode()/decode() functions -- [NODEJS-204] - Change default consistency level to LOCAL_ONE -- [NODEJS-198] - Avoid using Function.prototype.bind() for common execution path -- [NODEJS-200] - Use Error.captureStackTrace() only when setting enabled - -### Bug Fixes - -- [NODEJS-193] - BigDecimal.fromString() should throw a TypeError if there is a conversion error -- [NODEJS-197] - Can't parse column type if it contains UDT that is a quoted identifier -- [NODEJS-202] - Support for "custom" types after CASSANDRA-10365 -- [NODEJS-203] - RoundRobinPolicies: Missing return statement when calling callback - -## 3.0.0-rc1 - -2015-11-11 - -### Notable Changes - -- Added support for Cassandra 3.0.0 -- _Breaking_ Changed default consistency to `LOCAL QUORUM` [#103](https://github.com/datastax/nodejs-driver/pull/103) -- _Breaking_ `Aggregate#initCondition` now returns the string representation of the value -[#102](https://github.com/datastax/nodejs-driver/pull/102) -- Manual paging via `ResultSet#nextPage()` and `Client#stream()` throttling -[#111](https://github.com/datastax/nodejs-driver/pull/111) - -### Features - -- [NODEJS-186] - Update schema type representation to CQL -- [NODEJS-68] - Manual paging support via nextPage() and client.stream() throttling -- [NODEJS-130] - Add buffer for non-streaming rows messages -- [NODEJS-142] - Frame coalescing on connection -- [NODEJS-169] - Update async dependency -- [NODEJS-178] - Change default consistency level to LOCAL_QUORUM -- [NODEJS-181] - Update default behavior unbound values in prepared statements - -### Bug Fixes - -- [NODEJS-164] - Defunct connection is not properly removed from pool -- [NODEJS-190] - useUndefinedAsUnset should not apply to udt, tuple, set, list and map members. - -## 3.0.0-beta1 - -2015-10-19 - -### Notable Changes - -- Added support for Cassandra 3.0-rc1 -- New index metadata API [#98](https://github.com/datastax/nodejs-driver/pull/98) - -### Features - -- [NODEJS-163] - Process Modernized Schema Tables for C* 3.0 -- [NODEJS-166] - Process Materialized View Metadata -- [NODEJS-170] - Process materialized view events -- [NODEJS-171] - Process changes in 'columns' table in C* 3.0-rc1+ -- [NODEJS-172] - Process crc_check_chance column from 'tables' and 'views' metadata tables -- [NODEJS-182] - Add missing options to table / view metadata -- [NODEJS-183] - Add support for parsing Index metadata - -### Bug Fixes - -- [NODEJS-185] - Metadata fetch of table with ColumnToCollectionType fails - -## 2.2.2 - -2015-10-14 - -### Features - -- [NODEJS-187] - Expose Metadata prototype to be available for _promisification_ - -### Bug Fixes - -- [NODEJS-160] - Error setting routing keys before query execution -- [NODEJS-175] - Select from table after a new field is added to a UDT can result in callback never fired -- [NODEJS-185] - Metadata fetch of table with ColumnToCollectionType fails - -## 2.2.1 - -2015-09-14 - -### Features - -- [NODEJS-162] - Add coordinator of query to error object - -### Bug Fixes - -- [NODEJS-154] - Local datacenter could not be determined -- [NODEJS-165] - Driver 2.2 fails to connect under windows server for cassandra 2.1 - -## 2.2.0 - -2015-08-10 - -### Notable Changes - -- **Client**: All requests use `readTimeout` that can be configured in the `socketOptions`, enabled by default to -12secs -- **Client**: Now exposes topology and node status change events: `hostAdd`, `hostRemove`, `hostUp` and `hostDown` - -### Features - -- [NODEJS-140] - WhiteListPolicy -- [NODEJS-114] - Client-Configurable High Level Request Timeout -- [NODEJS-138] - Provide option to open all connections at startup -- [NODEJS-149] - Expose node status and topology changes -- [NODEJS-152] - Enable client read timeout by default - -### Bug Fixes - -- [NODEJS-111] - Connect should callback in error after shutdown -- [NODEJS-151] - 'All host(s) tried for query failed' error immediately after Cassandra node failure -- [NODEJS-156] - RequestHandler retry should not use a new query plan -- [NODEJS-157] - Control connection can fail and not be re-established if it errors on initOnConnection - -## 2.2.0-rc1 - -2015-06-18 - -### Notable Changes - -- Added support for Cassandra 2.2 and native protocol v4 - -### Features - -- [NODEJS-117] - Small int and byte types for C* 2.2 -- [NODEJS-118] - Support new date and time types -- [NODEJS-121] - Distinguish between `NULL` and `UNSET` values in Prepared Statements -- [NODEJS-122] - Add support for client warnings -- [NODEJS-123] - Support Key-value payloads in native protocol v4 -- [NODEJS-124] - Use PK columns from v4 prepared responses -- [NODEJS-125] - Support UDF and Aggregate Function Schema Meta -- [NODEJS-126] - Add client address to query trace -- [NODEJS-129] - Support server error in Startup response for C* 2.1 -- [NODEJS-131] - Handle new C* 2.2 errors - -### Bug Fixes - -- [NODEJS-119] - Rare 'write after end' error encountered while reconnecting with lower protocol version on nodejs 0.10.x -- [NODEJS-120] - Connection 'object is not a function' at Connection.handleResult -- [NODEJS-127] - Integer.toBuffer() gives wrong representation for positive numbers with the msb on -- [NODEJS-128] - getPeersSchemaVersions uses system.local instead of system.peers -- [NODEJS-136] - LocalDate fails to parse dates less than -271821-04-20 and greater than 275760-09-13 -- [NODEJS-137] - DriverInternalError - No active connection found -- [NODEJS-139] - Use retry policy defined in the query options -- [NODEJS-141] - Node schema change - keyspace metadata does not exist -- [NODEJS-146] - Unhandled 'error' event caused by RST on Socket on Connection Initialization causes app to terminate diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/Jenkinsfile b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/Jenkinsfile deleted file mode 100644 index 12db5cae9c..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/Jenkinsfile +++ /dev/null @@ -1,648 +0,0 @@ -#!groovy - - -def initializeEnvironment() { - def nodeVersions = ['8': '8.16.2', '10': '10.17.0', '12': '12.13.0'] - env.DRIVER_DISPLAY_NAME = 'Cassandra Node.js Driver' - env.DRIVER_METRIC_TYPE = 'oss' - if (env.GIT_URL.contains('riptano/nodejs-driver')) { - env.DRIVER_DISPLAY_NAME = 'private ' + env.DRIVER_DISPLAY_NAME - env.DRIVER_METRIC_TYPE = 'oss-private' - } else if (env.GIT_URL.contains('nodejs-dse-driver')) { - env.DRIVER_DISPLAY_NAME = 'DSE Node.js Driver' - env.DRIVER_METRIC_TYPE = 'dse' - } - - env.GIT_SHA = "${env.GIT_COMMIT.take(7)}" - env.GITHUB_PROJECT_URL = "https://${GIT_URL.replaceFirst(/(git@|http:\/\/|https:\/\/)/, '').replace(':', '/').replace('.git', '')}" - env.GITHUB_BRANCH_URL = "${GITHUB_PROJECT_URL}/tree/${env.BRANCH_NAME}" - env.GITHUB_COMMIT_URL = "${GITHUB_PROJECT_URL}/commit/${env.GIT_COMMIT}" - env.NODEJS_VERSION_FULL = nodeVersions[env.NODEJS_VERSION] - - sh label: 'Assign Node.js global environment', script: '''#!/bin/bash -lex - nodenv versions - echo "Using Node.js runtime ${NODEJS_VERSION} (${NODEJS_VERSION_FULL})" - nodenv global ${NODEJS_VERSION_FULL} - ''' - - sh label: 'Download Apache Cassandra or DataStax Enterprise', script: '''#!/bin/bash -lex - . ${CCM_ENVIRONMENT_SHELL} ${CASSANDRA_VERSION} - ''' - - sh label: 'Display Node.js and environment information', script: '''#!/bin/bash -le - # Load CCM environment variables - set -o allexport - . ${HOME}/environment.txt - set +o allexport - - node --version - npm --version - printenv | sort - ''' -} - -def installDriverAndDependencies() { - sh label: 'Install the driver', script: '''#!/bin/bash -lex - npm install - ''' - - sh label: 'Install driver dependencies', script: '''#!/bin/bash -lex - npm install mocha-jenkins-reporter@0 - npm install kerberos@1 - npm install -g eslint@4 - ''' -} - -def executeLinter() { - sh label: 'Perform static analysis of source code', script: '''#!/bin/bash -lex - npm run eslint - ''' -} - -def executeTests() { - sh label: 'Execute tests', script: '''#!/bin/bash -lex - # Load CCM environment variables - set -o allexport - . ${HOME}/environment.txt - set +o allexport - - npm run ci_jenkins - ''' -} - -def executeExamples() { - sh label: 'Create CCM cluster for examples', script: '''#!/bin/bash -lex - # Load CCM environment variables - set -o allexport - . ${HOME}/environment.txt - set +o allexport - - ccm create test_samples --dse -v ${CCM_VERSION} -n 1:0 -b -s - ''' - - sh label: 'Execute examples', script: '''#!/bin/bash -lex - set -o allexport - . ${HOME}/environment.txt - set +o allexport - - ( - cd examples - npm install - node runner.js - ) - ''' - - sh label: 'Clean-up CCM cluster for examples', script: '''#!/bin/bash -lex - ccm remove - ''' -} - -def notifySlack(status = 'started') { - // Set the global pipeline scoped environment (this is above each matrix) - env.BUILD_STATED_SLACK_NOTIFIED = 'true' - - def buildType = 'Commit' - if (params.CI_SCHEDULE != 'DO-NOT-CHANGE-THIS-SELECTION') { - buildType = "${params.CI_SCHEDULE.toLowerCase().capitalize()}" - } - - def color = 'good' // Green - if (status.equalsIgnoreCase('aborted')) { - color = '808080' // Grey - } else if (status.equalsIgnoreCase('unstable')) { - color = 'warning' // Orange - } else if (status.equalsIgnoreCase('failed')) { - color = 'danger' // Red - } - - def message = """Build ${status} for ${env.DRIVER_DISPLAY_NAME} [${buildType}] -<${env.GITHUB_BRANCH_URL}|${env.BRANCH_NAME}> - <${env.RUN_DISPLAY_URL}|#${env.BUILD_NUMBER}> - <${env.GITHUB_COMMIT_URL}|${env.GIT_SHA}>""" - if (!status.equalsIgnoreCase('Started')) { - message += """ -${status} after ${currentBuild.durationString - ' and counting'}""" - } - -// slackSend color: "${color}", -// channel: "#nodejs-driver-dev-bots", -// message: "${message}" -} - -def submitCIMetrics(buildType) { - long durationMs = currentBuild.duration - long durationSec = durationMs / 1000 - long nowSec = (currentBuild.startTimeInMillis + durationMs) / 1000 - def branchNameNoPeriods = env.BRANCH_NAME.replaceAll('\\.', '_') - def durationMetric = "okr.ci.nodejs.${env.DRIVER_METRIC_TYPE}.${buildType}.${branchNameNoPeriods} ${durationSec} ${nowSec}" - - timeout(time: 1, unit: 'MINUTES') { - withCredentials([string(credentialsId: 'lab-grafana-address', variable: 'LAB_GRAFANA_ADDRESS'), - string(credentialsId: 'lab-grafana-port', variable: 'LAB_GRAFANA_PORT')]) { - withEnv(["DURATION_METRIC=${durationMetric}"]) { - sh label: 'Send runtime metrics to labgrafana', script: '''#!/bin/bash -lex - echo "${DURATION_METRIC}" | nc -q 5 ${LAB_GRAFANA_ADDRESS} ${LAB_GRAFANA_PORT} - ''' - } - } - } -} - -def describePerCommitStage() { - script { - currentBuild.displayName = "Per-Commit" - currentBuild.description = '''Per-Commit build and testing''' - } -} - -def describeScheduledTestingStage() { - script { - def type = params.CI_SCHEDULE.toLowerCase().capitalize() - currentBuild.displayName = "${type} schedule" - currentBuild.description = "${type} scheduled build and testing of all supported Apache Cassandra and DataStax " + - "Enterprise against multiple Node.js runtimes" - } -} - -def describeAdhocTestingStage() { - script { - def serverType = params.ADHOC_BUILD_AND_EXECUTE_TESTS_SERVER_VERSION.split('-')[0] - def serverDisplayName = 'Apache Cassandra' - def serverVersion = " v${serverType}" - if (serverType == 'ALL') { - serverDisplayName = "all ${serverDisplayName} and DataStax Enterprise server versions" - serverVersion = '' - } else { - try { - serverVersion = " v${env.ADHOC_BUILD_AND_EXECUTE_TESTS_SERVER_VERSION.split('-')[1]}" - } catch (e) { - ;; // no-op - } - if (serverType == 'ddac') { - serverDisplayName = "DataStax Distribution of ${serverDisplayName}" - } else if (serverType == 'dse') { - serverDisplayName = 'DataStax Enterprise' - } - } - - def nodeJsVersionInformation = "Node.js v${params.ADHOC_BUILD_AND_EXECUTE_TESTS_NODEJS_VERSION}" - if (params.ADHOC_BUILD_AND_EXECUTE_TESTS_NODEJS_VERSION == 'ALL') { - nodeJsVersionInformation = 'all Node.js versions' - } - - def examplesInformation = '' - if (ADHOC_BUILD_AND_EXECUTE_TESTS_EXECUTE_EXAMPLES) { - examplesInformation = ' with examples' - } - - currentBuild.displayName = "${params.ADHOC_BUILD_AND_EXECUTE_TESTS_SERVER_VERSION} against ${nodeJsVersionInformation}" - currentBuild.description = "Testing ${serverDisplayName} ${serverVersion} against ${nodeJsVersionInformation}${examplesInformation}" - } -} - -// branch pattern for cron -def branchPatternCron = ~"(master)" - -pipeline { - agent none - - // Global pipeline timeout - options { - disableConcurrentBuilds() - timeout(time: 5, unit: 'HOURS') - buildDiscarder(logRotator(artifactNumToKeepStr: '10', // Keep only the last 10 artifacts - numToKeepStr: '50')) // Keep only the last 50 build records - } - - parameters { - choice( - name: 'ADHOC_BUILD_TYPE', - choices: ['BUILD', 'BUILD-AND-EXECUTE-TESTS'], - description: '''

Perform a adhoc build operation

- - - - - - - - - - - - - - - -
ChoiceDescription
BUILDPerforms a Per-Commit build
BUILD-AND-EXECUTE-TESTSPerforms a build and executes the integration and unit tests
''') - choice( - name: 'ADHOC_BUILD_AND_EXECUTE_TESTS_NODEJS_VERSION', - choices: ['8', '10', '12.13.0', 'ALL'], - description: 'Node.js version to use for adhoc BUILD-AND-EXECUTE-TESTS ONLY!') - choice( - name: 'ADHOC_BUILD_AND_EXECUTE_TESTS_SERVER_VERSION', - choices: ['2.1', // Legacy Apache Cassandra - '3.11', // Current Apache Cassandra - '4.0', // Development Apache Cassandra - 'dse-5.1', // Legacy DataStax Enterprise - 'dse-6.0', // Previous DataStax Enterprise - 'dse-6.7', // Current DataStax Enterprise - 'dse-6.8', // Development DataStax Enterprise - 'ALL'], - description: '''Apache Cassandra and DataStax Enterprise server version to use for adhoc BUILD-AND-EXECUTE-TESTS ONLY! - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
ChoiceDescription
2.1Apache Cassandra v2.1.x
3.11Apache Cassandra v3.11.x
4.0Apache Cassandra v4.x (CURRENTLY UNDER DEVELOPMENT)
dse-5.1DataStax Enterprise v5.1.x
dse-6.0DataStax Enterprise v6.0.x
dse-6.7DataStax Enterprise v6.7.x
dse-6.8DataStax Enterprise v6.8.x (CURRENTLY UNDER DEVELOPMENT)
''') - booleanParam( - name: 'ADHOC_BUILD_AND_EXECUTE_TESTS_EXECUTE_EXAMPLES', - defaultValue: false, - description: 'Flag to determine if the examples should be executed for adhoc builds') - booleanParam( - name: 'JUNIT_REPORT_STACK', - defaultValue: true, - description: 'Flag to determine if stack trace should be enabled with test failures for scheduled or adhoc builds') - booleanParam( - name: 'TEST_TRACE', - defaultValue: true, - description: 'Flag to determine if test tracing should be enabled for scheduled or adhoc builds') - choice( - name: 'CI_SCHEDULE', - choices: ['DO-NOT-CHANGE-THIS-SELECTION', 'WEEKNIGHTS'], - description: 'CI testing schedule to execute periodically scheduled builds and tests of the driver (DO NOT CHANGE THIS SELECTION)') - } - - triggers { - parameterizedCron(branchPatternCron.matcher(env.BRANCH_NAME).matches() ? """ - # Every weeknight (Monday - Friday) around 7 PM - H 19 * * 1-5 %CI_SCHEDULE=WEEKNIGHTS - """ : "") - } - - environment { - OS_VERSION = 'ubuntu/bionic64/nodejs-driver' - JUNIT_REPORT_STACK = "${params.JUNIT_REPORT_STACK ? '1' : '0'}" - JUNIT_REPORT_PATH = '.' - TEST_TRACE = "${params.TEST_TRACE ? 'on' : 'off'}" - SIMULACRON_PATH = '/home/jenkins/simulacron.jar' - CCM_PATH = '/home/jenkins/ccm' - CCM_ENVIRONMENT_SHELL = '/usr/local/bin/ccm_environment.sh' - } - - stages { - stage('Per-Commit') { - when { - beforeAgent true - allOf { - expression { params.ADHOC_BUILD_TYPE == 'BUILD' } - expression { params.CI_SCHEDULE == 'DO-NOT-CHANGE-THIS-SELECTION' } - not { buildingTag() } - } - } - - matrix { - axes { - axis { - name 'CASSANDRA_VERSION' - values '2.1', // Legacy Apache Cassandra - '3.11', // Current Apache Cassandra - '4.0', // Development Apache Cassandra - 'dse-5.1', // Legacy DataStax Enterprise - 'dse-6.0', // Previous DataStax Enterprise - 'dse-6.7', // Current DataStax Enterprise - 'dse-6.8' // Development DataStax Enterprise - } - axis { - name 'NODEJS_VERSION' - values '8', '10', '12' - } - } - - excludes { - exclude { - axis { - name 'NODEJS_VERSION' - values '8' - } - axis { - name 'CASSANDRA_VERSION' - values '3.11', '4.0', 'dse-5.1', 'dse-6.8' - } - } - exclude { - axis { - name 'NODEJS_VERSION' - values '10' - } - axis { - name 'CASSANDRA_VERSION' - values '2.1', '4.0', 'dse-5.1', 'dse-6.0', 'dse-6.7' - } - } - exclude { - axis { - name 'NODEJS_VERSION' - values '12' - } - axis { - name 'CASSANDRA_VERSION' - values '2.1', '3.11', 'dse-6.0', 'dse-6.8' - } - } - } - - agent { - label "${OS_VERSION}" - } - - stages { - stage('Initialize-Environment') { - steps { - initializeEnvironment() - script { - if (env.BUILD_STATED_SLACK_NOTIFIED != 'true') { - notifySlack() - } - } - } - } - stage('Describe-Build') { - steps { - describePerCommitStage() - } - } - stage('Install-Driver-And-Dependencies') { - steps { - installDriverAndDependencies() - } - } - stage('Execute-Linter') { - steps { - executeLinter() - } - } - stage('Execute-Tests') { - steps { - catchError { // Handle error conditions in the event examples should be executed - executeTests() - } - } - post { - always { - junit testResults: '*.xml' - } - } - } - stage('Execute-Examples') { - when { - expression { env.CASSANDRA_VERSION == 'dse-6.7' } - } - steps { - executeExamples() - } - } - } - } - post { - always { - node('master') { - submitCIMetrics('commit') - } - } - aborted { - notifySlack('aborted') - } - success { - notifySlack('completed') - } - unstable { - notifySlack('unstable') - } - failure { - notifySlack('FAILED') - } - } - } - - stage('Scheduled-Testing') { - when { - beforeAgent true - branch pattern: '((\\d+(\\.[\\dx]+)+)|dse|master)', comparator: 'REGEXP' - allOf { - expression { params.ADHOC_BUILD_TYPE == 'BUILD' } - expression { params.CI_SCHEDULE != 'DO-NOT-CHANGE-THIS-SELECTION' } - not { buildingTag() } - } - } - matrix { - axes { - axis { - name 'CASSANDRA_VERSION' - values '2.1', // Legacy Apache Cassandra - '3.11', // Current Apache Cassandra - '4.0', // Development Apache Cassandra - 'dse-5.1', // Legacy DataStax Enterprise - 'dse-6.0', // Previous DataStax Enterprise - 'dse-6.7', // Current DataStax Enterprise - 'dse-6.8' // Development DataStax Enterprise - } - axis { - name 'NODEJS_VERSION' - values '8', '10', '12' - } - } - - excludes { - exclude { - axis { - name 'NODEJS_VERSION' - values '10' - } - axis { - name 'CASSANDRA_VERSION' - values '2.1', '3.11', '4.0', 'dse-5.1', 'dse-6.0', 'dse-6.7' - } - } - } - - agent { - label "${OS_VERSION}" - } - - stages { - stage('Initialize-Environment') { - steps { - initializeEnvironment() - script { - if (env.BUILD_STATED_SLACK_NOTIFIED != 'true') { - notifySlack() - } - } - } - } - stage('Describe-Build') { - steps { - describeScheduledTestingStage() - } - } - stage('Install-Driver-And-Dependencies') { - steps { - installDriverAndDependencies() - } - } - stage('Execute-Linter') { - steps { - executeLinter() - } - } - stage('Execute-Tests') { - steps { - catchError { // Handle error conditions in the event examples should be executed - executeTests() - } - } - post { - always { - junit testResults: '*.xml' - } - } - } - stage('Execute-Examples') { - when { - expression { env.CASSANDRA_VERSION == 'dse-6.7' } - } - steps { - executeExamples() - } - } - } - } - post { - aborted { - notifySlack('aborted') - } - success { - notifySlack('completed') - } - unstable { - notifySlack('unstable') - } - failure { - notifySlack('FAILED') - } - } - } - - stage('Adhoc-Testing') { - when { - beforeAgent true - allOf { - expression { params.ADHOC_BUILD_TYPE == 'BUILD-AND-EXECUTE-TESTS' } - not { buildingTag() } - } - } - matrix { - axes { - axis { - name 'CASSANDRA_VERSION' - values '2.1', // Legacy Apache Cassandra - '3.11', // Current Apache Cassandra - '4.0', // Development Apache Cassandra - 'dse-5.1', // Legacy DataStax Enterprise - 'dse-6.0', // Previous DataStax Enterprise - 'dse-6.7', // Current DataStax Enterprise - 'dse-6.8' // Development DataStax Enterprise - } - axis { - name 'NODEJS_VERSION' - values '8', '10', '12' - } - } - when { - beforeAgent true - allOf { - expression { params.ADHOC_BUILD_AND_EXECUTE_TESTS_SERVER_VERSION ==~ /(ALL|${env.CASSANDRA_VERSION})/ } - expression { params.ADHOC_BUILD_AND_EXECUTE_TESTS_NODEJS_VERSION ==~ /(ALL|${env.NODEJS_VERSION})/ } - } - } - - agent { - label "${OS_VERSION}" - } - - stages { - stage('Describe-Build') { - steps { - describeAdhocTestingStage() - } - } - stage('Initialize-Environment') { - steps { - initializeEnvironment() - } - } - stage('Install-Driver-And-Dependencies') { - steps { - installDriverAndDependencies() - } - } - stage('Execute-Linter') { - steps { - executeLinter() - } - } - stage('Execute-Tests') { - steps { - catchError { // Handle error conditions in the event examples should be executed - executeTests() - } - } - post { - always { - junit testResults: '*.xml' - } - } - } - stage('Execute-Examples') { - when { - expression { param.ADHOC_BUILD_AND_EXECUTE_TESTS_EXECUTE_EXAMPLES } - } - steps { - executeExamples() - } - } - } - } - } - } -} diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/LICENSE.txt b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/LICENSE.txt deleted file mode 100644 index 4947287f7b..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/LICENSE.txt +++ /dev/null @@ -1,177 +0,0 @@ - - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS \ No newline at end of file diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/NOTICE.txt b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/NOTICE.txt deleted file mode 100644 index 711158cf0f..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/NOTICE.txt +++ /dev/null @@ -1,4 +0,0 @@ -Integer provided by The Closure Library from -https://github.com/google/closure-library/ -under the Apache License 2.0. -Copyright (c) 2010 Google Inc. \ No newline at end of file diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/README.md b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/README.md deleted file mode 100644 index 5db9a4713c..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/README.md +++ /dev/null @@ -1,294 +0,0 @@ -# DataStax Node.js Driver for Apache Cassandra® - -A modern, [feature-rich](#features) and highly tunable Node.js client library for Apache Cassandra and [DSE][dse] using -exclusively Cassandra's binary protocol and Cassandra Query Language. - -## Installation - -```bash -$ npm install cassandra-driver -``` - -[![Build Status](https://api.travis-ci.com/datastax/nodejs-driver.svg?branch=master)](https://travis-ci.org/datastax/nodejs-driver) -[![Build status](https://ci.appveyor.com/api/projects/status/m21t2tfdpmkjex1l/branch/master?svg=true)](https://ci.appveyor.com/project/datastax/nodejs-driver/branch/master) - - -## Features - -- Simple, Prepared, and [Batch][batch] statements -- Asynchronous IO, parallel execution, request pipelining -- [Connection pooling][pooling] -- Auto node discovery -- Automatic reconnection -- Configurable [load balancing][load-balancing] and [retry policies][retry] -- Works with any cluster size -- Built-in [object mapper][doc-mapper] -- Both [promise and callback-based API][doc-promise-callback] -- [Row streaming and pipes](#row-streaming-and-pipes) -- Built-in TypeScript support - -## Documentation - -- [Documentation index][doc-index] -- [CQL types to JavaScript types][doc-datatypes] -- [API docs][doc-api] -- [FAQ][faq] - -## Getting Help - -You can use the [project mailing list][mailinglist] or create a ticket on the [Jira issue tracker][jira]. - -## Basic usage - -```javascript -const cassandra = require('cassandra-driver'); - -const client = new cassandra.Client({ - contactPoints: ['h1', 'h2'], - localDataCenter: 'datacenter1', - keyspace: 'ks1' -}); - -const query = 'SELECT name, email FROM users WHERE key = ?'; - -client.execute(query, [ 'someone' ]) - .then(result => console.log('User with email %s', result.rows[0].email)); -``` - -The driver supports both [promises and callbacks][doc-promise-callback] for the asynchronous methods, -you can choose the approach that suits your needs. - -Note that in order to have concise code examples in this documentation, we will use the promise-based API of the -driver along with the `await` keyword. - -If you are using [DataStax Astra][astra] you can configure your client by setting the secure bundle and the - user credentials: - -```javascript -const client = new cassandra.Client({ - cloud: { secureConnectBundle: 'path/to/secure-connect-DATABASE_NAME.zip' }, - credentials: { username: 'user_name', password: 'p@ssword1' } -}); -``` - -### Prepare your queries - -Using prepared statements provides multiple benefits. - -Prepared statements are parsed and prepared on the Cassandra nodes and are ready for future execution. -Also, when preparing, the driver retrieves information about the parameter types which - **allows an accurate mapping between a JavaScript type and a Cassandra type**. - -The driver will prepare the query once on each host and execute the statement with the bound parameters. - -```javascript -// Use query markers (?) and parameters -const query = 'UPDATE users SET birth = ? WHERE key=?'; -const params = [ new Date(1942, 10, 1), 'jimi-hendrix' ]; - -// Set the prepare flag in the query options -await client.execute(query, params, { prepare: true }); -console.log('Row updated on the cluster'); -``` - -### Row streaming and pipes - -When using `#eachRow()` and `#stream()` methods, the driver parses each row as soon as it is received, - yielding rows without buffering them. - -```javascript -// Reducing a large result -client.eachRow( - 'SELECT time, val FROM temperature WHERE station_id=', - ['abc'], - (n, row) => { - // The callback will be invoked per each row as soon as they are received - minTemperature = Math.min(row.val, minTemperature); - }, - err => { - // This function will be invoked when all rows where consumed or an error was encountered - } -); -``` - -The `#stream()` method works in the same way but instead of callback it returns a [Readable Streams2][streams2] object - in `objectMode` that emits instances of `Row`. - -It can be **piped** downstream and provides automatic pause/resume logic (it buffers when not read). - -```javascript -client.stream('SELECT time, val FROM temperature WHERE station_id=', [ 'abc' ]) - .on('readable', function () { - // 'readable' is emitted as soon a row is received and parsed - let row; - while (row = this.read()) { - console.log('time %s and value %s', row.time, row.val); - } - }) - .on('end', function () { - // Stream ended, there aren't any more rows - }) - .on('error', function (err) { - // Something went wrong: err is a response error from Cassandra - }); -``` - -### User defined types - -[User defined types (UDT)][cql-udt] are represented as JavaScript objects. - -For example: -Consider the following UDT and table - -```cql -CREATE TYPE address ( - street text, - city text, - state text, - zip int, - phones set -); -CREATE TABLE users ( - name text PRIMARY KEY, - email text, - address frozen
-); -``` - -You can retrieve the user address details as a regular JavaScript object. - -```javascript -const query = 'SELECT name, address FROM users WHERE key = ?'; -const result = await client.execute(query, [ key ], { prepare: true }); -const row = result.first(); -const address = row.address; -console.log('User lives in %s, %s - %s', address.street, address.city, address.state); -``` - -Read more information about using [UDTs with the Node.js Driver][doc-udt]. - -### Paging - -All driver methods use a default `fetchSize` of 5000 rows, retrieving only first page of results up to a -maximum of 5000 rows to shield an application against accidentally retrieving large result sets in a single response. - -`stream()` method automatically fetches the following page once the current one was read. You can also use `eachRow()` -method to retrieve the following pages by using `autoPage` flag. See [paging documentation for more -information][doc-paging]. - -### Batch multiple statements - -You can execute multiple statements in a batch to update/insert several rows atomically even in different column families. - -```javascript -const queries = [ - { - query: 'UPDATE user_profiles SET email=? WHERE key=?', - params: [ emailAddress, 'hendrix' ] - }, { - query: 'INSERT INTO user_track (key, text, date) VALUES (?, ?, ?)', - params: [ 'hendrix', 'Changed email', new Date() ] - } -]; - -await client.batch(queries, { prepare: true }); -console.log('Data updated on cluster'); -``` - -## Object Mapper - -The driver provides a built-in [object mapper][doc-mapper] that lets you interact with your data like you -would interact with a set of documents. - -Retrieving objects from the database: - -```javascript -const videos = await videoMapper.find({ userId }); -for (let video of videos) { - console.log(video.name); -} -``` - -Updating an object from the database: - -```javascript -await videoMapper.update({ id, userId, name, addedDate, description }); -``` - -You can read more information about [getting started with the Mapper in our -documentation][doc-mapper-start]. - ----- - -## Data types - -There are few data types defined in the ECMAScript specification, this usually represents a problem when you are trying - to deal with data types that come from other systems in JavaScript. - -The driver supports all the CQL data types in Apache Cassandra (3.0 and below) even for types with no built-in -JavaScript representation, like decimal, varint and bigint. Check the documentation on working with - [numerical values][doc-numerical], [uuids][doc-uuid] and [collections][doc-collections]. - -## Logging - -Instances of `Client()` are `EventEmitter` and emit `log` events: - -```javascript -client.on('log', (level, loggerName, message, furtherInfo) => { - console.log(`${level} - ${loggerName}: ${message}`); -}); -``` - -The `level` being passed to the listener can be `verbose`, `info`, `warning` or `error`. Visit the [logging -documentation][doc-logging] for more information. - -## Compatibility - -- Apache Cassandra versions 2.1 and above. -- DataStax Enterprise versions 4.8 and above. -- Node.js versions 8 and above. - -Note: DataStax products do not support big-endian systems. - -## Credits - -This driver is based on the original work of [Jorge Bay][jorgebay] on [node-cassandra-cql][old-driver] and adds a series of advanced features that are common across all other [DataStax drivers][drivers] for Apache Cassandra. - -The development effort to provide an up to date, high performance, fully featured Node.js Driver for Apache Cassandra will continue on this project, while [node-cassandra-cql][old-driver] will be discontinued. - -## License - -© DataStax, Inc. - -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. - -[cassandra]: https://cassandra.apache.org/ -[doc-api]: https://docs.datastax.com/en/developer/nodejs-driver/latest/api/ -[doc-index]: https://docs.datastax.com/en/developer/nodejs-driver/latest/ -[doc-datatypes]: https://docs.datastax.com/en/developer/nodejs-driver/latest/features/datatypes/ -[doc-numerical]: https://docs.datastax.com/en/developer/nodejs-driver/latest/features/datatypes/numerical/ -[doc-uuid]: https://docs.datastax.com/en/developer/nodejs-driver/latest/features/datatypes/uuids/ -[doc-collections]: https://docs.datastax.com/en/developer/nodejs-driver/latest/features/datatypes/collections/ -[doc-udt]: https://docs.datastax.com/en/developer/nodejs-driver/latest/features/datatypes/udts/ -[doc-promise-callback]: https://docs.datastax.com/en/developer/nodejs-driver/latest/features/promise-callback/ -[doc-mapper]: https://docs.datastax.com/en/developer/nodejs-driver/latest/features/mapper/ -[doc-mapper-start]: https://docs.datastax.com/en/developer/nodejs-driver/latest/features/mapper/getting-started/ -[doc-logging]: https://docs.datastax.com/en/developer/nodejs-driver/latest/features/logging/ -[faq]: https://docs.datastax.com/en/developer/nodejs-driver/latest/faq/ -[load-balancing]: https://docs.datastax.com/en/developer/nodejs-driver/latest/features/tuning-policies/#load-balancing-policy -[retry]: https://docs.datastax.com/en/developer/nodejs-driver/latest/features/tuning-policies/#retry-policy -[pooling]: https://docs.datastax.com/en/developer/nodejs-driver/latest/features/connection-pooling/ -[batch]: https://docs.datastax.com/en/developer/nodejs-driver/latest/features/batch/ -[old-driver]: https://github.com/jorgebay/node-cassandra-cql -[jorgebay]: https://github.com/jorgebay -[drivers]: https://github.com/datastax -[mailinglist]: https://groups.google.com/a/lists.datastax.com/forum/#!forum/nodejs-driver-user -[jira]: https://datastax-oss.atlassian.net/projects/NODEJS/issues -[streams2]: https://nodejs.org/api/stream.html#stream_class_stream_readable -[cql-udt]: https://cassandra.apache.org/doc/latest/cql/types.html#udts -[dse]: https://www.datastax.com/products/datastax-enterprise -[astra]: https://www.datastax.com/products/datastax-astra \ No newline at end of file diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/build.yaml b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/build.yaml deleted file mode 100644 index 135920d0ed..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/build.yaml +++ /dev/null @@ -1,70 +0,0 @@ -schedules: - commit: - # per commit job for all branches to run a subset of configs. - schedule: per_commit - matrix: - exclude: - - nodejs: ['8'] - # Include 2.1, dse-6.0, dse-6.7 - cassandra: ['3.11', '4.0', 'dse-5.1', 'dse-6.8'] - - nodejs: ['10'] - # Include 3.11, dse-6.8 - cassandra: ['2.1', '4.0', 'dse-5.1', 'dse-6.0', 'dse-6.7'] - - nodejs: ['12'] - # Include 4.0, dse-5.1, dse-6.7 - # Examples are run against DSE 6.7 - cassandra: ['2.1', '3.11', 'dse-6.0', 'dse-6.8'] - nightly: - # nightly job for primary branches to run all configs. - schedule: nightly - branches: - # regex matches primary branch format (2.1, 3.x, 3.0.x, 3.1.x, dse, master, etc). - include: ["/((\\d+(\\.[\\dx]+)+)|dse|master)/"] - adhoc: - # adhoc job for non-primary branches that doesn't have a schedule but may be used to run all configs. - schedule: adhoc - enable_pull_requests: true - branches: - exclude: ["/((\\d+(\\.[\\dx]+)+)|dse|master)/"] -nodejs: - - '8' - - '10' - - '12' -os: - - ubuntu/bionic64/nodejs-driver -cassandra: - - '2.1' - - '3.11' - - '4.0' - - 'dse-5.1' - - 'dse-6.0' - - 'dse-6.7' - - 'dse-6.8' -build: - - type: envinject - properties: | - JAVA_HOME=$CCM_JAVA_HOME - CCM_PATH=$HOME/ccm - JUNIT_REPORT_STACK=1 - JUNIT_REPORT_PATH=. - SIMULACRON_PATH=$HOME/simulacron.jar - TEST_TRACE=on - - npm: install - - npm: install mocha-jenkins-reporter@0 - - npm: install kerberos@1 - - npm: install -g eslint@4 - - npm: run eslint - - npm: run ci_jenkins - - script: | - if [ "$CCM_IS_DSE" == "true" ] && [ "${CCM_VERSION:0:3}" == "6.7" ]; then - pushd examples - npm install - ccm create test_samples --dse -v $CCM_VERSION -n 1:0 -b -s - node runner.js - run_rc=$? - ccm remove - popd - exit $run_rc - fi - strict: false - - xunit: "*.xml" diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/index.d.ts b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/index.d.ts deleted file mode 100644 index cf44d76e90..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/index.d.ts +++ /dev/null @@ -1,414 +0,0 @@ -/* - * Copyright DataStax, Inc. - * - * 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. - */ - -import * as events from 'events'; -import * as tls from 'tls'; -import { URL } from 'url'; -import { auth } from './lib/auth'; -import { policies } from './lib/policies'; -import { types } from './lib/types'; -import { metrics } from './lib/metrics'; -import { tracker } from './lib/tracker'; -import { metadata } from './lib/metadata'; -import { datastax } from './lib/datastax/'; -import Long = types.Long; -import Uuid = types.Uuid; -import graph = datastax.graph; - -// Export imported submodules -export { concurrent } from './lib/concurrent'; -export { mapping } from './lib/mapping'; -export { geometry } from './lib/geometry'; -export { auth, datastax, metadata, metrics, policies, tracker, types }; - -export const version: number; - -export function defaultOptions(): ClientOptions; - -export type ValueCallback = (err: Error, val: T) => void; -export type EmptyCallback = (err: Error) => void; -export type ArrayOrObject = any[]|{[key: string]: any}; - -export class Client extends events.EventEmitter { - hosts: HostMap; - keyspace: string; - metadata: metadata.Metadata; - metrics: metrics.ClientMetrics; - - constructor(options: DseClientOptions); - - connect(): Promise; - - connect(callback: EmptyCallback): void; - - execute(query: string, params?: ArrayOrObject, options?: QueryOptions): Promise; - - execute(query: string, params: ArrayOrObject, options: QueryOptions, callback: ValueCallback): void; - - execute(query: string, params: ArrayOrObject, callback: ValueCallback): void; - - execute(query: string, callback: ValueCallback): void; - - executeGraph( - traversal: string, - parameters: { [name: string]: any } | undefined, - options: GraphQueryOptions, - callback: ValueCallback): void; - - executeGraph( - traversal: string, - parameters: { [name: string]: any } | undefined, - callback: ValueCallback): void; - - executeGraph(traversal: string, callback: ValueCallback): void; - - executeGraph( - traversal: string, - parameters?: { [name: string]: any }, - options?: GraphQueryOptions): Promise; - - eachRow(query: string, - params: ArrayOrObject, - options: QueryOptions, - rowCallback: (n: number, row: types.Row) => void, - callback?: ValueCallback): void; - - eachRow(query: string, - params: ArrayOrObject, - rowCallback: (n: number, row: types.Row) => void, - callback?: ValueCallback): void; - - eachRow(query: string, - rowCallback: (n: number, row: types.Row) => void): void; - - stream(query: string, params?: ArrayOrObject, options?: QueryOptions, callback?: EmptyCallback): events.EventEmitter; - - batch( - queries: Array, - options?: QueryOptions): Promise; - - batch( - queries: Array, - options: QueryOptions, - callback: ValueCallback): void; - - batch( - queries: Array, - callback: ValueCallback): void; - - shutdown(): Promise; - - shutdown(callback: EmptyCallback): void; - - getReplicas(keyspace: string, token: Buffer): Host[]; - - getState(): metadata.ClientState; -} - -export interface HostMap extends events.EventEmitter { - length: number; - - forEach(callback: (value: Host, key: string) => void): void; - - get(key: string): Host; - - keys(): string[]; - - values(): Host[]; -} - -export interface Host extends events.EventEmitter { - address: string; - cassandraVersion: string; - datacenter: string; - rack: string; - tokens: string[]; - hostId: types.Uuid; - - canBeConsideredAsUp(): boolean; - - getCassandraVersion(): number[]; - - isUp(): boolean; -} - -export interface ExecutionOptions { - getCaptureStackTrace(): boolean; - - getConsistency(): types.consistencies; - - getCustomPayload(): { [key: string]: any }; - - getFetchSize(): number; - - getFixedHost(): Host; - - getHints(): string[] | string[][]; - - isAutoPage(): boolean; - - isBatchCounter(): boolean; - - isBatchLogged(): boolean; - - isIdempotent(): boolean; - - isPrepared(): boolean; - - isQueryTracing(): boolean; - - getKeyspace(): string; - - getLoadBalancingPolicy(): policies.loadBalancing.LoadBalancingPolicy; - - getPageState(): Buffer; - - getRawQueryOptions(): QueryOptions; - - getReadTimeout(): number; - - getRetryPolicy(): policies.retry.RetryPolicy; - - getRoutingKey(): Buffer | Buffer[]; - - getSerialConsistency(): types.consistencies; - - getTimestamp(): number | Long | undefined | null; - - setHints(hints: string[]): void; -} - -export interface ClientOptions { - contactPoints?: string[]; - localDataCenter?: string; - keyspace?: string; - authProvider?: auth.AuthProvider; - credentials?: { - username: string; - password: string; - } - - cloud?: { - secureConnectBundle: string | URL; - }; - - encoding?: { - map?: Function; - set?: Function; - copyBuffer?: boolean; - useUndefinedAsUnset?: boolean; - useBigIntAsLong?: boolean; - useBigIntAsVarint?: boolean; - }; - isMetadataSyncEnabled?: boolean; - maxPrepared?: number; - metrics?: metrics.ClientMetrics; - policies?: { - addressResolution?: policies.addressResolution.AddressTranslator; - loadBalancing?: policies.loadBalancing.LoadBalancingPolicy; - reconnection?: policies.reconnection.ReconnectionPolicy; - retry?: policies.retry.RetryPolicy; - speculativeExecution?: policies.speculativeExecution.SpeculativeExecutionPolicy; - timestampGeneration?: policies.timestampGeneration.TimestampGenerator; - }; - pooling?: { - coreConnectionsPerHost?: { [key: number]: number; }; - heartBeatInterval?: number; - maxRequestsPerConnection?: number; - warmup?: boolean; - }; - prepareOnAllHosts?: boolean; - profiles?: ExecutionProfile[]; - protocolOptions?: { - maxSchemaAgreementWaitSeconds?: number; - maxVersion?: number; - noCompact?: boolean; - port?: number; - }; - promiseFactory?: (handler: (callback: (err: Error, result?: any) => void) => void) => Promise; - queryOptions?: QueryOptions; - refreshSchemaDelay?: number; - rePrepareOnUp?: boolean; - requestTracker?: tracker.RequestTracker; - socketOptions?: { - coalescingThreshold?: number; - connectTimeout?: number; - defunctReadTimeoutThreshold?: number; - keepAlive?: boolean; - keepAliveDelay?: number; - readTimeout?: number; - tcpNoDelay?: boolean; - }; - sslOptions?: tls.ConnectionOptions; -} - -export interface QueryOptions { - autoPage?: boolean; - captureStackTrace?: boolean; - consistency?: number; - counter?: boolean; - customPayload?: any; - executionProfile?: string | ExecutionProfile; - fetchSize?: number; - hints?: string[] | string[][]; - host?: Host; - isIdempotent?: boolean; - keyspace?: string; - logged?: boolean; - pageState?: Buffer | string; - prepare?: boolean; - readTimeout?: number; - retry?: policies.retry.RetryPolicy; - routingIndexes?: number[]; - routingKey?: Buffer | Buffer[]; - routingNames?: string[]; - serialConsistency?: number; - timestamp?: number | Long; - traceQuery?: boolean; -} - -export interface DseClientOptions extends ClientOptions { - id?: Uuid; - applicationName?: string; - applicationVersion?: string; - monitorReporting?: { enabled?: boolean }; - graphOptions?: GraphOptions; -} - -export interface GraphQueryOptions extends QueryOptions { - graphLanguage?: string; - graphName?: string; - graphReadConsistency?: types.consistencies; - graphSource?: string; - graphWriteConsistency?: types.consistencies; -} - -export type GraphOptions = { - language?: string; - name?: string; - readConsistency?: types.consistencies; - readTimeout?: number; - source?: string; - writeConsistency?: types.consistencies; -}; - -export class ExecutionProfile { - consistency?: types.consistencies; - loadBalancing?: policies.loadBalancing.LoadBalancingPolicy; - name: string; - readTimeout?: number; - retry?: policies.retry.RetryPolicy; - serialConsistency?: types.consistencies; - graphOptions?: { - name?: string; - language?: string; - source?: string; - readConsistency?: types.consistencies; - writeConsistency?: types.consistencies; - }; - - constructor(name: string, options: { - consistency?: types.consistencies; - loadBalancing?: policies.loadBalancing.LoadBalancingPolicy; - readTimeout?: number; - retry?: policies.retry.RetryPolicy; - serialConsistency?: types.consistencies; - graphOptions?: { - name?: string; - language?: string; - source?: string; - readConsistency?: types.consistencies; - writeConsistency?: types.consistencies; - }; - }); -} - -export namespace errors { - class ArgumentError extends DriverError { - constructor(message: string); - } - - class AuthenticationError extends DriverError { - constructor(message: string); - } - - class BusyConnectionError extends DriverError { - constructor(address: string, maxRequestsPerConnection: number, connectionLength: number); - } - - abstract class DriverError extends Error { - info: string; - - constructor(message: string, constructor?: any); - } - - class DriverInternalError extends DriverError { - constructor(message: string); - } - - class NoHostAvailableError extends DriverError { - innerErrors: any; - - constructor(innerErrors: any, message?: string); - } - - class NotSupportedError extends DriverError { - constructor(message: string); - } - - class OperationTimedOutError extends DriverError { - host?: string; - - constructor(message: string, host?: string); - } - - class ResponseError extends DriverError { - code: number; - - constructor(code: number, message: string); - } -} - -export namespace token { - interface Token { - compare(other: Token): number; - - equals(other: Token): boolean; - - getType(): { code: types.dataTypes, info: any }; - - getValue(): any; - } - - interface TokenRange { - start: Token; - end: Token; - - compare(other: TokenRange): number; - - contains(token: Token): boolean; - - equals(other: TokenRange): boolean; - - isEmpty(): boolean; - - isWrappedAround(): boolean; - - splitEvenly(numberOfSplits: number): TokenRange[]; - - unwrap(): TokenRange[]; - } -} \ No newline at end of file diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/index.js b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/index.js deleted file mode 100644 index 2acf5ccb69..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/index.js +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright DataStax, Inc. - * - * 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 clientOptions = require('./lib/client-options'); -exports.Client = require('./lib/client'); -exports.ExecutionProfile = require('./lib/execution-profile').ExecutionProfile; -exports.ExecutionOptions = require('./lib/execution-options').ExecutionOptions; -exports.types = require('./lib/types'); -exports.errors = require('./lib/errors'); -exports.policies = require('./lib/policies'); -exports.auth = require('./lib/auth'); -exports.mapping = require('./lib/mapping'); -exports.tracker = require('./lib/tracker'); -exports.metrics = require('./lib/metrics'); -exports.concurrent = require('./lib/concurrent'); - -const token = require('./lib/token'); -exports.token = { - Token: token.Token, - TokenRange: token.TokenRange -}; -const Metadata = require('./lib/metadata'); -exports.metadata = { - Metadata: Metadata -}; -exports.Encoder = require('./lib/encoder'); -exports.geometry = require('./lib/geometry'); -exports.datastax = require('./lib/datastax'); -/** - * Returns a new instance of the default [options]{@link ClientOptions} used by the driver. - */ -exports.defaultOptions = function () { - return clientOptions.defaultOptions(); -}; -exports.version = require('./package.json').version; \ No newline at end of file diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/auth/base-dse-authenticator.js b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/auth/base-dse-authenticator.js deleted file mode 100644 index bddc6493eb..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/auth/base-dse-authenticator.js +++ /dev/null @@ -1,76 +0,0 @@ -/* - * Copyright DataStax, Inc. - * - * 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 util = require('util'); -const { Authenticator } = require('./provider'); - -const dseAuthenticatorName = 'com.datastax.bdp.cassandra.auth.DseAuthenticator'; - -/** - * Base class for Authenticator implementations that want to make use of - * the authentication scheme negotiation in the DseAuthenticator - * @param {String} authenticatorName - * @extends Authenticator - * @constructor - * @ignore - */ -function BaseDseAuthenticator(authenticatorName) { - this.authenticatorName = authenticatorName; -} - -util.inherits(BaseDseAuthenticator, Authenticator); - -/** - * Return a Buffer containing the required SASL mechanism. - * @abstract - * @returns {Buffer} - */ -BaseDseAuthenticator.prototype.getMechanism = function () { - throw new Error('Not implemented'); -}; - -/** - * Return a byte array containing the expected successful server challenge. - * @abstract - * @returns {Buffer} - */ -BaseDseAuthenticator.prototype.getInitialServerChallenge = function () { - throw new Error('Not implemented'); -}; - -/** - * @param {Function} callback - * @override - */ -BaseDseAuthenticator.prototype.initialResponse = function (callback) { - if (!this._isDseAuthenticator()) { - //fallback - return this.evaluateChallenge(this.getInitialServerChallenge(), callback); - } - //send the mechanism as a first auth message - callback(null, this.getMechanism()); -}; - -/** - * Determines if the name of the authenticator matches DSE 5+ - * @protected - * @ignore - */ -BaseDseAuthenticator.prototype._isDseAuthenticator = function () { - return this.authenticatorName === dseAuthenticatorName; -}; - -module.exports = BaseDseAuthenticator; \ No newline at end of file diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/auth/dse-gssapi-auth-provider.js b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/auth/dse-gssapi-auth-provider.js deleted file mode 100644 index ac25a51852..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/auth/dse-gssapi-auth-provider.js +++ /dev/null @@ -1,231 +0,0 @@ -/* - * Copyright DataStax, Inc. - * - * 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 util = require('util'); -const { AuthProvider } = require('./provider'); -const BaseDseAuthenticator = require('./base-dse-authenticator'); -const GssapiClient = require('./gssapi-client'); -const dns = require('dns'); -const utils = require('../utils'); - -const mechanism = utils.allocBufferFromString('GSSAPI'); -const initialServerChallenge = 'GSSAPI-START'; -const emptyBuffer = utils.allocBuffer(0); - -/** - * Creates a new instance of DseGssapiAuthProvider. - * @classdesc - * AuthProvider that provides GSSAPI authenticator instances for clients to connect - * to DSE clusters secured with the DseAuthenticator. - * @param {Object} [gssOptions] GSSAPI authenticator options - * @param {String} [gssOptions.authorizationId] The optional authorization ID. Providing an authorization ID allows the - * currently authenticated user to act as a different user (a.k.a. proxy authentication). - * @param {String} [gssOptions.service] The service to use. Defaults to 'dse'. - * @param {Function} [gssOptions.hostNameResolver] A method to be used to resolve the name of the Cassandra node based - * on the IP Address. Defaults to [lookupServiceResolver]{@link module:auth~DseGssapiAuthProvider.lookupServiceResolver} - * which resolves the FQDN of the provided IP to generate principals in the format of - * dse/example.com@MYREALM.COM. - * Alternatively, you can use [reverseDnsResolver]{@link module:auth~DseGssapiAuthProvider.reverseDnsResolver} to do a - * reverse DNS lookup or [useIpResolver]{@link module:auth~DseGssapiAuthProvider.useIpResolver} to simply use the IP - * address provided. - * @param {String} [gssOptions.user] DEPRECATED, it will be removed in future versions. For proxy authentication, use - * authorizationId instead. - * @example - * const client = new cassandra.Client({ - * contactPoints: ['h1', 'h2'], - * authProvider: new cassandra.auth.DseGssapiAuthProvider() - * }); - * @alias module:auth~DseGssapiAuthProvider - * @constructor - */ -function DseGssapiAuthProvider(gssOptions) { - //load the kerberos at construction time - try { - // eslint-disable-next-line - this._kerberos = require('kerberos'); - } - catch (err) { - if (err.code === 'MODULE_NOT_FOUND') { - const newErr = new Error('You must install module "kerberos" to use GSSAPI auth provider: ' + - 'https://www.npmjs.com/package/kerberos'); - newErr.code = err.code; - throw newErr; - } - throw err; - } - gssOptions = gssOptions || utils.emptyObject; - this.authorizationId = gssOptions.authorizationId || gssOptions.user; - this.service = gssOptions.service; - this.hostNameResolver = gssOptions.hostNameResolver || DseGssapiAuthProvider.lookupServiceResolver; -} - -util.inherits(DseGssapiAuthProvider, AuthProvider); - -/** - * Returns an Authenticator instance to be used by the driver when connecting to a host. - * @param {String} endpoint The IP address and port number in the format ip:port. - * @param {String} name Authenticator name. - * @override - * @returns {Authenticator} - */ -DseGssapiAuthProvider.prototype.newAuthenticator = function (endpoint, name) { - let address = endpoint; - if (endpoint.indexOf(':') > 0) { - address = endpoint.split(':')[0]; - } - return new GssapiAuthenticator( - this._kerberos, address, name, this.authorizationId, this.service, this.hostNameResolver); -}; - -/** - * Performs a lookupService query that resolves an IPv4 or IPv6 address to a hostname. This ultimately makes a - * getnameinfo() system call which depends on the OS to do hostname resolution. - *

- * Note: Depends on dns.lookupService which was added in 0.12. For older versions falls back on - * [reverseDnsResolver]{@link module:auth~DseGssapiAuthProvider.reverseDnsResolver}. - * - * @param {String} ip IP address to resolve. - * @param {Function} callback The callback function with err and hostname arguments. - */ -DseGssapiAuthProvider.lookupServiceResolver = function (ip, callback) { - if (!dns.lookupService) { - return DseGssapiAuthProvider.reverseDnsResolver(ip, callback); - } - dns.lookupService(ip, 0, function (err, hostname) { - if (err) { - return callback(err); - } - if (!hostname) { - //fallback to ip - return callback(null, ip); - } - callback(null, hostname); - }); -}; - -/** - * Performs a reverse DNS query that resolves an IPv4 or IPv6 address to a hostname. - * @param {String} ip IP address to resolve. - * @param {Function} callback The callback function with err and hostname arguments. - */ -DseGssapiAuthProvider.reverseDnsResolver = function (ip, callback) { - dns.reverse(ip, function (err, names) { - if (err) { - return callback(err); - } - if (!names || !names.length) { - //fallback to ip - return callback(null, ip); - } - callback(null, names[0]); - }); -}; - -/** - * Effectively a no op operation, returns the IP address provided. - * @param {String} ip IP address to use. - * @param {Function} callback The callback function with err and hostname arguments. - */ -DseGssapiAuthProvider.useIpResolver = function (ip, callback) { - callback(null, ip); -}; - -/** - * @param {Object} kerberosModule - * @param {String} address Host address. - * @param {String} authenticatorName - * @param {String} authorizationId - * @param {String} service - * @param {Function} hostNameResolver - * @extends Authenticator - * @private - */ -function GssapiAuthenticator(kerberosModule, address, authenticatorName, authorizationId, service, hostNameResolver) { - BaseDseAuthenticator.call(this, authenticatorName); - this.authorizationId = authorizationId; - this.address = address; - this.client = GssapiClient.createNew(kerberosModule, authorizationId, service); - this.hostNameResolver = hostNameResolver; -} - -//noinspection JSCheckFunctionSignatures -util.inherits(GssapiAuthenticator, BaseDseAuthenticator); - -GssapiAuthenticator.prototype.getMechanism = function () { - return mechanism; -}; - -GssapiAuthenticator.prototype.getInitialServerChallenge = function () { - return utils.allocBufferFromString(initialServerChallenge); -}; - -//noinspection JSUnusedGlobalSymbols -/** - * Obtain an initial response token for initializing the SASL handshake. - * @param {Function} callback - */ -GssapiAuthenticator.prototype.initialResponse = function (callback) { - const self = this; - //initialize the GSS client - let host = this.address; - utils.series([ - function getHostName(next) { - self.hostNameResolver(self.address, function (err, name) { - if (!err && name) { - host = name; - } - next(); - }); - }, - function initClient(next) { - self.client.init(host, function (err) { - if (err) { - return next(err); - } - if (!self._isDseAuthenticator()) { - //fallback - return self.evaluateChallenge(self.getInitialServerChallenge(), next); - } - //send the mechanism as a first auth message - next(null, self.getMechanism()); - }); - } - ], callback); -}; - -/** - * Evaluates a challenge received from the Server. Generally, this method should callback with - * no error and no additional params when authentication is complete from the client perspective. - * @param {Buffer} challenge - * @param {Function} callback - * @override - */ -GssapiAuthenticator.prototype.evaluateChallenge = function (challenge, callback) { - if (!challenge || challenge.toString() === initialServerChallenge) { - challenge = emptyBuffer; - } - this.client.evaluateChallenge(challenge, callback); -}; - -/** - * @override - */ -GssapiAuthenticator.prototype.onAuthenticationSuccess = function (token) { - this.client.shutdown(function noop() { }); -}; - - -module.exports = DseGssapiAuthProvider; \ No newline at end of file diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/auth/dse-plain-text-auth-provider.js b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/auth/dse-plain-text-auth-provider.js deleted file mode 100644 index 64a0f649e2..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/auth/dse-plain-text-auth-provider.js +++ /dev/null @@ -1,110 +0,0 @@ -/* - * Copyright DataStax, Inc. - * - * 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 util = require('util'); -const { AuthProvider } = require('./provider'); -const BaseDseAuthenticator = require('./base-dse-authenticator'); -const utils = require('../utils'); - -const mechanism = utils.allocBufferFromString('PLAIN'); -const separatorBuffer = utils.allocBufferFromArray([0]); -const initialServerChallenge = 'PLAIN-START'; - -/** - * Creates a new instance of DsePlainTextAuthProvider. - * @classdesc - * AuthProvider that provides plain text authenticator instances for clients to connect - * to DSE clusters secured with the DseAuthenticator. - * @param {String} username The username; cannot be null. - * @param {String} password The password; cannot be null. - * @param {String} [authorizationId] The optional authorization ID. Providing an authorization ID allows the currently - * authenticated user to act as a different user (a.k.a. proxy authentication). - * @extends AuthProvider - * @alias module:auth~DsePlainTextAuthProvider - * @example - * const client = new cassandra.Client({ - * contactPoints: ['h1', 'h2'], - * authProvider: new cassandra.auth.DsePlainTextAuthProvider('user', 'p@ssword1'); - * }); - * @constructor - */ -function DsePlainTextAuthProvider(username, password, authorizationId) { - if (typeof username !== 'string' || typeof password !== 'string') { - // Validate for null and undefined - throw new TypeError('Username and password must be a string'); - } - this.username = username; - this.password = password; - this.authorizationId = authorizationId; -} - -util.inherits(DsePlainTextAuthProvider, AuthProvider); - -/** - * Returns an Authenticator instance to be used by the driver when connecting to a host. - * @param {String} endpoint The IP address and port number in the format ip:port. - * @param {String} name Authenticator name. - * @override - * @returns {Authenticator} - */ -DsePlainTextAuthProvider.prototype.newAuthenticator = function (endpoint, name) { - return new PlainTextAuthenticator(name, this.username, this.password, this.authorizationId); -}; - -/** - * @param {String} authenticatorName - * @param {String} authenticatorId - * @param {String} password - * @param {String} authorizationId - * @extends BaseDseAuthenticator - * @constructor - * @private - */ -function PlainTextAuthenticator(authenticatorName, authenticatorId, password, authorizationId) { - BaseDseAuthenticator.call(this, authenticatorName); - this.authenticatorId = utils.allocBufferFromString(authenticatorId); - this.password = utils.allocBufferFromString(password); - this.authorizationId = utils.allocBufferFromString(authorizationId || ''); -} - -util.inherits(PlainTextAuthenticator, BaseDseAuthenticator); - -/** @override */ -PlainTextAuthenticator.prototype.getMechanism = function () { - return mechanism; -}; - -/** @override */ -PlainTextAuthenticator.prototype.getInitialServerChallenge = function () { - return utils.allocBufferFromString(initialServerChallenge); -}; - -/** @override */ -PlainTextAuthenticator.prototype.evaluateChallenge = function (challenge, callback) { - if (!challenge || challenge.toString() !== initialServerChallenge) { - return callback(new Error('Incorrect SASL challenge from server')); - } - // The SASL plain text format is authorizationId 0 username 0 password - callback(null, Buffer.concat([ - this.authorizationId, - separatorBuffer, - this.authenticatorId, - separatorBuffer, - this.password - ])); -}; - -module.exports = DsePlainTextAuthProvider; \ No newline at end of file diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/auth/gssapi-client.js b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/auth/gssapi-client.js deleted file mode 100644 index 92af818ba0..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/auth/gssapi-client.js +++ /dev/null @@ -1,155 +0,0 @@ -/* - * Copyright DataStax, Inc. - * - * 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 util = require('util'); -const utils = require('../utils'); - -/** - * GSSAPI Client interface. - * @ignore - */ -class GssapiClient { - /** - * @param {String} [authorizationId] - * @param {String} [service] - */ - constructor(authorizationId, service) { - this.authorizationId = authorizationId; - this.service = service !== undefined ? service : 'dse'; - } - - /** - * @abstract - * @param {String} host Host name or ip - * @param {Function} callback - */ - init(host, callback) { - throw new Error('Not implemented'); - } - - /** - * @param {Buffer} challenge - * @param {Function} callback - * @abstract - */ - evaluateChallenge(challenge, callback) { - throw new Error('Not implemented'); - } - - /** - * @abstract - * @param {Function} [callback] - */ - shutdown(callback) { - throw new Error('Not implemented'); - } - - /** - * Factory to get the actual implementation of GSSAPI (unix or win) - * @param {Object} kerberosModule Kerberos client library dependency - * @param {String} [authorizationId] An identity to act as (for proxy authentication). - * @param {String} [service] The service to use. (defaults to 'dse') - * @returns GssapiClient - */ - static createNew(kerberosModule, authorizationId, service) { - return new StandardGssClient(kerberosModule, authorizationId, service); - } -} - -/** - * GSSAPI Client implementation using kerberos module. - * @ignore - */ -class StandardGssClient extends GssapiClient { - constructor(kerberosModule, authorizationId, service) { - if (typeof kerberosModule.initializeClient !== 'function') { - throw new Error('The driver expects version 1.x of the kerberos library'); - } - - super(authorizationId, service); - this.kerberos = kerberosModule; - this.transitionIndex = 0; - } - - init(host, callback) { - this.host = host; - let uri = this.service; - if (this.host) { - //For the principal "dse/cassandra1.datastax.com@DATASTAX.COM" - //the expected uri is: "dse@cassandra1.datastax.com" - uri = util.format("%s@%s", this.service, this.host); - } - const options = { - gssFlags: this.kerberos.GSS_C_MUTUAL_FLAG //authenticate itself flag - }; - this.kerberos.initializeClient(uri, options, (err, kerberosClient) => { - if (err) { - return callback(err); - } - this.kerberosClient = kerberosClient; - callback(); - }); - } - - /** @override */ - evaluateChallenge(challenge, callback) { - this['transition' + this.transitionIndex](challenge, (err, response) => { - if (err) { - return callback(err); - } - this.transitionIndex++; - callback(null, response ? utils.allocBufferFromString(response, 'base64') : utils.allocBuffer(0)); - }); - } - - transition0(challenge, callback) { - this.kerberosClient.step('', callback); - } - - transition1(challenge, callback) { - const charPointerChallenge = challenge.toString('base64'); - this.kerberosClient.step(charPointerChallenge, callback); - } - - transition2(challenge, callback) { - this.kerberosClient.unwrap(challenge.toString('base64'), (err, response) => { - if (err) { - return callback(err, false); - } - const cb = function (err, wrapped) { - if (err) { - return callback(err); - } - callback(null, wrapped); - }; - if (this.authorizationId !== undefined) { - this.kerberosClient.wrap(response, { user: this.authorizationId }, cb); - } - else { - this.kerberosClient.wrap(response, null, cb); - } - }); - } - - shutdown(callback) { - this.kerberosClient = null; - callback(); - } -} - -module.exports = GssapiClient; \ No newline at end of file diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/auth/index.d.ts b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/auth/index.d.ts deleted file mode 100644 index c1c3741343..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/auth/index.d.ts +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Copyright DataStax, Inc. - * - * 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. - */ - -export namespace auth { - interface Authenticator { - initialResponse(callback: Function): void; - - evaluateChallenge(challenge: Buffer, callback: Function): void; - - onAuthenticationSuccess(token?: Buffer): void; - } - - interface AuthProvider { - newAuthenticator(endpoint: string, name: string): Authenticator; - } - - class PlainTextAuthProvider implements AuthProvider { - constructor(username: string, password: string); - - newAuthenticator(endpoint: string, name: string): Authenticator; - } - - class DsePlainTextAuthProvider implements AuthProvider { - constructor(username: string, password: string, authorizationId?: string); - - newAuthenticator(endpoint: string, name: string): Authenticator; - } - - class DseGssapiAuthProvider implements AuthProvider { - constructor(gssOptions?: { authorizationId?: string, service?: string, hostNameResolver?: Function }); - - newAuthenticator(endpoint: string, name: string): Authenticator; - } -} \ No newline at end of file diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/auth/index.js b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/auth/index.js deleted file mode 100644 index b79b14e220..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/auth/index.js +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright DataStax, Inc. - * - * 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'; - -/** - * DSE Authentication module. - *

- * Contains the classes used for connecting to a DSE cluster secured with DseAuthenticator. - *

- * @module auth - */ - -const { Authenticator, AuthProvider } = require('./provider'); -const { PlainTextAuthProvider } = require('./plain-text-auth-provider'); -const DseGssapiAuthProvider = require('./dse-gssapi-auth-provider'); -const DsePlainTextAuthProvider = require('./dse-plain-text-auth-provider'); -const NoAuthProvider = require('./no-auth-provider'); - -module.exports = { - Authenticator, - AuthProvider, - DseGssapiAuthProvider, - DsePlainTextAuthProvider, - NoAuthProvider, - PlainTextAuthProvider -}; diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/auth/no-auth-provider.js b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/auth/no-auth-provider.js deleted file mode 100644 index 7dbcd9ea5d..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/auth/no-auth-provider.js +++ /dev/null @@ -1,70 +0,0 @@ -/* - * Copyright DataStax, Inc. - * - * 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 { AuthProvider, Authenticator } = require('./provider'); -const { PlainTextAuthenticator } = require('./plain-text-auth-provider'); -const errors = require('../errors'); - -const dseAuthenticator = 'com.datastax.bdp.cassandra.auth.DseAuthenticator'; - -/** - * Internal authentication provider that is used when no provider has been set by the user. - * @ignore - */ -class NoAuthProvider extends AuthProvider { - newAuthenticator(endpoint, name) { - if (name === dseAuthenticator) { - // Try to use transitional mode - return new TransitionalModePlainTextAuthenticator(); - } - - // Use an authenticator that doesn't allow auth flow - return new NoAuthAuthenticator(endpoint); - } -} - -/** - * An authenticator throws an error when authentication flow is started. - * @ignore - */ -class NoAuthAuthenticator extends Authenticator { - constructor(endpoint) { - super(); - this.endpoint = endpoint; - } - - initialResponse(callback) { - callback(new errors.AuthenticationError( - `Host ${this.endpoint} requires authentication, but no authenticator found in the options`)); - } -} - -/** - * Authenticator that accounts for DSE authentication configured with transitional mode: normal. - * - * In this situation, the client is allowed to connect without authentication, but DSE - * would still send an AUTHENTICATE response. This Authenticator handles this situation - * by sending back a dummy credential. - */ -class TransitionalModePlainTextAuthenticator extends PlainTextAuthenticator { - constructor() { - super('', ''); - } -} - -module.exports = NoAuthProvider; diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/auth/plain-text-auth-provider.js b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/auth/plain-text-auth-provider.js deleted file mode 100644 index f5241f7e46..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/auth/plain-text-auth-provider.js +++ /dev/null @@ -1,81 +0,0 @@ -/* - * Copyright DataStax, Inc. - * - * 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 util = require('util'); - -const provider = require('./provider.js'); -const utils = require('../utils'); -const AuthProvider = provider.AuthProvider; -const Authenticator = provider.Authenticator; -/** - * Creates a new instance of the Authenticator provider - * @classdesc Provides plain text [Authenticator]{@link module:auth~Authenticator} instances to be used when - * connecting to a host. - * @extends module:auth~AuthProvider - * @example - * var authProvider = new cassandra.auth.PlainTextAuthProvider('my_user', 'p@ssword1!'); - * //Set the auth provider in the clientOptions when creating the Client instance - * const client = new Client({ contactPoints: contactPoints, authProvider: authProvider }); - * @param {String} username User name in plain text - * @param {String} password Password in plain text - * @alias module:auth~PlainTextAuthProvider - * @constructor - */ -function PlainTextAuthProvider(username, password) { - this.username = username; - this.password = password; -} - -util.inherits(PlainTextAuthProvider, AuthProvider); - -/** - * Returns a new [Authenticator]{@link module:auth~Authenticator} instance to be used for plain text authentication. - * @override - * @returns {Authenticator} - */ -PlainTextAuthProvider.prototype.newAuthenticator = function () { - return new PlainTextAuthenticator(this.username, this.password); -}; - -/** - * @ignore - */ -function PlainTextAuthenticator(username, password) { - this.username = username; - this.password = password; -} - -util.inherits(PlainTextAuthenticator, Authenticator); - -PlainTextAuthenticator.prototype.initialResponse = function (callback) { - const initialToken = Buffer.concat([ - utils.allocBufferFromArray([0]), - utils.allocBufferFromString(this.username, 'utf8'), - utils.allocBufferFromArray([0]), - utils.allocBufferFromString(this.password, 'utf8') - ]); - callback(null, initialToken); -}; - -PlainTextAuthenticator.prototype.evaluateChallenge = function (challenge, callback) { - //noop - callback(); -}; - -module.exports = { - PlainTextAuthenticator, - PlainTextAuthProvider, -}; diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/auth/provider.js b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/auth/provider.js deleted file mode 100644 index d4bf9ed101..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/auth/provider.js +++ /dev/null @@ -1,79 +0,0 @@ -/* - * Copyright DataStax, Inc. - * - * 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'; -/** - * @classdesc Provides [Authenticator]{@link module:auth~Authenticator} instances to be used when connecting to a host. - * @constructor - * @abstract - * @alias module:auth~AuthProvider - */ -function AuthProvider() { - -} - -/** - * Returns an [Authenticator]{@link module:auth~Authenticator} instance to be used when connecting to a host. - * @param {String} endpoint The ip address and port number in the format ip:port - * @param {String} name Authenticator name - * @abstract - * @returns {Authenticator} - */ -AuthProvider.prototype.newAuthenticator = function (endpoint, name) { - throw new Error('This is an abstract class, you must implement newAuthenticator method or ' + - 'use another auth provider that inherits from this class'); -}; - -/** - * @class - * @classdesc Handles SASL authentication with Cassandra servers. - * Each time a new connection is created and the server requires authentication, - * a new instance of this class will be created by the corresponding. - * @constructor - * @alias module:auth~Authenticator - */ -function Authenticator() { - -} - -/** - * Obtain an initial response token for initializing the SASL handshake. - * @param {Function} callback - */ -Authenticator.prototype.initialResponse = function (callback) { - callback(new Error('Not implemented')); -}; - -/** - * Evaluates a challenge received from the Server. Generally, this method should callback with - * no error and no additional params when authentication is complete from the client perspective. - * @param {Buffer} challenge - * @param {Function} callback - */ -Authenticator.prototype.evaluateChallenge = function (challenge, callback) { - callback(new Error('Not implemented')); -}; - -/** - * Called when authentication is successful with the last information - * optionally sent by the server. - * @param {Buffer} [token] - */ -Authenticator.prototype.onAuthenticationSuccess = function (token) { - -}; - -exports.AuthProvider = AuthProvider; -exports.Authenticator = Authenticator; \ No newline at end of file diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/client-options.js b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/client-options.js deleted file mode 100644 index 029e5c8b35..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/client-options.js +++ /dev/null @@ -1,361 +0,0 @@ -/* - * Copyright DataStax, Inc. - * - * 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 util = require('util'); -const policies = require('./policies'); -const types = require('./types'); -const utils = require('./utils'); -const tracker = require('./tracker'); -const metrics = require('./metrics'); -const auth = require('./auth'); - -/** Core connections per host for protocol versions 1 and 2 */ -const coreConnectionsPerHostV2 = { - [types.distance.local]: 2, - [types.distance.remote]: 1, - [types.distance.ignored]: 0 -}; - -/** Core connections per host for protocol version 3 and above */ -const coreConnectionsPerHostV3 = { - [types.distance.local]: 1, - [types.distance.remote]: 1, - [types.distance.ignored]: 0 -}; - -/** Default maxRequestsPerConnection value for protocol v1 and v2 */ -const maxRequestsPerConnectionV2 = 128; - -/** Default maxRequestsPerConnection value for protocol v3+ */ -const maxRequestsPerConnectionV3 = 2048; - -const continuousPageUnitBytes = 'bytes'; -const continuousPageDefaultSize = 5000; -const continuousPageDefaultHighWaterMark = 10000; - -/** - * @returns {ClientOptions} - */ -function defaultOptions () { - return ({ - policies: { - addressResolution: policies.defaultAddressTranslator(), - loadBalancing: policies.defaultLoadBalancingPolicy(), - reconnection: policies.defaultReconnectionPolicy(), - retry: policies.defaultRetryPolicy(), - speculativeExecution: policies.defaultSpeculativeExecutionPolicy(), - timestampGeneration: policies.defaultTimestampGenerator() - }, - queryOptions: { - fetchSize: 5000, - prepare: false, - captureStackTrace: false - }, - protocolOptions: { - port: 9042, - maxSchemaAgreementWaitSeconds: 10, - maxVersion: 0, - noCompact: false - }, - pooling: { - heartBeatInterval: 30000, - warmup: true - }, - socketOptions: { - connectTimeout: 5000, - defunctReadTimeoutThreshold: 64, - keepAlive: true, - keepAliveDelay: 0, - readTimeout: 12000, - tcpNoDelay: true, - coalescingThreshold: 65536 - }, - authProvider: null, - requestTracker: null, - metrics: new metrics.DefaultMetrics(), - maxPrepared: 500, - refreshSchemaDelay: 1000, - isMetadataSyncEnabled: true, - prepareOnAllHosts: true, - rePrepareOnUp: true, - encoding: { - copyBuffer: true, - useUndefinedAsUnset: true - }, - monitorReporting: { - enabled: true - } - }); -} - -/** - * Extends and validates the user options - * @param {Object} [baseOptions] The source object instance that will be overridden - * @param {Object} userOptions - * @returns {Object} - */ -function extend(baseOptions, userOptions) { - if (arguments.length === 1) { - userOptions = arguments[0]; - baseOptions = {}; - } - const options = utils.deepExtend(baseOptions, defaultOptions(), userOptions); - - if (!options.cloud) { - if (!Array.isArray(options.contactPoints) || options.contactPoints.length === 0) { - throw new TypeError('Contacts points are not defined.'); - } - - for (let i = 0; i < options.contactPoints.length; i++) { - const hostName = options.contactPoints[i]; - if (!hostName) { - throw new TypeError(util.format('Contact point %s (%s) is not a valid host name, ' + - 'the following values are valid contact points: ipAddress, hostName or ipAddress:port', i, hostName)); - } - } - - options.sni = undefined; - } else { - validateCloudOptions(options); - } - - if (!options.logEmitter) { - options.logEmitter = function () {}; - } - if (!options.queryOptions) { - throw new TypeError('queryOptions not defined in options'); - } - - if (options.requestTracker !== null && !(options.requestTracker instanceof tracker.RequestTracker)) { - throw new TypeError('requestTracker must be an instance of RequestTracker'); - } - - if (!(options.metrics instanceof metrics.ClientMetrics)) { - throw new TypeError('metrics must be an instance of ClientMetrics'); - } - - validatePoliciesOptions(options.policies); - - validateProtocolOptions(options.protocolOptions); - - validateSocketOptions(options.socketOptions); - - validateAuthenticationOptions(options); - - options.encoding = options.encoding || {}; - - validateEncodingOptions(options.encoding); - - if (options.profiles && !Array.isArray(options.profiles)) { - throw new TypeError('profiles must be an Array of ExecutionProfile instances'); - } - - validateApplicationInfo(options); - - validateMonitorReporting(options); - - return options; -} - -/** - * Validates the options to connect to a cloud instance. - * @private - */ -function validateCloudOptions(options) { - const bundle = options.cloud.secureConnectBundle; - - // eslint-disable-next-line no-undef - if (!(typeof bundle === 'string' || (typeof URL !== 'undefined' && bundle instanceof URL))) { - throw new TypeError('secureConnectBundle in cloud options must be of type string'); - } - - if (options.contactPoints) { - throw new TypeError('Contact points can not be defined when cloud settings are provided'); - } - - if (options.sslOptions) { - throw new TypeError('SSL options can not be defined when cloud settings are provided'); - } -} - -/** - * Validates the policies from the client options. - * @param {ClientOptions.policies} policiesOptions - * @private - */ -function validatePoliciesOptions(policiesOptions) { - if (!policiesOptions) { - throw new TypeError('policies not defined in options'); - } - if (!(policiesOptions.loadBalancing instanceof policies.loadBalancing.LoadBalancingPolicy)) { - throw new TypeError('Load balancing policy must be an instance of LoadBalancingPolicy'); - } - if (!(policiesOptions.reconnection instanceof policies.reconnection.ReconnectionPolicy)) { - throw new TypeError('Reconnection policy must be an instance of ReconnectionPolicy'); - } - if (!(policiesOptions.retry instanceof policies.retry.RetryPolicy)) { - throw new TypeError('Retry policy must be an instance of RetryPolicy'); - } - if (!(policiesOptions.addressResolution instanceof policies.addressResolution.AddressTranslator)) { - throw new TypeError('Address resolution policy must be an instance of AddressTranslator'); - } - if (policiesOptions.timestampGeneration !== null && - !(policiesOptions.timestampGeneration instanceof policies.timestampGeneration.TimestampGenerator)) { - throw new TypeError('Timestamp generation policy must be an instance of TimestampGenerator'); - } -} - -/** - * Validates the protocol options. - * @param {ClientOptions.protocolOptions} protocolOptions - * @private - */ -function validateProtocolOptions(protocolOptions) { - if (!protocolOptions) { - throw new TypeError('protocolOptions not defined in options'); - } - const version = protocolOptions.maxVersion; - if (version && (typeof version !== 'number' || !types.protocolVersion.isSupported(version))) { - throw new TypeError(util.format('protocolOptions.maxVersion provided (%s) is invalid', version)); - } -} - -/** - * Validates the socket options. - * @param {ClientOptions.socketOptions} socketOptions - * @private - */ -function validateSocketOptions(socketOptions) { - if (!socketOptions) { - throw new TypeError('socketOptions not defined in options'); - } - if (typeof socketOptions.readTimeout !== 'number') { - throw new TypeError('socketOptions.readTimeout must be a Number'); - } - if (typeof socketOptions.coalescingThreshold !== 'number' || socketOptions.coalescingThreshold <= 0) { - throw new TypeError('socketOptions.coalescingThreshold must be a positive Number'); - } -} - -/** - * Validates authentication provider and credentials. - * @param {ClientOptions} options - * @private - */ -function validateAuthenticationOptions(options) { - if (!options.authProvider) { - const credentials = options.credentials; - if (credentials) { - if (typeof credentials.username !== 'string' || typeof credentials.password !== 'string') { - throw new TypeError('credentials username and password must be a string'); - } - - options.authProvider = new auth.PlainTextAuthProvider(credentials.username, credentials.password); - } else { - options.authProvider = new auth.NoAuthProvider(); - } - } else if (!(options.authProvider instanceof auth.AuthProvider)) { - throw new TypeError('options.authProvider must be an instance of AuthProvider'); - } -} - -/** - * Validates the encoding options. - * @param {ClientOptions.encoding} encodingOptions - * @private - */ -function validateEncodingOptions(encodingOptions) { - if (encodingOptions.map) { - const mapConstructor = encodingOptions.map; - if (typeof mapConstructor !== 'function' || - typeof mapConstructor.prototype.forEach !== 'function' || - typeof mapConstructor.prototype.set !== 'function') { - throw new TypeError('Map constructor not valid'); - } - } - - if (encodingOptions.set) { - const setConstructor = encodingOptions.set; - if (typeof setConstructor !== 'function' || - typeof setConstructor.prototype.forEach !== 'function' || - typeof setConstructor.prototype.add !== 'function') { - throw new TypeError('Set constructor not valid'); - } - } - - if ((encodingOptions.useBigIntAsLong || encodingOptions.useBigIntAsVarint) && typeof BigInt === 'undefined') { - throw new TypeError('BigInt is not supported by the JavaScript engine'); - } -} - -function validateApplicationInfo(options) { - function validateString(key) { - const str = options[key]; - - if (str !== null && str !== undefined && typeof str !== 'string') { - throw new TypeError(`${key} should be a String`); - } - } - - validateString('applicationName'); - validateString('applicationVersion'); - - if (options.id !== null && options.id !== undefined && !(options.id instanceof types.Uuid)) { - throw new TypeError('Client id must be a Uuid'); - } -} - -function validateMonitorReporting(options) { - const o = options.monitorReporting; - if (o === null || typeof o !== 'object') { - throw new TypeError(`Monitor reporting must be an object, obtained: ${o}`); - } -} - -/** - * Sets the default options that depend on the protocol version and other metadata. - * @param {Client} client - */ -function setMetadataDependent(client) { - const version = client.controlConnection.protocolVersion; - let coreConnectionsPerHost = coreConnectionsPerHostV3; - let maxRequestsPerConnection = maxRequestsPerConnectionV3; - - if (!types.protocolVersion.uses2BytesStreamIds(version)) { - coreConnectionsPerHost = coreConnectionsPerHostV2; - maxRequestsPerConnection = maxRequestsPerConnectionV2; - } - - if (client.options.queryOptions.consistency === undefined) { - client.options.queryOptions.consistency = - client.metadata.isDbaas() ? types.consistencies.localQuorum : types.consistencies.localOne; - } - - client.options.pooling = utils.deepExtend( - {}, { coreConnectionsPerHost, maxRequestsPerConnection }, client.options.pooling); -} - -exports.extend = extend; -exports.defaultOptions = defaultOptions; -exports.coreConnectionsPerHostV2 = coreConnectionsPerHostV2; -exports.coreConnectionsPerHostV3 = coreConnectionsPerHostV3; -exports.maxRequestsPerConnectionV2 = maxRequestsPerConnectionV2; -exports.maxRequestsPerConnectionV3 = maxRequestsPerConnectionV3; -exports.setMetadataDependent = setMetadataDependent; -exports.continuousPageUnitBytes = continuousPageUnitBytes; -exports.continuousPageDefaultSize = continuousPageDefaultSize; -exports.continuousPageDefaultHighWaterMark = continuousPageDefaultHighWaterMark; diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/client.js b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/client.js deleted file mode 100644 index fae8ff83de..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/client.js +++ /dev/null @@ -1,1180 +0,0 @@ -/* - * Copyright DataStax, Inc. - * - * 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 events = require('events'); -const util = require('util'); - -const utils = require('./utils.js'); -const errors = require('./errors.js'); -const types = require('./types'); -const { ProfileManager } = require('./execution-profile'); -const requests = require('./requests'); -const clientOptions = require('./client-options'); -const ClientState = require('./metadata/client-state'); -const description = require('../package.json').description; -const { version } = require('../package.json'); -const { DefaultExecutionOptions } = require('./execution-options'); -const ControlConnection = require('./control-connection'); -const RequestHandler = require('./request-handler'); -const PrepareHandler = require('./prepare-handler'); -const InsightsClient = require('./insights-client'); -const cloud = require('./datastax/cloud'); -const GraphExecutor = require('./datastax/graph/graph-executor'); -const promiseUtils = require('./promise-utils'); - -/** - * Max amount of pools being warmup in parallel, when warmup is enabled - * @private - */ -const warmupLimit = 32; - -/** - * Client options. - *

While the driver provides lots of extensibility points and configurability, few client options are required.

- *

Default values for all settings are designed to be suitable for the majority of use cases, you should avoid - * fine tuning it when not needed.

- *

See [Client constructor]{@link Client} documentation for recommended options.

- * @typedef {Object} ClientOptions - * @property {Array.} contactPoints - * Array of addresses or host names of the nodes to add as contact points. - *

- * Contact points are addresses of Cassandra nodes that the driver uses to discover the cluster topology. - *

- *

- * Only one contact point is required (the driver will retrieve the address of the other nodes automatically), - * but it is usually a good idea to provide more than one contact point, because if that single contact point is - * unavailable, the driver will not be able to initialize correctly. - *

- * @property {String} [localDataCenter] The local data center to use. - *

- * If using DCAwareRoundRobinPolicy (default), this option is required and only hosts from this data center are - * connected to and used in query plans. - *

- * @property {String} [keyspace] The logged keyspace for all the connections created within the {@link Client} instance. - * @property {Object} [credentials] An object containing the username and password for plain-text authentication. - * It configures the authentication provider to be used against Apache Cassandra's PasswordAuthenticator or DSE's - * DseAuthenticator, when default auth scheme is plain-text. - *

- * Note that you should configure either credentials or authProvider to connect to an - * auth-enabled cluster, but not both. - *

- * @property {String} [credentials.username] The username to use for plain-text authentication. - * @property {String} [credentials.password] The password to use for plain-text authentication. - * @property {Uuid} [id] A unique identifier assigned to a {@link Client} object, that will be communicated to the - * server (DSE 6.0+) to identify the client instance created with this options. When not defined, the driver will - * generate a random identifier. - * @property {String} [applicationName] An optional setting identifying the name of the application using - * the {@link Client} instance. - *

This value is passed to DSE and is useful as metadata for describing a client connection on the server side.

- * @property {String} [applicationVersion] An optional setting identifying the version of the application using - * the {@link Client} instance. - *

This value is passed to DSE and is useful as metadata for describing a client connection on the server side.

- * @property {Object} [monitorReporting] Options for reporting mechanism from the client to the DSE server, for - * versions that support it. - * @property {Boolean} [monitorReporting.enabled=true] Determines whether the reporting mechanism is enabled. - * Defaults to true. - * @property {Object} [cloud] The options to connect to a cloud instance. - * @property {String|URL} cloud.secureConnectBundle Determines the file path for the credentials file bundle. - * @property {Number} [refreshSchemaDelay] The default window size in milliseconds used to debounce node list and schema - * refresh metadata requests. Default: 1000. - * @property {Boolean} [isMetadataSyncEnabled] Determines whether client-side schema metadata retrieval and update is - * enabled. - *

Setting this value to false will cause keyspace information not to be automatically loaded, affecting - * replica calculation per token in the different keyspaces. When disabling metadata synchronization, use - * [Metadata.refreshKeyspaces()]{@link module:metadata~Metadata#refreshKeyspaces} to keep keyspace information up to - * date or token-awareness will not work correctly.

- * Default: true. - * @property {Boolean} [prepareOnAllHosts] Determines if the driver should prepare queries on all hosts in the cluster. - * Default: true. - * @property {Boolean} [rePrepareOnUp] Determines if the driver should re-prepare all cached prepared queries on a - * host when it marks it back up. - * Default: true. - * @property {Number} [maxPrepared] Determines the maximum amount of different prepared queries before evicting items - * from the internal cache. Reaching a high threshold hints that the queries are not being reused, like when - * hard-coding parameter values inside the queries. - * Default: 500. - * @property {Object} [policies] - * @property {LoadBalancingPolicy} [policies.loadBalancing] The load balancing policy instance to be used to determine - * the coordinator per query. - * @property {RetryPolicy} [policies.retry] The retry policy. - * @property {ReconnectionPolicy} [policies.reconnection] The reconnection policy to be used. - * @property {AddressTranslator} [policies.addressResolution] The address resolution policy. - * @property {SpeculativeExecutionPolicy} [policies.speculativeExecution] The SpeculativeExecutionPolicy - * instance to be used to determine if the client should send speculative queries when the selected host takes more - * time than expected. - *

- * Default: [NoSpeculativeExecutionPolicy]{@link - * module:policies/speculativeExecution~NoSpeculativeExecutionPolicy} - *

- * @property {TimestampGenerator} [policies.timestampGeneration] The client-side - * [query timestamp generator]{@link module:policies/timestampGeneration~TimestampGenerator}. - *

- * Default: [MonotonicTimestampGenerator]{@link module:policies/timestampGeneration~MonotonicTimestampGenerator} - * - *

- *

Use null to disable client-side timestamp generation.

- * @property {QueryOptions} [queryOptions] Default options for all queries. - * @property {Object} [pooling] Pooling options. - * @property {Number} [pooling.heartBeatInterval] The amount of idle time in milliseconds that has to pass before the - * driver issues a request on an active connection to avoid idle time disconnections. Default: 30000. - * @property {Object} [pooling.coreConnectionsPerHost] Associative array containing amount of connections per host - * distance. - * @property {Number} [pooling.maxRequestsPerConnection] The maximum number of requests per connection. The default - * value is: - *
    - *
  • For modern protocol versions (v3 and above): 2048
  • - *
  • For older protocol versions (v1 and v2): 128
  • - *
- * @property {Boolean} [pooling.warmup] Determines if all connections to hosts in the local datacenter must be opened on - * connect. Default: true. - * @property {Object} [protocolOptions] - * @property {Number} [protocolOptions.port] The port to use to connect to the Cassandra host. If not set through this - * method, the default port (9042) will be used instead. - * @property {Number} [protocolOptions.maxSchemaAgreementWaitSeconds] The maximum time in seconds to wait for schema - * agreement between nodes before returning from a DDL query. Default: 10. - * @property {Number} [protocolOptions.maxVersion] When set, it limits the maximum protocol version used to connect to - * the nodes. - * Useful for using the driver against a cluster that contains nodes with different major/minor versions of Cassandra. - * @property {Boolean} [protocolOptions.noCompact] When set to true, enables the NO_COMPACT startup option. - *

- * When this option is supplied SELECT, UPDATE, DELETE, and BATCH - * statements on COMPACT STORAGE tables function in "compatibility" mode which allows seeing these tables - * as if they were "regular" CQL tables. - *

- *

- * This option only effects interactions with interactions with tables using COMPACT STORAGE and is only - * supported by C* 3.0.16+, 3.11.2+, 4.0+ and DSE 6.0+. - *

- * @property {Object} [socketOptions] - * @property {Number} [socketOptions.connectTimeout] Connection timeout in milliseconds. Default: 5000. - * @property {Number} [socketOptions.defunctReadTimeoutThreshold] Determines the amount of requests that simultaneously - * have to timeout before closing the connection. Default: 64. - * @property {Boolean} [socketOptions.keepAlive] Whether to enable TCP keep-alive on the socket. Default: true. - * @property {Number} [socketOptions.keepAliveDelay] TCP keep-alive delay in milliseconds. Default: 0. - * @property {Number} [socketOptions.readTimeout] Per-host read timeout in milliseconds. - *

- * Please note that this is not the maximum time a call to {@link Client#execute} may have to wait; - * this is the maximum time that call will wait for one particular Cassandra host, but other hosts will be tried if - * one of them timeout. In other words, a {@link Client#execute} call may theoretically wait up to - * readTimeout * number_of_cassandra_hosts (though the total number of hosts tried for a given query also - * depends on the LoadBalancingPolicy in use). - *

When setting this value, keep in mind the following:

- *
    - *
  • the timeout settings used on the Cassandra side (*_request_timeout_in_ms in cassandra.yaml) should be taken - * into account when picking a value for this read timeout. You should pick a value a couple of seconds greater than - * the Cassandra timeout settings. - *
  • - *
  • - * the read timeout is only approximate and only control the timeout to one Cassandra host, not the full query. - *
  • - *
- * Setting a value of 0 disables read timeouts. Default: 12000. - * @property {Boolean} [socketOptions.tcpNoDelay] When set to true, it disables the Nagle algorithm. Default: true. - * @property {Number} [socketOptions.coalescingThreshold] Buffer length in bytes use by the write queue before flushing - * the frames. Default: 8000. - * @property {AuthProvider} [authProvider] Provider to be used to authenticate to an auth-enabled cluster. - * @property {RequestTracker} [requestTracker] The instance of RequestTracker used to monitor or log requests executed - * with this instance. - * @property {Object} [sslOptions] Client-to-node ssl options. When set the driver will use the secure layer. - * You can specify cert, ca, ... options named after the Node.js tls.connect() options. - *

- * It uses the same default values as Node.js tls.connect() except for rejectUnauthorized - * which is set to false by default (for historical reasons). This setting is likely to change - * in upcoming versions to enable validation by default. - *

- * @property {Object} [encoding] Encoding options. - * @property {Function} [encoding.map] Map constructor to use for Cassandra map type encoding and decoding. - * If not set, it will default to Javascript Object with map keys as property names. - * @property {Function} [encoding.set] Set constructor to use for Cassandra set type encoding and decoding. - * If not set, it will default to Javascript Array. - * @property {Boolean} [encoding.copyBuffer] Determines if the network buffer should be copied for buffer based data - * types (blob, uuid, timeuuid and inet). - *

- * Setting it to true will cause that the network buffer is copied for each row value of those types, - * causing additional allocations but freeing the network buffer to be reused. - * Setting it to true is a good choice for cases where the Row and ResultSet returned by the queries are long-lived - * objects. - *

- *

- * Setting it to false will cause less overhead and the reference of the network buffer to be maintained until the row - * / result set are de-referenced. - * Default: true. - *

- * @property {Boolean} [encoding.useUndefinedAsUnset] Valid for Cassandra 2.2 and above. Determines that, if a parameter - * is set to - * undefined it should be encoded as unset. - *

- * By default, ECMAScript undefined is encoded as null in the driver. Cassandra 2.2 - * introduced the concept of unset. - * At driver level, you can set a parameter to unset using the field types.unset. Setting this flag to - * true allows you to use ECMAScript undefined as Cassandra unset. - *

- *

- * Default: true. - *

- * @property {Boolean} [encoding.useBigIntAsLong] Use [BigInt ECMAScript type](https://tc39.github.io/proposal-bigint/) - * to represent CQL bigint and counter data types. - * @property {Boolean} [encoding.useBigIntAsVarint] Use [BigInt ECMAScript - * type](https://tc39.github.io/proposal-bigint/) to represent CQL varint data type. - * @property {Array.} [profiles] The array of [execution profiles]{@link ExecutionProfile}. - * @property {Function} [promiseFactory] Function to be used to create a Promise from a - * callback-style function. - *

- * Promise libraries often provide different methods to create a promise. For example, you can use Bluebird's - * Promise.fromCallback() method. - *

- *

- * By default, the driver will use the - * [Promise constructor]{@link https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise}. - *

- */ - -/** - * Query options - * @typedef {Object} QueryOptions - * @property {Boolean} [autoPage] Determines if the driver must retrieve the following result pages automatically. - *

- * This setting is only considered by the [Client#eachRow()]{@link Client#eachRow} method. For more information, - * check the - * [paging results documentation]{@link https://docs.datastax.com/en/developer/nodejs-driver/latest/features/paging/}. - *

- * @property {Boolean} [captureStackTrace] Determines if the stack trace before the query execution should be - * maintained. - *

- * Useful for debugging purposes, it should be set to false under production environment as it adds an - * unnecessary overhead to each execution. - *

- * Default: false. - * @property {Number} [consistency] [Consistency level]{@link module:types~consistencies}. - *

- * Defaults to localOne for Apache Cassandra and DSE deployments. - * For DataStax Astra, it defaults to localQuorum. - *

- * @property {Object} [customPayload] Key-value payload to be passed to the server. On the Cassandra side, - * implementations of QueryHandler can use this data. - * @property {String} [executeAs] The user or role name to act as when executing this statement. - *

When set, it executes as a different user/role than the one currently authenticated (a.k.a. proxy execution).

- *

This feature is only available in DSE 5.1+.

- * @property {String|ExecutionProfile} [executionProfile] Name or instance of the [profile]{@link ExecutionProfile} to - * be used for this execution. If not set, it will the use "default" execution profile. - * @property {Number} [fetchSize] Amount of rows to retrieve per page. - * @property {Array|Array} [hints] Type hints for parameters given in the query, ordered as for the parameters. - *

For batch queries, an array of such arrays, ordered as with the queries in the batch.

- * @property {Host} [host] The host that should handle the query. - *

- * Use of this option is heavily discouraged and should only be used in the following cases: - *

- *
    - *
  1. - * Querying node-local tables, such as tables in the system and system_views - * keyspaces. - *
  2. - *
  3. - * Applying a series of schema changes, where it may be advantageous to execute schema changes in sequence on the - * same node. - *
  4. - *
- *

- * Configuring a specific host causes the configured - * [LoadBalancingPolicy]{@link module:policies/loadBalancing~LoadBalancingPolicy} to be completely bypassed. - * However, if the load balancing policy dictates that the host is at a - * [distance of ignored]{@link module:types~distance} or there is no active connectivity to the host, the request will - * fail with a [NoHostAvailableError]{@link module:errors~NoHostAvailableError}. - *

- * @property {Boolean} [isIdempotent] Defines whether the query can be applied multiple times without changing the result - * beyond the initial application. - *

- * The query execution idempotence can be used at [RetryPolicy]{@link module:policies/retry~RetryPolicy} level to - * determine if an statement can be retried in case of request error or write timeout. - *

- *

Default: false.

- * @property {String} [keyspace] Specifies the keyspace for the query. It is used for the following: - *
    - *
  1. To indicate what keyspace the statement is applicable to (protocol V5+ only). This is useful when the - * query does not provide an explicit keyspace and you want to override the current {@link Client#keyspace}.
  2. - *
  3. For query routing when the query operates on a different keyspace than the current {@link Client#keyspace}.
  4. - *
- * @property {Boolean} [logged] Determines if the batch should be written to the batchlog. Only valid for - * [Client#batch()]{@link Client#batch}, it will be ignored by other methods. Default: true. - * @property {Boolean} [counter] Determines if its a counter batch. Only valid for - * [Client#batch()]{@link Client#batch}, it will be ignored by other methods. Default: false. - * @property {Buffer|String} [pageState] Buffer or string token representing the paging state. - *

Useful for manual paging, if provided, the query will be executed starting from a given paging state.

- * @property {Boolean} [prepare] Determines if the query must be executed as a prepared statement. - * @property {Number} [readTimeout] When defined, it overrides the default read timeout - * (socketOptions.readTimeout) in milliseconds for this execution per coordinator. - *

- * Suitable for statements for which the coordinator may allow a longer server-side timeout, for example aggregation - * queries. - *

- *

- * A value of 0 disables client side read timeout for the execution. Default: undefined. - *

- * @property {RetryPolicy} [retry] Retry policy for the query. - *

- * This property can be used to specify a different [retry policy]{@link module:policies/retry} to the one specified - * in the {@link ClientOptions}.policies. - *

- * @property {Array} [routingIndexes] Index of the parameters that are part of the partition key to determine - * the routing. - * @property {Buffer|Array} [routingKey] Partition key(s) to determine which coordinator should be used for the query. - * @property {Array} [routingNames] Array of the parameters names that are part of the partition key to determine the - * routing. Only valid for non-prepared requests, it's recommended that you use the prepare flag instead. - * @property {Number} [serialConsistency] Serial consistency is the consistency level for the serial phase of - * conditional updates. - * This option will be ignored for anything else that a conditional update/insert. - * @property {Number|Long} [timestamp] The default timestamp for the query in microseconds from the unix epoch - * (00:00:00, January 1st, 1970). - *

If provided, this will replace the server side assigned timestamp as default timestamp.

- *

Use [generateTimestamp()]{@link module:types~generateTimestamp} utility method to generate a valid timestamp - * based on a Date and microseconds parts.

- * @property {Boolean} [traceQuery] Enable query tracing for the execution. Use query tracing to diagnose performance - * problems related to query executions. Default: false. - *

To retrieve trace, you can call [Metadata.getTrace()]{@link module:metadata~Metadata#getTrace} method.

- * @property {Object} [graphOptions] Default options for graph query executions. - *

- * These options are meant to provide defaults for all graph query executions. Consider using - * [execution profiles]{@link ExecutionProfile} if you plan to reuse different set of options across different - * query executions. - *

- * @property {String} [graphOptions.language] The graph language to use in graph queries. Default: - * 'gremlin-groovy'. - * @property {String} [graphOptions.name] The graph name to be used in all graph queries. - *

- * This property is required but there is no default value for it. This value can be overridden at query level. - *

- * @property {Number} [graphOptions.readConsistency] Overrides the - * [consistency level]{@link module:types~consistencies} - * defined in the query options for graph read queries. - * @property {Number} [graphOptions.readTimeout] Overrides the default per-host read timeout (in milliseconds) for all - * graph queries. Default: 0. - *

- * Use null to reset the value and use the default on socketOptions.readTimeout . - *

- * @property {String} [graphOptions.source] The graph traversal source name to use in graph queries. Default: - * 'g'. - * @property {Number} [graphOptions.writeConsistency] Overrides the [consistency - * level]{@link module:types~consistencies} defined in the query options for graph write queries. - */ - -/** - * Creates a new instance of {@link Client}. - * @classdesc - * Represents a database client that maintains multiple connections to the cluster nodes, providing methods to - * execute CQL statements. - *

- * The Client uses [policies]{@link module:policies} to decide which nodes to connect to, which node - * to use per each query execution, when it should retry failed or timed-out executions and how reconnection to down - * nodes should be made. - *

- * @extends EventEmitter - * @param {ClientOptions} options The options for this instance. - * @example Creating a new client instance - * const client = new Client({ - * contactPoints: ['10.0.1.101', '10.0.1.102'], - * localDataCenter: 'datacenter1' - * }); - * @example Executing a query - * const result = await client.connect(); - * console.log(`Connected to ${client.hosts.length} nodes in the cluster: ${client.hosts.keys().join(', ')}`); - * @example Executing a query - * const result = await client.execute('SELECT key FROM system.local'); - * const row = result.first(); - * console.log(row['key']); - * @constructor - */ -function Client(options) { - events.EventEmitter.call(this); - this.options = clientOptions.extend({ logEmitter: this.emit.bind(this), id: types.Uuid.random() }, options); - Object.defineProperty(this, 'profileManager', { value: new ProfileManager(this.options) }); - Object.defineProperty(this, 'controlConnection', { - value: new ControlConnection(this.options, this.profileManager), writable: true } - ); - Object.defineProperty(this, 'insightsClient', { value: new InsightsClient(this)}); - - //Unlimited amount of listeners for internal event queues by default - this.setMaxListeners(0); - this.connected = false; - this.isShuttingDown = false; - /** - * Gets the name of the active keyspace. - * @type {String} - */ - this.keyspace = options.keyspace; - /** - * Gets the schema and cluster metadata information. - * @type {Metadata} - */ - this.metadata = this.controlConnection.metadata; - /** - * Gets an associative array of cluster hosts. - * @type {HostMap} - */ - this.hosts = this.controlConnection.hosts; - - /** - * The [ClientMetrics]{@link module:metrics~ClientMetrics} instance used to expose measurements of its internal - * behavior and of the server as seen from the driver side. - *

By default, a [DefaultMetrics]{@link module:metrics~DefaultMetrics} instance is used.

- * @type {ClientMetrics} - */ - this.metrics = this.options.metrics; - - this._graphExecutor = new GraphExecutor(this, options, this._execute); -} - -util.inherits(Client, events.EventEmitter); - -/** - * Emitted when a new host is added to the cluster. - *
    - *
  • {@link Host} The host being added.
  • - *
- * @event Client#hostAdd - */ -/** - * Emitted when a host is removed from the cluster - *
    - *
  • {@link Host} The host being removed.
  • - *
- * @event Client#hostRemove - */ -/** - * Emitted when a host in the cluster changed status from down to up. - *
    - *
  • {@link Host host} The host that changed the status.
  • - *
- * @event Client#hostUp - */ -/** - * Emitted when a host in the cluster changed status from up to down. - *
    - *
  • {@link Host host} The host that changed the status.
  • - *
- * @event Client#hostDown - */ - -/** - * Attempts to connect to one of the [contactPoints]{@link ClientOptions} and discovers the rest the nodes of the - * cluster. - *

When the {@link Client} is already connected, it resolves immediately.

- *

It returns a Promise when a callback is not provided.

- * @param {function} [callback] The optional callback that is invoked when the pool is connected or it failed to - * connect. - * @example Usage example - * await client.connect(); - */ -Client.prototype.connect = function (callback) { - if (this.connected && callback) { - // Avoid creating Promise to immediately resolve them - return callback(); - } - - return promiseUtils.optionalCallback(this._connect(), callback); -}; - -/** - * Async-only version of {@link Client#connect()}. - * @private - */ -Client.prototype._connect = async function () { - if (this.connected) { - return; - } - - if (this.isShuttingDown) { - //it is being shutdown, don't allow further calls to connect() - throw new errors.NoHostAvailableError(null, 'Connecting after shutdown is not supported'); - } - - if (this.connecting) { - return promiseUtils.fromEvent(this, 'connected'); - } - - this.connecting = true; - this.log('info', util.format("Connecting to cluster using '%s' version %s", description, version)); - - try { - await cloud.init(this.options); - await this.controlConnection.init(); - this.hosts = this.controlConnection.hosts; - await this.profileManager.init(this, this.hosts); - - if (this.keyspace) { - await RequestHandler.setKeyspace(this); - } - - clientOptions.setMetadataDependent(this); - - await this._warmup(); - - } catch (err) { - // We should close the pools (if any) and reset the state to allow successive calls to connect() - await this.controlConnection.reset(); - this.connected = false; - this.connecting = false; - this.emit('connected', err); - throw err; - } - - this._setHostListeners(); - - // Set the distance of the control connection host relatively to this instance - this.profileManager.getDistance(this.controlConnection.host); - this.insightsClient.init(); - this.connected = true; - this.connecting = false; - this.emit('connected'); -}; - -/** - * Executes a query on an available connection. - *

The query can be prepared (recommended) or not depending on the [prepare]{@linkcode QueryOptions} flag.

- *

- * Some execution failures can be handled transparently by the driver, according to the - * [RetryPolicy]{@linkcode module:policies/retry~RetryPolicy} or the - * [SpeculativeExecutionPolicy]{@linkcode module:policies/speculativeExecution} used. - *

- *

It returns a Promise when a callback is not provided.

- * @param {String} query The query to execute. - * @param {Array|Object} [params] Array of parameter values or an associative array (object) containing parameter names - * as keys and its value. - * @param {QueryOptions} [options] The query options for the execution. - * @param {ResultCallback} [callback] Executes callback(err, result) when execution completed. When not defined, the - * method will return a promise. - * @example Promise-based API, using async/await - * const query = 'SELECT name, email FROM users WHERE id = ?'; - * const result = await client.execute(query, [ id ], { prepare: true }); - * const row = result.first(); - * console.log('%s: %s', row['name'], row['email']); - * @example Callback-based API - * const query = 'SELECT name, email FROM users WHERE id = ?'; - * client.execute(query, [ id ], { prepare: true }, function (err, result) { - * assert.ifError(err); - * const row = result.first(); - * console.log('%s: %s', row['name'], row['email']); - * }); - * @see {@link ExecutionProfile} to reuse a set of options across different query executions. - */ -Client.prototype.execute = function (query, params, options, callback) { - // This method acts as a wrapper for the async method _execute() - - if (!callback) { - // Set default argument values for optional parameters - if (typeof options === 'function') { - callback = options; - options = null; - } else if (typeof params === 'function') { - callback = params; - params = null; - } - } - - try { - const execOptions = DefaultExecutionOptions.create(options, this); - return promiseUtils.optionalCallback(this._execute(query, params, execOptions), callback); - } - catch (err) { - // There was an error when parsing the user options - if (callback) { - return callback(err); - } - - return Promise.reject(err); - } -}; - -/** - * Executes a graph query. - *

It returns a Promise when a callback is not provided.

- * @param {String} query The gremlin query. - * @param {Object|null} [parameters] An associative array containing the key and values of the parameters. - * @param {GraphQueryOptions|null} [options] The graph query options. - * @param {Function} [callback] Function to execute when the response is retrieved, taking two arguments: - * err and result. When not defined, the method will return a promise. - * @example Promise-based API, using async/await - * const result = await client.executeGraph('g.V()'); - * // Get the first item (vertex, edge, scalar value, ...) - * const vertex = result.first(); - * console.log(vertex.label); - * @example Callback-based API - * client.executeGraph('g.V()', (err, result) => { - * const vertex = result.first(); - * console.log(vertex.label); - * }); - * @example Iterating through the results - * const result = await client.executeGraph('g.E()'); - * for (let edge of result) { - * console.log(edge.label); // created - * }); - * @example Using result.forEach() - * const result = await client.executeGraph('g.V().hasLabel("person")'); - * result.forEach(function(vertex) { - * console.log(vertex.type); // vertex - * console.log(vertex.label); // person - * }); - * @see {@link ExecutionProfile} to reuse a set of options across different query executions. - */ -Client.prototype.executeGraph = function (query, parameters, options, callback) { - callback = callback || (options ? options : parameters); - - if (typeof callback === 'function') { - parameters = typeof parameters !== 'function' ? parameters : null; - return promiseUtils.toCallback(this._graphExecutor.send(query, parameters, options), callback); - } - - return this._graphExecutor.send(query, parameters, options); -}; - -/** - * Executes the query and calls rowCallback for each row as soon as they are received. Calls the final - * callback after all rows have been sent, or when there is an error. - *

- * The query can be prepared (recommended) or not depending on the [prepare]{@linkcode QueryOptions} flag. - *

- * @param {String} query The query to execute - * @param {Array|Object} [params] Array of parameter values or an associative array (object) containing parameter names - * as keys and its value. - * @param {QueryOptions} [options] The query options. - * @param {function} rowCallback Executes rowCallback(n, row) per each row received, where n is the row - * index and row is the current Row. - * @param {function} [callback] Executes callback(err, result) after all rows have been received. - *

- * When dealing with paged results, [ResultSet#nextPage()]{@link module:types~ResultSet#nextPage} method can be used - * to retrieve the following page. In that case, rowCallback() will be again called for each row and - * the final callback will be invoked when all rows in the following page has been retrieved. - *

- * @example Using per-row callback and arrow functions - * client.eachRow(query, params, { prepare: true }, (n, row) => console.log(n, row), err => console.error(err)); - * @example Overloads - * client.eachRow(query, rowCallback); - * client.eachRow(query, params, rowCallback); - * client.eachRow(query, params, options, rowCallback); - * client.eachRow(query, params, rowCallback, callback); - * client.eachRow(query, params, options, rowCallback, callback); - */ -Client.prototype.eachRow = function (query, params, options, rowCallback, callback) { - if (!callback && rowCallback && typeof options === 'function') { - callback = utils.validateFn(rowCallback, 'rowCallback'); - rowCallback = options; - } else { - callback = callback || utils.noop; - rowCallback = utils.validateFn(rowCallback || options || params, 'rowCallback'); - } - - params = typeof params !== 'function' ? params : null; - - let execOptions; - try { - execOptions = DefaultExecutionOptions.create(options, this, rowCallback); - } - catch (e) { - return callback(e); - } - - let rowLength = 0; - - const nextPage = () => promiseUtils.toCallback(this._execute(query, params, execOptions), pageCallback); - - function pageCallback (err, result) { - if (err) { - return callback(err); - } - // Next requests in case paging (auto or explicit) is used - rowLength += result.rowLength; - - if (result.rawPageState !== undefined) { - // Use new page state as next request page state - execOptions.setPageState(result.rawPageState); - if (execOptions.isAutoPage()) { - // Issue next request for the next page - return nextPage(); - } - // Allows for explicit (manual) paging, in case the caller needs it - result.nextPage = nextPage; - } - - // Finished auto-paging - result.rowLength = rowLength; - callback(null, result); - } - - promiseUtils.toCallback(this._execute(query, params, execOptions), pageCallback); -}; - -/** - * Executes the query and pushes the rows to the result stream as soon as they received. - *

- * The stream is a [ReadableStream]{@linkcode https://nodejs.org/api/stream.html#stream_class_stream_readable} object - * that emits rows. - * It can be piped downstream and provides automatic pause/resume logic (it buffers when not read). - *

- *

- * The query can be prepared (recommended) or not depending on {@link QueryOptions}.prepare flag. Retries on multiple - * hosts if needed. - *

- * @param {String} query The query to prepare and execute. - * @param {Array|Object} [params] Array of parameter values or an associative array (object) containing parameter names - * as keys and its value - * @param {QueryOptions} [options] The query options. - * @param {function} [callback] executes callback(err) after all rows have been received or if there is an error - * @returns {ResultStream} - */ -Client.prototype.stream = function (query, params, options, callback) { - callback = callback || utils.noop; - // NOTE: the nodejs stream maintains yet another internal buffer - // we rely on the default stream implementation to keep memory - // usage reasonable. - const resultStream = new types.ResultStream({ objectMode: 1 }); - function onFinish(err, result) { - if (err) { - resultStream.emit('error', err); - } - if (result && result.nextPage ) { - // allows for throttling as per the - // default nodejs stream implementation - resultStream._valve(function pageValve() { - try { - result.nextPage(); - } - catch( ex ) { - resultStream.emit('error', ex ); - } - }); - return; - } - // Explicitly dropping the valve (closure) - resultStream._valve(null); - resultStream.add(null); - callback(err); - } - let sync = true; - this.eachRow(query, params, options, function rowCallback(n, row) { - resultStream.add(row); - }, function eachRowFinished(err, result) { - if (sync) { - // Prevent sync callback - return setImmediate(function eachRowFinishedImmediate() { - onFinish(err, result); - }); - } - onFinish(err, result); - }); - sync = false; - return resultStream; -}; - -/** - * Executes batch of queries on an available connection to a host. - *

It returns a Promise when a callback is not provided.

- * @param {Array.|Array.<{query, params}>} queries The queries to execute as an Array of strings or as an array - * of object containing the query and params - * @param {QueryOptions} [options] The query options. - * @param {ResultCallback} [callback] Executes callback(err, result) when the batch was executed - */ -Client.prototype.batch = function (queries, options, callback) { - if (!callback && typeof options === 'function') { - callback = options; - options = null; - } - - return promiseUtils.optionalCallback(this._batch(queries, options), callback); -}; - -/** - * Async-only version of {@link Client#batch()} . - * @param {Array.|Array.<{query, params}>}queries - * @param {QueryOptions} options - * @returns {Promise} - * @private - */ -Client.prototype._batch = async function (queries, options) { - if (!Array.isArray(queries)) { - throw new errors.ArgumentError('Queries should be an Array'); - } - - if (queries.length === 0) { - throw new errors.ArgumentError('Queries array should not be empty'); - } - - await this._connect(); - - const execOptions = DefaultExecutionOptions.create(options, this); - let queryItems; - - if (execOptions.isPrepared()) { - // use keyspace from query options if protocol supports per-query keyspace, otherwise use connection keyspace. - const version = this.controlConnection.protocolVersion; - const queryKeyspace = types.protocolVersion.supportsKeyspaceInRequest(version) && options.keyspace || this.keyspace; - queryItems = await PrepareHandler.getPreparedMultiple( - this, execOptions.getLoadBalancingPolicy(), queries, queryKeyspace); - } else { - queryItems = new Array(queries.length); - - for (let i = 0; i < queries.length; i++) { - const item = queries[i]; - if (!item) { - throw new errors.ArgumentError(`Invalid query at index ${i}`); - } - - const query = typeof item === 'string' ? item : item.query; - if (!query) { - throw new errors.ArgumentError(`Invalid query at index ${i}`); - } - - queryItems[i] = { query, params: item.params }; - } - } - - const request = await this._createBatchRequest(queryItems, execOptions); - return await RequestHandler.send(request, execOptions, this); -}; - -/** - * Gets the host that are replicas of a given token. - * @param {String} keyspace - * @param {Buffer} token - * @returns {Array} - */ -Client.prototype.getReplicas = function (keyspace, token) { - return this.metadata.getReplicas(keyspace, token); -}; - -/** - * Gets a snapshot containing information on the connections pools held by this Client at the current time. - *

- * The information provided in the returned object only represents the state at the moment this method was called and - * it's not maintained in sync with the driver metadata. - *

- * @returns {ClientState} A [ClientState]{@linkcode module:metadata~ClientState} instance. - */ -Client.prototype.getState = function () { - return ClientState.from(this); -}; - -Client.prototype.log = utils.log; - -/** - * Closes all connections to all hosts. - *

It returns a Promise when a callback is not provided.

- * @param {Function} [callback] Optional callback to be invoked when finished closing all connections. - */ -Client.prototype.shutdown = function (callback) { - return promiseUtils.optionalCallback(this._shutdown(), callback); -}; - -/** @private */ -Client.prototype._shutdown = async function () { - this.log('info', 'Shutting down'); - - if (!this.hosts || !this.connected) { - // not initialized - this.connected = false; - return; - } - - if (this.connecting) { - this.log('warning', 'Shutting down while connecting'); - // wait until finish connecting for easier troubleshooting - await promiseUtils.fromEvent(this, 'connected'); - } - - this.connected = false; - this.isShuttingDown = true; - const hosts = this.hosts.values(); - - this.insightsClient.shutdown(); - - // Shutdown the ControlConnection before shutting down the pools - this.controlConnection.shutdown(); - this.options.policies.speculativeExecution.shutdown(); - - if (this.options.requestTracker) { - this.options.requestTracker.shutdown(); - } - - // go through all the host and shut down their pools - await Promise.all(hosts.map(h => h.shutdown(false))); -}; - -/** - * Waits until that the schema version in all nodes is the same or the waiting time passed. - * @param {Connection} connection - * @returns {Promise} - * @ignore - */ -Client.prototype._waitForSchemaAgreement = async function (connection) { - if (this.hosts.length === 1) { - return true; - } - - const start = process.hrtime(); - const maxWaitSeconds = this.options.protocolOptions.maxSchemaAgreementWaitSeconds; - - this.log('info', 'Waiting for schema agreement'); - - let versionsMatch; - - while (!versionsMatch && process.hrtime(start)[0] < maxWaitSeconds) { - versionsMatch = await this.metadata.compareSchemaVersions(connection); - - if (versionsMatch) { - this.log('info', 'Schema versions match'); - break; - } - - // Let some time pass before the next check - await promiseUtils.delay(500); - } - - return versionsMatch; -}; - -/** - * Waits for schema agreements and schedules schema metadata refresh. - * @param {Connection} connection - * @param event - * @returns {Promise} - * @ignore - * @internal - */ -Client.prototype.handleSchemaAgreementAndRefresh = async function (connection, event) { - let agreement = false; - - try { - agreement = await this._waitForSchemaAgreement(connection); - } catch (err) { - //we issue a warning but we continue with the normal flow - this.log('warning', 'There was an error while waiting for the schema agreement between nodes', err); - } - - if (!this.options.isMetadataSyncEnabled) { - return agreement; - } - - // Refresh metadata immediately - try { - await this.controlConnection.handleSchemaChange(event, true); - } catch (err) { - this.log('warning', 'There was an error while handling schema change', err); - } - - return agreement; -}; - -/** - * Connects and handles the execution of prepared and simple statements. - * @param {string} query - * @param {Array} params - * @param {ExecutionOptions} execOptions - * @returns {Promise} - * @private - */ -Client.prototype._execute = async function (query, params, execOptions) { - const version = this.controlConnection.protocolVersion; - - if (!execOptions.isPrepared() && params && !Array.isArray(params) && - !types.protocolVersion.supportsNamedParameters(version)) { - // Only Cassandra 2.1 and above supports named parameters - throw new errors.ArgumentError('Named parameters for simple statements are not supported, use prepare flag'); - } - - let request; - - if (!this.connected) { - // Micro optimization to avoid an async execution for a simple check - await this._connect(); - } - - if (!execOptions.isPrepared()) { - request = await this._createQueryRequest(query, execOptions, params); - } else { - const lbp = execOptions.getLoadBalancingPolicy(); - - // Use keyspace from query options if protocol supports per-query keyspace, otherwise use connection keyspace. - const queryKeyspace = types.protocolVersion.supportsKeyspaceInRequest(version) && - execOptions.getKeyspace() || this.keyspace; - - const { queryId, meta } = await PrepareHandler.getPrepared(this, lbp, query, queryKeyspace); - request = await this._createExecuteRequest(query, queryId, execOptions, params, meta); - } - - return await RequestHandler.send(request, execOptions, this); -}; - -/** - * Sets the listeners for the nodes. - * @private - */ -Client.prototype._setHostListeners = function () { - function getHostUpListener(emitter, h) { - return () => emitter.emit('hostUp', h); - } - - function getHostDownListener(emitter, h) { - return () => emitter.emit('hostDown', h); - } - - const self = this; - - // Add status listeners when new nodes are added and emit hostAdd - this.hosts.on('add', function hostAddedListener(h) { - h.on('up', getHostUpListener(self, h)); - h.on('down', getHostDownListener(self, h)); - self.emit('hostAdd', h); - }); - - // Remove all listeners and emit hostRemove - this.hosts.on('remove', function hostRemovedListener(h) { - h.removeAllListeners(); - self.emit('hostRemove', h); - }); - - // Add status listeners for existing hosts - this.hosts.forEach(function (h) { - h.on('up', getHostUpListener(self, h)); - h.on('down', getHostDownListener(self, h)); - }); -}; - -/** - * Sets the distance to each host and when warmup is true, creates all connections to local hosts. - * @returns {Promise} - * @private - */ -Client.prototype._warmup = function () { - const hosts = this.hosts.values(); - - return promiseUtils.times(hosts.length, warmupLimit, async (index) => { - const h = hosts[index]; - const distance = this.profileManager.getDistance(h); - - if (distance === types.distance.ignored) { - return; - } - - if (this.options.pooling.warmup && distance === types.distance.local) { - try { - await h.warmupPool(this.keyspace); - } catch (err) { - // An error while trying to create a connection to one of the hosts. - // Warn the user and move on. - this.log('warning', `Connection pool to host ${h.address} could not be created: ${err}`, err); - } - } else { - h.initializePool(); - } - }); -}; - -/** - * @returns {Encoder} - * @private - */ -Client.prototype._getEncoder = function () { - const encoder = this.controlConnection.getEncoder(); - if (!encoder) { - throw new errors.DriverInternalError('Encoder is not defined'); - } - return encoder; -}; - -/** - * Returns a BatchRequest instance and fills the routing key information in the provided options. - * @private - */ -Client.prototype._createBatchRequest = async function (queryItems, info) { - const firstQuery = queryItems[0]; - if (!firstQuery.meta) { - return new requests.BatchRequest(queryItems, info); - } - - await this._setRoutingInfo(info, firstQuery.params, firstQuery.meta); - return new requests.BatchRequest(queryItems, info); -}; - -/** - * Returns an ExecuteRequest instance and fills the routing key information in the provided options. - * @private - */ -Client.prototype._createExecuteRequest = async function(query, queryId, info, params, meta) { - params = utils.adaptNamedParamsPrepared(params, meta.columns); - await this._setRoutingInfo(info, params, meta); - return new requests.ExecuteRequest(query, queryId, params, info, meta); -}; - -/** - * Returns a QueryRequest instance and fills the routing key information in the provided options. - * @private - */ -Client.prototype._createQueryRequest = async function (query, execOptions, params) { - await this.metadata.adaptUserHints(this.keyspace, execOptions.getHints()); - const paramsInfo = utils.adaptNamedParamsWithHints(params, execOptions); - this._getEncoder().setRoutingKeyFromUser(paramsInfo.params, execOptions, paramsInfo.keyIndexes); - - return new requests.QueryRequest(query, paramsInfo.params, execOptions, paramsInfo.namedParameters); -}; - -/** - * Sets the routing key based on the parameter values or the provided routing key components. - * @param {ExecutionOptions} execOptions - * @param {Array} params - * @param meta - * @private - */ -Client.prototype._setRoutingInfo = async function (execOptions, params, meta) { - const encoder = this._getEncoder(); - - if (!execOptions.getKeyspace() && meta.keyspace) { - execOptions.setKeyspace(meta.keyspace); - } - if (execOptions.getRoutingKey()) { - // Routing information provided by the user - return encoder.setRoutingKeyFromUser(params, execOptions); - } - if (Array.isArray(meta.partitionKeys)) { - // The partition keys are provided as part of the metadata for modern protocol versions - execOptions.setRoutingIndexes(meta.partitionKeys); - return encoder.setRoutingKeyFromMeta(meta, params, execOptions); - } - - // Older versions of the protocol (v3 and below) don't provide routing information - try { - const tableInfo = await this.metadata.getTable(meta.keyspace, meta.table); - - if (!tableInfo) { - // The schema data is not there, maybe it is being recreated, avoid setting the routing information - return; - } - - execOptions.setRoutingIndexes(tableInfo.partitionKeys.map(c => meta.columnsByName[c.name])); - // Skip parsing metadata next time - meta.partitionKeys = execOptions.getRoutingIndexes(); - encoder.setRoutingKeyFromMeta(meta, params, execOptions); - } catch (err) { - this.log('warning', util.format('Table %s.%s metadata could not be retrieved', meta.keyspace, meta.table)); - } -}; - -/** - * Callback used by execution methods. - * @callback ResultCallback - * @param {Error} err Error occurred in the execution of the query. - * @param {ResultSet} [result] Result of the execution of the query. - */ - -module.exports = Client; diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/concurrent/index.d.ts b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/concurrent/index.d.ts deleted file mode 100644 index 91ab56f7dd..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/concurrent/index.d.ts +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Copyright DataStax, Inc. - * - * 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. - */ - -import { Client } from '../../'; -import { Readable } from 'stream'; - -export namespace concurrent { - interface ResultSetGroup { - errors: Error[]; - resultItems: any[]; - totalExecuted: number; - } - - type Options = { - collectResults?: boolean; - concurrencyLevel?: number; - executionProfile?: string; - maxErrors?: number; - raiseOnFirstError?: boolean; - } - - function executeConcurrent( - client: Client, - query: string, - parameters: any[][]|Readable, - options?: Options): Promise; - - function executeConcurrent( - client: Client, - queries: Array<{query: string, params: any[]}>, - options?: Options): Promise; -} \ No newline at end of file diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/concurrent/index.js b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/concurrent/index.js deleted file mode 100644 index c618693bb7..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/concurrent/index.js +++ /dev/null @@ -1,335 +0,0 @@ -/* - * Copyright DataStax, Inc. - * - * 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 { Stream } = require('stream'); -const utils = require('../utils'); - -/** - * Utilities for concurrent query execution with the DataStax Node.js Driver. - * @module concurrent - */ - -/** - * Executes multiple queries concurrently at the defined concurrency level. - * @static - * @param {Client} client The {@link Client} instance. - * @param {String|Array<{query, params}>} query The query to execute per each parameter item. - * @param {Array|Stream|Object} parameters An {@link Array} or a readable {@link Stream} composed of {@link Array} - * items representing each individual set of parameters. Per each item in the {@link Array} or {@link Stream}, an - * execution is going to be made. - * @param {Object} [options] The execution options. - * @param {String} [options.executionProfile] The execution profile to be used. - * @param {Number} [options.concurrencyLevel=100] The concurrency level to determine the maximum amount of in-flight - * operations at any given time - * @param {Boolean} [options.raiseOnFirstError=true] Determines whether execution should stop after the first failed - * execution and the corresponding exception will be raised. - * @param {Boolean} [options.collectResults=false] Determines whether each individual - * [ResultSet]{@link module:types~ResultSet} instance should be collected in the grouped result. - * @param {Number} [options.maxErrors=100] The maximum amount of errors to be collected before ignoring the rest of - * the error results. - * @returns {Promise} A Promise of {@link ResultSetGroup} that is resolved when all the - * executions completed and it's rejected when raiseOnFirstError is true and there is one - * or more failures. - * @example Using a fixed query and an Array of Arrays as parameters - * const query = 'INSERT INTO table1 (id, value) VALUES (?, ?)'; - * const parameters = [[1, 'a'], [2, 'b'], [3, 'c'], ]; // ... - * const result = await executeConcurrent(client, query, parameters); - * @example Using a fixed query and a readable stream - * const stream = csvStream.pipe(transformLineToArrayStream); - * const result = await executeConcurrent(client, query, stream); - * @example Using a different queries - * const queryAndParameters = [ - * { query: 'INSERT INTO videos (id, name, user_id) VALUES (?, ?, ?)', - * params: [ id, name, userId ] }, - * { query: 'INSERT INTO user_videos (user_id, id, name) VALUES (?, ?, ?)', - * params: [ userId, id, name ] }, - * { query: 'INSERT INTO latest_videos (id, name, user_id) VALUES (?, ?, ?)', - * params: [ id, name, userId ] }, - * ]; - * - * const result = await executeConcurrent(client, queryAndParameters); - */ -function executeConcurrent(client, query, parameters, options) { - if (!client) { - throw new TypeError('Client instance is not defined'); - } - - if (typeof query === 'string') { - if (Array.isArray(parameters)) { - return new ArrayBasedExecutor(client, query, parameters, options).execute(); - } - - if (parameters instanceof Stream) { - return new StreamBasedExecutor(client, query, parameters, options).execute(); - } - - throw new TypeError('parameters should be an Array or a Stream instance'); - } - - if (Array.isArray(query)) { - options = parameters; - return new ArrayBasedExecutor(client, null, query, options).execute(); - } - - throw new TypeError('A string query or query and parameters array should be provided'); -} - -/** - * Wraps the functionality to execute given an Array. - * @ignore - */ -class ArrayBasedExecutor { - - /** - * @param {Client} client - * @param {String} query - * @param {Array|Array<{query, params}>} parameters - * @param {Object} [options] The execution options. - * @private - */ - constructor(client, query, parameters, options) { - this._client = client; - this._query = query; - this._parameters = parameters; - options = options || utils.emptyObject; - this._raiseOnFirstError = options.raiseOnFirstError !== false; - this._concurrencyLevel = Math.min(options.concurrencyLevel || 100, this._parameters.length); - this._queryOptions = { prepare: true, executionProfile: options.executionProfile }; - this._result = new ResultSetGroup(options); - this._stop = false; - } - - execute() { - const promises = new Array(this._concurrencyLevel); - - for (let i = 0; i < this._concurrencyLevel; i++) { - promises[i] = this._executeOneAtATime(i, 0); - } - - return Promise.all(promises).then(() => this._result); - } - - _executeOneAtATime(initialIndex, iteration) { - const index = initialIndex + this._concurrencyLevel * iteration; - - if (index >= this._parameters.length || this._stop) { - return Promise.resolve(); - } - - const item = this._parameters[index]; - let query; - let params; - - if (this._query === null) { - query = item.query; - params = item.params; - } else { - query = this._query; - params = item; - } - - return this._client.execute(query, params, this._queryOptions) - .then(rs => this._result.setResultItem(index, rs)) - .catch(err => this._setError(index, err)) - .then(() => this._executeOneAtATime(initialIndex, iteration + 1)); - } - - _setError(index, err) { - this._result.setError(index, err); - - if (this._raiseOnFirstError) { - this._stop = true; - throw err; - } - } -} - -/** - * Wraps the functionality to execute given a Stream. - * @ignore - */ -class StreamBasedExecutor { - - /** - * @param {Client} client - * @param {String} query - * @param {Stream} stream - * @param {Object} [options] The execution options. - * @private - */ - constructor(client, query, stream, options) { - this._client = client; - this._query = query; - this._stream = stream; - options = options || utils.emptyObject; - this._raiseOnFirstError = options.raiseOnFirstError !== false; - this._concurrencyLevel = options.concurrencyLevel || 100; - this._queryOptions = { prepare: true, executionProfile: options.executionProfile }; - this._inFlight = 0; - this._index = 0; - this._result = new ResultSetGroup(options); - this._resolveCallback = null; - this._rejectCallback = null; - this._readEnded = false; - } - - execute() { - return new Promise((resolve, reject) => { - this._resolveCallback = resolve; - this._rejectCallback = reject; - - this._stream - .on('data', params => this._executeOne(params)) - .on('error', err => this._setReadEnded(err)) - .on('end', () => this._setReadEnded()); - }); - } - - _executeOne(params) { - if (!Array.isArray(params)) { - return this._setReadEnded(new TypeError('Stream should be in objectMode and should emit Array instances')); - } - - if (this._readEnded) { - // Read ended abruptly because of incorrect format or error event being emitted. - // We shouldn't consider additional items. - return; - } - - const index = this._index++; - this._inFlight++; - - this._client.execute(this._query, params, this._queryOptions) - .then(rs => { - this._result.setResultItem(index, rs); - this._inFlight--; - }) - .catch(err => { - this._inFlight--; - this._setError(index, err); - }) - .then(() => { - if (this._stream.isPaused()) { - this._stream.resume(); - } - - if (this._readEnded && this._inFlight === 0) { - // When read ended and there are no more in-flight requests - // We yield the result to the user. - // It could have ended prematurely when there is a read error - // or there was an execution error and raiseOnFirstError is true - // In that case, calling the resolve callback has no effect - this._resolveCallback(this._result); - } - }); - - if (this._inFlight >= this._concurrencyLevel) { - this._stream.pause(); - } - } - - /** - * Marks the stream read process as ended. - * @param {Error} [err] The stream read error. - * @private - */ - _setReadEnded(err) { - if (!this._readEnded) { - this._readEnded = true; - - if (err) { - // There was an error while reading from the input stream. - // This should be surfaced as a failure - this._rejectCallback(err); - } else if (this._inFlight === 0) { - // Ended signaled and there are no more pending messages. - this._resolveCallback(this._result); - } - } - } - - _setError(index, err) { - this._result.setError(index, err); - - if (this._raiseOnFirstError) { - this._readEnded = true; - this._rejectCallback(err); - } - } -} - -/** - * Represents results from different related executions. - */ -class ResultSetGroup { - - /** - * Creates a new instance of {@link ResultSetGroup}. - * @ignore - */ - constructor(options) { - this._collectResults = options.collectResults; - this._maxErrors = options.maxErrors || 100; - this.totalExecuted = 0; - this.errors = []; - - if (this._collectResults) { - /** - * Gets an {@link Array} containing the [ResultSet]{@link module:types~ResultSet} instances from each execution. - *

- * Note that when collectResults is set to false, accessing this property will - * throw an error. - *

- * @type {Array} - */ - this.resultItems = []; - } else { - Object.defineProperty(this, 'resultItems', { enumerable: false, get: () => { - throw new Error('Property resultItems can not be accessed when collectResults is set to false'); - }}); - } - } - - /** @ignore */ - setResultItem(index, rs) { - this.totalExecuted++; - - if (this._collectResults) { - this.resultItems[index] = rs; - } - } - - /** - * Internal method to set the error of an execution. - * @ignore - */ - setError(index, err) { - this.totalExecuted++; - - if (this.errors.length < this._maxErrors) { - this.errors.push(err); - } - - if (this._collectResults) { - this.resultItems[index] = err; - } - } -} - -exports.executeConcurrent = executeConcurrent; -exports.ResultSetGroup = ResultSetGroup; \ No newline at end of file diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/connection.js b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/connection.js deleted file mode 100644 index b4ce1cd814..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/connection.js +++ /dev/null @@ -1,786 +0,0 @@ -/* - * Copyright DataStax, Inc. - * - * 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 events = require('events'); -const util = require('util'); -const tls = require('tls'); -const net = require('net'); - -const Encoder = require('./encoder.js'); -const { WriteQueue } = require('./writers'); -const requests = require('./requests'); -const streams = require('./streams'); -const utils = require('./utils'); -const types = require('./types'); -const errors = require('./errors'); -const StreamIdStack = require('./stream-id-stack'); -const OperationState = require('./operation-state'); -const promiseUtils = require('./promise-utils'); -const { ExecutionOptions } = require('./execution-options'); - -/** - * Represents a connection to a Cassandra node - */ -class Connection extends events.EventEmitter { - - /** - * Creates a new instance of Connection. - * @param {String} endpoint An string containing ip address and port of the host - * @param {Number|null} protocolVersion - * @param {ClientOptions} options - */ - constructor(endpoint, protocolVersion, options) { - super(); - - this.setMaxListeners(0); - - if (!options) { - throw new Error('options is not defined'); - } - - /** - * Gets the ip and port of the server endpoint. - * @type {String} - */ - this.endpoint = endpoint; - - /** - * Gets the friendly name of the host, used to identify the connection in log messages. - * With direct connect, this is the address and port. - * With SNI, this will be the address and port of the proxy, plus the server name. - * @type {String} - */ - this.endpointFriendlyName = this.endpoint; - - if (options.sni) { - this._serverName = endpoint; - this.endpoint = `${options.sni.addressResolver.getIp()}:${options.sni.port}`; - this.endpointFriendlyName = `${this.endpoint} (${this._serverName})`; - } - - if (!this.endpoint || this.endpoint.indexOf(':') < 0) { - throw new Error('EndPoint must contain the ip address and port separated by : symbol'); - } - - const portSeparatorIndex = this.endpoint.lastIndexOf(':'); - this.address = this.endpoint.substr(0, portSeparatorIndex); - this.port = this.endpoint.substr(portSeparatorIndex + 1); - - Object.defineProperty(this, "options", { value: options, enumerable: false, writable: false}); - - if (protocolVersion === null) { - // Set initial protocol version - protocolVersion = types.protocolVersion.maxSupported; - if (options.protocolOptions.maxVersion) { - // User provided the protocol version - protocolVersion = options.protocolOptions.maxVersion; - } - // Allow to check version using this connection instance - this._checkingVersion = true; - } - - this.log = utils.log; - this.protocolVersion = protocolVersion; - this._operations = new Map(); - this._pendingWrites = []; - this._preparing = new Map(); - - /** - * The timeout state for the idle request (heartbeat) - */ - this._idleTimeout = null; - this.timedOutOperations = 0; - this._streamIds = new StreamIdStack(this.protocolVersion); - this._metrics = options.metrics; - - this.encoder = new Encoder(protocolVersion, options); - this.keyspace = null; - this.emitDrain = false; - /** - * Determines if the socket is open and startup succeeded, whether the connection can be used to send requests / - * receive events - */ - this.connected = false; - /** - * Determines if the socket can be considered as open - */ - this.isSocketOpen = false; - - this.send = util.promisify(this.sendStream); - this.closeAsync = util.promisify(this.close); - this.openAsync = util.promisify(this.open); - this.prepareOnceAsync = util.promisify(this.prepareOnce); - } - - /** - * Binds the necessary event listeners for the socket - */ - bindSocketListeners() { - //Remove listeners that were used for connecting - this.netClient.removeAllListeners('connect'); - this.netClient.removeAllListeners('timeout'); - // The socket is expected to be open at this point - this.isSocketOpen = true; - this.netClient.on('close', () => { - this.log('info', `Connection to ${this.endpointFriendlyName} closed`); - this.isSocketOpen = false; - const wasConnected = this.connected; - this.close(); - if (wasConnected) { - // Emit only when it was closed unexpectedly - this.emit('socketClose'); - } - }); - - this.protocol = new streams.Protocol({ objectMode: true }); - this.parser = new streams.Parser({ objectMode: true }, this.encoder); - const resultEmitter = new streams.ResultEmitter({objectMode: true}); - resultEmitter.on('result', this.handleResult.bind(this)); - resultEmitter.on('row', this.handleRow.bind(this)); - resultEmitter.on('frameEnded', this.freeStreamId.bind(this)); - resultEmitter.on('nodeEvent', this.handleNodeEvent.bind(this)); - - this.netClient - .pipe(this.protocol) - .pipe(this.parser) - .pipe(resultEmitter); - - this.writeQueue = new WriteQueue(this.netClient, this.encoder, this.options); - } - - /** - * Connects a socket and sends the startup protocol messages. - * Note that when open() callbacks in error, the caller should immediately call {@link Connection#close}. - */ - open(callback) { - const self = this; - this.log('info', `Connecting to ${this.endpointFriendlyName}`); - - if (!this.options.sslOptions) { - this.netClient = new net.Socket({ highWaterMark: this.options.socketOptions.coalescingThreshold }); - this.netClient.connect(this.port, this.address, function connectCallback() { - self.log('verbose', `Socket connected to ${self.endpointFriendlyName}`); - self.bindSocketListeners(); - self.startup(callback); - }); - } - else { - // Use TLS - const sslOptions = utils.extend({ rejectUnauthorized: false }, this.options.sslOptions); - - if (this.options.sni) { - sslOptions.servername = this._serverName; - } - - this.netClient = tls.connect(this.port, this.address, sslOptions, function tlsConnectCallback() { - self.log('verbose', `Secure socket connected to ${self.endpointFriendlyName}`); - self.bindSocketListeners(); - self.startup(callback); - }); - - // TLSSocket will validate for values from 512 to 16K (depending on the SSL protocol version) - this.netClient.setMaxSendFragment(this.options.socketOptions.coalescingThreshold); - } - - this.netClient.once('error', function socketError(err) { - self.errorConnecting(err, false, callback); - }); - - this.netClient.once('timeout', function connectTimedOut() { - const err = new types.DriverError('Connection timeout'); - self.errorConnecting(err, true, callback); - }); - - this.netClient.setTimeout(this.options.socketOptions.connectTimeout); - - // Improve failure detection with TCP keep-alives - if (this.options.socketOptions.keepAlive) { - this.netClient.setKeepAlive(true, this.options.socketOptions.keepAliveDelay); - } - - this.netClient.setNoDelay(!!this.options.socketOptions.tcpNoDelay); - } - - /** - * Determines the protocol version to use and sends the STARTUP request - * @param {Function} callback - */ - startup(callback) { - if (this._checkingVersion) { - this.log('info', 'Trying to use protocol version 0x' + this.protocolVersion.toString(16)); - } - - const self = this; - const request = new requests.StartupRequest({ - noCompact: this.options.protocolOptions.noCompact, - clientId: this.options.id, - applicationName: this.options.applicationName, - applicationVersion: this.options.applicationVersion - }); - - this.sendStream(request, null, function responseCallback(err, response) { - if (err && self._checkingVersion) { - let invalidProtocol = (err instanceof errors.ResponseError && - err.code === types.responseErrorCodes.protocolError && - err.message.indexOf('Invalid or unsupported protocol version') >= 0); - - if (!invalidProtocol && types.protocolVersion.canStartupResponseErrorBeWrapped(self.protocolVersion)) { - //For some versions of Cassandra, the error is wrapped into a server error - //See CASSANDRA-9451 - invalidProtocol = (err instanceof errors.ResponseError && - err.code === types.responseErrorCodes.serverError && - err.message.indexOf('ProtocolException: Invalid or unsupported protocol version') > 0); - } - - if (invalidProtocol) { - // The server can respond with a message using the lower protocol version supported - // or using the same version as the one provided - let lowerVersion = self.protocol.version; - - if (lowerVersion === self.protocolVersion) { - lowerVersion = types.protocolVersion.getLowerSupported(self.protocolVersion); - } else if (types.protocolVersion.isBeta(self.protocol.version)) { - // Avoid downgrading the protocol version to a BETA protocol - lowerVersion = types.protocolVersion.getLowerSupported(self.protocol.version); - } - - if (!lowerVersion) { - return startupCallback( - new Error('Connection was unable to STARTUP using protocol version ' + self.protocolVersion)); - } - - self.log('info', 'Protocol 0x' + self.protocolVersion.toString(16) + ' not supported, using 0x' + lowerVersion.toString(16)); - self.decreaseVersion(lowerVersion); - - // The host closed the connection, close the socket and start the connection flow again - setImmediate(function decreasingVersionClosing() { - self.close(function decreasingVersionOpening() { - // Attempt to open with the correct protocol version - self.open(callback); - }); - }); - - return; - } - } - - if (response && response.mustAuthenticate) { - return self.startAuthenticating(response.authenticatorName, startupCallback); - } - - startupCallback(err); - }); - - function startupCallback(err) { - if (err) { - return self.errorConnecting(err, false, callback); - } - //The socket is connected and the connection is authenticated - return self.connectionReady(callback); - } - } - - errorConnecting(err, destroy, callback) { - this.log('warning', `There was an error when trying to connect to the host ${this.endpointFriendlyName}`, err); - if (destroy) { - //there is a TCP connection that should be killed. - this.netClient.destroy(); - } - - this._metrics.onConnectionError(err); - - callback(err); - } - - /** - * Sets the connection to ready/connected status - */ - connectionReady(callback) { - this.emit('connected'); - this.connected = true; - // Remove existing error handlers as the connection is now ready. - this.netClient.removeAllListeners('error'); - this.netClient.on('error', this.handleSocketError.bind(this)); - callback(); - } - - /** @param {Number} lowerVersion */ - decreaseVersion(lowerVersion) { - // The response already has the max protocol version supported by the Cassandra host. - this.protocolVersion = lowerVersion; - this.encoder.setProtocolVersion(lowerVersion); - this._streamIds.setVersion(lowerVersion); - } - - /** - * Handle socket errors, if the socket is not readable invoke all pending callbacks - */ - handleSocketError(err) { - this._metrics.onConnectionError(err); - this.clearAndInvokePending(err); - } - - /** - * Cleans all internal state and invokes all pending callbacks of sent streams - */ - clearAndInvokePending(innerError) { - if (this._idleTimeout) { - //Remove the idle request - clearTimeout(this._idleTimeout); - this._idleTimeout = null; - } - this._streamIds.clear(); - if (this.emitDrain) { - this.emit('drain'); - } - const err = new types.DriverError('Socket was closed'); - err.isSocketError = true; - if (innerError) { - err.innerError = innerError; - } - - // Get all handlers - const operations = Array.from(this._operations.values()); - // Clear pending operation map - this._operations = new Map(); - - if (operations.length > 0) { - this.log('info', 'Invoking ' + operations.length + ' pending callbacks'); - } - - // Invoke all handlers - utils.each(operations, function (operation, next) { - operation.setResult(err); - next(); - }); - - const pendingWritesCopy = this._pendingWrites; - this._pendingWrites = []; - utils.each(pendingWritesCopy, function (operation, next) { - operation.setResult(err); - next(); - }); - } - - /** - * Starts the SASL flow - * @param {String} authenticatorName - * @param {Function} callback - */ - startAuthenticating(authenticatorName, callback) { - if (!this.options.authProvider) { - return callback(new errors.AuthenticationError('Authentication provider not set')); - } - const authenticator = this.options.authProvider.newAuthenticator(this.endpoint, authenticatorName); - const self = this; - authenticator.initialResponse(function initialResponseCallback(err, token) { - // Start the flow with the initial token - if (err) { - return self.onAuthenticationError(callback, err); - } - self.authenticate(authenticator, token, callback); - }); - } - - /** - * Handles authentication requests and responses. - * @param {Authenticator} authenticator - * @param {Buffer} token - * @param {Function} callback - */ - authenticate(authenticator, token, callback) { - const self = this; - let request = new requests.AuthResponseRequest(token); - if (this.protocolVersion === 1) { - //No Sasl support, use CREDENTIALS - if (!authenticator.username) { - return self.onAuthenticationError( - callback, new errors.AuthenticationError('Only plain text authenticator providers allowed under protocol v1')); - } - - request = new requests.CredentialsRequest(authenticator.username, authenticator.password); - } - - this.sendStream(request, null, function authResponseCallback(err, result) { - if (err) { - if (err instanceof errors.ResponseError && err.code === types.responseErrorCodes.badCredentials) { - const authError = new errors.AuthenticationError(err.message); - authError.additionalInfo = err; - err = authError; - } - return self.onAuthenticationError(callback, err); - } - - if (result.ready) { - authenticator.onAuthenticationSuccess(); - return callback(); - } - - if (result.authChallenge) { - return authenticator.evaluateChallenge(result.token, function evaluateCallback(err, t) { - if (err) { - return self.onAuthenticationError(callback, err); - } - //here we go again - self.authenticate(authenticator, t, callback); - }); - } - - callback(new errors.DriverInternalError('Unexpected response from Cassandra: ' + util.inspect(result))); - }); - } - - onAuthenticationError(callback, err) { - this._metrics.onAuthenticationError(err); - callback(err); - } - - /** - * Executes a 'USE ' query, if keyspace is provided and it is different from the current keyspace - * @param {?String} keyspace - */ - async changeKeyspace(keyspace) { - if (!keyspace || this.keyspace === keyspace) { - return; - } - - if (this.toBeKeyspace === keyspace) { - // It will be invoked once the keyspace is changed - return promiseUtils.fromEvent(this, 'keyspaceChanged'); - } - - this.toBeKeyspace = keyspace; - - const query = `USE "${keyspace}"`; - - try { - await this.send(new requests.QueryRequest(query, null, null), null); - this.keyspace = keyspace; - this.emit('keyspaceChanged', null, keyspace); - } catch (err) { - this.log('error', `Connection to ${this.endpointFriendlyName} could not switch active keyspace: ${err}`, err); - this.emit('keyspaceChanged', err); - throw err; - } finally { - this.toBeKeyspace = null; - } - } - - /** - * Prepares a query on a given connection. If its already being prepared, it queues the callback. - * @param {String} query - * @param {String} keyspace - * @param {function} callback - */ - prepareOnce(query, keyspace, callback) { - const name = ( keyspace || '' ) + query; - let info = this._preparing.get(name); - - if (info) { - // Its being already prepared - return info.once('prepared', callback); - } - - info = new events.EventEmitter(); - info.setMaxListeners(0); - info.once('prepared', callback); - this._preparing.set(name, info); - - this.sendStream(new requests.PrepareRequest(query, keyspace), null, (err, response) => { - info.emit('prepared', err, response); - this._preparing.delete(name); - }); - } - - /** - * Queues the operation to be written to the wire and invokes the callback once the response was obtained or with an - * error (socket error or OperationTimedOutError or serialization-related error). - * @param {Request} request - * @param {ExecutionOptions|null} execOptions - * @param {function} callback Function to be called once the response has been received - * @return {OperationState} - */ - sendStream(request, execOptions, callback) { - execOptions = execOptions || ExecutionOptions.empty(); - - // Create a new operation that will contain the request, callback and timeouts - const operation = new OperationState(request, execOptions.getRowCallback(), (err, response, length) => { - if (!err || !err.isSocketError) { - // Emit that a response was obtained when there is a valid response - // or when the error is not a socket error - this.emit('responseDequeued'); - } - callback(err, response, length); - }); - - const streamId = this._getStreamId(); - - // Start the request timeout without waiting for the request to be written - operation.setRequestTimeout(execOptions, this.options.socketOptions.readTimeout, this.endpoint, - () => this.timedOutOperations++, - () => this.timedOutOperations--); - - if (streamId === null) { - this.log('info', - 'Enqueuing ' + - this._pendingWrites.length + - ', if this message is recurrent consider configuring more connections per host or lowering the pressure'); - this._pendingWrites.push(operation); - return operation; - } - this._write(operation, streamId); - return operation; - } - - /** - * Pushes the item into the queue. - * @param {OperationState} operation - * @param {Number} streamId - * @private - */ - _write(operation, streamId) { - operation.streamId = streamId; - const self = this; - this.writeQueue.push(operation, function writeCallback (err) { - if (err) { - // The request was not written. - // There was a serialization error or the operation has already timed out or was cancelled - self._streamIds.push(streamId); - return operation.setResult(err); - } - self.log('verbose', 'Sent stream #' + streamId + ' to ' + self.endpointFriendlyName); - if (operation.isByRow()) { - self.parser.setOptions(streamId, { byRow: true }); - } - self._setIdleTimeout(); - self._operations.set(streamId, operation); - }); - } - - _setIdleTimeout() { - if (!this.options.pooling.heartBeatInterval) { - return; - } - const self = this; - // Scheduling the new timeout before de-scheduling the previous performs significantly better - // than de-scheduling first, see nodejs implementation: https://github.com/nodejs/node/blob/master/lib/timers.js - const previousTimeout = this._idleTimeout; - self._idleTimeout = setTimeout(() => self._idleTimeoutHandler(), self.options.pooling.heartBeatInterval); - if (previousTimeout) { - //remove the previous timeout for the idle request - clearTimeout(previousTimeout); - } - } - - /** - * Function that gets executed once the idle timeout has passed to issue a request to keep the connection alive - */ - _idleTimeoutHandler() { - if (this.sendingIdleQuery) { - //don't issue another - //schedule for next time - this._idleTimeout = setTimeout(() => this._idleTimeoutHandler(), this.options.pooling.heartBeatInterval); - return; - } - - this.log('verbose', `Connection to ${this.endpointFriendlyName} idling, issuing a request to prevent disconnects`); - this.sendingIdleQuery = true; - this.sendStream(requests.options, null, (err) => { - this.sendingIdleQuery = false; - if (!err) { - //The sending succeeded - //There is a valid response but we don't care about the response - return; - } - this.log('warning', 'Received heartbeat request error', err); - this.emit('idleRequestError', err, this); - }); - } - - /** - * Returns an available streamId or null if there isn't any available - * @returns {Number} - */ - _getStreamId() { - return this._streamIds.pop(); - } - - freeStreamId(header) { - const streamId = header.streamId; - - if (streamId < 0) { - // Event ids don't have a matching request operation - return; - } - - this._operations.delete(streamId); - this._streamIds.push(streamId); - - if (this.emitDrain && this._streamIds.inUse === 0 && this._pendingWrites.length === 0) { - this.emit('drain'); - } - - this._writeNext(); - } - - _writeNext() { - if (this._pendingWrites.length === 0) { - return; - } - const streamId = this._getStreamId(); - if (streamId === null) { - // No streamId available - return; - } - const self = this; - let operation; - while ((operation = this._pendingWrites.shift()) && !operation.canBeWritten()) { - // Trying to obtain an pending operation that can be written - } - - if (!operation) { - // There isn't a pending operation that can be written - this._streamIds.push(streamId); - return; - } - - // Schedule after current I/O callbacks have been executed - setImmediate(function writeNextPending() { - self._write(operation, streamId); - }); - } - - /** - * Returns the number of requests waiting for response - * @returns {Number} - */ - getInFlight() { - return this._streamIds.inUse; - } - - /** - * Handles a result and error response - */ - handleResult(header, err, result) { - const streamId = header.streamId; - if(streamId < 0) { - return this.log('verbose', 'event received', header); - } - const operation = this._operations.get(streamId); - if (!operation) { - return this.log('error', 'The server replied with a wrong streamId #' + streamId); - } - this.log('verbose', 'Received frame #' + streamId + ' from ' + this.endpointFriendlyName); - operation.setResult(err, result, header.bodyLength); - } - - handleNodeEvent(header, event) { - switch (event.eventType) { - case types.protocolEvents.schemaChange: - this.emit('nodeSchemaChange', event); - break; - case types.protocolEvents.topologyChange: - this.emit('nodeTopologyChange', event); - break; - case types.protocolEvents.statusChange: - this.emit('nodeStatusChange', event); - break; - } - } - - /** - * Handles a row response - */ - handleRow(header, row, meta, rowLength, flags) { - const streamId = header.streamId; - if(streamId < 0) { - return this.log('verbose', 'Event received', header); - } - const operation = this._operations.get(streamId); - if (!operation) { - return this.log('error', 'The server replied with a wrong streamId #' + streamId); - } - operation.setResultRow(row, meta, rowLength, flags, header); - } - - /** - * Closes the socket (if not already closed) and cancels all in-flight requests. - * Multiple calls to this method have no additional side-effects. - * @param {Function} [callback] - */ - close(callback) { - callback = callback || utils.noop; - - if (!this.connected && !this.isSocketOpen) { - return callback(); - } - - this.connected = false; - // Drain is never going to be emitted, once it is set to closed - this.removeAllListeners('drain'); - this.clearAndInvokePending(); - - if (!this.isSocketOpen) { - return callback(); - } - - // Set the socket as closed now (before socket.end() is called) to avoid being invoked more than once - this.isSocketOpen = false; - this.log('verbose', `Closing connection to ${this.endpointFriendlyName}`); - const self = this; - - // If server doesn't acknowledge the half-close within connection timeout, destroy the socket. - const endTimeout = setTimeout(() => { - this.log('info', `${this.endpointFriendlyName} did not respond to connection close within ` + - `${this.options.socketOptions.connectTimeout}ms, destroying connection`); - this.netClient.destroy(); - }, this.options.socketOptions.connectTimeout); - - this.netClient.once('close', function (hadError) { - clearTimeout(endTimeout); - if (hadError) { - self.log('info', 'The socket closed with a transmission error'); - } - setImmediate(callback); - }); - - // At this point, the error event can be triggered because: - // - It's connected and writes haven't completed yet - // - The server abruptly closed its end of the connection (ECONNRESET) as a result of protocol error / auth error - // We need to remove any listeners and make sure we callback are pending writes - this.netClient.removeAllListeners('error'); - this.netClient.on('error', err => this.clearAndInvokePending(err)); - - // Half-close the socket, it will result in 'close' event being fired - this.netClient.end(); - } - - /** - * Gets the local IP address to which this connection socket is bound to. - * @returns {String|undefined} - */ - getLocalAddress() { - if (!this.netClient) { - return undefined; - } - - return this.netClient.localAddress; - } -} - -module.exports = Connection; diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/control-connection.js b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/control-connection.js deleted file mode 100644 index 5f4c165d3a..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/control-connection.js +++ /dev/null @@ -1,1046 +0,0 @@ -/* - * Copyright DataStax, Inc. - * - * 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 events = require('events'); -const util = require('util'); -const net = require('net'); -const dns = require('dns'); - -const errors = require('./errors'); -const { Host, HostMap } = require('./host'); -const Metadata = require('./metadata'); -const EventDebouncer = require('./metadata/event-debouncer'); -const Connection = require('./connection'); -const requests = require('./requests'); -const utils = require('./utils'); -const types = require('./types'); -const promiseUtils = require('./promise-utils'); -const f = util.format; - -const selectPeers = "SELECT * FROM system.peers"; -const selectLocal = "SELECT * FROM system.local WHERE key='local'"; -const newNodeDelay = 1000; -const metadataQueryAbortTimeout = 2000; -const schemaChangeTypes = { - created: 'CREATED', - updated: 'UPDATED', - dropped: 'DROPPED' -}; -const supportedProductTypeKey = 'PRODUCT_TYPE'; -const supportedDbaas = 'DATASTAX_APOLLO'; - -/** - * Represents a connection used by the driver to receive events and to check the status of the cluster. - *

It uses an existing connection from the hosts' connection pool to maintain the driver metadata up-to-date.

- */ -class ControlConnection extends events.EventEmitter { - - /** - * Creates a new instance of ControlConnection. - * @param {Object} options - * @param {ProfileManager} profileManager - * @param {{borrowHostConnection: function, createConnection: function}} [context] An object containing methods to - * allow dependency injection. - */ - constructor(options, profileManager, context) { - super(); - - this.protocolVersion = null; - this.hosts = new HostMap(); - this.setMaxListeners(0); - this.log = utils.log; - Object.defineProperty(this, "options", { value: options, enumerable: false, writable: false}); - - /** - * Cluster metadata that is going to be shared between the Client and ControlConnection - */ - this.metadata = new Metadata(this.options, this); - this.initialized = false; - - /** - * Host used by the control connection - * @type {Host|null} - */ - this.host = null; - - /** - * Connection used to retrieve metadata and subscribed to events - * @type {Connection|null} - */ - this.connection = null; - - this._addressTranslator = this.options.policies.addressResolution; - this._reconnectionPolicy = this.options.policies.reconnection; - this._reconnectionSchedule = this._reconnectionPolicy.newSchedule(); - this._isShuttingDown = false; - - // Reference to the encoder of the last valid connection - this._encoder = null; - this._debouncer = new EventDebouncer(options.refreshSchemaDelay, this.log.bind(this)); - this._profileManager = profileManager; - this._triedHosts = null; - this._resolvedContactPoints = new Map(); - this._contactPoints = new Set(); - - // Timeout used for delayed handling of topology changes - this._topologyChangeTimeout = null; - // Timeout used for delayed handling of node status changes - this._nodeStatusChangeTimeout = null; - - if (context && context.borrowHostConnection) { - this._borrowHostConnection = context.borrowHostConnection; - } - - if (context && context.createConnection) { - this._createConnection = context.createConnection; - } - } - - /** - * Stores the contact point information and what it resolved to. - * @param {String|null} address - * @param {String} port - * @param {String} name - * @param {Boolean} isIPv6 - */ - _addContactPoint(address, port, name, isIPv6) { - if (address === null) { - // Contact point could not be resolved, store that the resolution came back empty - this._resolvedContactPoints.set(name, utils.emptyArray); - return; - } - - const portNumber = parseInt(port, 10) || this.options.protocolOptions.port; - const endpoint = `${address}:${portNumber}`; - this._contactPoints.add(endpoint); - - // Use RFC 3986 for IPv4 and IPv6 - const standardEndpoint = !isIPv6 ? endpoint : `[${address}]:${portNumber}`; - - let resolvedAddressedByName = this._resolvedContactPoints.get(name); - if (resolvedAddressedByName === undefined) { - resolvedAddressedByName = []; - this._resolvedContactPoints.set(name, resolvedAddressedByName); - } - - resolvedAddressedByName.push(standardEndpoint); - } - - async _parseContactPoint(name) { - let addressOrName = name; - let port = null; - - if (name.indexOf('[') === 0 && name.indexOf(']:') > 1) { - // IPv6 host notation [ip]:port (RFC 3986 section 3.2.2) - const index = name.lastIndexOf(']:'); - addressOrName = name.substr(1, index - 1); - port = name.substr(index + 2); - } else if (name.indexOf(':') > 0) { - // IPv4 or host name with port notation - const parts = name.split(':'); - if (parts.length === 2) { - addressOrName = parts[0]; - port = parts[1]; - } - } - - if (net.isIP(addressOrName)) { - this._addContactPoint(addressOrName, port, name, net.isIPv6(addressOrName)); - return; - } - - const addresses = await this._resolveAll(addressOrName); - if (addresses.length > 0) { - addresses.forEach(addressInfo => this._addContactPoint(addressInfo.address, port, name, addressInfo.isIPv6)); - } else { - // Store that we attempted resolving the name but was not found - this._addContactPoint(null, null, name, false); - } - } - - /** - * Initializes the control connection by establishing a Connection using a suitable protocol - * version to be used and retrieving cluster metadata. - */ - async init() { - if (this.initialized) { - // Prevent multiple serial initializations - return; - } - - if (!this.options.sni) { - // Parse and resolve contact points - await Promise.all(this.options.contactPoints.map(name => this._parseContactPoint(name))); - } else { - this.options.contactPoints.forEach(cp => this._contactPoints.add(cp)); - const address = this.options.sni.address; - const separatorIndex = address.lastIndexOf(':'); - - if (separatorIndex === -1) { - throw new new errors.DriverInternalError('The SNI endpoint address should contain ip/name and port'); - } - - const nameOrIp = address.substr(0, separatorIndex); - this.options.sni.port = address.substr(separatorIndex + 1); - this.options.sni.addressResolver = new utils.AddressResolver({ nameOrIp, dns }); - await this.options.sni.addressResolver.init(); - } - - if (this._contactPoints.size === 0) { - throw new errors.NoHostAvailableError({}, 'No host could be resolved'); - } - - await this._initializeConnection(); - } - - _setHealthListeners(host, connection) { - const self = this; - let wasRefreshCalled = 0; - - function removeListeners() { - host.removeListener('down', downOrIgnoredHandler); - host.removeListener('ignore', downOrIgnoredHandler); - connection.removeListener('socketClose', socketClosedHandler); - } - - function startReconnecting(hostDown) { - if (wasRefreshCalled++ !== 0) { - // Prevent multiple calls to reconnect - return; - } - - removeListeners(); - - if (self._isShuttingDown) { - // Don't attempt to reconnect when the ControlConnection is being shutdown - return; - } - - if (hostDown) { - self.log('warning', - `Host ${host.address} used by the ControlConnection DOWN, ` + - `connection to ${connection.endpointFriendlyName} will not longer be used`); - } else { - self.log('warning', `Connection to ${connection.endpointFriendlyName} used by the ControlConnection was closed`); - } - - promiseUtils.toBackground(self._refresh()); - } - - function downOrIgnoredHandler() { - startReconnecting(true); - } - - function socketClosedHandler() { - startReconnecting(false); - } - - host.once('down', downOrIgnoredHandler); - host.once('ignore', downOrIgnoredHandler); - connection.once('socketClose', socketClosedHandler); - } - - /** - * Iterates through the hostIterator and Gets the following open connection. - * @param {Iterator} hostIterator - * @returns {Connection!} - */ - _borrowAConnection(hostIterator) { - let connection = null; - - while (!connection) { - const item = hostIterator.next(); - const host = item.value; - - if (item.done) { - throw new errors.NoHostAvailableError(this._triedHosts); - } - - // Only check distance once the load-balancing policies have been initialized - const distance = this._profileManager.getDistance(host); - if (!host.isUp() || distance === types.distance.ignored) { - continue; - } - - try { - connection = this._borrowHostConnection(host); - } catch (err) { - this._triedHosts[host.address] = err; - } - } - - return connection; - } - - /** - * Iterates through the contact points and tries to open a connection. - * @param {Iterator} contactPointsIterator - * @returns {Promise} - */ - async _borrowFirstConnection(contactPointsIterator) { - let connection = null; - - while (!connection) { - const item = contactPointsIterator.next(); - const contactPoint = item.value; - - if (item.done) { - throw new errors.NoHostAvailableError(this._triedHosts); - } - - try { - connection = await this._createConnection(contactPoint); - } catch (err) { - this._triedHosts[contactPoint] = err; - } - } - - if (!connection) { - const err = new errors.NoHostAvailableError(this._triedHosts); - this.log('error', 'ControlConnection failed to acquire a connection'); - throw err; - } - - this.protocolVersion = connection.protocolVersion; - this._encoder = connection.encoder; - this.connection = connection; - } - - /** Default implementation for borrowing connections, that can be injected at constructor level */ - _borrowHostConnection(host) { - // Borrow any open connection, regardless of the keyspace - return host.borrowConnection(); - } - - /** - * Default implementation for creating initial connections, that can be injected at constructor level - * @param {String} contactPoint - */ - async _createConnection(contactPoint) { - const c = new Connection(contactPoint, null, this.options); - - try { - await c.openAsync(); - } catch (err) { - promiseUtils.toBackground(c.closeAsync()); - throw err; - } - - return c; - } - - /** - * Gets the info from local and peer metadata, reloads the keyspaces metadata and rebuilds tokens. - *

It throws an error when there's a failure or when reconnecting and there's no connection.

- * @param {Boolean} initializing Determines whether this function was called in order to initialize the control - * connection the first time - * @param {Boolean} isReconnecting Determines whether the refresh is being done because the ControlConnection is - * switching to use this connection to this host. - */ - async _refreshHosts(initializing, isReconnecting) { - // Get a reference to the current connection as it might change from external events - const c = this.connection; - - if (!c) { - if (isReconnecting) { - throw new errors.DriverInternalError('Connection reference has been lost when reconnecting'); - } - - // it's possible that this was called as a result of a topology change, but the connection was lost - // between scheduling time and now. This will be called again when there is a new connection. - return; - } - - this.log('info', 'Refreshing local and peers info'); - - const rsLocal = await c.send(new requests.QueryRequest(selectLocal), null); - this._setLocalInfo(initializing, isReconnecting, c, rsLocal); - - if (!this.host) { - throw new errors.DriverInternalError('Information from system.local could not be retrieved'); - } - - const rsPeers = await c.send(new requests.QueryRequest(selectPeers), null); - await this.setPeersInfo(initializing, rsPeers); - - if (!this.initialized) { - // resolve protocol version from highest common version among hosts. - const highestCommon = types.protocolVersion.getHighestCommon(c, this.hosts); - const reconnect = highestCommon !== this.protocolVersion; - - // set protocol version on each host. - this.protocolVersion = highestCommon; - this.hosts.forEach(h => h.setProtocolVersion(this.protocolVersion)); - - // if protocol version changed, reconnect the control connection with new version. - if (reconnect) { - this.log('info', `Reconnecting since the protocol version changed to 0x${highestCommon.toString(16)}`); - c.decreaseVersion(this.protocolVersion); - await c.closeAsync(); - - try { - await c.openAsync(); - } catch (err) { - // Close in the background - promiseUtils.toBackground(c.closeAsync()); - - throw err; - } - } - - // To acquire metadata we need to specify the cassandra version - this.metadata.setCassandraVersion(this.host.getCassandraVersion()); - this.metadata.buildTokens(this.hosts); - - if (!this.options.isMetadataSyncEnabled) { - this.metadata.initialized = true; - return; - } - - await this.metadata.refreshKeyspacesInternal(false); - this.metadata.initialized = true; - } - } - - /** - * Acquires a new connection and refreshes topology and keyspace metadata. - *

When it fails obtaining a connection and there aren't any more hosts, it schedules reconnection.

- *

When it fails obtaining the metadata, it marks connection and/or host unusable and retries using the same - * iterator from query plan / host list

- * @param {Iterator} [hostIterator] - */ - async _refresh(hostIterator) { - if (this._isShuttingDown) { - this.log('info', 'The ControlConnection will not be refreshed as the Client is being shutdown'); - return; - } - - // Reset host and connection - this.host = null; - this.connection = null; - - try { - if (!hostIterator) { - this.log('info', 'Trying to acquire a connection to a new host'); - this._triedHosts = {}; - hostIterator = await promiseUtils.newQueryPlan(this._profileManager.getDefaultLoadBalancing(), null, null); - } - - this.connection = this._borrowAConnection(hostIterator); - - } catch (err) { - // There was a failure obtaining a connection or during metadata retrieval - this.log('error', 'ControlConnection failed to acquire a connection', err); - - if (!this._isShuttingDown) { - const delay = this._reconnectionSchedule.next().value; - this.log('warning', `ControlConnection could not reconnect, scheduling reconnection in ${delay}ms`); - setTimeout(() => this._refresh(), delay); - this.emit('newConnection', err); - } - - return; - } - - this.log('info',`ControlConnection connected to ${this.connection.endpointFriendlyName}`); - - try { - await this._refreshHosts(false, true); - - await this._registerToConnectionEvents(); - } catch (err) { - this.log('error', 'ControlConnection failed to retrieve topology and keyspaces information', err); - this._triedHosts[this.connection.endpoint] = err; - - if (err.isSocketError && this.host) { - this.host.removeFromPool(this.connection); - } - - // Retry the whole thing with the same query plan - return await this._refresh(hostIterator); - } - - this._reconnectionSchedule = this._reconnectionPolicy.newSchedule(); - this._setHealthListeners(this.host, this.connection); - this.emit('newConnection', null, this.connection, this.host); - - this.log('info', `ControlConnection connected to ${this.connection.endpointFriendlyName} and up to date`); - } - - /** - * Acquires a connection and refreshes topology and keyspace metadata for the first time. - * @returns {Promise} - */ - async _initializeConnection() { - this.log('info', 'Getting first connection'); - - // Reset host and connection - this.host = null; - this.connection = null; - this._triedHosts = {}; - - // Randomize order of contact points resolved. - const contactPointsIterator = utils.shuffleArray(Array.from(this._contactPoints))[Symbol.iterator](); - - while (true) { - await this._borrowFirstConnection(contactPointsIterator); - - this.log('info', `ControlConnection using protocol version 0x${ - this.protocolVersion.toString(16)}, connected to ${this.connection.endpointFriendlyName}`); - - try { - await this._getSupportedOptions(); - await this._refreshHosts(true, true); - await this._registerToConnectionEvents(); - - // We have a valid connection, leave the loop - break; - - } catch (err) { - this.log('error', 'ControlConnection failed to retrieve topology and keyspaces information', err); - this._triedHosts[this.connection.endpoint] = err; - } - } - - // The healthy connection used to initialize should be part of the Host pool - this.host.pool.addExistingConnection(this.connection); - - this.initialized = true; - this._setHealthListeners(this.host, this.connection); - this.log('info', `ControlConnection connected to ${this.connection.endpointFriendlyName}`); - } - - async _getSupportedOptions() { - const response = await this.connection.send(requests.options, null); - - // response.supported is a string multi map, decoded as an Object. - const productType = response.supported && response.supported[supportedProductTypeKey]; - if (Array.isArray(productType) && productType[0] === supportedDbaas) { - this.metadata.setProductTypeAsDbaas(); - } - } - - async _registerToConnectionEvents() { - this.connection.on('nodeTopologyChange', this._nodeTopologyChangeHandler.bind(this)); - this.connection.on('nodeStatusChange', this._nodeStatusChangeHandler.bind(this)); - this.connection.on('nodeSchemaChange', this._nodeSchemaChangeHandler.bind(this)); - const request = new requests.RegisterRequest(['TOPOLOGY_CHANGE', 'STATUS_CHANGE', 'SCHEMA_CHANGE']); - await this.connection.send(request, null); - } - - /** - * Handles a TOPOLOGY_CHANGE event - */ - _nodeTopologyChangeHandler(event) { - this.log('info', 'Received topology change', event); - - // all hosts information needs to be refreshed as tokens might have changed - clearTimeout(this._topologyChangeTimeout); - - // Use an additional timer to make sure that the refresh hosts is executed only AFTER the delay - // In this case, the event debouncer doesn't help because it could not honor the sliding delay (ie: processNow) - this._topologyChangeTimeout = setTimeout(() => - promiseUtils.toBackground(this._scheduleRefreshHosts()), newNodeDelay); - } - - /** - * Handles a STATUS_CHANGE event - */ - _nodeStatusChangeHandler(event) { - const self = this; - const addressToTranslate = event.inet.address.toString(); - const port = this.options.protocolOptions.port; - this._addressTranslator.translate(addressToTranslate, port, function translateCallback(endPoint) { - const host = self.hosts.get(endPoint); - if (!host) { - self.log('warning', 'Received status change event but host was not found: ' + addressToTranslate); - return; - } - const distance = self._profileManager.getDistance(host); - if (event.up) { - if (distance === types.distance.ignored) { - return host.setUp(true); - } - clearTimeout(self._nodeStatusChangeTimeout); - // Waits a couple of seconds before marking it as UP - self._nodeStatusChangeTimeout = setTimeout(() => host.checkIsUp(), newNodeDelay); - return; - } - // marked as down - if (distance === types.distance.ignored) { - return host.setDown(); - } - self.log('warning', 'Received status change to DOWN for host ' + host.address); - }); - } - - /** - * Handles a SCHEMA_CHANGE event - */ - _nodeSchemaChangeHandler(event) { - this.log('info', 'Schema change', event); - if (!this.options.isMetadataSyncEnabled) { - return; - } - - promiseUtils.toBackground(this.handleSchemaChange(event, false)); - } - - /** - * Schedules metadata refresh and callbacks when is refreshed. - * @param {{keyspace: string, isKeyspace: boolean, schemaChangeType, table, udt, functionName, aggregate}} event - * @param {Boolean} processNow - * @returns {Promise} - */ - handleSchemaChange(event, processNow) { - const self = this; - let handler, cqlObject; - - if (event.isKeyspace) { - if (event.schemaChangeType === schemaChangeTypes.dropped) { - handler = function removeKeyspace() { - // if on the same event queue there is a creation, this handler is not going to be executed - // it is safe to remove the keyspace metadata - delete self.metadata.keyspaces[event.keyspace]; - }; - - return this._scheduleObjectRefresh(handler, event.keyspace, null, processNow); - } - - return this._scheduleKeyspaceRefresh(event.keyspace, processNow); - } - - const ksInfo = this.metadata.keyspaces[event.keyspace]; - if (!ksInfo) { - // it hasn't been loaded and it is not part of the metadata, don't mind - return Promise.resolve(); - } - - if (event.table) { - cqlObject = event.table; - handler = function clearTableState() { - delete ksInfo.tables[event.table]; - delete ksInfo.views[event.table]; - }; - } - else if (event.udt) { - cqlObject = event.udt; - handler = function clearUdtState() { - delete ksInfo.udts[event.udt]; - }; - } - else if (event.functionName) { - cqlObject = event.functionName; - handler = function clearFunctionState() { - delete ksInfo.functions[event.functionName]; - }; - } - else if (event.aggregate) { - cqlObject = event.aggregate; - handler = function clearKeyspaceState() { - delete ksInfo.aggregates[event.aggregate]; - }; - } - - if (!handler) { - // Forward compatibility - return Promise.resolve(); - } - - // It's a cql object change clean the internal cache - return this._scheduleObjectRefresh(handler, event.keyspace, cqlObject, processNow); - } - - /** - * @param {Function} handler - * @param {String} keyspace - * @param {String} cqlObject - * @param {Boolean} processNow - * @returns {Promise} - */ - _scheduleObjectRefresh(handler, keyspace, cqlObject, processNow) { - return this._debouncer.eventReceived({ handler, keyspace, cqlObject }, processNow); - } - - /** - * @param {String} keyspace - * @param {Boolean} processNow - * @returns {Promise} - */ - _scheduleKeyspaceRefresh(keyspace, processNow) { - return this._debouncer.eventReceived({ - handler: () => this.metadata.refreshKeyspace(keyspace), - keyspace - }, processNow); - } - - /** @returns {Promise} */ - _scheduleRefreshHosts() { - return this._debouncer.eventReceived({ - handler: () => this._refreshHosts(false, false), - all: true - }, false); - } - - /** - * Sets the information for the host used by the control connection. - * @param {Boolean} initializing - * @param {Connection} c - * @param {Boolean} setCurrentHost Determines if the host retrieved must be set as the current host - * @param result - */ - _setLocalInfo(initializing, setCurrentHost, c, result) { - if (!result || !result.rows || !result.rows.length) { - this.log('warning', 'No local info could be obtained'); - return; - } - - const row = result.rows[0]; - - let localHost; - - // Note that with SNI enabled, we can trust that rpc_address will contain a valid value. - const endpoint = !this.options.sni - ? c.endpoint - : `${row['rpc_address']}:${this.options.protocolOptions.port}`; - - if (initializing) { - localHost = new Host(endpoint, this.protocolVersion, this.options, this.metadata); - this.hosts.set(endpoint, localHost); - this.log('info', `Adding host ${endpoint}`); - } else { - localHost = this.hosts.get(endpoint); - - if (!localHost) { - this.log('error', 'Localhost could not be found'); - return; - } - } - - localHost.datacenter = row['data_center']; - localHost.rack = row['rack']; - localHost.tokens = row['tokens']; - localHost.hostId = row['host_id']; - localHost.cassandraVersion = row['release_version']; - setDseParameters(localHost, row); - this.metadata.setPartitioner(row['partitioner']); - this.log('info', 'Local info retrieved'); - - if (setCurrentHost) { - // Set the host as the one being used by the ControlConnection. - this.host = localHost; - } - } - - /** - * @param {Boolean} initializing Determines whether this function was called in order to initialize the control - * connection the first time. - * @param {ResultSet} result - */ - async setPeersInfo(initializing, result) { - if (!result || !result.rows) { - return; - } - - // A map of peers, could useful for in case there are discrepancies - const peers = {}; - const port = this.options.protocolOptions.port; - const foundDataCenters = new Set(); - - if (this.host && this.host.datacenter) { - foundDataCenters.add(this.host.datacenter); - } - - for (const row of result.rows) { - const endpoint = await this.getAddressForPeerHost(row, port); - - if (!endpoint) { - continue; - } - - peers[endpoint] = true; - let host = this.hosts.get(endpoint); - let isNewHost = !host; - - if (isNewHost) { - host = new Host(endpoint, this.protocolVersion, this.options, this.metadata); - this.log('info', `Adding host ${endpoint}`); - isNewHost = true; - } - - host.datacenter = row['data_center']; - host.rack = row['rack']; - host.tokens = row['tokens']; - host.hostId = row['host_id']; - host.cassandraVersion = row['release_version']; - setDseParameters(host, row); - - if (host.datacenter) { - foundDataCenters.add(host.datacenter); - } - - if (isNewHost) { - // Add it to the map (and trigger events) after all the properties - // were set to avoid race conditions - this.hosts.set(endpoint, host); - - if (!initializing) { - // Set the distance at Host level, that way the connection pool is created with the correct settings - this._profileManager.getDistance(host); - - // When we are not initializing, we start with the node set as DOWN - host.setDown(); - } - } - } - - // Is there a difference in number between peers + local != hosts - if (this.hosts.length > result.rows.length + 1) { - // There are hosts in the current state that don't belong (nodes removed or wrong contactPoints) - this.log('info', 'Removing nodes from the pool'); - const toRemove = []; - - this.hosts.forEach(h => { - //It is not a peer and it is not local host - if (!peers[h.address] && h !== this.host) { - this.log('info', 'Removing host ' + h.address); - toRemove.push(h.address); - h.shutdown(true); - } - }); - - this.hosts.removeMultiple(toRemove); - } - - if (initializing && this.options.localDataCenter) { - const localDc = this.options.localDataCenter; - - if (!foundDataCenters.has(localDc)) { - throw new errors.ArgumentError(`localDataCenter was configured as '${ - localDc}', but only found hosts in data centers: [${Array.from(foundDataCenters).join(', ')}]`); - } - } - - this.log('info', 'Peers info retrieved'); - } - - /** - * Gets the address from a peers row and translates the address. - * @param {Object|Row} row - * @param {Number} defaultPort - * @returns {Promise} - */ - getAddressForPeerHost(row, defaultPort) { - return new Promise(resolve => { - let address = row['rpc_address']; - const peer = row['peer']; - const bindAllAddress = '0.0.0.0'; - - if (!address) { - this.log('error', f('No rpc_address found for host %s in %s\'s peers system table. %s will be ignored.', - peer, this.host.address, peer)); - return resolve(null); - } - - if (address.toString() === bindAllAddress) { - this.log('warning', f('Found host with 0.0.0.0 as rpc_address, using listen_address (%s) to contact it instead.' + - ' If this is incorrect you should avoid the use of 0.0.0.0 server side.', peer)); - address = peer; - } - - this._addressTranslator.translate(address.toString(), defaultPort, resolve); - }); - } - - /** - * Uses the DNS protocol to resolve a IPv4 and IPv6 addresses (A and AAAA records) for the hostname. - * It returns an Array of addresses that can be empty and logs the error. - * @private - * @param name - */ - async _resolveAll(name) { - const addresses = []; - const resolve4 = util.promisify(dns.resolve4); - const resolve6 = util.promisify(dns.resolve6); - const lookup = util.promisify(dns.lookup); - - // Ignore errors for resolve calls - const ipv4Promise = resolve4(name).catch(() => {}).then(r => r || utils.emptyArray); - const ipv6Promise = resolve6(name).catch(() => {}).then(r => r || utils.emptyArray); - - let arr; - arr = await ipv4Promise; - arr.forEach(address => addresses.push({address, isIPv6: false})); - - arr = await ipv6Promise; - arr.forEach(address => addresses.push({address, isIPv6: true})); - - if (addresses.length === 0) { - // In case dns.resolve*() methods don't yield a valid address for the host name - // Use system call getaddrinfo() that might resolve according to host system definitions - try { - arr = await lookup(name, { all: true }); - arr.forEach(({address, family}) => addresses.push({address, isIPv6: family === 6})); - } catch (err) { - this.log('error', `Host with name ${name} could not be resolved`, err); - } - } - - return addresses; - } - - /** - * Waits for a connection to be available. If timeout expires before getting a connection it callbacks in error. - * @returns {Promise} - */ - _waitForReconnection() { - return new Promise((resolve, reject) => { - const callback = promiseUtils.getCallback(resolve, reject); - - // eslint-disable-next-line prefer-const - let timeout; - - function newConnectionListener(err) { - clearTimeout(timeout); - callback(err); - } - - this.once('newConnection', newConnectionListener); - - timeout = setTimeout(() => { - this.removeListener('newConnection', newConnectionListener); - callback(new errors.OperationTimedOutError('A connection could not be acquired before timeout.')); - }, metadataQueryAbortTimeout); - }); - } - - /** - * Executes a query using the active connection - * @param {String|Request} cqlQuery - * @param {Boolean} [waitReconnect] Determines if it should wait for reconnection in case the control connection is not - * connected at the moment. Default: true. - */ - async query(cqlQuery, waitReconnect = true) { - const queryOnConnection = async () => { - if (!this.connection || this._isShuttingDown) { - throw new errors.NoHostAvailableError({}, 'ControlConnection is not connected at the time'); - } - - const request = typeof cqlQuery === 'string' ? new requests.QueryRequest(cqlQuery, null, null) : cqlQuery; - return await this.connection.send(request, null); - }; - - if (!this.connection && waitReconnect) { - // Wait until its reconnected (or timer elapses) - await this._waitForReconnection(); - } - - return await queryOnConnection(); - } - - /** @returns {Encoder} The encoder used by the current connection */ - getEncoder() { - if (!this._encoder) { - throw new errors.DriverInternalError('Encoder is not defined'); - } - return this._encoder; - } - - /** - * Cancels all timers and shuts down synchronously. - */ - shutdown() { - this._isShuttingDown = true; - this._debouncer.shutdown(); - // Emit a "newConnection" event with Error, as it may clear timeouts that were waiting new connections - this.emit('newConnection', new errors.DriverError('ControlConnection is being shutdown')); - // Cancel timers - clearTimeout(this._topologyChangeTimeout); - clearTimeout(this._nodeStatusChangeTimeout); - } - - /** - * Resets the Connection to its initial state. - */ - async reset() { - // Reset the internal state of the ControlConnection for future initialization attempts - const currentHosts = this.hosts.clear(); - - // Set the shutting down flag temporarily to avoid reconnects. - this._isShuttingDown = true; - - // Shutdown all individual pools, ignoring any shutdown error - await Promise.all(currentHosts.map(h => h.shutdown())); - - this.initialized = false; - this._isShuttingDown = false; - } - - /** - * Gets a Map containing the original contact points and the addresses that each one resolved to. - */ - getResolvedContactPoints() { - return this._resolvedContactPoints; - } - - /** - * Gets the local IP address to which the control connection socket is bound to. - * @returns {String|undefined} - */ - getLocalAddress() { - if (!this.connection) { - return undefined; - } - - return this.connection.getLocalAddress(); - } - - /** - * Gets the address and port of host the control connection is connected to. - * @returns {String|undefined} - */ - getEndpoint() { - if (!this.connection) { - return undefined; - } - - return this.connection.endpoint; - } -} - -/** - * Parses the DSE workload and assigns it to a host. - * @param {Host} host - * @param {Row} row - * @private - */ -function setDseParameters(host, row) { - if (row['workloads'] !== undefined) { - host.workloads = row['workloads']; - } - else if (row['workload']) { - host.workloads = [ row['workload'] ]; - } - else { - host.workloads = utils.emptyArray; - } - - if (row['dse_version'] !== undefined) { - host.dseVersion = row['dse_version']; - } -} - -module.exports = ControlConnection; diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/datastax/cloud/index.js b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/datastax/cloud/index.js deleted file mode 100644 index 8177cbb43c..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/datastax/cloud/index.js +++ /dev/null @@ -1,334 +0,0 @@ -/* - * Copyright DataStax, Inc. - * - * 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 https = require('https'); -const fs = require('fs'); -const util = require('util'); -const AdmZip = require('adm-zip'); -const { URL } = require('url'); - -const errors = require('../../errors'); -const utils = require('../../utils'); -const { DsePlainTextAuthProvider, NoAuthProvider } = require('../../auth'); - -// Use the callback-based method fs.readFile() instead of fs.promises as we have to support Node.js 8+ -const readFile = util.promisify(fs.readFile); - -/** - * When the user sets the cloud options, it uses the secure bundle or endpoint to access the metadata service and - * setting the connection options - * @param {ClientOptions} options - * @returns {Promise} - */ -async function init(options) { - if (!options.cloud) { - return; - } - - const cloudOptions = new CloudOptions(options); - await parseZipFile(cloudOptions); - await getMetadataServiceInfoAsync(cloudOptions); - - if (!cloudOptions.clientOptions.sslOptions.checkServerIdentity) { - // With SNI enabled, hostname (uuid) and CN will not match - // Use a custom validation function to validate against the proxy address. - // Note: this function is only called if the certificate passed all other checks, like CA validation. - cloudOptions.clientOptions.sslOptions.checkServerIdentity = (_, cert) => - checkServerIdentity(cert, cloudOptions.clientOptions.sni.address); - } -} - -class CloudOptions { - constructor(clientOptions) { - this.clientOptions = clientOptions; - - if (clientOptions.cloud.secureConnectBundle) { - this.secureConnectBundle = clientOptions.cloud.secureConnectBundle; - this.serviceUrl = null; - } else { - this.serviceUrl = clientOptions.cloud.endpoint; - } - - this.contactPoints = null; - this.localDataCenter = null; - } - - /** - * The sslOptions in the client options from a given map. - * @param {Map} zipEntries - */ - setSslOptions(zipEntries) { - this.clientOptions.sslOptions = Object.assign({ - ca: [zipEntries.get('ca.crt') ], - cert: zipEntries.get('cert'), - key: zipEntries.get('key'), - rejectUnauthorized: true - }, this.clientOptions.sslOptions); - } - - /** - * - * @param username - * @param password - */ - setAuthProvider(username, password) { - if (!username || !password) { - return; - } - - if (this.clientOptions.authProvider && !(this.clientOptions.authProvider instanceof NoAuthProvider)) { - // There is an auth provider set by the user - return; - } - - this.clientOptions.authProvider = new DsePlainTextAuthProvider(username, password); - } -} - -/** - * @param {CloudOptions} cloudOptions - * @returns {Promise} - */ -async function parseZipFile(cloudOptions) { - if (cloudOptions.serviceUrl) { - // Service url already was provided - return; - } - - if (!cloudOptions.secureConnectBundle) { - throw new TypeError('secureConnectBundle must be provided'); - } - - const data = await readFile(cloudOptions.secureConnectBundle); - const zip = new AdmZip(data); - const zipEntries = new Map(zip.getEntries().map(e => [e.entryName, e.getData()])); - - if (!zipEntries.get('config.json')) { - throw new TypeError('Config file must be contained in secure bundle'); - } - - const config = JSON.parse(zipEntries.get('config.json').toString('utf8')); - if (!config['host'] || !config['port']) { - throw new TypeError('Config file must include host and port information'); - } - - cloudOptions.serviceUrl = `${config['host']}:${config['port']}/metadata`; - cloudOptions.setSslOptions(zipEntries); - cloudOptions.setAuthProvider(config.username, config.password); -} - -/** - * Gets the information retrieved from the metadata service. - * Invokes the callback with {proxyAddress, localDataCenter, contactPoints} as result - * @param {CloudOptions} cloudOptions - * @param {Function} callback - */ -function getMetadataServiceInfo(cloudOptions, callback) { - const regex = /^(.+?):(\d+)(.*)$/; - const matches = regex.exec(cloudOptions.serviceUrl); - callback = utils.callbackOnce(callback); - - if (!matches || matches.length !== 4) { - throw new TypeError('url should be composed of host, port number and path, without scheme'); - } - - const requestOptions = Object.assign({ - hostname: matches[1], - port: matches[2], - path: matches[3] || undefined, - timeout: cloudOptions.clientOptions.socketOptions.connectTimeout - }, cloudOptions.clientOptions.sslOptions); - - const req = https.get(requestOptions, res => { - let data = ''; - - res - .on('data', chunk => data += chunk.toString()) - .on('end', () => { - if (res.statusCode !== 200) { - return callback(getServiceRequestError(new Error(`Obtained http status ${res.statusCode}`), requestOptions)); - } - - let message; - - try { - message = JSON.parse(data); - - if (!message || !message['contact_info']) { - throw new TypeError('contact_info should be defined in response'); - } - - } catch (err) { - return callback(getServiceRequestError(err, requestOptions, true)); - } - - const contactInfo = message['contact_info']; - - // Set the connect options - cloudOptions.clientOptions.contactPoints = contactInfo['contact_points']; - cloudOptions.clientOptions.localDataCenter = contactInfo['local_dc']; - cloudOptions.clientOptions.sni = { address: contactInfo['sni_proxy_address'] }; - - callback(); - }); - }); - - req.on('error', err => callback(getServiceRequestError(err, requestOptions))); - - // We need to both set the timeout in the requestOptions and invoke ClientRequest#setTimeout() - // to handle all possible scenarios, for some reason... (tested with one OR the other and didn't fully work) - // Setting the also the timeout handler, aborting will emit 'error' and close - req.setTimeout(cloudOptions.clientOptions.socketOptions.connectTimeout, () => req.abort()); -} - -const getMetadataServiceInfoAsync = util.promisify(getMetadataServiceInfo); - -/** - * Returns an Error that wraps the inner error obtained while fetching metadata information. - * @private - */ -function getServiceRequestError(err, requestOptions, isParsingError) { - const message = isParsingError - ? 'There was an error while parsing the metadata service information' - : 'There was an error fetching the metadata information'; - - const url = `${requestOptions.hostname}:${requestOptions.port}${(requestOptions.path) ? requestOptions.path : '/'}`; - return new errors.NoHostAvailableError({ [url] : err }, message); -} - -/** - * @param {{subject: {CN: string}, subjectaltname: string?}} cert A certificate object as defined by - * TLS module https://nodejs.org/docs/latest-v12.x/api/tls.html#tls_certificate_object - * @param {string} sniAddress - * @returns {Error|undefined} Similar to tls.checkServerIdentity() returns an Error object, populating it with reason, - * host, and cert on failure. Otherwise, it returns undefined. - * @internal - * @ignore - */ -function checkServerIdentity(cert, sniAddress) { - // Based on logic defined by the Node.js Core module - // https://github.com/nodejs/node/blob/ff48009fefcecedfee2c6ff1719e5be3f6969049/lib/tls.js#L212-L290 - - // SNI address is composed by hostname and port - const hostName = sniAddress.split(':')[0]; - const altNames = cert.subjectaltname; - const cn = cert.subject.CN; - - if (hostName === cn) { - // quick check based on common name - return undefined; - } - - const parsedAltNames = []; - if (altNames) { - for (const name of altNames.split(', ')) { - if (name.startsWith('DNS:')) { - parsedAltNames.push(name.slice(4)); - } else if (name.startsWith('URI:')) { - parsedAltNames.push(new URL(name.slice(4)).hostname); - } - } - } - - const hostParts = hostName.split('.'); - const wildcard = (pattern) => checkParts(hostParts, pattern); - - let valid; - if (parsedAltNames.length > 0) { - valid = parsedAltNames.some(wildcard); - } else { - // Use the common name - valid = wildcard(cn); - } - - if (!valid) { - const error = new Error(`Host: ${hostName} is not cert's CN/altnames: ${cn} / ${altNames}`); - error.reason = error.message; - error.host = hostName; - error.cert = cert; - return error; - } -} - -/** - * Simplified version of Node.js tls core lib check() function - * https://github.com/nodejs/node/blob/ff48009fefcecedfee2c6ff1719e5be3f6969049/lib/tls.js#L148-L209 - * @private - * @returns {boolean} - */ -function checkParts(hostParts, pattern) { - // Empty strings, null, undefined, etc. never match. - if (!pattern) { - return false; - } - - const patternParts = pattern.split('.'); - - if (hostParts.length !== patternParts.length) { - return false; - } - - // Check host parts from right to left first. - for (let i = hostParts.length - 1; i > 0; i -= 1) { - if (hostParts[i] !== patternParts[i]) { - return false; - } - } - - const hostSubdomain = hostParts[0]; - const patternSubdomain = patternParts[0]; - const patternSubdomainParts = patternSubdomain.split('*'); - - // Short-circuit when the subdomain does not contain a wildcard. - // RFC 6125 does not allow wildcard substitution for components - // containing IDNA A-labels (Punycode) so match those verbatim. - if (patternSubdomainParts.length === 1 || patternSubdomain.includes('xn--')) { - return hostSubdomain === patternSubdomain; - } - - // More than one wildcard is always wrong. - if (patternSubdomainParts.length > 2) { - return false; - } - - // *.tld wildcards are not allowed. - if (patternParts.length <= 2) { - return false; - } - - const [prefix, suffix] = patternSubdomainParts; - - if (prefix.length + suffix.length > hostSubdomain.length) { - return false; - } - - if (!hostSubdomain.startsWith(prefix)) { - return false; - } - - if (!hostSubdomain.endsWith(suffix)) { - return false; - } - - return true; -} - -module.exports = { - checkServerIdentity, - init -}; \ No newline at end of file diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/datastax/graph/complex-type-helper.js b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/datastax/graph/complex-type-helper.js deleted file mode 100644 index 130bf0a1d0..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/datastax/graph/complex-type-helper.js +++ /dev/null @@ -1,99 +0,0 @@ -/* - * Copyright DataStax, Inc. - * - * 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 { GraphTypeWrapper, UdtGraphWrapper } = require('./wrappers'); -const types = require('../../types'); -const Encoder = require('../../encoder'); -const { dataTypes } = types; - -function getTypeDefinitionByValue(value) { - if (value instanceof types.Tuple) { - return { - 'cqlType': 'tuple', - 'definition': value.elements.map(getTypeDefinitionByValue) - }; - } - - if (value instanceof Map) { - // Try to guess the types of the key and value based on the first element - const result = { 'cqlType': 'map' }; - if (value.size > 0) { - const first = value.entries().next().value; - result['definition'] = first.map(getTypeDefinitionByValue); - } - - return result; - } - - if (value instanceof UdtGraphWrapper) { - return getUdtTypeDefinitionByValue(value); - } - - let type; - if (value instanceof GraphTypeWrapper) { - type = value.typeInfo; - } else { - type = Encoder.guessDataType(value); - } - - if (!type) { - return null; - } - - return getDefinitionByType(type); -} - -function getDefinitionByType(type) { - if (type.code === dataTypes.udt) { - return getUdtTypeDefinition(type.info); - } - - if (type.code === dataTypes.tuple || type.code === dataTypes.map) { - return { - 'cqlType': types.getDataTypeNameByCode(type), - 'definition': type.info.map(getDefinitionByType) - }; - } - - if (type.code === dataTypes.list || type.code === dataTypes.set) { - return { - 'cqlType': type.code === dataTypes.list ? 'list' : 'set', - 'definition': [ getDefinitionByType(type.info) ] - }; - } - - return { 'cqlType': types.getDataTypeNameByCode(type) }; -} - -function getUdtTypeDefinition(udtInfo) { - return { - 'cqlType': 'udt', - 'keyspace': udtInfo.keyspace, - 'name': udtInfo.name, - 'definition': udtInfo.fields.map(field => - // fieldName should be the first property serialized - Object.assign({ 'fieldName': field.name }, getDefinitionByType(field.type)) - ), - }; -} - -function getUdtTypeDefinitionByValue(wrappedValue) { - return getUdtTypeDefinition(wrappedValue.udtInfo); -} - -module.exports = { getTypeDefinitionByValue, getUdtTypeDefinitionByValue }; \ No newline at end of file diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/datastax/graph/custom-type-serializers.js b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/datastax/graph/custom-type-serializers.js deleted file mode 100644 index e25ef3bbc9..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/datastax/graph/custom-type-serializers.js +++ /dev/null @@ -1,362 +0,0 @@ -/* - * Copyright DataStax, Inc. - * - * 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 types = require('../../types'); -const utils = require('../../utils'); -const { getTypeDefinitionByValue, getUdtTypeDefinitionByValue } = require('./complex-type-helper'); -const { Point, Polygon, LineString } = require('../../geometry'); -const { Edge } = require('./structure'); -const { GraphTypeWrapper, UdtGraphWrapper } = require('./wrappers'); -const { Tuple, dataTypes } = types; - -const typeKey = '@type'; -const valueKey = '@value'; - -class EdgeDeserializer { - constructor() { - this.key = 'g:Edge'; - } - - deserialize(obj) { - const value = obj[valueKey]; - return new Edge(this.reader.read(value['id']), this.reader.read(value['outV']), value['outVLabel'], value['label'], this.reader.read(value['inV']), value['inVLabel'], this.reader.read(value['properties'])); - } -} - -/** - * Uses toString() instance method and fromString() static method to serialize and deserialize the value. - * @abstract - * @private - */ -class StringBasedTypeSerializer { - - /** - * Creates a new instance of the deserializer. - * @param {String} key - * @param {Function} targetType - */ - constructor(key, targetType) { - if (!key) { - throw new Error('Deserializer must provide a type key'); - } - if (!targetType) { - throw new Error('Deserializer must provide a target type'); - } - this.key = key; - this.targetType = targetType; - } - - deserialize(obj) { - let value = obj[valueKey]; - if (typeof value !== 'string') { - value = value.toString(); - } - return this.targetType.fromString(value); - } - - serialize(value) { - return { - [typeKey]: this.key, - [valueKey]: value.toString() - }; - } - - canBeUsedFor(value) { - return value instanceof this.targetType; - } -} - -class UuidSerializer extends StringBasedTypeSerializer { - constructor() { - super('g:UUID', types.Uuid); - } -} - -class LongSerializer extends StringBasedTypeSerializer { - constructor() { - super('g:Int64', types.Long); - } -} - -class BigDecimalSerializer extends StringBasedTypeSerializer { - constructor() { - super('gx:BigDecimal', types.BigDecimal); - } -} - -class BigIntegerSerializer extends StringBasedTypeSerializer { - constructor() { - super('gx:BigInteger', types.Integer); - } -} - -class InetAddressSerializer extends StringBasedTypeSerializer { - constructor() { - super('gx:InetAddress', types.InetAddress); - } -} - -class LocalDateSerializer extends StringBasedTypeSerializer { - constructor() { - super('gx:LocalDate', types.LocalDate); - } -} - -class LocalTimeSerializer extends StringBasedTypeSerializer { - constructor() { - super('gx:LocalTime', types.LocalTime); - } -} - -class InstantSerializer extends StringBasedTypeSerializer { - constructor() { - super('gx:Instant', Date); - } - - serialize(item) { - return { - [typeKey]: this.key, - [valueKey]: item.toISOString() - }; - } - - deserialize(obj) { - return new Date(obj[valueKey]); - } -} - -class BlobSerializer extends StringBasedTypeSerializer { - constructor() { - super('dse:Blob', Buffer); - } - - deserialize(obj) { - return utils.allocBufferFromString(obj[valueKey], 'base64'); - } - - serialize(item) { - return { - [typeKey]: this.key, - [valueKey]: item.toString('base64') - }; - } -} - -class PointSerializer extends StringBasedTypeSerializer { - constructor() { - super('dse:Point', Point); - } -} - -class LineStringSerializer extends StringBasedTypeSerializer { - constructor() { - super('dse:LineString', LineString); - } -} - -class PolygonSerializer extends StringBasedTypeSerializer { - constructor() { - super('dse:Polygon', Polygon); - } -} - -class TupleSerializer { - constructor() { - this.key = 'dse:Tuple'; - } - - deserialize(obj) { - // Skip definitions and go to the value - const value = obj[valueKey]['value']; - - if (!Array.isArray(value)) { - throw new Error('Expected Array, obtained: ' + value); - } - - const result = []; - - for (const element of value) { - result.push(this.reader.read(element)); - } - - return Tuple.fromArray(result); - } - - /** @param {Tuple} tuple */ - serialize(tuple) { - const result = { - 'cqlType': 'tuple', - 'definition': tuple.elements.map(getTypeDefinitionByValue), - 'value': tuple.elements.map(e => this.writer.adaptObject(e)) - }; - - return { - [typeKey]: this.key, - [valueKey]: result - }; - } - - canBeUsedFor(value) { - return value instanceof Tuple; - } -} - -class DurationSerializer { - constructor() { - this.key = 'dse:Duration'; - } - - deserialize(obj) { - // Skip definitions and go to the value - const value = obj[valueKey]; - - return new types.Duration( - this.reader.read(value['months']), this.reader.read(value['days']), this.reader.read(value['nanos'])); - } - - /** @param {Duration} value */ - serialize(value) { - return { - [typeKey]: this.key, - [valueKey]: { - 'months': value['months'], - 'days': value['days'], - 'nanos': value['nanoseconds'], - } - }; - } - - canBeUsedFor(value) { - return value instanceof types.Duration; - } -} - -class UdtSerializer { - constructor() { - this.key = 'dse:UDT'; - } - - deserialize(obj) { - // Skip definitions and go to the value - const valueRoot = obj[valueKey]; - const result = {}; - const value = valueRoot['value']; - - valueRoot['definition'].forEach((definition, index) => { - result[definition.fieldName] = this.reader.read(value[index]); - }); - - return result; - } - - serialize(udtWrapper) { - const serializedValue = getUdtTypeDefinitionByValue(udtWrapper); - // New properties can be added to the existing object without need to clone - // as getTypeDefinition() returns a new object each time - serializedValue['value'] = Object.entries(udtWrapper.value).map(([_, v]) => this.writer.adaptObject(v)); - - return { - [typeKey]: this.key, - [valueKey]: serializedValue - }; - } - - canBeUsedFor(value) { - return value instanceof UdtGraphWrapper; - } -} - -class InternalSerializer { - constructor(name, transformFn) { - this._name = name; - this._transformFn = transformFn || (x => x); - } - - serialize(item) { - return { - [typeKey]: this._name, - [valueKey]: this._transformFn(item) - }; - } -} - -// Associative array of graph type name by CQL type code, used by the type wrapper -const graphSONSerializerByCqlType = { - [dataTypes.int]: new InternalSerializer('g:Int32'), - [dataTypes.bigint]: new InternalSerializer('g:Int64'), - [dataTypes.double]: new InternalSerializer('g:Double'), - [dataTypes.float]: new InternalSerializer('g:Float'), - [dataTypes.timestamp]: new InternalSerializer('g:Timestamp', x => x.getTime()) -}; - -class GraphTypeWrapperSerializer { - constructor() { - // Use a fixed name that doesn't conflict with TinkerPop and DS Graph - this.key = 'client:wrapper'; - } - - serialize(wrappedValue) { - const s = graphSONSerializerByCqlType[wrappedValue.typeInfo.code]; - - if (!s) { - throw new Error(`No serializer found for wrapped value ${wrappedValue}`); - } - - return s.serialize(wrappedValue.value); - } - - canBeUsedFor(value) { - return value instanceof GraphTypeWrapper; - } -} - -const serializersArray = [ - EdgeDeserializer, - UuidSerializer, - LongSerializer, - BigDecimalSerializer, - BigIntegerSerializer, - InetAddressSerializer, - LocalDateSerializer, - LocalTimeSerializer, - InstantSerializer, - BlobSerializer, - PointSerializer, - LineStringSerializer, - PolygonSerializer, - TupleSerializer, - UdtSerializer, - GraphTypeWrapperSerializer, - DurationSerializer -]; - -function getCustomSerializers() { - const customSerializers = {}; - - serializersArray.forEach(sConstructor => { - const instance = new sConstructor(); - if (!instance.key) { - throw new TypeError(`Key for ${sConstructor} instance not set`); - } - - customSerializers[instance.key] = instance; - }); - - return customSerializers; -} - -module.exports = getCustomSerializers; \ No newline at end of file diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/datastax/graph/graph-executor.js b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/datastax/graph/graph-executor.js deleted file mode 100644 index 7015826759..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/datastax/graph/graph-executor.js +++ /dev/null @@ -1,280 +0,0 @@ -/* - * Copyright DataStax, Inc. - * - * 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 utils = require('../../utils'); -const policies = require('../../policies'); -const GraphResultSet = require('./result-set'); -const { GraphSON2Reader, GraphSON2Writer, GraphSON3Reader, GraphSON3Writer } = require('./graph-serializer'); -const getCustomTypeSerializers = require('./custom-type-serializers'); -const { GraphExecutionOptions, graphProtocol } = require('./options'); - -const graphLanguageGroovyString = 'gremlin-groovy'; -const graphEngineCore = 'Core'; - -const graphSON2Reader = new GraphSON2Reader({ serializers: getCustomTypeSerializers() }); -const graphSON2Writer = new GraphSON2Writer({ serializers: getCustomTypeSerializers() }); -const graphSON3Reader = new GraphSON3Reader({ serializers: getCustomTypeSerializers() }); -const graphSON3Writer = new GraphSON3Writer({ serializers: getCustomTypeSerializers() }); - -const rowParsers = new Map([ - [ graphProtocol.graphson2, getRowParser(graphSON2Reader) ], - [ graphProtocol.graphson3, getRowParser(graphSON3Reader) ] -]); - -const defaultWriters = new Map([ - [ graphProtocol.graphson1, x => JSON.stringify(x) ], - [ graphProtocol.graphson2, getDefaultWriter(graphSON2Writer) ], - [ graphProtocol.graphson3, getDefaultWriter(graphSON3Writer) ] -]); - -/** - * Internal class that contains the logic for executing a graph traversal. - * @ignore - */ -class GraphExecutor { - - /** - * Creates a new instance of GraphExecutor. - * @param {Client} client - * @param {ClientOptions} rawOptions - * @param {Function} handler - */ - constructor(client, rawOptions, handler) { - this._client = client; - this._handler = handler; - - // Retrieve the retry policy for the default profile to determine if it was specified - this._defaultProfileRetryPolicy = client.profileManager.getDefaultConfiguredRetryPolicy(); - - // Use graphBaseOptions as a way to gather all defaults that affect graph executions - this._graphBaseOptions = utils.extend({ - executeAs: client.options.queryOptions.executeAs, - language: graphLanguageGroovyString, - source: 'g', - readTimeout: 0, - // As the default retry policy might retry non-idempotent queries - // we should use default retry policy for all graph queries that does not retry - retry: new policies.retry.FallthroughRetryPolicy() - }, rawOptions.graphOptions, client.profileManager.getDefault().graphOptions); - - if (this._graphBaseOptions.readTimeout === null) { - this._graphBaseOptions.readTimeout = client.options.socketOptions.readTimeout; - } - } - - /** - * Executes the graph traversal. - * @param {String|Object} query - * @param {Object} parameters - * @param {GraphQueryOptions} options - */ - async send(query, parameters, options) { - if (Array.isArray(parameters)) { - throw new TypeError('Parameters must be a Object instance as an associative array'); - } - - if (!query) { - throw new TypeError('Query must be defined'); - } - - const execOptions = new GraphExecutionOptions( - options, this._client, this._graphBaseOptions, this._defaultProfileRetryPolicy); - - if (execOptions.getGraphSource() === 'a') { - const host = await this._getAnalyticsMaster(); - execOptions.setPreferredHost(host); - } - - // A query object that allows to plugin any executable thing - const isQueryObject = typeof query === 'object' && query.graphLanguage && query.value && query.queryWriterFactory; - - if (isQueryObject) { - // Use the provided graph language to override the current - execOptions.setGraphLanguage(query.graphLanguage); - } - - this._setGraphProtocol(execOptions); - execOptions.setGraphPayload(); - parameters = GraphExecutor._buildGraphParameters(parameters, execOptions.getGraphSubProtocol()); - - if (typeof query !== 'string') { - // Its a traversal that needs to be converted - // Transforming the provided query into a traversal requires the protocol to be set first. - // Query writer factory can be defined in the options or in the query object - let queryWriter = execOptions.getQueryWriter(); - - if (isQueryObject) { - queryWriter = query.queryWriterFactory(execOptions.getGraphSubProtocol()); - } else if (!queryWriter) { - queryWriter = GraphExecutor._writerFactory(execOptions.getGraphSubProtocol()); - } - - query = queryWriter(!isQueryObject ? query : query.value); - } - - return await this._executeGraphQuery(query, parameters, execOptions); - } - - /** - * Sends the graph traversal. - * @param {string} query - * @param {object} parameters - * @param {GraphExecutionOptions} execOptions - * @returns {Promise} - * @private - */ - async _executeGraphQuery(query, parameters, execOptions) { - const result = await this._handler.call(this._client, query, parameters, execOptions); - - // Instances of rowParser transform Row instances into Traverser instances. - // Traverser instance is an object with the following form { object: any, bulk: number } - const rowParser = execOptions.getRowParser() || GraphExecutor._rowParserFactory(execOptions.getGraphSubProtocol()); - - return new GraphResultSet(result, rowParser); - } - - /** - * Uses the RPC call to obtain the analytics master host. - * @returns {Promise} - * @private - */ - async _getAnalyticsMaster() { - try { - const result = await this._client.execute('CALL DseClientTool.getAnalyticsGraphServer()', utils.emptyArray); - - if (result.rows.length === 0) { - this._client.log('verbose', - 'Empty response querying graph analytics server, query will not be routed optimally'); - return null; - } - - const resultField = result.rows[0]['result']; - if (!resultField || !resultField['location']) { - this._client.log('verbose', - 'Unexpected response querying graph analytics server, query will not be routed optimally', - result.rows[0]); - return null; - } - - const hostName = resultField['location'].substr(0, resultField['location'].lastIndexOf(':')); - const addressTranslator = this._client.options.policies.addressResolution; - - return await new Promise(resolve => { - addressTranslator.translate(hostName, this._client.options.protocolOptions.port, (endpoint) => - resolve(this._client.hosts.get(endpoint))); - }); - } catch (err) { - this._client.log('verbose', 'Error querying graph analytics server, query will not be routed optimally', err); - return null; - } - } - - /** - * Resolves what protocol should be used for decoding graph results for the given execution. - * - *

Resolution is done in the following manner if graphResults is not set:

- * - *
    - *
  • If graph name is set, and associated keyspace's graph engine is set to "Core", use {@link - * graphProtocol#graphson3}. - *
  • Else, if the graph language is not 'gremlin-groovy', use {@link graphProtocol#graphson2} - *
  • Otherwise, use {@link graphProtocol#graphson1} - *
- * @param {GraphExecutionOptions} execOptions - */ - _setGraphProtocol(execOptions) { - let protocol = execOptions.getGraphSubProtocol(); - - if (protocol) { - return; - } - - if (execOptions.getGraphName()) { - const keyspace = this._client.metadata.keyspaces[execOptions.getGraphName()]; - if (keyspace && keyspace.graphEngine === graphEngineCore) { - protocol = graphProtocol.graphson3; - } - } - - if (!protocol) { - // Decide the minimal version supported by the graph language - if (execOptions.getGraphLanguage() === graphLanguageGroovyString) { - protocol = graphProtocol.graphson1; - } else { - protocol = graphProtocol.graphson2; - } - } - - execOptions.setGraphSubProtocol(protocol); - } - - /** - * Only GraphSON1 parameters are supported. - * @param {Array|function|null} parameters - * @param {string} protocol - * @returns {string[]|null} - * @private - */ - static _buildGraphParameters(parameters, protocol) { - if (!parameters || typeof parameters !== 'object') { - return null; - } - - const queryWriter = GraphExecutor._writerFactory(protocol); - - return [ - (protocol !== graphProtocol.graphson1 && protocol !== graphProtocol.graphson2) - ? queryWriter(new Map(Object.entries(parameters))) - : queryWriter(parameters) - ]; - } - - static _rowParserFactory(protocol) { - const handler = rowParsers.get(protocol); - - if (!handler) { - // Default to no row parser - return null; - } - - return handler; - } - - static _writerFactory(protocol) { - const handler = defaultWriters.get(protocol); - - if (!handler) { - throw new Error(`No writer defined for protocol ${protocol}`); - } - - return handler; - } -} - -function getRowParser(reader) { - return row => { - const item = reader.read(JSON.parse(row['gremlin'])); - return { object: item['result'], bulk: item['bulk'] || 1 }; - }; -} - -function getDefaultWriter(writer) { - return value => writer.write(value); -} - -module.exports = GraphExecutor; \ No newline at end of file diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/datastax/graph/graph-serializer.js b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/datastax/graph/graph-serializer.js deleted file mode 100644 index 4331161a50..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/datastax/graph/graph-serializer.js +++ /dev/null @@ -1,260 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you 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 datastax/graph/tinkerpop/graphSerializers - * @ignore - */ - - -/** - * @author Jorge Bay Gondra - */ -'use strict'; - -const typeSerializers = require('./type-serializers'); - -/** - * GraphSON2 writer. - */ -class GraphSON2Writer { - - /** - * @param {Object} [options] - * @param {Object} [options.serializers] An object used as an associative array with GraphSON 2 type name as keys and - * serializer instances as values, ie: { 'g:Int64': longSerializer }. - * @constructor - */ - constructor(options) { - this._options = options || {}; - // Create instance of the default serializers - this._serializers = this.getDefaultSerializers().map(serializerConstructor => { - const s = new serializerConstructor(); - s.writer = this; - return s; - }); - - const customSerializers = this._options.serializers || {}; - - Object.keys(customSerializers).forEach(key => { - const s = customSerializers[key]; - if (!s.serialize) { - return; - } - s.writer = this; - // Insert custom serializers first - this._serializers.unshift(s); - }); - } - - /** - * Gets the default serializers to be used. - * @returns {Array} - */ - getDefaultSerializers() { - return graphSON2Serializers; - } - - adaptObject(value) { - let s; - - for (let i = 0; i < this._serializers.length; i++) { - const currentSerializer = this._serializers[i]; - if (currentSerializer.canBeUsedFor && currentSerializer.canBeUsedFor(value)) { - s = currentSerializer; - break; - } - } - - if (s) { - return s.serialize(value); - } - - if (Array.isArray(value)) { - // We need to handle arrays when there is no serializer - // for older versions of GraphSON - return value.map(item => this.adaptObject(item)); - } - - // Default (strings / objects / ...) - return value; - } - - /** - * Returns the GraphSON representation of the provided object instance. - * @param {Object} obj - * @returns {String} - */ - write(obj) { - return JSON.stringify(this.adaptObject(obj)); - } -} - -/** - * GraphSON3 writer. - */ -class GraphSON3Writer extends GraphSON2Writer { - getDefaultSerializers() { - return graphSON3Serializers; - } -} - -/** - * GraphSON2 reader. - */ -class GraphSON2Reader { - /** - * GraphSON Reader - * @param {Object} [options] - * @param {Object} [options.serializers] An object used as an associative array with GraphSON 2 type name as keys and - * deserializer instances as values, ie: { 'g:Int64': longSerializer }. - * @constructor - */ - constructor(options) { - this._options = options || {}; - this._deserializers = {}; - - const defaultDeserializers = this.getDefaultDeserializers(); - Object.keys(defaultDeserializers).forEach(typeName => { - const serializerConstructor = defaultDeserializers[typeName]; - const s = new serializerConstructor(); - s.reader = this; - this._deserializers[typeName] = s; - }); - - if (this._options.serializers) { - const customSerializers = this._options.serializers || {}; - Object.keys(customSerializers).forEach(key => { - const s = customSerializers[key]; - if (!s.deserialize) { - return; - } - s.reader = this; - this._deserializers[key] = s; - }); - } - } - - /** - * Gets the default deserializers as an associative array. - * @returns {Object} - */ - getDefaultDeserializers() { - return graphSON2Deserializers; - } - - read(obj) { - if (obj === undefined) { - return undefined; - } - if (obj === null) { - return null; - } - if (Array.isArray(obj)) { - return obj.map(item => this.read(item)); - } - const type = obj[typeSerializers.typeKey]; - if (type) { - const d = this._deserializers[type]; - if (d) { - // Use type serializer - return d.deserialize(obj); - } - return obj[typeSerializers.valueKey]; - } - if (obj && typeof obj === 'object' && obj.constructor === Object) { - return this._deserializeObject(obj); - } - // Default (for boolean, number and other scalars) - return obj; - } - - _deserializeObject(obj) { - const keys = Object.keys(obj); - const result = {}; - for (let i = 0; i < keys.length; i++) { - result[keys[i]] = this.read(obj[keys[i]]); - } - return result; - } -} - -/** - * GraphSON3 reader. - */ -class GraphSON3Reader extends GraphSON2Reader { - getDefaultDeserializers() { - return graphSON3Deserializers; - } -} - -const graphSON2Deserializers = { - 'g:Traverser': typeSerializers.TraverserSerializer, - 'g:TraversalStrategy': typeSerializers.TraversalStrategySerializer, - 'g:Int32': typeSerializers.NumberSerializer, - 'g:Int64': typeSerializers.NumberSerializer, - 'g:Float': typeSerializers.NumberSerializer, - 'g:Double': typeSerializers.NumberSerializer, - 'g:Date': typeSerializers.DateSerializer, - 'g:Direction': typeSerializers.DirectionSerializer, - 'g:Vertex': typeSerializers.VertexSerializer, - 'g:Edge': typeSerializers.EdgeSerializer, - 'g:VertexProperty': typeSerializers.VertexPropertySerializer, - 'g:Property': typeSerializers.PropertySerializer, - 'g:Path': typeSerializers.Path3Serializer, - 'g:TextP': typeSerializers.TextPSerializer, - 'g:T': typeSerializers.TSerializer, - 'g:BulkSet': typeSerializers.BulkSetSerializer -}; - -const graphSON3Deserializers = Object.assign({}, graphSON2Deserializers, { - 'g:List': typeSerializers.ListSerializer, - 'g:Set': typeSerializers.SetSerializer, - 'g:Map': typeSerializers.MapSerializer -}); - -const graphSON2Serializers = [ - typeSerializers.NumberSerializer, - typeSerializers.DateSerializer, - typeSerializers.BytecodeSerializer, - typeSerializers.TraverserSerializer, - typeSerializers.TraversalStrategySerializer, - typeSerializers.PSerializer, - typeSerializers.TextPSerializer, - typeSerializers.LambdaSerializer, - typeSerializers.EnumSerializer, - typeSerializers.VertexSerializer, - typeSerializers.EdgeSerializer, - typeSerializers.LongSerializer -]; - -const graphSON3Serializers = graphSON2Serializers.concat([ - typeSerializers.ListSerializer, - typeSerializers.SetSerializer, - typeSerializers.MapSerializer -]); - -module.exports = { - GraphSON3Writer, - GraphSON3Reader, - GraphSON2Writer, - GraphSON2Reader, - GraphSONWriter: GraphSON3Writer, - GraphSONReader: GraphSON3Reader -}; \ No newline at end of file diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/datastax/graph/index.d.ts b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/datastax/graph/index.d.ts deleted file mode 100644 index b6e860c429..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/datastax/graph/index.d.ts +++ /dev/null @@ -1,92 +0,0 @@ -/* - * Copyright DataStax, Inc. - * - * 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. - */ - -import { types } from '../../types'; - -export namespace graph { - interface Edge extends Element { - outV?: Vertex; - outVLabel?: string; - inV?: Vertex; - inVLabel?: string; - properties?: object; - } - - interface Element { - id: any; - label: string; - } - - class GraphResultSet implements Iterator { - constructor(rs: types.ResultSet); - - first(): any; - - toArray(): any[]; - - values(): Iterator; - - next(value?: any): IteratorResult; - } - - interface Path { - labels: any[]; - objects: any[]; - } - - interface Property { - value: any - key: any - } - - interface Vertex extends Element { - properties?: { [key: string]: any[] } - } - - interface VertexProperty extends Element { - value: any - key: string - properties?: any - } - - function asDouble(value: number): object; - - function asFloat(value: number): object; - - function asInt(value: number): object; - - function asTimestamp(value: Date): object; - - function asUdt(value: object): object; - - interface EnumValue { - toString(): string - } - - namespace t { - const id: EnumValue; - const key: EnumValue; - const label: EnumValue; - const value: EnumValue; - } - - namespace direction { - // `in` is a reserved word - const in_: EnumValue; - const out: EnumValue; - const both: EnumValue; - } -} \ No newline at end of file diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/datastax/graph/index.js b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/datastax/graph/index.js deleted file mode 100644 index a0333a06ef..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/datastax/graph/index.js +++ /dev/null @@ -1,82 +0,0 @@ -/* - * Copyright DataStax, Inc. - * - * 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'; - -/** - * Graph module. - * @module datastax/graph - */ - -const GraphResultSet = require('./result-set'); -const getCustomTypeSerializers = require('./custom-type-serializers'); -const { asInt, asDouble, asFloat, asTimestamp, asUdt, UdtGraphWrapper, GraphTypeWrapper} = require('./wrappers'); -const { Edge, Element, Path, Property, Vertex, VertexProperty } = require('./structure'); - -class EnumValue { - constructor(typeName, elementName) { - this.typeName = typeName; - this.elementName = elementName; - } - - toString() { - return this.elementName; - } -} - -/** - * Represents a collection of tokens for more concise Traversal definitions. - */ -const t = { - id: new EnumValue('T', 'id'), - key: new EnumValue('T', 'key'), - label: new EnumValue('T', 'label'), - value: new EnumValue('T', 'value'), -}; - -/** - * Represents the edge direction. - */ -const direction = { - 'both': new EnumValue('Direction', 'BOTH'), - 'in': new EnumValue('Direction', 'IN'), - 'out': new EnumValue('Direction', 'OUT') -}; - -// `in` is a reserved keyword depending on the context -// TinkerPop JavaScript GLV only exposes `in` but it can lead to issues for TypeScript users and others. -// Expose an extra property to represent `Direction.IN`. -direction.in_ = direction.in; - -module.exports = { - Edge, - Element, - Path, - Property, - Vertex, - VertexProperty, - - asInt, - asDouble, - asFloat, - asTimestamp, - asUdt, - direction, - getCustomTypeSerializers, - GraphResultSet, - GraphTypeWrapper, - t, - UdtGraphWrapper -}; \ No newline at end of file diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/datastax/graph/options.js b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/datastax/graph/options.js deleted file mode 100644 index 2e0e7e711e..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/datastax/graph/options.js +++ /dev/null @@ -1,334 +0,0 @@ -/* - * Copyright DataStax, Inc. - * - * 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 util = require('util'); -const types = require('../../types'); -const utils = require('../../utils'); -const { DefaultExecutionOptions, proxyExecuteKey } = require('../../execution-options'); -const Long = types.Long; - -let consistencyNames; - -const graphProtocol = Object.freeze({ - graphson1: 'graphson-1.0', - graphson2: 'graphson-2.0', - graphson3: 'graphson-3.0' -}); - -const payloadKeys = Object.freeze({ - language :'graph-language', - source: 'graph-source', - name: 'graph-name', - results: 'graph-results', - writeConsistency: 'graph-write-consistency', - readConsistency: 'graph-read-consistency', - timeout: 'request-timeout' -}); - -/** - * Graph options that extends {@link QueryOptions}. - *

- * Consider using [execution profiles]{@link ExecutionProfile} if you plan to reuse options across different - * query executions. - *

- * @typedef {QueryOptions} module:datastax/graph~GraphQueryOptions - * @property {String} [graphLanguage] The graph language to use in graph queries. - * @property {String} [graphResults] The protocol to use for serializing and deserializing graph results. - *

- * Note that this value should rarely be set by users and will otherwise be unset. When unset the server resolves - * the protocol based on the graphLanguage specified. - *

- * @property {String} [graphName] The graph name to be used in the query. You can use null to clear the - * value from the DseClientOptions and execute a query without a default graph. - * @property {Number} [graphReadConsistency] Specifies the - * [consistency level]{@link module:types~consistencies} - * to be used for the graph read queries in this execution. - *

- * When defined, it overrides the consistency level only for the READ part of the graph query. - *

- * @property {String} [graphSource] The graph traversal source name to use in graph queries. - * @property {Number} [graphWriteConsistency] Specifies the [consistency level]{@link module:types~consistencies} to - * be used for the graph write queries in this execution. - *

- * When defined, it overrides the consistency level only for the WRITE part of the graph query. - *

- * @property {RetryPolicy} [retry] Sets the retry policy to be used for the graph query execution. - *

- * When not specified in the {@link GraphQueryOptions} or in the {@link ExecutionProfile}, it will use by default - * a retry policy that does not retry graph executions. - *

- */ - -/** - * Gets the default options with the custom payload for a given profile. - * @param {ProfileManager} profileManager - * @param baseOptions - * @param {RetryPolicy|null} defaultRetryPolicy - * @param {ExecutionProfile} profile - * @returns {DseClientOptions} - * @private - */ -function getDefaultGraphOptions(profileManager, baseOptions, defaultRetryPolicy, profile) { - return profileManager.getOrCreateGraphOptions(profile, function createDefaultOptions() { - const profileOptions = profile.graphOptions || utils.emptyObject; - const defaultProfile = profileManager.getDefault(); - const options = { - customPayload: { - [payloadKeys.language]: utils.allocBufferFromString(profileOptions.language || baseOptions.language), - [payloadKeys.source]: utils.allocBufferFromString(profileOptions.source || baseOptions.source) - }, - graphLanguage: profileOptions.language || baseOptions.language, - graphResults: profileOptions.results || baseOptions.results, - graphSource: profileOptions.source || baseOptions.source, - graphName: utils.ifUndefined(profileOptions.name, baseOptions.name) - }; - - if (profile !== defaultProfile) { - options.retry = profile.retry || baseOptions.retry; - } else { - // Based on an implementation detail of the execution profiles, the retry policy for the default profile is - // always loaded (required), but that doesn't mean that it was specified by the user. - // If it wasn't specified by the user, use the default retry policy for graph statements. - options.retry = defaultRetryPolicy || baseOptions.retry; - } - - if (baseOptions.executeAs) { - options.customPayload[proxyExecuteKey] = utils.allocBufferFromString(baseOptions.executeAs); - } - - if (options.graphName) { - options.customPayload[payloadKeys.name] = utils.allocBufferFromString(options.graphName); - } - - const graphResults = utils.ifUndefined(profileOptions.results, baseOptions.graphResults); - if (graphResults !== undefined) { - options.customPayload[payloadKeys.results] = utils.allocBufferFromString(graphResults); - } - - const readConsistency = utils.ifUndefined(profileOptions.readConsistency, baseOptions.readConsistency); - if (readConsistency !== undefined) { - options.customPayload[payloadKeys.readConsistency] = - utils.allocBufferFromString(getConsistencyName(readConsistency)); - } - - const writeConsistency = utils.ifUndefined(profileOptions.writeConsistency, baseOptions.writeConsistency); - if (writeConsistency !== undefined) { - options.customPayload[payloadKeys.writeConsistency] = - utils.allocBufferFromString(getConsistencyName(writeConsistency)); - } - - options.readTimeout = utils.ifUndefined3(profile.readTimeout, defaultProfile.readTimeout, baseOptions.readTimeout); - if (options.readTimeout > 0) { - // Write the graph read timeout payload - options.customPayload[payloadKeys.timeout] = longBuffer(options.readTimeout); - } - - return options; - }); -} - -/** - * Sets the payload key. If the value is not provided, it uses the value from the default profile options. - * @param {Object} payload - * @param {QueryOptions} profileOptions - * @param {String} key - * @param {String|Number|null} value - * @param {Function} [converter] - * @private - */ -function setPayloadKey(payload, profileOptions, key, value, converter) { - converter = converter || utils.allocBufferFromString; - if (value === null) { - // Use null to avoid set payload for a key - return; - } - - if (value !== undefined) { - payload[key] = converter(value); - return; - } - - if (profileOptions.customPayload[key]) { - payload[key] = profileOptions.customPayload[key]; - } -} - -function longBuffer(value) { - value = Long.fromNumber(value); - return Long.toBuffer(value); -} - -/** - * Gets the name in upper case of the consistency level. - * @param {Number} consistency - * @private - */ -function getConsistencyName(consistency) { - // eslint-disable-next-line - if (consistency == undefined) { - //null or undefined => undefined - return undefined; - } - loadConsistencyNames(); - const name = consistencyNames[consistency]; - if (!name) { - throw new Error(util.format( - 'Consistency %s not found, use values defined as properties in types.consistencies object', consistency - )); - } - return name; -} - -function loadConsistencyNames() { - if (consistencyNames) { - return; - } - consistencyNames = {}; - const propertyNames = Object.keys(types.consistencies); - for (let i = 0; i < propertyNames.length; i++) { - const name = propertyNames[i]; - consistencyNames[types.consistencies[name]] = name.toUpperCase(); - } - //Using java constants naming conventions - consistencyNames[types.consistencies.localQuorum] = 'LOCAL_QUORUM'; - consistencyNames[types.consistencies.eachQuorum] = 'EACH_QUORUM'; - consistencyNames[types.consistencies.localSerial] = 'LOCAL_SERIAL'; - consistencyNames[types.consistencies.localOne] = 'LOCAL_ONE'; -} - -/** - * Represents a wrapper around the options related to a graph execution. - * @internal - * @ignore - */ -class GraphExecutionOptions extends DefaultExecutionOptions { - - /** - * Creates a new instance of GraphExecutionOptions. - * @param {GraphQueryOptions} queryOptions The user provided query options. - * @param {Client} client the client instance. - * @param graphBaseOptions The default graph base options. - * @param {RetryPolicy} defaultProfileRetryPolicy - */ - constructor(queryOptions, client, graphBaseOptions, defaultProfileRetryPolicy) { - - queryOptions = queryOptions || utils.emptyObject; - super(queryOptions, client, null); - - this._defaultGraphOptions = getDefaultGraphOptions( - client.profileManager, graphBaseOptions, defaultProfileRetryPolicy, this.getProfile()); - - this._preferredHost = null; - this._graphSubProtocol = queryOptions.graphResults || this._defaultGraphOptions.graphResults; - this._graphLanguage = queryOptions.graphLanguage || this._defaultGraphOptions.graphLanguage; - } - - setPreferredHost(host) { - this._preferredHost = host; - } - - getPreferredHost() { - return this._preferredHost; - } - - getGraphSource() { - return this.getRawQueryOptions().graphSource || this._defaultGraphOptions.graphSource; - } - - getGraphLanguage() { - return this._graphLanguage; - } - - setGraphLanguage(value) { - this._graphLanguage = value; - } - - getGraphName() { - return utils.ifUndefined(this.getRawQueryOptions().graphName, this._defaultGraphOptions.graphName); - } - - getGraphSubProtocol() { - return this._graphSubProtocol; - } - - setGraphSubProtocol(protocol) { - this._graphSubProtocol = protocol; - } - - /** Graph executions have a specific default read timeout */ - getReadTimeout() { - return this.getRawQueryOptions().readTimeout || this._defaultGraphOptions.readTimeout; - } - - /** Graph executions have a specific default retry policy */ - getRetryPolicy() { - return this.getRawQueryOptions().retry || this._defaultGraphOptions.retry; - } - - getRowParser() { - const factory = this.getRawQueryOptions().rowParserFactory; - - if (!factory) { - return null; - } - - return factory(this.getGraphSubProtocol()); - } - - getQueryWriter() { - const factory = this.getRawQueryOptions().queryWriterFactory; - - if (!factory) { - return null; - } - - return factory(this.getGraphSubProtocol()); - } - - setGraphPayload() { - const options = this.getRawQueryOptions(); - const defaultOptions = this._defaultGraphOptions; - - // Clone the existing custom payload (if any) - const payload = Object.assign({}, this.getCustomPayload()); - - // Override the payload for DSE Graph exclusive options - setPayloadKey(payload, defaultOptions, payloadKeys.language, - this.getGraphLanguage() !== this._defaultGraphOptions.graphLanguage ? this.getGraphLanguage() : undefined); - setPayloadKey(payload, defaultOptions, payloadKeys.source, options.graphSource); - setPayloadKey(payload, defaultOptions, payloadKeys.name, options.graphName); - setPayloadKey(payload, defaultOptions, payloadKeys.readConsistency, - getConsistencyName(options.graphReadConsistency)); - setPayloadKey(payload, defaultOptions, payloadKeys.writeConsistency, - getConsistencyName(options.graphWriteConsistency)); - - // Use the read timeout defined by the user or the one default to graph executions - setPayloadKey(payload, defaultOptions, payloadKeys.timeout, - this.getReadTimeout() > 0 ? this.getReadTimeout() : null, longBuffer); - - // Graph result is always set - payload[payloadKeys.results] = defaultOptions.graphResults === this.getGraphSubProtocol() - ? defaultOptions.customPayload[payloadKeys.results] : utils.allocBufferFromString(this.getGraphSubProtocol()); - - this.setCustomPayload(payload); - } -} - -module.exports = { - GraphExecutionOptions, - graphProtocol, - payloadKeys -}; \ No newline at end of file diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/datastax/graph/result-set.js b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/datastax/graph/result-set.js deleted file mode 100644 index 8e84670656..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/datastax/graph/result-set.js +++ /dev/null @@ -1,156 +0,0 @@ -/* - * Copyright DataStax, Inc. - * - * 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 utils = require('../../utils'); - -/** - * Creates a new instance of GraphResultSet. - * @class - * @classdesc - * Represents the result set of a [graph query execution]{@link Client#executeGraph} containing vertices, edges or - * scalar values depending on the query. - *

- * It allows iteration of the items using for..of statements under ES2015 and exposes - * forEach(), first() and toArray() to access the underlying items. - *

- * @example - * for (let vertex of result} { ... } - * @example - * const arr = result.toArray(); - * @example - * const vertex = result.first(); - * @param {ResultSet} result - * @param {Function} [rowParser] - * @alias module:datastax/graph~GraphResultSet - * @constructor - */ -function GraphResultSet(result, rowParser) { - /** - * Information on the execution of a successful query: - * @member {Object} - * @property {Number} achievedConsistency The consistency level that has been actually achieved by the query. - * @property {String} queriedHost The Cassandra host that coordinated this query. - * @property {Object} triedHosts Gets the associative array of host that were queried before getting a valid response, - * being the last host the one that replied correctly. - * @property {Uuid} traceId Identifier of the trace session. - * @property {Array.} warnings Warning messages generated by the server when executing the query. - */ - this.info = result.info; - const rows = result.rows; - rowParser = rowParser || parsePlainJsonRow; - - /** - * This property has been deprecated because it may return a lower value than the actual length of the results. - * Use toArray() instead. - *

Gets the length of the result.

- * @deprecated Use toArray() instead. This property will be removed in the following major version. - * @member {Number} - */ - this.length = result.rowLength; - - /** - * A string token representing the current page state of query. It can be used in the following executions to - * continue paging and retrieve the remained of the result for the query. - * @member {String} - */ - this.pageState = result.pageState; - - /** - * Returns the first element of the result or null if the result is empty. - * @returns {Object} - */ - this.first = function first() { - const iterator = this.values(); - const item = iterator.next(); - if (item.done) { - return null; - } - - return item.value; - }; - - /** - * Executes a provided function once per result element. - * @param {Function} callback Function to execute for each element, taking two arguments: currentValue and index. - * @param {Object} [thisArg] Value to use as this when executing callback. - */ - this.forEach = function forEach(callback, thisArg) { - if (!rows.length) { - return; - } - const iterator = this.values(); - let item = iterator.next(); - let index = 0; - while (!item.done) { - callback.call(thisArg || this, item.value, index++); - item = iterator.next(); - } - }; - - /** - * Results an Array of graph result elements (vertex, edge, scalar). - * @returns {Array} - */ - this.toArray = function toArray() { - if (!rows.length) { - return utils.emptyArray; - } - return utils.iteratorToArray(this.values()); - }; - - /** - * Returns a new Iterator object that contains the values for each index in the result. - * @returns {Iterator} - */ - this.values = function* values() { - for (const traverser of this.getTraversers()) { - const bulk = traverser.bulk || 1; - - for (let j = 0; j < bulk; j++) { - yield traverser.object; - } - } - }; - - /** - * Gets the traversers represented contained in the result set. - * @returns {Iterator} - */ - this.getTraversers = function* () { - for (const row of rows) { - yield rowParser(row); - } - }; -} - -if (typeof Symbol !== 'undefined' && typeof Symbol.iterator === 'symbol') { - // Make iterable - GraphResultSet.prototype[Symbol.iterator] = function getIterator() { - return this.values(); - }; -} - -/** - * @param {Row} row - * @private - */ -function parsePlainJsonRow(row) { - const parsed = JSON.parse(row['gremlin']); - return { object: parsed.result, bulk: parsed.bulk || 1 }; -} - -module.exports = GraphResultSet; \ No newline at end of file diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/datastax/graph/structure.js b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/datastax/graph/structure.js deleted file mode 100644 index deef3e134a..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/datastax/graph/structure.js +++ /dev/null @@ -1,167 +0,0 @@ -/* - * Copyright DataStax, Inc. - * - * 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 util = require('util'); - -/** - * @classdesc - * Represents a graph Element. - * @param id - * @param label - * @abstract - * @memberOf module:datastax/graph - * @constructor - */ -function Element(id, label) { - /** - * Gets the element id. - */ - this.id = id; - /** - * Gets the element label. - * @type {String} - */ - this.label = label; -} - -/** - * @classdesc - * Represents a graph Vertex. - * @param id - * @param {String} label - * @param {Object} properties - * @extends {Element} - * @memberOf module:datastax/graph - * @constructor - */ -function Vertex(id, label, properties) { - Element.call(this, id, label); - /** - * Gets the vertex properties. - * @type {Object} - */ - this.properties = properties; -} - -util.inherits(Vertex, Element); - -/** - * @classdesc - * Represents a graph Edge. - * @param id - * @param outV - * @param {outVLabel} outVLabel - * @param {String} label - * @param inV - * @param {String} inVLabel - * @param {Object} properties - * @extends {Element} - * @memberOf module:datastax/graph - * @constructor - */ -function Edge(id, outV, outVLabel, label, inV, inVLabel, properties) { - Element.call(this, id, label); - /** - * Gets the id of outgoing vertex of the edge. - */ - this.outV = outV; - /** - * Gets the label of the outgoing vertex. - */ - this.outVLabel = outVLabel; - /** - * Gets the id of the incoming vertex of the edge. - */ - this.inV = inV; - - /** - * Gets the label of the incoming vertex. - */ - this.inVLabel = inVLabel; - /** - * Gets the properties of the edge as an associative array. - * @type {Object} - */ - this.properties = {}; - (function adaptProperties(self) { - if (properties) { - const keys = Object.keys(properties); - for (let i = 0; i < keys.length; i++) { - const k = keys[i]; - self.properties[k] = properties[k].value; - } - } - })(this); -} - -util.inherits(Edge, Element); - -/** - * @classdesc - * Represents a graph vertex property. - * @param id - * @param {String} label - * @param value - * @param {Object} properties - * @extends {Element} - * @memberOf module:datastax/graph - * @constructor - */ -function VertexProperty(id, label, value, properties) { - Element.call(this, id, label); - this.value = value; - this.key = this.label; - this.properties = properties; -} - -util.inherits(VertexProperty, Element); - -/** - * @classdesc - * Represents a property. - * @param key - * @param value - * @memberOf module:datastax/graph - * @constructor - */ -function Property(key, value) { - this.key = key; - this.value = value; -} - -/** - * @classdesc - * Represents a walk through a graph as defined by a traversal. - * @param {Array} labels - * @param {Array} objects - * @memberOf module:datastax/graph - * @constructor - */ -function Path(labels, objects) { - this.labels = labels; - this.objects = objects; -} - -module.exports = { - Edge, - Element, - Path, - Property, - Vertex, - VertexProperty -}; \ No newline at end of file diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/datastax/graph/type-serializers.js b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/datastax/graph/type-serializers.js deleted file mode 100644 index 880c0f336f..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/datastax/graph/type-serializers.js +++ /dev/null @@ -1,501 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you 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 datastax/graph/tinkerpop/typeSerializers - * @ignore - */ - -/** - * @author Jorge Bay Gondra - */ -'use strict'; - -// Replace dependencies to minimize code changes from Apache TinkerPop -const t = { - P: UnsupportedType, TextP: UnsupportedType, Traversal: UnsupportedType, Traverser: UnsupportedType, - EnumValue: UnsupportedType -}; -const ts = { TraversalStrategy: UnsupportedType }; -const Bytecode = UnsupportedType; -const g = require('./index'); -const utils = { Long: UnsupportedType }; -t.t = g.t; -t.direction = g.direction; - -function UnsupportedType() { } - -const valueKey = '@value'; -const typeKey = '@type'; - -/** - * @abstract - */ -class TypeSerializer { - serialize() { - throw new Error('serialize() method not implemented for ' + this.constructor.name); - } - - deserialize() { - throw new Error('deserialize() method not implemented for ' + this.constructor.name); - } - - canBeUsedFor() { - throw new Error('canBeUsedFor() method not implemented for ' + this.constructor.name); - } -} - -class NumberSerializer extends TypeSerializer { - serialize(item) { - if (isNaN(item)) { - return { - [typeKey]: 'g:Double', - [valueKey]: 'NaN' - }; - } else if (item === Number.POSITIVE_INFINITY) { - return { - [typeKey]: 'g:Double', - [valueKey]: 'Infinity' - }; - } else if (item === Number.NEGATIVE_INFINITY) { - return { - [typeKey]: 'g:Double', - [valueKey]: '-Infinity' - }; - } else { - return item; - } - } - - deserialize(obj) { - var val = obj[valueKey]; - if (val === 'NaN') { - return NaN; - } else if (val === 'Infinity') { - return Number.POSITIVE_INFINITY; - } else if (val === '-Infinity') { - return Number.NEGATIVE_INFINITY; - } else { - return parseFloat(val); - } - } - - canBeUsedFor(value) { - return (typeof value === 'number'); - } -} - -class DateSerializer extends TypeSerializer { - serialize(item) { - return { - [typeKey]: 'g:Date', - [valueKey]: item.getTime() - }; - } - - deserialize(obj) { - return new Date(obj[valueKey]); - } - - canBeUsedFor(value) { - return (value instanceof Date); - } -} - -class LongSerializer extends TypeSerializer { - serialize(item) { - return { - [typeKey]: 'g:Int64', - [valueKey]: item.value - }; - } - - canBeUsedFor(value) { - return (value instanceof utils.Long); - } -} - -class BytecodeSerializer extends TypeSerializer { - serialize(item) { - let bytecode = item; - if (item instanceof t.Traversal) { - bytecode = item.getBytecode(); - } - const result = {}; - result[typeKey] = 'g:Bytecode'; - const resultValue = result[valueKey] = {}; - const sources = this._serializeInstructions(bytecode.sourceInstructions); - if (sources) { - resultValue['source'] = sources; - } - const steps = this._serializeInstructions(bytecode.stepInstructions); - if (steps) { - resultValue['step'] = steps; - } - return result; - } - - _serializeInstructions(instructions) { - if (instructions.length === 0) { - return null; - } - const result = new Array(instructions.length); - result[0] = instructions[0]; - for (let i = 0; i < instructions.length; i++) { - result[i] = instructions[i].map(item => this.writer.adaptObject(item)); - } - return result; - } - - canBeUsedFor(value) { - return (value instanceof Bytecode) || (value instanceof t.Traversal); - } -} - -class PSerializer extends TypeSerializer { - /** @param {P} item */ - serialize(item) { - const result = {}; - result[typeKey] = 'g:P'; - const resultValue = result[valueKey] = { - 'predicate': item.operator - }; - if (item.other === undefined || item.other === null) { - resultValue['value'] = this.writer.adaptObject(item.value); - } - else { - resultValue['value'] = [ this.writer.adaptObject(item.value), this.writer.adaptObject(item.other) ]; - } - return result; - } - - canBeUsedFor(value) { - return (value instanceof t.P); - } -} - -class TextPSerializer extends TypeSerializer { - /** @param {TextP} item */ - serialize(item) { - const result = {}; - result[typeKey] = 'g:TextP'; - const resultValue = result[valueKey] = { - 'predicate': item.operator - }; - if (item.other === undefined || item.other === null) { - resultValue['value'] = this.writer.adaptObject(item.value); - } - else { - resultValue['value'] = [ this.writer.adaptObject(item.value), this.writer.adaptObject(item.other) ]; - } - return result; - } - - canBeUsedFor(value) { - return (value instanceof t.TextP); - } -} - -class LambdaSerializer extends TypeSerializer { - /** @param {Function} item */ - serialize(item) { - return { - [typeKey]: 'g:Lambda', - [valueKey]: { - 'arguments': item.length, - 'language': 'gremlin-javascript', - 'script': item.toString() - } - }; - } - - canBeUsedFor(value) { - return (typeof value === 'function'); - } -} - -class EnumSerializer extends TypeSerializer { - /** @param {EnumValue} item */ - serialize(item) { - return { - [typeKey]: 'g:' + item.typeName, - [valueKey]: item.elementName - }; - } - - canBeUsedFor(value) { - return value && value.typeName && value instanceof t.EnumValue; - } -} - -class TraverserSerializer extends TypeSerializer { - /** @param {Traverser} item */ - serialize(item) { - return { - [typeKey]: 'g:Traverser', - [valueKey]: { - 'value': this.writer.adaptObject(item.object), - 'bulk': this.writer.adaptObject(item.bulk) - } - }; - } - - deserialize(obj) { - const value = obj[valueKey]; - return new t.Traverser(this.reader.read(value['value']), this.reader.read(value['bulk'])); - } - - canBeUsedFor(value) { - return (value instanceof t.Traverser); - } -} - -class TraversalStrategySerializer extends TypeSerializer { - /** @param {TraversalStrategy} item */ - serialize(item) { - return { - [typeKey]: 'g:' + item.constructor.name, - [valueKey]: item.configuration - }; - } - - canBeUsedFor(value) { - return (value instanceof ts.TraversalStrategy); - } -} - -class VertexSerializer extends TypeSerializer { - deserialize(obj) { - const value = obj[valueKey]; - return new g.Vertex(this.reader.read(value['id']), value['label'], this.reader.read(value['properties'])); - } - - /** @param {Vertex} item */ - serialize(item) { - return { - [typeKey]: 'g:Vertex', - [valueKey]: { - 'id': this.writer.adaptObject(item.id), - 'label': item.label - } - }; - } - - canBeUsedFor(value) { - return (value instanceof g.Vertex); - } -} - -class VertexPropertySerializer extends TypeSerializer { - deserialize(obj) { - const value = obj[valueKey]; - return new g.VertexProperty( - this.reader.read(value['id']), - value['label'], - this.reader.read(value['value']), - this.reader.read(value['properties']) - ); - } -} - -class PropertySerializer extends TypeSerializer { - deserialize(obj) { - const value = obj[valueKey]; - return new g.Property( - value['key'], - this.reader.read(value['value'])); - } -} - -class EdgeSerializer extends TypeSerializer { - deserialize(obj) { - const value = obj[valueKey]; - return new g.Edge( - this.reader.read(value['id']), - new g.Vertex(this.reader.read(value['outV']), this.reader.read(value['outVLabel'])), - value['label'], - new g.Vertex(this.reader.read(value['inV']), this.reader.read(value['inVLabel'])), - this.reader.read(value['properties']) - ); - } - - /** @param {Edge} item */ - serialize(item) { - return { - [typeKey]: 'g:Edge', - [valueKey]: { - 'id': this.writer.adaptObject(item.id), - 'label': item.label, - 'outV': this.writer.adaptObject(item.outV.id), - 'outVLabel': item.outV.label, - 'inV': this.writer.adaptObject(item.inV.id), - 'inVLabel': item.inV.label - } - }; - } - - canBeUsedFor(value) { - return (value instanceof g.Edge); - } -} - -class PathSerializer extends TypeSerializer { - deserialize(obj) { - const value = obj[valueKey]; - const objects = value['objects'].map(o => this.reader.read(o)); - return new g.Path(this.reader.read(value['labels']), objects); - } -} - -class Path3Serializer extends TypeSerializer { - deserialize(obj) { - const value = obj[valueKey]; - return new g.Path(this.reader.read(value['labels']), this.reader.read(value['objects'])); - } -} - -class TSerializer extends TypeSerializer { - deserialize(obj) { - return t.t[obj[valueKey]]; - } -} - -class DirectionSerializer extends TypeSerializer { - deserialize(obj) { - return t.direction[obj[valueKey].toLowerCase()]; - } -} - -class ArraySerializer extends TypeSerializer { - constructor(typeKey) { - super(); - this.typeKey = typeKey; - } - - deserialize(obj) { - const value = obj[valueKey]; - if (!Array.isArray(value)) { - throw new Error('Expected Array, obtained: ' + value); - } - return value.map(x => this.reader.read(x)); - } - - /** @param {Array} item */ - serialize(item) { - return { - [typeKey]: this.typeKey, - [valueKey]: item.map(x => this.writer.adaptObject(x)) - }; - } - - canBeUsedFor(value) { - return Array.isArray(value); - } -} - -class BulkSetSerializer extends TypeSerializer { - deserialize(obj) { - const value = obj[valueKey]; - if (!Array.isArray(value)) { - throw new Error('Expected Array, obtained: ' + value); - } - - // coerce the BulkSet to List. if the bulk exceeds the int space then we can't coerce to List anyway, - // so this query will be trouble. we'd need a legit BulkSet implementation here in js. this current - // implementation is here to replicate the previous functionality that existed on the server side in - // previous versions. - let result = []; - for (let ix = 0, iy = value.length; ix < iy; ix += 2) { - const pair = value.slice(ix, ix + 2); - result = result.concat(Array(this.reader.read(pair[1])).fill(this.reader.read(pair[0]))); - } - - return result; - } -} - -class MapSerializer extends TypeSerializer { - deserialize(obj) { - const value = obj[valueKey]; - if (!Array.isArray(value)) { - throw new Error('Expected Array, obtained: ' + value); - } - const result = new Map(); - for (let i = 0; i < value.length; i += 2) { - result.set(this.reader.read(value[i]), this.reader.read(value[i + 1])); - } - return result; - } - - /** @param {Map} map */ - serialize(map) { - const arr = []; - map.forEach((v, k) => { - arr.push(this.writer.adaptObject(k)); - arr.push(this.writer.adaptObject(v)); - }); - return { - [typeKey]: 'g:Map', - [valueKey]: arr - }; - } - - canBeUsedFor(value) { - return value instanceof Map; - } -} - -class ListSerializer extends ArraySerializer { - constructor() { - super('g:List'); - } -} - -class SetSerializer extends ArraySerializer { - constructor() { - super('g:Set'); - } -} - -module.exports = { - BulkSetSerializer, - BytecodeSerializer, - DateSerializer, - DirectionSerializer, - EdgeSerializer, - EnumSerializer, - LambdaSerializer, - ListSerializer, - LongSerializer, - MapSerializer, - NumberSerializer, - Path3Serializer, - PathSerializer, - PropertySerializer, - PSerializer, - TextPSerializer, - SetSerializer, - TSerializer, - TraverserSerializer, - TraversalStrategySerializer, - typeKey, - valueKey, - VertexPropertySerializer, - VertexSerializer -}; diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/datastax/graph/wrappers.js b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/datastax/graph/wrappers.js deleted file mode 100644 index 0bbf8c0864..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/datastax/graph/wrappers.js +++ /dev/null @@ -1,84 +0,0 @@ -/* - * Copyright DataStax, Inc. - * - * 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 types = require('../../types'); -const { dataTypes } = types; - -/** - * Internal representation of a value with additional type information. - * @internal - * @ignore - */ -class GraphTypeWrapper { - constructor(value, typeInfo) { - this.value = value; - this.typeInfo = typeof typeInfo === 'number' ? { code: typeInfo } : typeInfo; - } -} - - -/** - * Internal representation of user-defined type with the metadata. - * @internal - * @ignore - */ -class UdtGraphWrapper { - constructor(value, udtInfo) { - this.value = value; - - if (!udtInfo || !udtInfo.name || !udtInfo.keyspace || !udtInfo.fields) { - throw new TypeError(`udtInfo must be an object with name, keyspace and field properties defined`); - } - - this.udtInfo = udtInfo; - } -} - -/** - * Wraps a number or null value to hint the client driver that the data type of the value is an int - * @memberOf module:datastax/graph - */ -function asInt(value) { return new GraphTypeWrapper(value, dataTypes.int); } - -/** - * Wraps a number or null value to hint the client driver that the data type of the value is a double - * @memberOf module:datastax/graph - */ -function asDouble(value) { return new GraphTypeWrapper(value, dataTypes.double); } - -/** - * Wraps a number or null value to hint the client driver that the data type of the value is a double - * @memberOf module:datastax/graph - */ -function asFloat(value) { return new GraphTypeWrapper(value, dataTypes.float); } - -/** - * Wraps a Date or null value to hint the client driver that the data type of the value is a timestamp - * @memberOf module:datastax/graph - */ -function asTimestamp(value) { return new GraphTypeWrapper(value, dataTypes.timestamp); } - -/** - * Wraps an Object or null value to hint the client driver that the data type of the value is a user-defined type. - * @memberOf module:datastax/graph - * @param {object} value The object representing the UDT. - * @param {{name: string, keyspace: string, fields: Array}} udtInfo The UDT metadata as defined by the driver. - */ -function asUdt(value, udtInfo) { return new UdtGraphWrapper(value, udtInfo); } - -module.exports = { asInt, asDouble, asFloat, asTimestamp, asUdt, UdtGraphWrapper, GraphTypeWrapper }; \ No newline at end of file diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/datastax/index.d.ts b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/datastax/index.d.ts deleted file mode 100644 index e41483f8ea..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/datastax/index.d.ts +++ /dev/null @@ -1,24 +0,0 @@ -/* - * Copyright DataStax, Inc. - * - * 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. - */ - -import * as graphModule from './graph'; -import * as searchModule from './search'; - -export namespace datastax { - export import graph = graphModule.graph; - - export import search = searchModule.search; -} \ No newline at end of file diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/datastax/index.js b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/datastax/index.js deleted file mode 100644 index b193461a0e..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/datastax/index.js +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Copyright DataStax, Inc. - * - * 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'; - -/** - * DataStax module. - *

- * Contains modules and classes to represent functionality that is specific to DataStax products. - *

- * @module datastax - */ - -exports.graph = require('./graph'); -exports.search = require('./search'); \ No newline at end of file diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/datastax/search/date-range.js b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/datastax/search/date-range.js deleted file mode 100644 index 877c9a392c..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/datastax/search/date-range.js +++ /dev/null @@ -1,537 +0,0 @@ -/* - * Copyright DataStax, Inc. - * - * 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 utils = require('../../utils'); -const Long = require('long'); - -/** - * Regex to parse dates in the following format YYYY-MM-DDThh:mm:ss.mssZ - * Looks cumbersome but it's straightforward: - * - "(\d{1,6})": year mandatory 1 to 6 digits - * - (?:-(\d{1,2}))?(?:-(\d{1,2}))? two non-capturing groups representing the month and day (1 to 2 digits captured). - * - (?:T(\d{1,2}?)?(?::(\d{1,2}))?(?::(\d{1,2}))?)?Z? A non-capturing group for the time portion - * @private - */ -const dateRegex = - /^[-+]?(\d{1,6})(?:-(\d{1,2}))?(?:-(\d{1,2}))?(?:T(\d{1,2}?)?(?::(\d{1,2}))?(?::(\d{1,2})(?:\.(\d{1,3}))?)?)?Z?$/; -const multipleBoundariesRegex = /^\[(.+?) TO (.+)]$/; -const unbounded = Object.freeze(new DateRangeBound(null, -1)); - -const dateRangeType = { - // single value as in "2001-01-01" - singleValue: 0, - // closed range as in "[2001-01-01 TO 2001-01-31]" - closedRange: 1, - // open range high as in "[2001-01-01 TO *]" - openRangeHigh: 2, - // - 0x03 - open range low as in "[* TO 2001-01-01]" - openRangeLow: 3, - // - 0x04 - both ranges open as in "[* TO *]" - openBoth: 4, - // - 0x05 - single open range as in "[*]" - openSingle: 5 -}; - -/** - * Defines the possible values of date range precision. - * @type {Object} - * @property {Number} year - * @property {Number} month - * @property {Number} day - * @property {Number} hour - * @property {Number} minute - * @property {Number} second - * @property {Number} millisecond - * @memberof module:search - */ -const dateRangePrecision = { - year: 0, - month: 1, - day: 2, - hour: 3, - minute: 4, - second: 5, - millisecond: 6 -}; - -/** - * Creates a new instance of DateRange using a lower bound and an upper bound. - *

Consider using DateRange.fromString() to create instances more easily.

- * @classdesc - * Represents a range of dates, corresponding to the Apache Solr type - * DateRangeField. - *

- * A date range can have one or two bounds, namely lower bound and upper bound, to represent an interval of time. - * Date range bounds are both inclusive. For example: - *

- *
    - *
  • 2015 TO 2016-10 represents from the first day of 2015 to the last day of October 2016
  • - *
  • 2015 represents during the course of the year 2015.
  • - *
  • 2017 TO * represents any date greater or equals to the first day of the year 2017.
  • - *
- *

- * Note that this JavaScript representation of DateRangeField does not support Dates outside of the range - * supported by ECMAScript Date: –100,000,000 days to 100,000,000 days measured relative to midnight at the - * beginning of 01 January, 1970 UTC. Being -271821-04-20T00:00:00.000Z the minimum lower boundary - * and 275760-09-13T00:00:00.000Z the maximum higher boundary. - *

- * @param {DateRangeBound} lowerBound A value representing the range lower bound, composed by a - * Date and a precision. Use DateRangeBound.unbounded for an open lower bound. - * @param {DateRangeBound} [upperBound] A value representing the range upper bound, composed by a - * Date and a precision. Use DateRangeBound.unbounded for an open upper bound. When it's not - * defined, the DateRange instance is considered as a single value range. - * @constructor - * @memberOf module:datastax/search - */ -function DateRange(lowerBound, upperBound) { - if (!lowerBound) { - throw new TypeError('The lower boundaries must be defined'); - } - /** - * Gets the lower bound of this range (inclusive). - * @type {DateRangeBound} - */ - this.lowerBound = lowerBound; - /** - * Gets the upper bound of this range (inclusive). - * @type {DateRangeBound|null} - */ - this.upperBound = upperBound || null; - - // Define the type - if (this.upperBound === null) { - if (this.lowerBound !== unbounded) { - this._type = dateRangeType.singleValue; - } - else { - this._type = dateRangeType.openSingle; - } - } - else { - if (this.lowerBound !== unbounded) { - this._type = this.upperBound !== unbounded ? dateRangeType.closedRange : dateRangeType.openRangeHigh; - } - else { - this._type = this.upperBound !== unbounded ? dateRangeType.openRangeLow : dateRangeType.openBoth; - } - } -} - -/** - * Returns true if the value of this DateRange instance and other are the same. - * @param {DateRange} other - * @returns {Boolean} - */ -DateRange.prototype.equals = function (other) { - if (!(other instanceof DateRange)) { - return false; - } - return (other.lowerBound.equals(this.lowerBound) && - (other.upperBound ? other.upperBound.equals(this.upperBound) : !this.upperBound)); -}; - -/** - * Returns the string representation of the instance. - * @return {String} - */ -DateRange.prototype.toString = function () { - if (this.upperBound === null) { - return this.lowerBound.toString(); - } - return '[' + this.lowerBound.toString() + ' TO ' + this.upperBound.toString() + ']'; -}; - -DateRange.prototype.toBuffer = function () { - // Serializes the value containing: - // [] - if (this._type === dateRangeType.openBoth || this._type === dateRangeType.openSingle) { - return utils.allocBufferFromArray([ this._type ]); - } - let buffer; - let offset = 0; - if (this._type !== dateRangeType.closedRange) { - // byte + long + byte - const boundary = this._type !== dateRangeType.openRangeLow ? this.lowerBound : this.upperBound; - buffer = utils.allocBufferUnsafe(10); - buffer.writeUInt8(this._type, offset++); - offset = writeDate(boundary.date, buffer, offset); - buffer.writeUInt8(boundary.precision, offset); - return buffer; - } - // byte + long + byte + long + byte - buffer = utils.allocBufferUnsafe(19); - buffer.writeUInt8(this._type, offset++); - offset = writeDate(this.lowerBound.date, buffer, offset); - buffer.writeUInt8(this.lowerBound.precision, offset++); - offset = writeDate(this.upperBound.date, buffer, offset); - buffer.writeUInt8(this.upperBound.precision, offset); - return buffer; -}; - -/** - * Returns the DateRange representation of a given string. - *

String representations of dates are always expressed in Coordinated Universal Time (UTC)

- * @param {String} dateRangeString - */ -DateRange.fromString = function (dateRangeString) { - const matches = multipleBoundariesRegex.exec(dateRangeString); - if (!matches) { - return new DateRange(DateRangeBound.toLowerBound(DateRangeBound.fromString(dateRangeString))); - } - return new DateRange(DateRangeBound.toLowerBound(DateRangeBound.fromString(matches[1])), DateRangeBound.toUpperBound(DateRangeBound.fromString(matches[2]))); -}; - -/** - * Deserializes the buffer into a DateRange - * @param {Buffer} buffer - * @return {DateRange} - */ -DateRange.fromBuffer = function (buffer) { - if (buffer.length === 0) { - throw new TypeError('DateRange serialized value must have at least 1 byte'); - } - const type = buffer.readUInt8(0); - if (type === dateRangeType.openBoth) { - return new DateRange(unbounded, unbounded); - } - if (type === dateRangeType.openSingle) { - return new DateRange(unbounded); - } - let offset = 1; - let date1; - let lowerBound; - let upperBound = null; - if (type !== dateRangeType.closedRange) { - date1 = readDate(buffer, offset); - offset += 8; - lowerBound = new DateRangeBound(date1, buffer.readUInt8(offset)); - if (type === dateRangeType.openRangeLow) { - // lower boundary is open, the first serialized boundary is the upperBound - upperBound = lowerBound; - lowerBound = unbounded; - } - else { - upperBound = type === dateRangeType.openRangeHigh ? unbounded : null; - } - return new DateRange(lowerBound, upperBound); - } - date1 = readDate(buffer, offset); - offset += 8; - lowerBound = new DateRangeBound(date1, buffer.readUInt8(offset++)); - const date2 = readDate(buffer, offset); - offset += 8; - upperBound = new DateRangeBound(date2, buffer.readUInt8(offset)); - return new DateRange(lowerBound, upperBound); -}; - -/** - * Writes a Date, long millis since epoch, to a buffer starting from offset. - * @param {Date} date - * @param {Buffer} buffer - * @param {Number} offset - * @return {Number} The new offset. - * @private - */ -function writeDate(date, buffer, offset) { - const long = Long.fromNumber(date.getTime()); - buffer.writeUInt32BE(long.getHighBitsUnsigned(), offset); - buffer.writeUInt32BE(long.getLowBitsUnsigned(), offset + 4); - return offset + 8; -} - -/** - * Reads a Date, long millis since epoch, from a buffer starting from offset. - * @param {Buffer} buffer - * @param {Number} offset - * @return {Date} - * @private - */ -function readDate(buffer, offset) { - const long = new Long(buffer.readInt32BE(offset+4), buffer.readInt32BE(offset)); - return new Date(long.toNumber()); -} - -/** - * @classdesc - * Represents a date range boundary, composed by a Date and a precision. - * @param {Date} date The timestamp portion, representing a single moment in time. Consider using - * Date.UTC() method to build the Date instance. - * @param {Number} precision The precision portion. Valid values for DateRangeBound precision are - * defined in the [dateRangePrecision]{@link module:datastax/search~dateRangePrecision} member. - * @constructor - * @memberOf module:datastax/search - */ -function DateRangeBound(date, precision) { - /** - * The timestamp portion of the boundary. - * @type {Date} - */ - this.date = date; - /** - * The precision portion of the boundary. Valid values are defined in the - * [dateRangePrecision]{@link module:datastax/search~dateRangePrecision} member. - * @type {Number} - */ - this.precision = precision; -} - -/** - * Returns the string representation of the instance. - * @return {String} - */ -DateRangeBound.prototype.toString = function () { - if (this.precision === -1) { - return '*'; - } - let precision = 0; - const isoString = this.date.toISOString(); - let i; - let char; - // The years take at least the first 4 characters - for (i = 4; i < isoString.length && precision <= this.precision; i++) { - char = isoString.charAt(i); - if (precision === dateRangePrecision.day && char === 'T') { - precision = dateRangePrecision.hour; - continue; - } - if (precision >= dateRangePrecision.hour && char === ':' || char === '.') { - precision++; - continue; - } - if (precision < dateRangePrecision.day && char === '-') { - precision++; - } - } - let start = 0; - const firstChar = isoString.charAt(0); - let sign = ''; - let toRemoveIndex = 4; - if (firstChar === '+' || firstChar === '-') { - sign = firstChar; - if (firstChar === '-') { - // since we are retaining the -, don't remove as many zeros. - toRemoveIndex = 3; - } - // Remove additional zeros - for (start = 1; start < toRemoveIndex; start++) { - if (isoString.charAt(start) !== '0') { - break; - } - } - } - if (this.precision !== dateRangePrecision.millisecond) { - // i holds the position of the first char that marks the end of a precision (ie: '-', 'T', ...), - // we should not include it in the result, except its the 'Z' char for the complete representation - i--; - } - return sign + isoString.substring(start, i); -}; - -/** - * Returns true if the value of this DateRange instance and other are the same. - * @param {DateRangeBound} other - * @return {boolean} - */ -DateRangeBound.prototype.equals = function (other) { - if (!(other instanceof DateRangeBound)) { - return false; - } - if (other.precision !== this.precision) { - return false; - } - return datesEqual(other.date, this.date); -}; - -function datesEqual(d1, d2) { - const t1 = d1 ? d1.getTime() : null; - const t2 = d2 ? d2.getTime() : null; - return t1 === t2; -} - -DateRangeBound.prototype.isUnbounded = function () { - return (this.precision === -1); -}; - -/** - * Parses a date string and returns a DateRangeBound. - * @param {String} boundaryString - * @return {DateRangeBound} - */ -DateRangeBound.fromString = function(boundaryString) { - if (!boundaryString) { - return null; - } - if (boundaryString === '*') { - return unbounded; - } - const matches = dateRegex.exec(boundaryString); - if (!matches) { - throw TypeError('String provided is not a valid date ' + boundaryString); - } - if (matches[7] !== undefined && matches[5] === undefined) { - // Due to a limitation in the regex, its possible to match dates like 2015T03:02.001, without the seconds - // portion but with the milliseconds specified. - throw new TypeError('String representation of the date contains the milliseconds portion but not the seconds: ' + - boundaryString); - } - const builder = new BoundaryBuilder(boundaryString.charAt(0) === '-'); - for (let i = 1; i < matches.length; i++) { - builder.set(i-1, matches[i], boundaryString); - } - return builder.build(); -}; - -/** - * The unbounded {@link DateRangeBound} instance. Unbounded bounds are syntactically represented by a * - * (star) sign. - * @type {DateRangeBound} - */ -DateRangeBound.unbounded = unbounded; - -/** - * Converts a {DateRangeBound} into a lower-bounded bound by rounding down its date - * based on its precision. - * - * @param {DateRangeBound} bound The bound to round down. - * @returns {DateRangeBound} with the date rounded down to the given precision. - */ -DateRangeBound.toLowerBound = function (bound) { - if(bound === unbounded) { - return bound; - } - const rounded = new Date(bound.date.getTime()); - // in this case we want to fallthrough - /* eslint-disable no-fallthrough */ - switch (bound.precision) { - case dateRangePrecision.year: - rounded.setUTCMonth(0); - case dateRangePrecision.month: - rounded.setUTCDate(1); - case dateRangePrecision.day: - rounded.setUTCHours(0); - case dateRangePrecision.hour: - rounded.setUTCMinutes(0); - case dateRangePrecision.minute: - rounded.setUTCSeconds(0); - case dateRangePrecision.second: - rounded.setUTCMilliseconds(0); - } - /* eslint-enable no-fallthrough */ - return new DateRangeBound(rounded, bound.precision); -}; - -/** - * Converts a {DateRangeBound} into a upper-bounded bound by rounding up its date - * based on its precision. - * - * @param {DateRangeBound} bound The bound to round up. - * @returns {DateRangeBound} with the date rounded up to the given precision. - */ -DateRangeBound.toUpperBound = function (bound) { - if (bound === unbounded) { - return bound; - } - const rounded = new Date(bound.date.getTime()); - // in this case we want to fallthrough - /* eslint-disable no-fallthrough */ - switch (bound.precision) { - case dateRangePrecision.year: - rounded.setUTCMonth(11); - case dateRangePrecision.month: - // Advance to the beginning of next month and set day of month to 0 - // which sets the date to the last day of the previous month. - // This gives us the effect of YYYY-MM-LastDayOfThatMonth - rounded.setUTCMonth(rounded.getUTCMonth() + 1, 0); - case dateRangePrecision.day: - rounded.setUTCHours(23); - case dateRangePrecision.hour: - rounded.setUTCMinutes(59); - case dateRangePrecision.minute: - rounded.setUTCSeconds(59); - case dateRangePrecision.second: - rounded.setUTCMilliseconds(999); - } - /* eslint-enable no-fallthrough */ - return new DateRangeBound(rounded, bound.precision); -}; - -/** @private */ -function BoundaryBuilder(isNegative) { - this._sign = isNegative ? -1 : 1; - this._index = 0; - this._values = new Int32Array(7); -} - -BoundaryBuilder.prototype.set = function (index, value, stringDate) { - if (value === undefined) { - return; - } - if (index > 6) { - throw new TypeError('Index out of bounds: ' + index); - } - if (index > this._index) { - this._index = index; - } - const numValue = +value; - switch (index) { - case dateRangePrecision.month: - if (numValue < 1 || numValue > 12) { - throw new TypeError('Month portion is not valid for date: ' + stringDate); - } - break; - case dateRangePrecision.day: - if (numValue < 1 || numValue > 31) { - throw new TypeError('Day portion is not valid for date: ' + stringDate); - } - break; - case dateRangePrecision.hour: - if (numValue > 23) { - throw new TypeError('Hour portion is not valid for date: ' + stringDate); - } - break; - case dateRangePrecision.minute: - case dateRangePrecision.second: - if (numValue > 59) { - throw new TypeError('Minute/second portion is not valid for date: ' + stringDate); - } - break; - case dateRangePrecision.millisecond: - if (numValue > 999) { - throw new TypeError('Millisecond portion is not valid for date: ' + stringDate); - } - break; - } - this._values[index] = numValue; -}; - -/** @return {DateRangeBound} */ -BoundaryBuilder.prototype.build = function () { - const date = new Date(0); - let month = this._values[1]; - if (month) { - // ES Date months are represented from 0 to 11 - month--; - } - date.setUTCFullYear(this._sign * this._values[0], month, this._values[2] || 1); - date.setUTCHours(this._values[3], this._values[4], this._values[5], this._values[6]); - return new DateRangeBound(date, this._index); -}; - -exports.unbounded = unbounded; -exports.dateRangePrecision = dateRangePrecision; -exports.DateRange = DateRange; -exports.DateRangeBound = DateRangeBound; \ No newline at end of file diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/datastax/search/index.d.ts b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/datastax/search/index.d.ts deleted file mode 100644 index 57ba44f7a1..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/datastax/search/index.d.ts +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Copyright DataStax, Inc. - * - * 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. - */ - -export namespace search { - enum dateRangePrecision { - year = 0, - month, - day, - hour, - minute, - second, - millisecond - } - - class DateRange { - lowerBound: DateRangeBound; - upperBound: DateRangeBound; - - constructor(lowerBound: DateRangeBound, upperBound: DateRangeBound); - - equals(other: DateRangeBound): boolean; - - toString(): string; - - static fromString(value: string): DateRange; - - static fromBuffer(value: Buffer): DateRange; - } - - class DateRangeBound { - date: Date; - - precision: number; - - equals(other: DateRangeBound): boolean; - - toString(): string; - - static fromString(value: string): DateRangeBound; - - static toLowerBound(bound: DateRangeBound): DateRangeBound; - - static toUpperBound(bound: DateRangeBound): DateRangeBound; - } -} \ No newline at end of file diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/datastax/search/index.js b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/datastax/search/index.js deleted file mode 100644 index c101f5d145..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/datastax/search/index.js +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Copyright DataStax, Inc. - * - * 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 dateRangeModule = require('./date-range'); - -/** - * Search module. - *

- * Contains the classes to represent the set of types for search data that come with DSE 5.1+ - *

- * @module datastax/search - */ - -exports.DateRange = dateRangeModule.DateRange; -exports.DateRangeBound = dateRangeModule.DateRangeBound; -exports.dateRangePrecision = dateRangeModule.dateRangePrecision; \ No newline at end of file diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/encoder.js b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/encoder.js deleted file mode 100644 index deb8ae0f89..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/encoder.js +++ /dev/null @@ -1,1865 +0,0 @@ -/* - * Copyright DataStax, Inc. - * - * 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 util = require('util'); - -const types = require('./types'); -const dataTypes = types.dataTypes; -const Long = types.Long; -const Integer = types.Integer; -const BigDecimal = types.BigDecimal; -const MutableLong = require('./types/mutable-long'); -const utils = require('./utils'); -const token = require('./token'); -const { DateRange } = require('./datastax/search'); -const geo = require('./geometry'); -const Geometry = geo.Geometry; -const LineString = geo.LineString; -const Point = geo.Point; -const Polygon = geo.Polygon; - -const uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; - -const buffers = { - int16Zero: utils.allocBufferFromArray([0, 0]), - int32Zero: utils.allocBufferFromArray([0, 0, 0, 0]), - int8Zero: utils.allocBufferFromArray([0]), - int8One: utils.allocBufferFromArray([1]), - int8MaxValue: utils.allocBufferFromArray([0xff]) -}; - -// BigInt: Avoid using literals (e.g., 32n) as we must be able to compile with older engines -const isBigIntSupported = typeof BigInt !== 'undefined'; -const bigInt32 = isBigIntSupported ? BigInt(32) : null; -const bigInt8 = isBigIntSupported ? BigInt(8) : null; -const bigInt0 = isBigIntSupported ? BigInt(0) : null; -const bigIntMinus1 = isBigIntSupported ? BigInt(-1) : null; -const bigInt32BitsOn = isBigIntSupported ? BigInt(0xffffffff) : null; -const bigInt8BitsOn = isBigIntSupported ? BigInt(0xff) : null; - -const complexTypeNames = Object.freeze({ - list : 'org.apache.cassandra.db.marshal.ListType', - set : 'org.apache.cassandra.db.marshal.SetType', - map : 'org.apache.cassandra.db.marshal.MapType', - udt : 'org.apache.cassandra.db.marshal.UserType', - tuple : 'org.apache.cassandra.db.marshal.TupleType', - frozen : 'org.apache.cassandra.db.marshal.FrozenType', - reversed : 'org.apache.cassandra.db.marshal.ReversedType', - composite : 'org.apache.cassandra.db.marshal.CompositeType', - empty : 'org.apache.cassandra.db.marshal.EmptyType', - collection: 'org.apache.cassandra.db.marshal.ColumnToCollectionType' -}); -const cqlNames = Object.freeze({ - frozen: 'frozen', - list: 'list', - 'set': 'set', - map: 'map', - tuple: 'tuple', - empty: 'empty', - duration: 'duration' -}); -const singleTypeNames = Object.freeze({ - 'org.apache.cassandra.db.marshal.UTF8Type': dataTypes.varchar, - 'org.apache.cassandra.db.marshal.AsciiType': dataTypes.ascii, - 'org.apache.cassandra.db.marshal.UUIDType': dataTypes.uuid, - 'org.apache.cassandra.db.marshal.TimeUUIDType': dataTypes.timeuuid, - 'org.apache.cassandra.db.marshal.Int32Type': dataTypes.int, - 'org.apache.cassandra.db.marshal.BytesType': dataTypes.blob, - 'org.apache.cassandra.db.marshal.FloatType': dataTypes.float, - 'org.apache.cassandra.db.marshal.DoubleType': dataTypes.double, - 'org.apache.cassandra.db.marshal.BooleanType': dataTypes.boolean, - 'org.apache.cassandra.db.marshal.InetAddressType': dataTypes.inet, - 'org.apache.cassandra.db.marshal.SimpleDateType': dataTypes.date, - 'org.apache.cassandra.db.marshal.TimeType': dataTypes.time, - 'org.apache.cassandra.db.marshal.ShortType': dataTypes.smallint, - 'org.apache.cassandra.db.marshal.ByteType': dataTypes.tinyint, - 'org.apache.cassandra.db.marshal.DateType': dataTypes.timestamp, - 'org.apache.cassandra.db.marshal.TimestampType': dataTypes.timestamp, - 'org.apache.cassandra.db.marshal.LongType': dataTypes.bigint, - 'org.apache.cassandra.db.marshal.DecimalType': dataTypes.decimal, - 'org.apache.cassandra.db.marshal.IntegerType': dataTypes.varint, - 'org.apache.cassandra.db.marshal.CounterColumnType': dataTypes.counter -}); -const singleFqTypeNamesLength = Object.keys(singleTypeNames).reduce(function (previous, current) { - return current.length > previous ? current.length : previous; -}, 0); - -const customTypeNames = Object.freeze({ - duration: 'org.apache.cassandra.db.marshal.DurationType', - lineString: 'org.apache.cassandra.db.marshal.LineStringType', - point: 'org.apache.cassandra.db.marshal.PointType', - polygon: 'org.apache.cassandra.db.marshal.PolygonType', - dateRange: 'org.apache.cassandra.db.marshal.DateRangeType' -}); - -const nullValueBuffer = utils.allocBufferFromArray([255, 255, 255, 255]); -const unsetValueBuffer = utils.allocBufferFromArray([255, 255, 255, 254]); - -/** - * For backwards compatibility, empty buffers as text/blob/custom values are supported. - * In the case of other types, they are going to be decoded as a null value. - * @private - * @type {Set} - */ -const zeroLengthTypesSupported = new Set([ - dataTypes.text, - dataTypes.ascii, - dataTypes.varchar, - dataTypes.custom, - dataTypes.blob -]); - -/** - * Serializes and deserializes to and from a CQL type and a Javascript Type. - * @param {Number} protocolVersion - * @param {ClientOptions} options - * @constructor - */ -function Encoder(protocolVersion, options) { - this.encodingOptions = options.encoding || utils.emptyObject; - defineInstanceMembers.call(this); - this.setProtocolVersion(protocolVersion); - setEncoders.call(this); - if (this.encodingOptions.copyBuffer) { - this.handleBuffer = handleBufferCopy; - } - else { - this.handleBuffer = handleBufferRef; - } -} - -/** - * Declares the privileged instance members. - * @private - */ -function defineInstanceMembers() { - /** - * Sets the protocol version and the encoding/decoding methods depending on the protocol version - * @param {Number} value - * @ignore - * @internal - */ - this.setProtocolVersion = function (value) { - this.protocolVersion = value; - //Set the collection serialization based on the protocol version - this.decodeCollectionLength = decodeCollectionLengthV3; - this.getLengthBuffer = getLengthBufferV3; - this.collectionLengthSize = 4; - if (!types.protocolVersion.uses4BytesCollectionLength(this.protocolVersion)) { - this.decodeCollectionLength = decodeCollectionLengthV2; - this.getLengthBuffer = getLengthBufferV2; - this.collectionLengthSize = 2; - } - }; - - const customDecoders = { - [customTypeNames.duration]: decodeDuration, - [customTypeNames.lineString]: decodeLineString, - [customTypeNames.point]: decodePoint, - [customTypeNames.polygon]: decodePolygon, - [customTypeNames.dateRange]: decodeDateRange - }; - - const customEncoders = { - [customTypeNames.duration]: encodeDuration, - [customTypeNames.lineString]: encodeLineString, - [customTypeNames.point]: encodePoint, - [customTypeNames.polygon]: encodePolygon, - [customTypeNames.dateRange]: encodeDateRange - }; - - // Decoding methods - this.decodeBlob = function (bytes) { - return this.handleBuffer(bytes); - }; - this.decodeCustom = function (bytes, typeName) { - const handler = customDecoders[typeName]; - if (handler) { - return handler.call(this, bytes); - } - return this.handleBuffer(bytes); - }; - this.decodeUtf8String = function (bytes) { - return bytes.toString('utf8'); - }; - this.decodeAsciiString = function (bytes) { - return bytes.toString('ascii'); - }; - this.decodeBoolean = function (bytes) { - return !!bytes.readUInt8(0); - }; - this.decodeDouble = function (bytes) { - return bytes.readDoubleBE(0); - }; - this.decodeFloat = function (bytes) { - return bytes.readFloatBE(0); - }; - this.decodeInt = function (bytes) { - return bytes.readInt32BE(0); - }; - this.decodeSmallint = function (bytes) { - return bytes.readInt16BE(0); - }; - this.decodeTinyint = function (bytes) { - return bytes.readInt8(0); - }; - - this._decodeCqlLongAsLong = function (bytes) { - return Long.fromBuffer(bytes); - }; - - this._decodeCqlLongAsBigInt = function (bytes) { - return BigInt.asIntN(64, (BigInt(bytes.readUInt32BE(0)) << bigInt32) | BigInt(bytes.readUInt32BE(4))); - }; - - this.decodeLong = this.encodingOptions.useBigIntAsLong - ? this._decodeCqlLongAsBigInt - : this._decodeCqlLongAsLong; - - this._decodeVarintAsInteger = function (bytes) { - return Integer.fromBuffer(bytes); - }; - - this._decodeVarintAsBigInt = function decodeVarintAsBigInt(bytes) { - let result = bigInt0; - if (bytes[0] <= 0x7f) { - for (let i = 0; i < bytes.length; i++) { - const b = BigInt(bytes[bytes.length - 1 - i]); - result = result | (b << BigInt(i * 8)); - } - } else { - for (let i = 0; i < bytes.length; i++) { - const b = BigInt(bytes[bytes.length - 1 - i]); - result = result | ((~b & bigInt8BitsOn) << BigInt(i * 8)); - } - result = ~result; - } - - return result; - }; - - this.decodeVarint = this.encodingOptions.useBigIntAsVarint - ? this._decodeVarintAsBigInt - : this._decodeVarintAsInteger; - - this.decodeDecimal = function(bytes) { - return BigDecimal.fromBuffer(bytes); - }; - this.decodeTimestamp = function(bytes) { - return new Date(this._decodeCqlLongAsLong(bytes).toNumber()); - }; - this.decodeDate = function (bytes) { - return types.LocalDate.fromBuffer(bytes); - }; - this.decodeTime = function (bytes) { - return types.LocalTime.fromBuffer(bytes); - }; - /* - * Reads a list from bytes - */ - this.decodeList = function (bytes, subtype) { - const totalItems = this.decodeCollectionLength(bytes, 0); - let offset = this.collectionLengthSize; - const list = new Array(totalItems); - for (let i = 0; i < totalItems; i++) { - //bytes length of the item - const length = this.decodeCollectionLength(bytes, offset); - offset += this.collectionLengthSize; - //slice it - list[i] = this.decode(bytes.slice(offset, offset+length), subtype); - offset += length; - } - return list; - }; - /* - * Reads a Set from bytes - */ - this.decodeSet = function (bytes, subtype) { - const arr = this.decodeList(bytes, subtype); - if (this.encodingOptions.set) { - const setConstructor = this.encodingOptions.set; - return new setConstructor(arr); - } - return arr; - }; - /* - * Reads a map (key / value) from bytes - */ - this.decodeMap = function (bytes, subtypes) { - let map; - const totalItems = this.decodeCollectionLength(bytes, 0); - let offset = this.collectionLengthSize; - const self = this; - function readValues(callback, thisArg) { - for (let i = 0; i < totalItems; i++) { - const keyLength = self.decodeCollectionLength(bytes, offset); - offset += self.collectionLengthSize; - const key = self.decode(bytes.slice(offset, offset + keyLength), subtypes[0]); - offset += keyLength; - const valueLength = self.decodeCollectionLength(bytes, offset); - offset += self.collectionLengthSize; - if (valueLength < 0) { - callback.call(thisArg, key, null); - continue; - } - const value = self.decode(bytes.slice(offset, offset + valueLength), subtypes[1]); - offset += valueLength; - callback.call(thisArg, key, value); - } - } - if (this.encodingOptions.map) { - const mapConstructor = this.encodingOptions.map; - map = new mapConstructor(); - readValues(map.set, map); - } - else { - map = {}; - readValues(function (key, value) { - map[key] = value; - }); - } - return map; - }; - this.decodeUuid = function (bytes) { - return new types.Uuid(this.handleBuffer(bytes)); - }; - this.decodeTimeUuid = function (bytes) { - return new types.TimeUuid(this.handleBuffer(bytes)); - }; - this.decodeInet = function (bytes) { - return new types.InetAddress(this.handleBuffer(bytes)); - }; - /** - * Decodes a user defined type into an object - * @param {Buffer} bytes - * @param {{fields: Array}} udtInfo - * @private - */ - this.decodeUdt = function (bytes, udtInfo) { - const result = {}; - let offset = 0; - for (let i = 0; i < udtInfo.fields.length && offset < bytes.length; i++) { - //bytes length of the field value - const length = bytes.readInt32BE(offset); - offset += 4; - //slice it - const field = udtInfo.fields[i]; - if (length < 0) { - result[field.name] = null; - continue; - } - result[field.name] = this.decode(bytes.slice(offset, offset+length), field.type); - offset += length; - } - return result; - }; - - this.decodeTuple = function (bytes, tupleInfo) { - const elements = new Array(tupleInfo.length); - let offset = 0; - - for (let i = 0; i < tupleInfo.length && offset < bytes.length; i++) { - const length = bytes.readInt32BE(offset); - offset += 4; - - if (length < 0) { - elements[i] = null; - continue; - } - - elements[i] = this.decode(bytes.slice(offset, offset+length), tupleInfo[i]); - offset += length; - } - - return types.Tuple.fromArray(elements); - }; - - //Encoding methods - this.encodeFloat = function (value) { - if (typeof value === 'string') { - // All numeric types are supported as strings for historical reasons - value = parseFloat(value); - - if (Number.isNaN(value)) { - throw new TypeError(`Expected string representation of a number, obtained ${util.inspect(value)}`); - } - } - - if (typeof value !== 'number') { - throw new TypeError('Expected Number, obtained ' + util.inspect(value)); - } - - const buf = utils.allocBufferUnsafe(4); - buf.writeFloatBE(value, 0); - return buf; - }; - - this.encodeDouble = function (value) { - if (typeof value === 'string') { - // All numeric types are supported as strings for historical reasons - value = parseFloat(value); - - if (Number.isNaN(value)) { - throw new TypeError(`Expected string representation of a number, obtained ${util.inspect(value)}`); - } - } - - if (typeof value !== 'number') { - throw new TypeError('Expected Number, obtained ' + util.inspect(value)); - } - - const buf = utils.allocBufferUnsafe(8); - buf.writeDoubleBE(value, 0); - return buf; - }; - - /** - * @param {Date|String|Long|Number} value - * @private - */ - this.encodeTimestamp = function (value) { - const originalValue = value; - if (typeof value === 'string') { - value = new Date(value); - } - if (value instanceof Date) { - //milliseconds since epoch - value = value.getTime(); - if (isNaN(value)) { - throw new TypeError('Invalid date: ' + originalValue); - } - } - if (this.encodingOptions.useBigIntAsLong) { - value = BigInt(value); - } - return this.encodeLong(value); - }; - /** - * @param {Date|String|LocalDate} value - * @returns {Buffer} - * @throws {TypeError} - * @private - */ - this.encodeDate = function (value) { - const originalValue = value; - try { - if (typeof value === 'string') { - value = types.LocalDate.fromString(value); - } - if (value instanceof Date) { - value = types.LocalDate.fromDate(value); - } - } - catch (err) { - //Wrap into a TypeError - throw new TypeError('LocalDate could not be parsed ' + err); - } - if (!(value instanceof types.LocalDate)) { - throw new TypeError('Expected Date/String/LocalDate, obtained ' + util.inspect(originalValue)); - } - return value.toBuffer(); - }; - /** - * @param {String|LocalDate} value - * @returns {Buffer} - * @throws {TypeError} - * @private - */ - this.encodeTime = function (value) { - const originalValue = value; - try { - if (typeof value === 'string') { - value = types.LocalTime.fromString(value); - } - } - catch (err) { - //Wrap into a TypeError - throw new TypeError('LocalTime could not be parsed ' + err); - } - if (!(value instanceof types.LocalTime)) { - throw new TypeError('Expected String/LocalTime, obtained ' + util.inspect(originalValue)); - } - return value.toBuffer(); - }; - /** - * @param {Uuid|String|Buffer} value - * @private - */ - this.encodeUuid = function (value) { - if (typeof value === 'string') { - try { - value = types.Uuid.fromString(value).getBuffer(); - } - catch (err) { - throw new TypeError(err.message); - } - } else if (value instanceof types.Uuid) { - value = value.getBuffer(); - } else { - throw new TypeError('Not a valid Uuid, expected Uuid/String/Buffer, obtained ' + util.inspect(value)); - } - - return value; - }; - /** - * @param {String|InetAddress|Buffer} value - * @returns {Buffer} - * @private - */ - this.encodeInet = function (value) { - if (typeof value === 'string') { - value = types.InetAddress.fromString(value); - } - if (value instanceof types.InetAddress) { - value = value.getBuffer(); - } - if (!(value instanceof Buffer)) { - throw new TypeError('Not a valid Inet, expected InetAddress/Buffer, obtained ' + util.inspect(value)); - } - return value; - }; - - /** - * @param {Long|Buffer|String|Number} value - * @private - */ - this._encodeBigIntFromLong = function (value) { - if (typeof value === 'number') { - value = Long.fromNumber(value); - } else if (typeof value === 'string') { - value = Long.fromString(value); - } - - let buf = null; - - if (value instanceof Long) { - buf = Long.toBuffer(value); - } else if (value instanceof MutableLong) { - buf = Long.toBuffer(value.toImmutable()); - } - - if (buf === null) { - throw new TypeError('Not a valid bigint, expected Long/Number/String/Buffer, obtained ' + util.inspect(value)); - } - - return buf; - }; - - this._encodeBigIntFromBigInt = function (value) { - if (typeof value === 'string') { - // All numeric types are supported as strings for historical reasons - value = BigInt(value); - } - - // eslint-disable-next-line valid-typeof - if (typeof value !== 'bigint') { - // Only BigInt values are supported - throw new TypeError('Not a valid BigInt value, obtained ' + util.inspect(value)); - } - - const buffer = utils.allocBufferUnsafe(8); - buffer.writeUInt32BE(Number(value >> bigInt32) >>> 0, 0); - buffer.writeUInt32BE(Number(value & bigInt32BitsOn), 4); - return buffer; - }; - - this.encodeLong = this.encodingOptions.useBigIntAsLong - ? this._encodeBigIntFromBigInt - : this._encodeBigIntFromLong; - - /** - * @param {Integer|Buffer|String|Number} value - * @returns {Buffer} - * @private - */ - this._encodeVarintFromInteger = function (value) { - if (typeof value === 'number') { - value = Integer.fromNumber(value); - } - if (typeof value === 'string') { - value = Integer.fromString(value); - } - let buf = null; - if (value instanceof Buffer) { - buf = value; - } - if (value instanceof Integer) { - buf = Integer.toBuffer(value); - } - if (buf === null) { - throw new TypeError('Not a valid varint, expected Integer/Number/String/Buffer, obtained ' + util.inspect(value)); - } - return buf; - }; - - this._encodeVarintFromBigInt = function (value) { - if (typeof value === 'string') { - // All numeric types are supported as strings for historical reasons - value = BigInt(value); - } - - // eslint-disable-next-line valid-typeof - if (typeof value !== 'bigint') { - throw new TypeError('Not a valid varint, expected BigInt, obtained ' + util.inspect(value)); - } - - if (value === bigInt0) { - return buffers.int8Zero; - - } - else if (value === bigIntMinus1) { - return buffers.int8MaxValue; - } - - const parts = []; - - if (value > bigInt0){ - while (value !== bigInt0) { - parts.unshift(Number(value & bigInt8BitsOn)); - value = value >> bigInt8; - } - - if (parts[0] > 0x7f) { - // Positive value needs a padding - parts.unshift(0); - } - } else { - while (value !== bigIntMinus1) { - parts.unshift(Number(value & bigInt8BitsOn)); - value = value >> bigInt8; - } - - if (parts[0] <= 0x7f) { - // Negative value needs a padding - parts.unshift(0xff); - } - } - - return utils.allocBufferFromArray(parts); - }; - - this.encodeVarint = this.encodingOptions.useBigIntAsVarint - ? this._encodeVarintFromBigInt - : this._encodeVarintFromInteger; - - /** - * @param {BigDecimal|Buffer|String|Number} value - * @returns {Buffer} - * @private - */ - this.encodeDecimal = function (value) { - if (typeof value === 'number') { - value = BigDecimal.fromNumber(value); - } else if (typeof value === 'string') { - value = BigDecimal.fromString(value); - } - - let buf = null; - - if (value instanceof BigDecimal) { - buf = BigDecimal.toBuffer(value); - } else { - throw new TypeError('Not a valid varint, expected BigDecimal/Number/String/Buffer, obtained ' + util.inspect(value)); - } - - return buf; - }; - this.encodeString = function (value, encoding) { - if (typeof value !== 'string') { - throw new TypeError('Not a valid text value, expected String obtained ' + util.inspect(value)); - } - return utils.allocBufferFromString(value, encoding); - }; - this.encodeUtf8String = function (value) { - return this.encodeString(value, 'utf8'); - }; - this.encodeAsciiString = function (value) { - return this.encodeString(value, 'ascii'); - }; - this.encodeBlob = function (value) { - if (!(value instanceof Buffer)) { - throw new TypeError('Not a valid blob, expected Buffer obtained ' + util.inspect(value)); - } - return value; - }; - this.encodeCustom = function (value, name) { - const handler = customEncoders[name]; - if (handler) { - return handler.call(this, value); - } - throw new TypeError('No encoding handler found for type ' + name); - }; - /** - * @param {Boolean} value - * @returns {Buffer} - * @private - */ - this.encodeBoolean = function (value) { - return value ? buffers.int8One : buffers.int8Zero; - }; - /** - * @param {Number|String} value - * @private - */ - this.encodeInt = function (value) { - if (isNaN(value)) { - throw new TypeError('Expected Number, obtained ' + util.inspect(value)); - } - const buf = utils.allocBufferUnsafe(4); - buf.writeInt32BE(value, 0); - return buf; - }; - /** - * @param {Number|String} value - * @private - */ - this.encodeSmallint = function (value) { - if (isNaN(value)) { - throw new TypeError('Expected Number, obtained ' + util.inspect(value)); - } - const buf = utils.allocBufferUnsafe(2); - buf.writeInt16BE(value, 0); - return buf; - }; - /** - * @param {Number|String} value - * @private - */ - this.encodeTinyint = function (value) { - if (isNaN(value)) { - throw new TypeError('Expected Number, obtained ' + util.inspect(value)); - } - const buf = utils.allocBufferUnsafe(1); - buf.writeInt8(value, 0); - return buf; - }; - this.encodeList = function (value, subtype) { - if (!Array.isArray(value)) { - throw new TypeError('Not a valid list value, expected Array obtained ' + util.inspect(value)); - } - if (value.length === 0) { - return null; - } - const parts = []; - parts.push(this.getLengthBuffer(value)); - for (let i = 0;i < value.length;i++) { - const val = value[i]; - if (val === null || typeof val === 'undefined' || val === types.unset) { - throw new TypeError('A collection can\'t contain null or unset values'); - } - const bytes = this.encode(val, subtype); - //include item byte length - parts.push(this.getLengthBuffer(bytes)); - //include item - parts.push(bytes); - } - return Buffer.concat(parts); - }; - this.encodeSet = function (value, subtype) { - if (this.encodingOptions.set && value instanceof this.encodingOptions.set) { - const arr = []; - value.forEach(function (x) { - arr.push(x); - }); - return this.encodeList(arr, subtype); - } - return this.encodeList(value, subtype); - }; - /** - * Serializes a map into a Buffer - * @param value - * @param {Array} [subtypes] - * @returns {Buffer} - * @private - */ - this.encodeMap = function (value, subtypes) { - const parts = []; - let propCounter = 0; - let keySubtype = null; - let valueSubtype = null; - const self = this; - if (subtypes) { - keySubtype = subtypes[0]; - valueSubtype = subtypes[1]; - } - function addItem(val, key) { - if (key === null || typeof key === 'undefined' || key === types.unset) { - throw new TypeError('A map can\'t contain null or unset keys'); - } - if (val === null || typeof val === 'undefined' || val === types.unset) { - throw new TypeError('A map can\'t contain null or unset values'); - } - const keyBuffer = self.encode(key, keySubtype); - //include item byte length - parts.push(self.getLengthBuffer(keyBuffer)); - //include item - parts.push(keyBuffer); - //value - const valueBuffer = self.encode(val, valueSubtype); - //include item byte length - parts.push(self.getLengthBuffer(valueBuffer)); - //include item - if (valueBuffer !== null) { - parts.push(valueBuffer); - } - propCounter++; - } - if (this.encodingOptions.map && value instanceof this.encodingOptions.map) { - //Use Map#forEach() method to iterate - value.forEach(addItem); - } - else { - //Use object - for (const key in value) { - if (!value.hasOwnProperty(key)) { - continue; - } - const val = value[key]; - addItem(val, key); - } - } - - parts.unshift(this.getLengthBuffer(propCounter)); - return Buffer.concat(parts); - }; - this.encodeUdt = function (value, udtInfo) { - const parts = []; - let totalLength = 0; - for (let i = 0; i < udtInfo.fields.length; i++) { - const field = udtInfo.fields[i]; - const item = this.encode(value[field.name], field.type); - if (!item) { - parts.push(nullValueBuffer); - totalLength += 4; - continue; - } - if (item === types.unset) { - parts.push(unsetValueBuffer); - totalLength += 4; - continue; - } - const lengthBuffer = utils.allocBufferUnsafe(4); - lengthBuffer.writeInt32BE(item.length, 0); - parts.push(lengthBuffer); - parts.push(item); - totalLength += item.length + 4; - } - return Buffer.concat(parts, totalLength); - }; - this.encodeTuple = function (value, tupleInfo) { - const parts = []; - let totalLength = 0; - const length = Math.min(tupleInfo.length, value.length); - - for (let i = 0; i < length; i++) { - const type = tupleInfo[i]; - const item = this.encode(value.get(i), type); - - if (!item) { - parts.push(nullValueBuffer); - totalLength += 4; - continue; - } - - if (item === types.unset) { - parts.push(unsetValueBuffer); - totalLength += 4; - continue; - } - - const lengthBuffer = utils.allocBufferUnsafe(4); - lengthBuffer.writeInt32BE(item.length, 0); - parts.push(lengthBuffer); - parts.push(item); - totalLength += item.length + 4; - } - - return Buffer.concat(parts, totalLength); - }; - - /** - * If not provided, it uses the array of buffers or the parameters and hints to build the routingKey - * @param {Array} params - * @param {ExecutionOptions} execOptions - * @param [keys] parameter keys and positions in the params array - * @throws TypeError - * @internal - * @ignore - */ - this.setRoutingKeyFromUser = function (params, execOptions, keys) { - let totalLength = 0; - const userRoutingKey = execOptions.getRoutingKey(); - if (Array.isArray(userRoutingKey)) { - if (userRoutingKey.length === 1) { - execOptions.setRoutingKey(userRoutingKey[0]); - return; - } - - // Its a composite routing key - totalLength = 0; - for (let i = 0; i < userRoutingKey.length; i++) { - const item = userRoutingKey[i]; - if (!item) { - // Invalid routing key part provided by the user, clear the value - execOptions.setRoutingKey(null); - return; - } - totalLength += item.length + 3; - } - - execOptions.setRoutingKey(concatRoutingKey(userRoutingKey, totalLength)); - return; - } - // If routingKey is present, ensure it is a Buffer, Token, or TokenRange. Otherwise throw an error. - if (userRoutingKey) { - if (userRoutingKey instanceof Buffer || userRoutingKey instanceof token.Token - || userRoutingKey instanceof token.TokenRange) { - return; - } - - throw new TypeError(`Unexpected routingKey '${util.inspect(userRoutingKey)}' provided. ` + - `Expected Buffer, Array, Token, or TokenRange.`); - } - - // If no params are present, return as routing key cannot be determined. - if (!params || params.length === 0) { - return; - } - - let routingIndexes = execOptions.getRoutingIndexes(); - if (execOptions.getRoutingNames()) { - routingIndexes = execOptions.getRoutingNames().map(k => keys[k]); - } - if (!routingIndexes) { - return; - } - - const parts = []; - const hints = execOptions.getHints() || utils.emptyArray; - - const encodeParam = !keys ? - (i => this.encode(params[i], hints[i])) : - (i => this.encode(params[i].value, hints[i])); - - try { - totalLength = this._encodeRoutingKeyParts(parts, routingIndexes, encodeParam); - } catch (e) { - // There was an error encoding a parameter that is part of the routing key, - // ignore now to fail afterwards - } - - if (totalLength === 0) { - return; - } - - execOptions.setRoutingKey(concatRoutingKey(parts, totalLength)); - }; - - /** - * Sets the routing key in the options based on the prepared statement metadata. - * @param {Object} meta Prepared metadata - * @param {Array} params Array of parameters - * @param {ExecutionOptions} execOptions - * @throws TypeError - * @internal - * @ignore - */ - this.setRoutingKeyFromMeta = function (meta, params, execOptions) { - const routingIndexes = execOptions.getRoutingIndexes(); - if (!routingIndexes) { - return; - } - const parts = new Array(routingIndexes.length); - const encodeParam = i => { - const columnInfo = meta.columns[i]; - return this.encode(params[i], columnInfo ? columnInfo.type : null); - }; - - let totalLength = 0; - - try { - totalLength = this._encodeRoutingKeyParts(parts, routingIndexes, encodeParam); - } catch (e) { - // There was an error encoding a parameter that is part of the routing key, - // ignore now to fail afterwards - } - - if (totalLength === 0) { - return; - } - - execOptions.setRoutingKey(concatRoutingKey(parts, totalLength)); - }; - - /** - * @param {Array} parts - * @param {Array} routingIndexes - * @param {Function} encodeParam - * @returns {Number} The total length - * @private - */ - this._encodeRoutingKeyParts = function (parts, routingIndexes, encodeParam) { - let totalLength = 0; - for (let i = 0; i < routingIndexes.length; i++) { - const paramIndex = routingIndexes[i]; - if (paramIndex === undefined) { - // Bad input from the user, ignore - return 0; - } - - const item = encodeParam(paramIndex); - if (item === null || item === undefined || item === types.unset) { - // The encoded partition key should an instance of Buffer - // Let it fail later in the pipeline for null/undefined parameter values - return 0; - } - - // Per each part of the routing key, 3 extra bytes are needed - totalLength += item.length + 3; - parts[i] = item; - } - return totalLength; - }; - - /** - * Parses a CQL name string into data type information - * @param {String} keyspace - * @param {String} typeName - * @param {Number} startIndex - * @param {Number|null} length - * @param {Function} udtResolver - * @returns {Promise<{err, info, options}>} callback Callback invoked with err and {{code: number, info: Object|Array|null, options: {frozen: Boolean}}} - * @internal - * @ignore - */ - this.parseTypeName = async function (keyspace, typeName, startIndex, length, udtResolver) { - startIndex = startIndex || 0; - if (!length) { - length = typeName.length; - } - - const dataType = { - code: 0, - info: null, - options: { - frozen: false - } - }; - - let innerTypes; - - if (typeName.indexOf("'", startIndex) === startIndex) { - //If quoted, this is a custom type. - dataType.info = typeName.substr(startIndex+1, length-2); - return dataType; - } - - if (!length) { - length = typeName.length; - } - - if (typeName.indexOf(cqlNames.frozen, startIndex) === startIndex) { - //Remove the frozen token - startIndex += cqlNames.frozen.length + 1; - length -= cqlNames.frozen.length + 2; - dataType.options.frozen = true; - } - - if (typeName.indexOf(cqlNames.list, startIndex) === startIndex) { - //move cursor across the name and bypass the angle brackets - startIndex += cqlNames.list.length + 1; - length -= cqlNames.list.length + 2; - innerTypes = parseParams(typeName, startIndex, length, '<', '>'); - - if (innerTypes.length !== 1) { - throw new TypeError('Not a valid type ' + typeName); - } - - dataType.code = dataTypes.list; - dataType.info = await this.parseTypeName(keyspace, innerTypes[0], 0, null, udtResolver); - return dataType; - } - - if (typeName.indexOf(cqlNames.set, startIndex) === startIndex) { - //move cursor across the name and bypass the angle brackets - startIndex += cqlNames.set.length + 1; - length -= cqlNames.set.length + 2; - innerTypes = parseParams(typeName, startIndex, length, '<', '>'); - - if (innerTypes.length !== 1) { - throw new TypeError('Not a valid type ' + typeName); - } - - dataType.code = dataTypes.set; - dataType.info = await this.parseTypeName(keyspace, innerTypes[0], 0, null, udtResolver); - return dataType; - } - - if (typeName.indexOf(cqlNames.map, startIndex) === startIndex) { - //move cursor across the name and bypass the angle brackets - startIndex += cqlNames.map.length + 1; - length -= cqlNames.map.length + 2; - innerTypes = parseParams(typeName, startIndex, length, '<', '>'); - - //It should contain the key and value types - if (innerTypes.length !== 2) { - throw new TypeError('Not a valid type ' + typeName); - } - - dataType.code = dataTypes.map; - dataType.info = await this._parseChildTypes(keyspace, innerTypes, udtResolver); - return dataType; - } - - if (typeName.indexOf(cqlNames.tuple, startIndex) === startIndex) { - //move cursor across the name and bypass the angle brackets - startIndex += cqlNames.tuple.length + 1; - length -= cqlNames.tuple.length + 2; - innerTypes = parseParams(typeName, startIndex, length, '<', '>'); - - if (innerTypes.length < 1) { - throw new TypeError('Not a valid type ' + typeName); - } - - dataType.code = dataTypes.tuple; - dataType.info = await this._parseChildTypes(keyspace, innerTypes, udtResolver); - return dataType; - } - - const quoted = typeName.indexOf('"', startIndex) === startIndex; - if (quoted) { - // Remove quotes - startIndex++; - length -= 2; - } - - // Quick check if its a single type - if (startIndex > 0) { - typeName = typeName.substr(startIndex, length); - } - - // Un-escape double quotes if quoted. - if (quoted) { - typeName = typeName.replace('""', '"'); - } - - const typeCode = dataTypes[typeName]; - if (typeof typeCode === 'number') { - dataType.code = typeCode; - return dataType; - } - - if (typeName === cqlNames.duration) { - dataType.info = customTypeNames.duration; - return dataType; - } - - if (typeName === cqlNames.empty) { - // Set as custom - dataType.info = 'empty'; - return dataType; - } - - const udtInfo = await udtResolver(keyspace, typeName); - if (udtInfo) { - dataType.code = dataTypes.udt; - dataType.info = udtInfo; - return dataType; - } - - throw new TypeError('Not a valid type "' + typeName + '"'); - }; - - /** - * @param {String} keyspace - * @param {Array} typeNames - * @param {Function} udtResolver - * @returns {Promise} - * @private - */ - this._parseChildTypes = function (keyspace, typeNames, udtResolver) { - return Promise.all(typeNames.map(name => this.parseTypeName(keyspace, name.trim(), 0, null, udtResolver))); - }; - - /** - * Parses a Cassandra fully-qualified class name string into data type information - * @param {String} typeName - * @param {Number} [startIndex] - * @param {Number} [length] - * @throws TypeError - * @returns {{code: number, info: Object|Array|null, options: {frozen: Boolean, reversed: Boolean}}} - * @internal - * @ignore - */ - this.parseFqTypeName = function (typeName, startIndex, length) { - const dataType = { - code: 0, - info: null, - options: { - reversed: false, - frozen: false - } - }; - startIndex = startIndex || 0; - let innerTypes; - if (!length) { - length = typeName.length; - } - if (length > complexTypeNames.reversed.length && typeName.indexOf(complexTypeNames.reversed) === startIndex) { - //Remove the reversed token - startIndex += complexTypeNames.reversed.length + 1; - length -= complexTypeNames.reversed.length + 2; - dataType.options.reversed = true; - } - if (length > complexTypeNames.frozen.length && - typeName.indexOf(complexTypeNames.frozen, startIndex) === startIndex) { - //Remove the frozen token - startIndex += complexTypeNames.frozen.length + 1; - length -= complexTypeNames.frozen.length + 2; - dataType.options.frozen = true; - } - if (typeName === complexTypeNames.empty) { - //set as custom - dataType.info = 'empty'; - return dataType; - } - //Quick check if its a single type - if (length <= singleFqTypeNamesLength) { - if (startIndex > 0) { - typeName = typeName.substr(startIndex, length); - } - const typeCode = singleTypeNames[typeName]; - if (typeof typeCode === 'number') { - dataType.code = typeCode; - return dataType; - } - throw new TypeError('Not a valid type "' + typeName + '"'); - } - if (typeName.indexOf(complexTypeNames.list, startIndex) === startIndex) { - //Its a list - //org.apache.cassandra.db.marshal.ListType(innerType) - //move cursor across the name and bypass the parenthesis - startIndex += complexTypeNames.list.length + 1; - length -= complexTypeNames.list.length + 2; - innerTypes = parseParams(typeName, startIndex, length); - if (innerTypes.length !== 1) { - throw new TypeError('Not a valid type ' + typeName); - } - dataType.code = dataTypes.list; - dataType.info = this.parseFqTypeName(innerTypes[0]); - return dataType; - } - if (typeName.indexOf(complexTypeNames.set, startIndex) === startIndex) { - //Its a set - //org.apache.cassandra.db.marshal.SetType(innerType) - //move cursor across the name and bypass the parenthesis - startIndex += complexTypeNames.set.length + 1; - length -= complexTypeNames.set.length + 2; - innerTypes = parseParams(typeName, startIndex, length); - if (innerTypes.length !== 1) - { - throw new TypeError('Not a valid type ' + typeName); - } - dataType.code = dataTypes.set; - dataType.info = this.parseFqTypeName(innerTypes[0]); - return dataType; - } - if (typeName.indexOf(complexTypeNames.map, startIndex) === startIndex) { - //org.apache.cassandra.db.marshal.MapType(keyType,valueType) - //move cursor across the name and bypass the parenthesis - startIndex += complexTypeNames.map.length + 1; - length -= complexTypeNames.map.length + 2; - innerTypes = parseParams(typeName, startIndex, length); - //It should contain the key and value types - if (innerTypes.length !== 2) { - throw new TypeError('Not a valid type ' + typeName); - } - dataType.code = dataTypes.map; - dataType.info = [this.parseFqTypeName(innerTypes[0]), this.parseFqTypeName(innerTypes[1])]; - return dataType; - } - if (typeName.indexOf(complexTypeNames.udt, startIndex) === startIndex) { - //move cursor across the name and bypass the parenthesis - startIndex += complexTypeNames.udt.length + 1; - length -= complexTypeNames.udt.length + 2; - return this._parseUdtName(typeName, startIndex, length); - } - if (typeName.indexOf(complexTypeNames.tuple, startIndex) === startIndex) { - //move cursor across the name and bypass the parenthesis - startIndex += complexTypeNames.tuple.length + 1; - length -= complexTypeNames.tuple.length + 2; - innerTypes = parseParams(typeName, startIndex, length); - if (innerTypes.length < 1) { - throw new TypeError('Not a valid type ' + typeName); - } - dataType.code = dataTypes.tuple; - dataType.info = innerTypes.map(x => this.parseFqTypeName(x)); - return dataType; - } - - // Assume custom type if cannot be parsed up to this point. - dataType.info = typeName.substr(startIndex, length); - return dataType; - }; - /** - * Parses type names with composites - * @param {String} typesString - * @returns {{types: Array, isComposite: Boolean, hasCollections: Boolean}} - * @internal - * @ignore - */ - this.parseKeyTypes = function (typesString) { - let i = 0; - let length = typesString.length; - const isComposite = typesString.indexOf(complexTypeNames.composite) === 0; - if (isComposite) { - i = complexTypeNames.composite.length + 1; - length--; - } - const types = []; - let startIndex = i; - let nested = 0; - let inCollectionType = false; - let hasCollections = false; - //as collection types are not allowed, it is safe to split by , - while (++i < length) { - switch (typesString[i]) { - case ',': - if (nested > 0) { - break; - } - if (inCollectionType) { - //remove type id - startIndex = typesString.indexOf(':', startIndex) + 1; - } - types.push(typesString.substring(startIndex, i)); - startIndex = i + 1; - break; - case '(': - if (nested === 0 && typesString.indexOf(complexTypeNames.collection, startIndex) === startIndex) { - inCollectionType = true; - hasCollections = true; - //skip collection type - i++; - startIndex = i; - break; - } - nested++; - break; - case ')': - if (inCollectionType && nested === 0){ - types.push(typesString.substring(typesString.indexOf(':', startIndex) + 1, i)); - startIndex = i + 1; - break; - } - nested--; - break; - } - } - if (startIndex < length) { - types.push(typesString.substring(startIndex, length)); - } - return { - types: types.map(name => this.parseFqTypeName(name)), - hasCollections: hasCollections, - isComposite: isComposite - }; - }; - this._parseUdtName = function (typeName, startIndex, length) { - const udtParams = parseParams(typeName, startIndex, length); - if (udtParams.length < 2) { - //It should contain at least the keyspace, name of the udt and a type - throw new TypeError('Not a valid type ' + typeName); - } - const dataType = { - code: dataTypes.udt, - info: null - }; - const udtInfo = { - keyspace: udtParams[0], - name: utils.allocBufferFromString(udtParams[1], 'hex').toString(), - fields: [] - }; - for (let i = 2; i < udtParams.length; i++) { - const p = udtParams[i]; - const separatorIndex = p.indexOf(':'); - const fieldType = this.parseFqTypeName(p, separatorIndex + 1, p.length - (separatorIndex + 1)); - udtInfo.fields.push({ - name: utils.allocBufferFromString(p.substr(0, separatorIndex), 'hex').toString(), - type: fieldType - }); - } - dataType.info = udtInfo; - return dataType; - }; -} - -/** - * Sets the encoder and decoder methods for this instance - * @private - */ -function setEncoders() { - this.decoders = { - [dataTypes.custom]: this.decodeCustom, - [dataTypes.ascii]: this.decodeAsciiString, - [dataTypes.bigint]: this.decodeLong, - [dataTypes.blob]: this.decodeBlob, - [dataTypes.boolean]: this.decodeBoolean, - [dataTypes.counter]: this.decodeLong, - [dataTypes.decimal]: this.decodeDecimal, - [dataTypes.double]: this.decodeDouble, - [dataTypes.float]: this.decodeFloat, - [dataTypes.int]: this.decodeInt, - [dataTypes.text]: this.decodeUtf8String, - [dataTypes.timestamp]: this.decodeTimestamp, - [dataTypes.uuid]: this.decodeUuid, - [dataTypes.varchar]: this.decodeUtf8String, - [dataTypes.varint]: this.decodeVarint, - [dataTypes.timeuuid]: this.decodeTimeUuid, - [dataTypes.inet]: this.decodeInet, - [dataTypes.date]: this.decodeDate, - [dataTypes.time]: this.decodeTime, - [dataTypes.smallint]: this.decodeSmallint, - [dataTypes.tinyint]: this.decodeTinyint, - [dataTypes.duration]: decodeDuration, - [dataTypes.list]: this.decodeList, - [dataTypes.map]: this.decodeMap, - [dataTypes.set]: this.decodeSet, - [dataTypes.udt]: this.decodeUdt, - [dataTypes.tuple]: this.decodeTuple - }; - - this.encoders = { - [dataTypes.custom]: this.encodeCustom, - [dataTypes.ascii]: this.encodeAsciiString, - [dataTypes.bigint]: this.encodeLong, - [dataTypes.blob]: this.encodeBlob, - [dataTypes.boolean]: this.encodeBoolean, - [dataTypes.counter]: this.encodeLong, - [dataTypes.decimal]: this.encodeDecimal, - [dataTypes.double]: this.encodeDouble, - [dataTypes.float]: this.encodeFloat, - [dataTypes.int]: this.encodeInt, - [dataTypes.text]: this.encodeUtf8String, - [dataTypes.timestamp]: this.encodeTimestamp, - [dataTypes.uuid]: this.encodeUuid, - [dataTypes.varchar]: this.encodeUtf8String, - [dataTypes.varint]: this.encodeVarint, - [dataTypes.timeuuid]: this.encodeUuid, - [dataTypes.inet]: this.encodeInet, - [dataTypes.date]: this.encodeDate, - [dataTypes.time]: this.encodeTime, - [dataTypes.smallint]: this.encodeSmallint, - [dataTypes.tinyint]: this.encodeTinyint, - [dataTypes.duration]: encodeDuration, - [dataTypes.list]: this.encodeList, - [dataTypes.map]: this.encodeMap, - [dataTypes.set]: this.encodeSet, - [dataTypes.udt]: this.encodeUdt, - [dataTypes.tuple]: this.encodeTuple - }; -} - -/** - * Decodes Cassandra bytes into Javascript values. - *

- * This is part of an experimental API, this can be changed future releases. - *

- * @param {Buffer} buffer Raw buffer to be decoded. - * @param {Object} type An object containing the data type code and info. - * @param {Number} type.code Type code. - * @param {Object} [type.info] Additional information on the type for complex / nested types. - */ -Encoder.prototype.decode = function (buffer, type) { - if (buffer === null || (buffer.length === 0 && !zeroLengthTypesSupported.has(type.code))) { - return null; - } - - const decoder = this.decoders[type.code]; - - if (!decoder) { - throw new Error('Unknown data type: ' + type.code); - } - - return decoder.call(this, buffer, type.info); -}; - -/** - * Encodes Javascript types into Buffer according to the Cassandra protocol. - *

- * This is part of an experimental API, this can be changed future releases. - *

- * @param {*} value The value to be converted. - * @param {{code: number, info: *|Object}|String|Number} [typeInfo] The type information. - *

It can be either a:

- *
    - *
  • A String representing the data type.
  • - *
  • A Number with one of the values of {@link module:types~dataTypes dataTypes}.
  • - *
  • An Object containing the type.code as one of the values of - * {@link module:types~dataTypes dataTypes} and type.info. - *
  • - *
- * @returns {Buffer} - * @throws {TypeError} When there is an encoding error - */ -Encoder.prototype.encode = function (value, typeInfo) { - if (value === undefined) { - value = this.encodingOptions.useUndefinedAsUnset && this.protocolVersion >= 4 ? types.unset : null; - } - - if (value === types.unset) { - if (!types.protocolVersion.supportsUnset(this.protocolVersion)) { - throw new TypeError('Unset value can not be used for this version of Cassandra, protocol version: ' + - this.protocolVersion); - } - - return value; - } - - if (value === null || value instanceof Buffer) { - return value; - } - - /** @type {{code: Number, info: object}} */ - let type = { - code: null, - info: null - }; - - if (typeInfo) { - if (typeof typeInfo === 'number') { - type.code = typeInfo; - } - else if (typeof typeInfo === 'string') { - type = dataTypes.getByName(typeInfo); - } - if (typeof typeInfo.code === 'number') { - type.code = typeInfo.code; - type.info = typeInfo.info; - } - if (typeof type.code !== 'number') { - throw new TypeError('Type information not valid, only String and Number values are valid hints'); - } - } - else { - //Lets guess - type = Encoder.guessDataType(value); - if (!type) { - throw new TypeError('Target data type could not be guessed, you should use prepared statements for accurate type mapping. Value: ' + util.inspect(value)); - } - } - - const encoder = this.encoders[type.code]; - - if (!encoder) { - throw new Error('Type not supported ' + type.code); - } - - return encoder.call(this, value, type.info); -}; - -/** - * Try to guess the Cassandra type to be stored, based on the javascript value type - * @param value - * @returns {{code: number, info: object}|null} - * @ignore - * @internal - */ -Encoder.guessDataType = function (value) { - let code = null; - let info = null; - const esTypeName = (typeof value); - if (esTypeName === 'number') { - code = dataTypes.double; - } - else if (esTypeName === 'string') { - code = dataTypes.text; - if (value.length === 36 && uuidRegex.test(value)){ - code = dataTypes.uuid; - } - } - else if (esTypeName === 'boolean') { - code = dataTypes.boolean; - } - else if (value instanceof Buffer) { - code = dataTypes.blob; - } - else if (value instanceof Date) { - code = dataTypes.timestamp; - } - else if (value instanceof Long) { - code = dataTypes.bigint; - } - else if (value instanceof Integer) { - code = dataTypes.varint; - } - else if (value instanceof BigDecimal) { - code = dataTypes.decimal; - } - else if (value instanceof types.Uuid) { - code = dataTypes.uuid; - } - else if (value instanceof types.InetAddress) { - code = dataTypes.inet; - } - else if (value instanceof types.Tuple) { - code = dataTypes.tuple; - } - else if (value instanceof types.LocalDate) { - code = dataTypes.date; - } - else if (value instanceof types.LocalTime) { - code = dataTypes.time; - } - else if (value instanceof types.Duration) { - code = dataTypes.custom; - info = customTypeNames.duration; - } - else if (Array.isArray(value)) { - code = dataTypes.list; - } - else if (value instanceof Geometry) { - code = dataTypes.custom; - if (value instanceof LineString) { - info = customTypeNames.lineString; - } else if (value instanceof Point) { - info = customTypeNames.point; - } else if (value instanceof Polygon) { - info = customTypeNames.polygon; - } - } - else if (value instanceof DateRange) { - code = dataTypes.custom; - info = customTypeNames.dateRange; - } - - if (code === null) { - return null; - } - return { code: code, info: info }; -}; - -/** - * Gets a buffer containing with the bytes (BE) representing the collection length for protocol v2 and below - * @param {Buffer|Number} value - * @returns {Buffer} - * @private - */ -function getLengthBufferV2(value) { - if (!value) { - return buffers.int16Zero; - } - const lengthBuffer = utils.allocBufferUnsafe(2); - if (typeof value === 'number') { - lengthBuffer.writeUInt16BE(value, 0); - } - else { - lengthBuffer.writeUInt16BE(value.length, 0); - } - return lengthBuffer; -} - -/** - * Gets a buffer containing with the bytes (BE) representing the collection length for protocol v3 and above - * @param {Buffer|Number} value - * @returns {Buffer} - * @private - */ -function getLengthBufferV3(value) { - if (!value) { - return buffers.int32Zero; - } - const lengthBuffer = utils.allocBufferUnsafe(4); - if (typeof value === 'number') { - lengthBuffer.writeInt32BE(value, 0); - } - else { - lengthBuffer.writeInt32BE(value.length, 0); - } - return lengthBuffer; -} - -/** - * @param {Buffer} buffer - * @private - */ -function handleBufferCopy(buffer) { - if (buffer === null) { - return null; - } - return utils.copyBuffer(buffer); -} - -/** - * @param {Buffer} buffer - * @private - */ -function handleBufferRef(buffer) { - return buffer; -} -/** - * Decodes collection length for protocol v3 and above - * @param bytes - * @param offset - * @returns {Number} - * @private - */ -function decodeCollectionLengthV3(bytes, offset) { - return bytes.readInt32BE(offset); -} -/** - * Decodes collection length for protocol v2 and below - * @param bytes - * @param offset - * @returns {Number} - * @private - */ -function decodeCollectionLengthV2(bytes, offset) { - return bytes.readUInt16BE(offset); -} - -function decodeDuration(bytes) { - return types.Duration.fromBuffer(bytes); -} - -function encodeDuration(value) { - if (!(value instanceof types.Duration)) { - throw new TypeError('Not a valid duration, expected Duration/Buffer obtained ' + util.inspect(value)); - } - return value.toBuffer(); -} - -/** - * @private - * @param {Buffer} buffer - */ -function decodeLineString(buffer) { - return LineString.fromBuffer(buffer); -} - -/** - * @private - * @param {LineString} value - */ -function encodeLineString(value) { - return value.toBuffer(); -} - -/** - * @private - * @param {Buffer} buffer - */ -function decodePoint(buffer) { - return Point.fromBuffer(buffer); -} - -/** - * @private - * @param {LineString} value - */ -function encodePoint(value) { - return value.toBuffer(); -} - -/** - * @private - * @param {Buffer} buffer - */ -function decodePolygon(buffer) { - return Polygon.fromBuffer(buffer); -} - -/** - * @private - * @param {Polygon} value - */ -function encodePolygon(value) { - return value.toBuffer(); -} - -function decodeDateRange(buffer) { - return DateRange.fromBuffer(buffer); -} - -/** - * @private - * @param {DateRange} value - */ -function encodeDateRange(value) { - return value.toBuffer(); -} - -/** - * @param {String} value - * @param {Number} startIndex - * @param {Number} length - * @param {String} [open] - * @param {String} [close] - * @returns {Array} - * @private - */ -function parseParams(value, startIndex, length, open, close) { - open = open || '('; - close = close || ')'; - const types = []; - let paramStart = startIndex; - let level = 0; - for (let i = startIndex; i < startIndex + length; i++) { - const c = value[i]; - if (c === open) { - level++; - } - if (c === close) { - level--; - } - if (level === 0 && c === ',') { - types.push(value.substr(paramStart, i - paramStart)); - paramStart = i + 1; - } - } - //Add the last one - types.push(value.substr(paramStart, length - (paramStart - startIndex))); - return types; -} - -/** - * @param {Array.} parts - * @param {Number} totalLength - * @returns {Buffer} - * @private - */ -function concatRoutingKey(parts, totalLength) { - if (totalLength === 0) { - return null; - } - if (parts.length === 1) { - return parts[0]; - } - const routingKey = utils.allocBufferUnsafe(totalLength); - let offset = 0; - for (let i = 0; i < parts.length; i++) { - const item = parts[i]; - routingKey.writeUInt16BE(item.length, offset); - offset += 2; - item.copy(routingKey, offset); - offset += item.length; - routingKey[offset] = 0; - offset++; - } - return routingKey; -} - -module.exports = Encoder; diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/errors.js b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/errors.js deleted file mode 100644 index 8ec192f5df..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/errors.js +++ /dev/null @@ -1,175 +0,0 @@ -/* - * Copyright DataStax, Inc. - * - * 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 util = require('util'); -/** - * Contains the error classes exposed by the driver. - * @module errors - */ - -/** - * Base Error - * @private - */ -function DriverError (message) { - Error.call(this, message); - Error.captureStackTrace(this, this.constructor); - this.name = this.constructor.name; - this.info = 'Cassandra Driver Error'; - // Explicitly set the message property as the Error.call() doesn't set the property on v8 - this.message = message; -} - -util.inherits(DriverError, Error); - -/** - * Represents an error when a query cannot be performed because no host is available or could be reached by the driver. - * @param {Object} innerErrors An object map containing the error per host tried - * @param {String} [message] - * @constructor - */ -function NoHostAvailableError(innerErrors, message) { - DriverError.call(this, message); - this.innerErrors = innerErrors; - this.info = 'Represents an error when a query cannot be performed because no host is available or could be reached by the driver.'; - if (!message) { - this.message = 'All host(s) tried for query failed.'; - if (innerErrors) { - const hostList = Object.keys(innerErrors); - if (hostList.length > 0) { - const host = hostList[0]; - this.message += util.format(' First host tried, %s: %s. See innerErrors.', host, innerErrors[host]); - } - } - } -} - -util.inherits(NoHostAvailableError, DriverError); - -/** - * Represents an error message from the server - * @param {Number} code Cassandra exception code - * @param {String} message - * @constructor - */ -function ResponseError(code, message) { - DriverError.call(this, message); - /** - * The error code as defined in [responseErrorCodes]{@link module:types~responseErrorCodes}. - * @type {Number} - */ - this.code = code; - this.info = 'Represents an error message from the server'; -} - -util.inherits(ResponseError, DriverError); - -/** - * Represents a bug inside the driver or in a Cassandra host. - * @param {String} message - * @constructor - */ -function DriverInternalError(message) { - DriverError.call(this, message); - this.info = 'Represents a bug inside the driver or in a Cassandra host.'; -} - -util.inherits(DriverInternalError, DriverError); - -/** - * Represents an error when trying to authenticate with auth-enabled host - * @param {String} message - * @constructor - */ -function AuthenticationError(message) { - DriverError.call(this, message); - this.info = 'Represents an authentication error from the driver or from a Cassandra node.'; -} - -util.inherits(AuthenticationError, DriverError); - -/** - * Represents an error that is raised when one of the arguments provided to a method is not valid - * @param {String} message - * @constructor - */ -function ArgumentError(message) { - DriverError.call(this, message); - this.info = 'Represents an error that is raised when one of the arguments provided to a method is not valid.'; -} - -util.inherits(ArgumentError, DriverError); - -/** - * Represents a client-side error that is raised when the client didn't hear back from the server within - * {@link ClientOptions.socketOptions.readTimeout}. - * @param {String} message The error message. - * @param {String} [host] Address of the server host that caused the operation to time out. - * @constructor - */ -function OperationTimedOutError(message, host) { - DriverError.call(this, message, this.constructor); - this.info = 'Represents a client-side error that is raised when the client did not hear back from the server ' + - 'within socketOptions.readTimeout'; - - /** - * When defined, it gets the address of the host that caused the operation to time out. - * @type {String|undefined} - */ - this.host = host; -} - -util.inherits(OperationTimedOutError, DriverError); - -/** - * Represents an error that is raised when a feature is not supported in the driver or in the current Cassandra version. - * @param message - * @constructor - */ -function NotSupportedError(message) { - DriverError.call(this, message, this.constructor); - this.info = 'Represents a feature that is not supported in the driver or in the Cassandra version.'; -} - -util.inherits(NotSupportedError, DriverError); - -/** - * Represents a client-side error indicating that all connections to a certain host have reached - * the maximum amount of in-flight requests supported. - * @param {String} address - * @param {Number} maxRequestsPerConnection - * @param {Number} connectionLength - * @constructor - */ -function BusyConnectionError(address, maxRequestsPerConnection, connectionLength) { - const message = util.format('All connections to host %s are busy, %d requests are in-flight on %s', - address, maxRequestsPerConnection, connectionLength === 1 ? 'a single connection': 'each connection'); - DriverError.call(this, message, this.constructor); - this.info = 'Represents a client-side error indicating that all connections to a certain host have reached ' + - 'the maximum amount of in-flight requests supported (pooling.maxRequestsPerConnection)'; -} - -util.inherits(BusyConnectionError, DriverError); - -exports.ArgumentError = ArgumentError; -exports.AuthenticationError = AuthenticationError; -exports.BusyConnectionError = BusyConnectionError; -exports.DriverError = DriverError; -exports.OperationTimedOutError = OperationTimedOutError; -exports.DriverInternalError = DriverInternalError; -exports.NoHostAvailableError = NoHostAvailableError; -exports.NotSupportedError = NotSupportedError; -exports.ResponseError = ResponseError; \ No newline at end of file diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/execution-options.js b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/execution-options.js deleted file mode 100644 index cc3df181f6..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/execution-options.js +++ /dev/null @@ -1,619 +0,0 @@ -/* - * Copyright DataStax, Inc. - * - * 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 utils = require('./utils'); -const types = require('./types'); -const errors = require('./errors'); - -const proxyExecuteKey = 'ProxyExecute'; - -/** - * A base class that represents a wrapper around the user provided query options with getter methods and proper - * default values. - *

- * Note that getter methods might return undefined when not set on the query options or default - * {@link Client} options. - *

- */ -class ExecutionOptions { - - /** - * Creates a new instance of {@link ExecutionOptions}. - */ - constructor() { - } - - /** - * Creates an empty instance, where all methods return undefined, used internally. - * @ignore - * @return {ExecutionOptions} - */ - static empty() { - return new ExecutionOptions(); - } - - /** - * Determines if the stack trace before the query execution should be maintained. - * @abstract - * @returns {Boolean} - */ - getCaptureStackTrace() { - - } - - /** - * Gets the [Consistency level]{@link module:types~consistencies} to be used for the execution. - * @abstract - * @returns {Number} - */ - getConsistency() { - - } - - /** - * Key-value payload to be passed to the server. On the server side, implementations of QueryHandler can use - * this data. - * @abstract - * @returns {Object} - */ - getCustomPayload() { - - } - - /** - * Gets the amount of rows to retrieve per page. - * @abstract - * @returns {Number} - */ - getFetchSize() { - - } - - /** - * When a fixed host is set on the query options and the query plan for the load-balancing policy is not used, it - * gets the host that should handle the query. - * @returns {Host} - */ - getFixedHost() { - - } - - /** - * Gets the type hints for parameters given in the query, ordered as for the parameters. - * @abstract - * @returns {Array|Array} - */ - getHints() { - - } - - /** - * Determines whether the driver must retrieve the following result pages automatically. - *

- * This setting is only considered by the [Client#eachRow()]{@link Client#eachRow} method. - *

- * @abstract - * @returns {Boolean} - */ - isAutoPage() { - - } - - /** - * Determines whether its a counter batch. Only valid for [Client#batch()]{@link Client#batch}, it will be ignored by - * other methods. - * @abstract - * @returns {Boolean} A Boolean value, it can't be undefined. - */ - isBatchCounter() { - - } - - /** - * Determines whether the batch should be written to the batchlog. Only valid for - * [Client#batch()]{@link Client#batch}, it will be ignored by other methods. - * @abstract - * @returns {Boolean} A Boolean value, it can't be undefined. - */ - isBatchLogged() { - - } - - /** - * Determines whether the query can be applied multiple times without changing the result beyond the initial - * application. - * @abstract - * @returns {Boolean} - */ - isIdempotent() { - - } - - /** - * Determines whether the query must be prepared beforehand. - * @abstract - * @returns {Boolean} A Boolean value, it can't be undefined. - */ - isPrepared() { - - } - - /** - * Determines whether query tracing is enabled for the execution. - * @abstract - * @returns {Boolean} - */ - isQueryTracing() { - - } - - /** - * Gets the keyspace for the query when set at query options level. - *

- * Note that this method will return undefined when the keyspace is not set at query options level. - * It will only return the keyspace name when the user provided a different keyspace than the current - * {@link Client} keyspace. - *

- * @abstract - * @returns {String} - */ - getKeyspace() { - - } - - /** - * Gets the load balancing policy used for this execution. - * @returns {LoadBalancingPolicy} A LoadBalancingPolicy instance, it can't be undefined. - */ - getLoadBalancingPolicy() { - - } - - /** - * Gets the Buffer representing the paging state. - * @abstract - * @returns {Buffer} - */ - getPageState() { - - } - - /** - * Internal method that gets the preferred host. - * @abstract - * @ignore - */ - getPreferredHost() { - - } - - /** - * Gets the query options as provided to the execution method without setting the default values. - * @returns {QueryOptions} - */ - getRawQueryOptions() { - - } - - /** - * Gets the timeout in milliseconds to be used for the execution per coordinator. - *

- * A value of 0 disables client side read timeout for the execution. Default: undefined. - *

- * @abstract - * @returns {Number} - */ - getReadTimeout() { - - } - - /** - * Gets the [retry policy]{@link module:policies/retry} to be used. - * @abstract - * @returns {RetryPolicy} A RetryPolicy instance, it can't be undefined. - */ - getRetryPolicy() { - - } - - /** - * Internal method to obtain the row callback, for "by row" results. - * @abstract - * @ignore - */ - getRowCallback() { - - } - - /** - * Internal method to get or generate a timestamp for the request execution. - * @ignore - * @returns {Long|null} - */ - getOrGenerateTimestamp() { - - } - - /** - * Gets the index of the parameters that are part of the partition key to determine the routing. - * @abstract - * @ignore - * @returns {Array} - */ - getRoutingIndexes() { - - } - - /** - * Gets the partition key(s) to determine which coordinator should be used for the query. - * @abstract - * @returns {Buffer|Array} - */ - getRoutingKey() { - - } - - /** - * Gets the array of the parameters names that are part of the partition key to determine the - * routing. Only valid for non-prepared requests. - * @abstract - * @ignore - */ - getRoutingNames() { - - } - - /** - * Gets the the consistency level to be used for the serial phase of conditional updates. - * @abstract - * @returns {Number} - */ - getSerialConsistency() { - - } - - /** - * Gets the provided timestamp for the execution in microseconds from the unix epoch (00:00:00, January 1st, 1970). - *

When a timestamp generator is used, this method returns undefined.

- * @abstract - * @returns {Number|Long|undefined|null} - */ - getTimestamp() { - - } - - /** - * @param {Array} hints - * @abstract - * @ignore - */ - setHints(hints) { - - } - - /** - * Sets the keyspace for the execution. - * @ignore - * @abstract - * @param {String} keyspace - */ - setKeyspace(keyspace) { - - } - - /** - * @abstract - * @ignore - */ - setPageState() { - - } - - /** - * Internal method that sets the preferred host. - * @abstract - * @ignore - */ - setPreferredHost() { - - } - - /** - * Sets the index of the parameters that are part of the partition key to determine the routing. - * @param {Array} routingIndexes - * @abstract - * @ignore - */ - setRoutingIndexes(routingIndexes) { - - } - - /** - * Sets the routing key. - * @abstract - * @ignore - */ - setRoutingKey(value) { - - } -} - -/** - * Internal implementation of {@link ExecutionOptions} that uses the value from the client options and execution - * profile into account. - * @ignore - */ -class DefaultExecutionOptions extends ExecutionOptions { - /** - * Creates a new instance of {@link ExecutionOptions}. - * @param {QueryOptions} queryOptions - * @param {Client} client - * @param {Function|null} rowCallback - */ - constructor(queryOptions, client, rowCallback) { - super(); - - this._queryOptions = queryOptions; - this._rowCallback = rowCallback; - this._routingKey = this._queryOptions.routingKey; - this._hints = this._queryOptions.hints; - this._keyspace = this._queryOptions.keyspace; - this._routingIndexes = this._queryOptions.routingIndexes; - this._pageState = typeof this._queryOptions.pageState === 'string' ? - utils.allocBufferFromString(this._queryOptions.pageState, 'hex') : this._queryOptions.pageState; - this._preferredHost = null; - - this._client = client; - this._defaultQueryOptions = client.options.queryOptions; - this._profile = client.profileManager.getProfile(this._queryOptions.executionProfile); - - // Build a custom payload object designed for DSE-specific functionality - this._customPayload = DefaultExecutionOptions.createCustomPayload(this._queryOptions, this._defaultQueryOptions); - - if (!this._profile) { - throw new errors.ArgumentError(`Execution profile "${this._queryOptions.executionProfile}" not found`); - } - } - - /** - * Creates a payload for given user. - * @param {QueryOptions} userOptions - * @param {QueryOptions} defaultQueryOptions - * @private - */ - static createCustomPayload(userOptions, defaultQueryOptions) { - let customPayload = userOptions.customPayload || defaultQueryOptions.customPayload; - const executeAs = userOptions.executeAs || defaultQueryOptions.executeAs; - - if (executeAs) { - if (!customPayload) { - customPayload = {}; - customPayload[proxyExecuteKey] = utils.allocBufferFromString(executeAs); - } else if (!customPayload[proxyExecuteKey]) { - // Avoid appending to the existing payload object - customPayload = utils.extend({}, customPayload); - customPayload[proxyExecuteKey] = utils.allocBufferFromString(executeAs); - } - } - - return customPayload; - } - - /** - * Creates a new instance {@link ExecutionOptions}, based on the query options. - * @param {QueryOptions|null} queryOptions - * @param {Client} client - * @param {Function|null} [rowCallback] - * @ignore - * @return {ExecutionOptions} - */ - static create(queryOptions, client, rowCallback) { - if (!queryOptions || typeof queryOptions === 'function') { - // queryOptions can be null/undefined and could be of type function when is an optional parameter - queryOptions = utils.emptyObject; - } - return new DefaultExecutionOptions(queryOptions, client, rowCallback); - } - - getCaptureStackTrace() { - return ifUndefined(this._queryOptions.captureStackTrace, this._defaultQueryOptions.captureStackTrace); - } - - getConsistency() { - return ifUndefined3(this._queryOptions.consistency, this._profile.consistency, - this._defaultQueryOptions.consistency); - } - - getCustomPayload() { - return this._customPayload; - } - - getFetchSize() { - return ifUndefined(this._queryOptions.fetchSize, this._defaultQueryOptions.fetchSize); - } - - getFixedHost() { - return this._queryOptions.host; - } - - getHints() { - return this._hints; - } - - isAutoPage() { - return ifUndefined(this._queryOptions.autoPage, this._defaultQueryOptions.autoPage); - } - - isBatchCounter() { - return ifUndefined(this._queryOptions.counter, false); - } - - isBatchLogged() { - return ifUndefined3(this._queryOptions.logged, this._defaultQueryOptions.logged, true); - } - - isIdempotent() { - return ifUndefined(this._queryOptions.isIdempotent, this._defaultQueryOptions.isIdempotent); - } - - /** - * Determines if the query execution must be prepared beforehand. - * @return {Boolean} - */ - isPrepared() { - return ifUndefined(this._queryOptions.prepare, this._defaultQueryOptions.prepare); - } - - isQueryTracing() { - return ifUndefined(this._queryOptions.traceQuery, this._defaultQueryOptions.traceQuery); - } - - getKeyspace() { - return this._keyspace; - } - - getLoadBalancingPolicy() { - return this._profile.loadBalancing; - } - - getOrGenerateTimestamp() { - let result = this.getTimestamp(); - - if (result === undefined) { - const generator = this._client.options.policies.timestampGeneration; - - if ( types.protocolVersion.supportsTimestamp(this._client.controlConnection.protocolVersion) && generator) { - result = generator.next(this._client); - } else { - result = null; - } - } - - return typeof result === 'number' ? types.Long.fromNumber(result) : result; - } - - getPageState() { - return this._pageState; - } - - /** - * Gets the profile defined by the user or the default profile - * @internal - * @ignore - */ - getProfile() { - return this._profile; - } - - getRawQueryOptions() { - return this._queryOptions; - } - - getReadTimeout() { - return ifUndefined3(this._queryOptions.readTimeout, this._profile.readTimeout, - this._client.options.socketOptions.readTimeout); - } - - getRetryPolicy() { - return ifUndefined3(this._queryOptions.retry, this._profile.retry, this._client.options.policies.retry); - } - - getRoutingIndexes() { - return this._routingIndexes; - } - - getRoutingKey() { - return this._routingKey; - } - - getRoutingNames() { - return this._queryOptions.routingNames; - } - - /** - * Internal method to obtain the row callback, for "by row" results. - * @ignore - */ - getRowCallback() { - return this._rowCallback; - } - - getSerialConsistency() { - return ifUndefined3( - this._queryOptions.serialConsistency, this._profile.serialConsistency, this._defaultQueryOptions.serialConsistency); - } - - getTimestamp() { - return this._queryOptions.timestamp; - } - - /** - * Internal property to set the custom payload. - * @ignore - * @internal - * @param {Object} payload - */ - setCustomPayload(payload) { - this._customPayload = payload; - } - - /** - * @param {Array} hints - */ - setHints(hints) { - this._hints = hints; - } - - /** - * @param {String} keyspace - */ - setKeyspace(keyspace) { - this._keyspace = keyspace; - } - - /** - * @param {Buffer} pageState - */ - setPageState(pageState) { - this._pageState = pageState; - } - - /** - * @param {Array} routingIndexes - */ - setRoutingIndexes(routingIndexes) { - this._routingIndexes = routingIndexes; - } - - setRoutingKey(value) { - this._routingKey = value; - } -} - -function ifUndefined(v1, v2) { - return v1 !== undefined ? v1 : v2; -} - -function ifUndefined3(v1, v2, v3) { - if (v1 !== undefined) { - return v1; - } - return v2 !== undefined ? v2 : v3; -} - -module.exports = { ExecutionOptions, DefaultExecutionOptions, proxyExecuteKey }; \ No newline at end of file diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/execution-profile.js b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/execution-profile.js deleted file mode 100644 index 78c4fc2b2c..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/execution-profile.js +++ /dev/null @@ -1,266 +0,0 @@ -/* - * Copyright DataStax, Inc. - * - * 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 utils = require('./utils'); -const types = require('./types'); -const promiseUtils = require('./promise-utils'); - -/** - * Creates a new instance of {@link ExecutionProfile}. - * @classdesc - * Represents a set configurations to be used in a statement execution to be used for a single {@link Client} instance. - *

- * An {@link ExecutionProfile} instance should not be shared across different {@link Client} instances. - *

- * @param {String} name Name of the execution profile. - *

- * Use 'default' to specify that the new instance should be the default {@link ExecutionProfile} if no - * profile is specified in the execution. - *

- * @param {Object} [options] Profile options, when any of the options is not specified the {@link Client} will the use - * the ones defined in the default profile. - * @param {Number} [options.consistency] The consistency level to use for this profile. - * @param {LoadBalancingPolicy} [options.loadBalancing] The load-balancing policy to use for this profile. - * @param {Number} [options.readTimeout] The client per-host request timeout to use for this profile. - * @param {RetryPolicy} [options.retry] The retry policy to use for this profile. - * @param {Number} [options.serialConsistency] The serial consistency level to use for this profile. - * @param {Object} [options.graphOptions] - * @param {String} [options.graphOptions.language] The graph language to use for graph queries. - *

- * Note that this setting should normally be undefined or set by a utility method and it's not expected - * to be defined manually by the user. - *

- * @param {String} [options.graphOptions.results] The protocol to use for serializing and deserializing graph results. - *

- * Note that this setting should normally be undefined or set by a utility method and it's not expected - * to be defined manually by the user. - *

- * @param {String} [options.graphOptions.name] The graph name to use for graph queries. - * @param {Number} [options.graphOptions.readConsistency] The consistency level to use for graph read queries. - * @param {String} [options.graphOptions.source] The graph traversal source name to use for graph queries. - * @param {Number} [options.graphOptions.writeConsistency] The consistency level to use for graph write queries. - * @param {LoadBalancingPolicy} [options.loadBalancing] The load-balancing policy to use for this profile. - * @param {Number} [options.readTimeout] The client per-host request timeout to use for this profile. - * @param {RetryPolicy} [options.retry] The retry policy to use for this profile. - * @param {Number} [options.serialConsistency] The serial consistency level to use for this profile. - * @example - * const { Client, ExecutionProfile } = require('cassandra-driver'); - * const client = new Client({ - * contactPoints: ['host1', 'host2'], - * profiles: [ - * new ExecutionProfile('metrics-oltp', { - * consistency: consistency.localQuorum, - * retry: myRetryPolicy - * }) - * ] - * }); - * - * client.execute(query, params, { executionProfile: 'metrics-oltp' }, callback); - * @constructor - */ -function ExecutionProfile(name, options) { - if (typeof name !== 'string') { - throw new TypeError('Execution profile name must be a string'); - } - options = options || utils.emptyObject; - const graphOptions = options.graphOptions || utils.emptyObject; - /** - * Name of the execution profile. - * @type {String} - */ - this.name = name; - /** - * Consistency level. - * @type {Number} - */ - this.consistency = options.consistency; - /** - * Load-balancing policy - * @type {LoadBalancingPolicy} - */ - this.loadBalancing = options.loadBalancing; - /** - * Client read timeout. - * @type {Number} - */ - this.readTimeout = options.readTimeout; - /** - * Retry policy. - * @type {RetryPolicy} - */ - this.retry = options.retry; - /** - * Serial consistency level. - * @type {Number} - */ - this.serialConsistency = options.serialConsistency; - /** - * The graph options for this profile. - * @type {Object} - * @property {String} language The graph language. - * @property {String} name The graph name. - * @property {String} readConsistency The consistency to use for graph write queries. - * @property {String} source The graph traversal source. - * @property {String} writeConsistency The consistency to use for graph write queries. - */ - this.graphOptions = { - language: graphOptions.language, - results: graphOptions.results, - name: graphOptions.name, - readConsistency: graphOptions.readConsistency, - source: graphOptions.source, - writeConsistency: graphOptions.writeConsistency - }; -} - -/** - * Contains the logic to handle the different execution profiles of a {@link Client}. - * @ignore - */ -class ProfileManager { - - /** - * @param {ClientOptions} options - */ - constructor(options) { - this._profiles = options.profiles || []; - this._defaultConfiguredRetryPolicy = undefined; - this._setDefault(options); - // A array of unique load balancing policies - this._loadBalancingPolicies = []; - // A dictionary of name keys and profile values - this._profilesMap = {}; - // A dictionary of name keys and custom payload dictionaries as values - this._customPayloadCache = {}; - // A dictionary of name keys and graph options as values - this._graphOptionsCache = {}; - this._profiles.forEach(function (p) { - this._profilesMap[p.name] = p; - // Set required properties - p.loadBalancing = p.loadBalancing || this._defaultProfile.loadBalancing; - // Using array indexOf is not very efficient (O(n)) but the amount of profiles should be limited - // and a handful of load-balancing policies (no hashcode for load-Balancing policies) - if (this._loadBalancingPolicies.indexOf(p.loadBalancing) === -1) { - this._loadBalancingPolicies.push(p.loadBalancing); - } - return p; - }, this); - } - - /** - * @param {Client} client - * @param {HostMap} hosts - */ - async init(client, hosts) { - for (const lbp of this._loadBalancingPolicies) { - await promiseUtils.fromCallback(callback => lbp.init(client, hosts, callback)); - } - } - - /** - * Uses the load-balancing policies to get the relative distance to the host and return the closest one. - * @param {Host} host - */ - getDistance(host) { - let distance = types.distance.ignored; - // this is performance critical: we can't use any other language features than for-loop :( - for (let i = 0; i < this._loadBalancingPolicies.length; i++) { - const d = this._loadBalancingPolicies[i].getDistance(host); - if (d < distance) { - distance = d; - if (distance === types.distance.local) { - break; - } - } - } - - host.setDistance(distance); - return distance; - } - - /** - * @param {String|ExecutionProfile} name - * @returns {ExecutionProfile|undefined} It returns the execution profile by name or the default profile when name is - * undefined. It returns undefined when the profile does not exist. - */ - getProfile(name) { - if (name instanceof ExecutionProfile) { - return name; - } - return this._profilesMap[name || 'default']; - } - - /** @returns {ExecutionProfile} */ - getDefault() { - return this._defaultProfile; - } - - /** @returns {LoadBalancingPolicy} */ - getDefaultLoadBalancing() { - return this._defaultProfile.loadBalancing; - } - - /** - * Gets the cached default graph options for a given profile. If it doesn't exist, it creates new options using the - * handler and inserts it into the cache - * @param {ExecutionProfile} profile - * @param {Function} createHandler - */ - getOrCreateGraphOptions(profile, createHandler) { - let graphOptions = this._graphOptionsCache[profile.name]; - if (!graphOptions) { - graphOptions = (this._graphOptionsCache[profile.name] = createHandler()); - } - return graphOptions; - } - - /** - * @private - * @param {ClientOptions} options - */ - _setDefault(options) { - this._defaultProfile = this._profiles.filter(function (p) { return p.name === 'default'; })[0]; - if (!this._defaultProfile) { - this._profiles.push(this._defaultProfile = new ExecutionProfile('default')); - } - - // Store the default configured retry policy - this._defaultConfiguredRetryPolicy = this._defaultProfile.retry; - - // Set the required properties - this._defaultProfile.loadBalancing = this._defaultProfile.loadBalancing || options.policies.loadBalancing; - this._defaultProfile.retry = this._defaultProfile.retry || options.policies.retry; - } - - /** - * Gets all the execution profiles currently defined. - * @returns {Array.} - */ - getAll() { - return this._profiles; - } - - getDefaultConfiguredRetryPolicy() { - return this._defaultConfiguredRetryPolicy; - } -} - -module.exports = { - ProfileManager, - ExecutionProfile -}; \ No newline at end of file diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/geometry/geometry.js b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/geometry/geometry.js deleted file mode 100644 index b91c8fdbbf..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/geometry/geometry.js +++ /dev/null @@ -1,133 +0,0 @@ -/* - * Copyright DataStax, Inc. - * - * 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 endianness = { - '0': 'BE', - '1': 'LE' -}; - -function Geometry() { - -} - -Geometry.types = { - Point2D: 1, - LineString: 2, - Polygon: 3 -}; - -/** - * @protected - * @param {Number} code - * @returns {String} - * @ignore - */ -Geometry.getEndianness = function (code) { - const value = endianness[code.toString()]; - if (typeof value === 'undefined') { - throw new TypeError('Invalid endianness with code ' + code); - } - return value; -}; - -/** - * Reads an int32 from binary representation based on endianness. - * @protected - * @param {Buffer} buffer - * @param {String} endianness - * @param {Number} offset - * @returns Number - * @ignore - */ -Geometry.readInt32 = function (buffer, endianness, offset) { - if (endianness === 'BE') { - return buffer.readInt32BE(offset, true); - } - return buffer.readInt32LE(offset, true); -}; - -/** - * Reads an 64-bit double from binary representation based on endianness. - * @protected - * @param {Buffer} buffer - * @param {String} endianness - * @param {Number} offset - * @returns Number - * @ignore - */ -Geometry.readDouble = function (buffer, endianness, offset) { - if (endianness === 'BE') { - return buffer.readDoubleBE(offset, true); - } - return buffer.readDoubleLE(offset, true); -}; - -/** - * Writes an 32-bit integer to binary representation based on OS endianness. - * @protected - * @param {Number} val - * @param {Buffer} buffer - * @param {Number} offset - * @ignore - */ -Geometry.prototype.writeInt32 = function (val, buffer, offset) { - if (this.useBESerialization()) { - return buffer.writeInt32BE(val, offset, true); - } - return buffer.writeInt32LE(val, offset, true); -}; - -/** - * Writes an 64-bit double to binary representation based on OS endianness. - * @protected - * @param {Number} val - * @param {Buffer} buffer - * @param {Number} offset - * @ignore - */ -Geometry.prototype.writeDouble = function (val, buffer, offset) { - if (this.useBESerialization()) { - return buffer.writeDoubleBE(val, offset, true); - } - return buffer.writeDoubleLE(val, offset, true); -}; - -/** - * Writes an 8-bit int that represents the OS endianness. - * @protected - * @param {Buffer} buffer - * @param {Number} offset - * @ignore - */ -Geometry.prototype.writeEndianness = function (buffer, offset) { - if (this.useBESerialization()) { - return buffer.writeInt8(0, offset, true); - } - return buffer.writeInt8(1, offset, true); -}; - -/** - * Returns true if the serialization must be done in big-endian format. - * Designed to allow injection of OS endianness. - * @abstract - * @ignore - */ -Geometry.prototype.useBESerialization = function () { - throw new Error('Not Implemented'); -}; - -module.exports = Geometry; \ No newline at end of file diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/geometry/index.d.ts b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/geometry/index.d.ts deleted file mode 100644 index 82ad292bad..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/geometry/index.d.ts +++ /dev/null @@ -1,67 +0,0 @@ -/* - * Copyright DataStax, Inc. - * - * 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. - */ - -export namespace geometry { - class LineString { - constructor(...args: Point[]); - - static fromBuffer(buffer: Buffer): LineString; - - static fromString(textValue: string): LineString; - - equals(other: LineString): boolean; - - toBuffer(): Buffer; - - toJSON(): string; - - toString(): string; - - } - - class Point { - constructor(x: number, y: number); - - static fromBuffer(buffer: Buffer): Point; - - static fromString(textValue: string): Point; - - equals(other: Point): boolean; - - toBuffer(): Buffer; - - toJSON(): string; - - toString(): string; - - } - - class Polygon { - constructor(...args: Point[]); - - static fromBuffer(buffer: Buffer): Polygon; - - static fromString(textValue: string): Polygon; - - equals(other: Polygon): boolean; - - toBuffer(): Buffer; - - toJSON(): string; - - toString(): string; - } -} \ No newline at end of file diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/geometry/index.js b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/geometry/index.js deleted file mode 100644 index 28c9bc7b66..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/geometry/index.js +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Copyright DataStax, Inc. - * - * 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'; - -/** - * Geometry module. - *

- * Contains the classes to represent the set of additional CQL types for geospatial data that come with - * DSE 5.0. - *

- * @module geometry - */ - -exports.Geometry = require('./geometry'); -exports.LineString = require('./line-string'); -exports.Point = require('./point'); -exports.Polygon = require('./polygon'); \ No newline at end of file diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/geometry/line-string.js b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/geometry/line-string.js deleted file mode 100644 index 3e7c8ee257..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/geometry/line-string.js +++ /dev/null @@ -1,197 +0,0 @@ -/* - * Copyright DataStax, Inc. - * - * 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 util = require('util'); -const utils = require('../utils'); -const Geometry = require('./geometry'); -const Point = require('./point'); - -/** - * Creates a new {@link LineString} instance. - * @classdesc - * A LineString is a one-dimensional object representing a sequence of points and the line segments connecting them. - * @param {...Point}[point] A sequence of [Point]{@link module:geometry~Point} items as arguments. - * @example - * new LineString(new Point(10.99, 20.02), new Point(14, 26), new Point(34, 1.2)); - * @constructor - * @alias module:geometry~LineString - * @extends {Geometry} - */ -function LineString(point) { - let points = Array.prototype.slice.call(arguments); - if (points.length === 1 && Array.isArray(points) && Array.isArray(points[0])) { - //The first argument is an array of the points - points = points[0]; - } - if (points.length === 1) { - throw new TypeError('LineString can be either empty or contain 2 or more points'); - } - /** - * Returns a frozen Array of points that represent the line. - * @type {Array.} - */ - this.points = Object.freeze(points); -} - -//noinspection JSCheckFunctionSignatures -util.inherits(LineString, Geometry); - -/** - * Creates a {@link LineString} instance from - * a Well-known Text (WKT) - * representation of a line. - * @param {Buffer} buffer - * @returns {LineString} - */ -LineString.fromBuffer = function (buffer) { - if (!buffer || buffer.length < 9) { - throw new TypeError('A linestring buffer should contain at least 9 bytes'); - } - const endianness = Geometry.getEndianness(buffer.readInt8(0, true)); - let offset = 1; - if (Geometry.readInt32(buffer, endianness, offset) !== Geometry.types.LineString) { - throw new TypeError('Binary representation was not a LineString'); - } - offset += 4; - const length = Geometry.readInt32(buffer, endianness, offset); - offset += 4; - if (buffer.length !== offset + length * 16) { - throw new TypeError(util.format('Length of the buffer does not match %d !== %d', buffer.length, offset + length * 8)); - } - const points = new Array(length); - for (let i = 0; i < length; i++) { - points[i] = new Point( - Geometry.readDouble(buffer, endianness, offset), - Geometry.readDouble(buffer, endianness, offset + 8)); - offset += 16; - } - //noinspection JSCheckFunctionSignatures - return new LineString(points); -}; - -/** - * Creates a {@link LineString} instance from - * a Well-known Text (WKT) - * representation of a line. - * @param {String} textValue - * @returns {LineString} - */ -LineString.fromString = function (textValue) { - const wktRegex = /^LINESTRING ?\(([-0-9. ,]+)\)+$/g; - const matches = wktRegex.exec(textValue); - if (!matches || matches.length !== 2) { - throw new TypeError('Invalid WKT: ' + textValue); - } - const points = LineString.parseSegments(matches[1]); - return new LineString(points); -}; - -/** - * Internal method that parses a series of WKT points. - * @param {String} textValue - * @returns {Array} - * @internal - * @ignore - */ -LineString.parseSegments = function (textValue) { - const points = []; - const pointParts = textValue.split(','); - for (let i = 0; i < pointParts.length; i++) { - const p = pointParts[i].trim(); - if (p.length === 0) { - throw new TypeError('Invalid WKT segment: ' + textValue); - } - const xyText = p.split(' ').filter(function (element) { - return (element.trim().length > 0); - }); - if (xyText.length !== 2) { - throw new TypeError('Invalid WKT segment: ' + textValue); - } - points.push(new Point(parseFloat(xyText[0]), parseFloat(xyText[1]))); - } - return points; -}; - -/** - * Returns a Well-known Binary (WKB) - * representation of this instance. - * @returns {Buffer} - */ -LineString.prototype.toBuffer = function () { - const buffer = utils.allocBufferUnsafe(9 + this.points.length * 16); - this.writeEndianness(buffer, 0); - let offset = 1; - this.writeInt32(Geometry.types.LineString, buffer, offset); - offset += 4; - this.writeInt32(this.points.length, buffer, offset); - offset += 4; - this.points.forEach(function (p) { - this.writeDouble(p.x, buffer, offset); - this.writeDouble(p.y, buffer, offset + 8); - offset += 16; - }, this); - return buffer; -}; - -/** - * Returns true if the values of the linestrings are the same, otherwise it returns false. - * @param {LineString} other - * @returns {Boolean} - */ -LineString.prototype.equals = function (other) { - if (!(other instanceof LineString)) { - return false; - } - if (this.points.length !== other.points.length) { - return false; - } - for (let i = 0; i < this.points.length; i++) { - if (!this.points[i].equals(other.points[i])) { - return false; - } - } - return true; -}; - -/** - * Returns Well-known text (WKT) representation of the geometry object. - * @returns {String} - */ -LineString.prototype.toString = function () { - if (this.points.length === 0) { - return 'LINESTRING EMPTY'; - } - return 'LINESTRING (' - + this.points.map(function (p) { - return p.x + ' ' + p.y; - }).join(', ') - + ')'; -}; - -LineString.prototype.useBESerialization = function () { - return false; -}; - -/** - * Returns a JSON representation of this geo-spatial type. - */ -LineString.prototype.toJSON = function () { - return { type: 'LineString', coordinates: this.points.map(function (p) { - return [p.x, p.y]; - })}; -}; - -module.exports = LineString; \ No newline at end of file diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/geometry/point.js b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/geometry/point.js deleted file mode 100644 index 473b6cd1d2..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/geometry/point.js +++ /dev/null @@ -1,134 +0,0 @@ -/* - * Copyright DataStax, Inc. - * - * 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 util = require('util'); -const utils = require('../utils'); -const Geometry = require('./geometry'); - -/** - * Creates a new {@link Point} instance. - * @classdesc - * A Point is a zero-dimensional object that represents a specific (X,Y) - * location in a two-dimensional XY-Plane. In case of Geographic Coordinate - * Systems, the X coordinate is the longitude and the Y is the latitude. - * @param {Number} x The X coordinate. - * @param {Number} y The Y coordinate. - * @extends {Geometry} - * @alias module:geometry~Point - * @constructor - */ -function Point(x, y) { - if (typeof x !== 'number' || typeof y !== 'number') { - throw new TypeError('X and Y must be numbers'); - } - if (isNaN(x) || isNaN(y)) { - throw new TypeError('X and Y must be numbers'); - } - /** - * Returns the X coordinate of this 2D point. - * @type {Number} - */ - this.x = x; - /** - * Returns the Y coordinate of this 2D point. - * @type {Number} - */ - this.y = y; -} - -//noinspection JSCheckFunctionSignatures -util.inherits(Point, Geometry); - -/** - * Creates a {@link Point} instance from - * a Well-known Text (WKT) - * representation of a 2D point. - * @param {Buffer} buffer - * @returns {Point} - */ -Point.fromBuffer = function (buffer) { - if (!buffer || buffer.length !== 21) { - throw new TypeError('2D Point buffer should contain 21 bytes'); - } - const endianness = Geometry.getEndianness(buffer.readInt8(0, true)); - if (Geometry.readInt32(buffer, endianness, 1) !== Geometry.types.Point2D) { - throw new TypeError('Binary representation was not a point'); - } - return new Point(Geometry.readDouble(buffer, endianness, 5), Geometry.readDouble(buffer, endianness, 13)); -}; - -/** - * Creates a {@link Point} instance from - * a Well-known Text (WKT) - * representation of a 2D point. - * @param {String} textValue - * @returns {Point} - */ -Point.fromString = function (textValue) { - const wktRegex = /^POINT\s?\(([-0-9.]+) ([-0-9.]+)\)$/g; - const matches = wktRegex.exec(textValue); - if (!matches || matches.length !== 3) { - throw new TypeError('2D Point WTK should contain 2 coordinates'); - } - return new Point(parseFloat(matches[1]), parseFloat(matches[2])); -}; - -/** - * Returns a Well-known Binary (WKB) - * representation of this instance. - * @returns {Buffer} - */ -Point.prototype.toBuffer = function () { - const buffer = utils.allocBufferUnsafe(21); - this.writeEndianness(buffer, 0); - this.writeInt32(Geometry.types.Point2D, buffer, 1); - this.writeDouble(this.x, buffer, 5); - this.writeDouble(this.y, buffer, 13); - return buffer; -}; - -/** - * Returns true if the values of the point are the same, otherwise it returns false. - * @param {Point} other - * @returns {Boolean} - */ -Point.prototype.equals = function (other) { - if (!(other instanceof Point)) { - return false; - } - return (this.x === other.x && this.y === other.y); -}; - -/** - * Returns Well-known text (WKT) representation of the geometry object. - * @returns {String} - */ -Point.prototype.toString = function () { - return util.format('POINT (%d %d)', this.x, this.y); -}; - -Point.prototype.useBESerialization = function () { - return false; -}; - -/** - * Returns a JSON representation of this geo-spatial type. - */ -Point.prototype.toJSON = function () { - return { type: 'Point', coordinates: [ this.x, this.y ]}; -}; - -module.exports = Point; \ No newline at end of file diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/geometry/polygon.js b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/geometry/polygon.js deleted file mode 100644 index c4536e1185..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/geometry/polygon.js +++ /dev/null @@ -1,239 +0,0 @@ -/* - * Copyright DataStax, Inc. - * - * 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 util = require('util'); -const utils = require('../utils'); -const Geometry = require('./geometry'); -const Point = require('./point'); -const LineString = require('./line-string'); - -/** - * Creates a new {@link Polygon} instance. - * @classdesc - * Represents is a plane geometry figure that is bounded by a finite chain of straight line segments closing in a loop - * to form a closed chain or circuit. - * @param {...Array.}[ringPoints] A sequence of Array of [Point]{@link module:geometry~Point} items as arguments - * representing the rings of the polygon. - * @example - * new Polygon([ new Point(30, 10), new Point(40, 40), new Point(10, 20), new Point(30, 10) ]); - * @example - * //polygon with a hole - * new Polygon( - * [ new Point(30, 10), new Point(40, 40), new Point(10, 20), new Point(30, 10) ], - * [ new Point(25, 20), new Point(30, 30), new Point(20, 20), new Point(25, 20) ] - * ); - * @alias module:geometry~Polygon - * @constructor - */ -function Polygon(ringPoints) { - const rings = Array.prototype.slice.call(arguments); - /** - * Returns a frozen Array of array of points that represent the different rings in the polygon. - * @type {Array} - */ - this.rings = Object.freeze(rings); -} - -//noinspection JSCheckFunctionSignatures -util.inherits(Polygon, Geometry); - -/** - * Creates a {@link Polygon} instance from - * a Well-known Text (WKT) - * representation of a polygon. - * @param {Buffer} buffer - * @returns {Polygon} - */ -Polygon.fromBuffer = function (buffer) { - if (!buffer || buffer.length < 9) { - throw new TypeError('A Polygon buffer should contain at least 9 bytes'); - } - const endianness = Geometry.getEndianness(buffer.readInt8(0, true)); - let offset = 1; - if (Geometry.readInt32(buffer, endianness, offset) !== Geometry.types.Polygon) { - throw new TypeError('Binary representation was not a Polygon'); - } - offset += 4; - const ringsLength = Geometry.readInt32(buffer, endianness, offset); - offset += 4; - const ringsArray = new Array(ringsLength); - for (let ringIndex = 0; ringIndex < ringsLength; ringIndex++) { - const pointsLength = Geometry.readInt32(buffer, endianness, offset); - offset += 4; - if (buffer.length < offset + pointsLength * 16) { - throw new TypeError(util.format('Length of the buffer does not match')); - } - const ring = new Array(pointsLength); - for (let i = 0; i < pointsLength; i++) { - ring[i] = new Point( - Geometry.readDouble(buffer, endianness, offset), - Geometry.readDouble(buffer, endianness, offset + 8)); - offset += 16; - } - ringsArray[ringIndex] = ring; - } - //Invoke the constructor with each ring as a parameter - //ringsArray.unshift(null); - //return new (Function.prototype.bind.apply(Polygon, ringsArray)); - return construct(ringsArray); -}; - -/** - * Creates a {@link Polygon} instance from - * a Well-known Text (WKT) - * representation of a shape. - * @param {String} textValue - * @returns {Polygon} - */ -Polygon.fromString = function (textValue) { - const wktRegex = /^POLYGON ?\((\(.*\))\)$/g; - const matches = wktRegex.exec(textValue); - function validateWkt(condition) { - if (condition) { - throw new TypeError('Invalid WKT: ' + textValue); - } - } - validateWkt(!matches || matches.length !== 2); - - const ringsText = matches[1]; - const ringsArray = []; - let ringStart = null; - for (let i = 0; i < ringsText.length; i++) { - const c = ringsText[i]; - if (c === '(') { - validateWkt(ringStart !== null); - ringStart = i+1; - continue; - } - if (c === ')') { - validateWkt(ringStart === null); - ringsArray.push(ringsText.substring(ringStart, i)); - ringStart = null; - continue; - } - validateWkt(ringStart === null && c !== ' ' && c !== ','); - } - return construct(ringsArray.map(LineString.parseSegments)); -}; - -/** - * Creates a new instance of Polygon with each array item as a parameter - * @private - * @param {Array>} argsArray - * @returns {Polygon} - */ -function construct(argsArray) { - function F() { - return Polygon.apply(this, argsArray); - } - F.prototype = Polygon.prototype; - return new F(); -} - -/** - * Returns a Well-known Binary (WKB) - * representation of this instance. - * @returns {Buffer} - */ -Polygon.prototype.toBuffer = function () { - let totalRingsLength = 0; - this.rings.forEach(function (ring) { - totalRingsLength += 4 + ring.length * 16; - }, this); - const buffer = utils.allocBufferUnsafe(9 + totalRingsLength); - this.writeEndianness(buffer, 0); - let offset = 1; - this.writeInt32(Geometry.types.Polygon, buffer, offset); - offset += 4; - this.writeInt32(this.rings.length, buffer, offset); - offset += 4; - this.rings.forEach(function (ring) { - this.writeInt32(ring.length, buffer, offset); - offset += 4; - ring.forEach(function (p) { - this.writeDouble(p.x, buffer, offset); - this.writeDouble(p.y, buffer, offset + 8); - offset += 16; - }, this); - }, this); - return buffer; -}; - -/** - * Returns true if the values of the polygons are the same, otherwise it returns false. - * @param {Polygon} other - * @returns {Boolean} - */ -Polygon.prototype.equals = function (other) { - if (!(other instanceof Polygon)) { - return false; - } - if (this.rings.length !== other.rings.length) { - return false; - } - for (let i = 0; i < this.rings.length; i++) { - const r1 = this.rings[i]; - const r2 = other.rings[i]; - if (r1.length !== r2.length) { - return false; - } - for (let j = 0; j < r1.length; j++) { - if (!r1[i].equals(r2[i])) { - return false; - } - } - } - return true; -}; - -Polygon.prototype.useBESerialization = function () { - return false; -}; - -/** - * Returns Well-known text (WKT) representation of the geometry object. - * @returns {String} - */ -Polygon.prototype.toString = function () { - if (this.rings.length === 0) { - return 'POLYGON EMPTY'; - } - let ringStrings = ''; - this.rings.forEach(function (r, i) { - if (i > 0) { - ringStrings += ', '; - } - ringStrings += '(' + - r.map(function (p) { - return p.x + ' ' + p.y; - }).join(', ') - + ')'; - }); - return 'POLYGON (' + ringStrings + ')'; -}; - -/** - * Returns a JSON representation of this geo-spatial type. - */ -Polygon.prototype.toJSON = function () { - return { type: 'Polygon', coordinates: this.rings.map(function (r) { - return r.map(function (p) { - return [ p.x, p.y ]; - }); - })}; -}; - -module.exports = Polygon; \ No newline at end of file diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/host-connection-pool.js b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/host-connection-pool.js deleted file mode 100644 index f03e6981e4..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/host-connection-pool.js +++ /dev/null @@ -1,522 +0,0 @@ -/* - * Copyright DataStax, Inc. - * - * 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 util = require('util'); -const events = require('events'); - -const Connection = require('./connection'); -const utils = require('./utils'); -const promiseUtils = require('./promise-utils'); -const errors = require('./errors'); -const clientOptions = require('./client-options'); - -// Used to get the index of the connection with less in-flight requests -let connectionIndex = 0; -const connectionIndexOverflow = Math.pow(2, 15); - -let defaultOptions; - -/** - * Represents the possible states of the pool. - * Possible state transitions: - * - From initial to closing: The pool must be closed because the host is ignored. - * - From initial to shuttingDown: The pool is being shutdown as a result of a client shutdown. - * - From closing to initial state: The pool finished closing connections (is now ignored) and it resets to - * initial state in case the host is marked as local/remote in the future. - * - From closing to shuttingDown (rare): It was marked as ignored, now the client is being shutdown. - * - From shuttingDown to shutdown: Finished shutting down, the pool should not be reused. - * @private - */ -const state = { - // Initial state: open / opening / ready to be opened - initial: 0, - // When the pool is being closed as part of a distance change - closing: 1, - // When the pool is being shutdown for good - shuttingDown: 2, - // When the pool has being shutdown - shutDown: 4 -}; - -/** - * Represents a pool of connections to a host - */ -class HostConnectionPool extends events.EventEmitter { - /** - * Creates a new instance of HostConnectionPool. - * @param {Host} host - * @param {Number} protocolVersion Initial protocol version - * @extends EventEmitter - */ - constructor(host, protocolVersion) { - super(); - this._address = host.address; - this._newConnectionTimeout = null; - this._state = state.initial; - this._opening = false; - this._host = host; - this.responseCounter = 0; - this.options = host.options; - this.protocolVersion = protocolVersion; - this.coreConnectionsLength = 1; - /** - * An immutable array of connections - * @type {Array.} - */ - this.connections = utils.emptyArray; - this.setMaxListeners(0); - this.log = utils.log; - } - - getInFlight() { - const length = this.connections.length; - if (length === 1) { - return this.connections[0].getInFlight(); - } - - let sum = 0; - for (let i = 0; i < length; i++) { - sum += this.connections[i].getInFlight(); - } - return sum; - } - - /** - * Gets the least busy connection from the pool. - * @param {Connection} [previousConnection] When provided, the pool should attempt to obtain a different connection. - * @returns {Connection!} - * @throws {Error} - * @throws {BusyConnectionError} - */ - borrowConnection(previousConnection) { - if (this.connections.length === 0) { - throw new Error('No connection available'); - } - - const maxRequests = this.options.pooling.maxRequestsPerConnection; - const c = HostConnectionPool.minInFlight(this.connections, maxRequests, previousConnection); - - if (c.getInFlight() >= maxRequests) { - throw new errors.BusyConnectionError(this._address, maxRequests, this.connections.length); - } - - return c; - } - - /** - * Gets the connection with the minimum number of in-flight requests. - * Only checks for 2 connections (round-robin) and gets the one with minimum in-flight requests, as long as - * the amount of in-flight requests is lower than maxRequests. - * @param {Array.} connections - * @param {Number} maxRequests - * @param {Connection} previousConnection When provided, it will attempt to obtain a different connection. - * @returns {Connection!} - */ - static minInFlight(connections, maxRequests, previousConnection) { - const length = connections.length; - if (length === 1) { - return connections[0]; - } - - // Use a single index for all hosts as a simplified way to balance the load between connections - connectionIndex++; - if (connectionIndex >= connectionIndexOverflow) { - connectionIndex = 0; - } - - let current; - for (let index = connectionIndex; index < connectionIndex + length; index++) { - current = connections[index % length]; - if (current === previousConnection) { - // Increment the index and skip - current = connections[(++index) % length]; - } - - let next = connections[(index + 1) % length]; - if (next === previousConnection) { - // Skip - next = connections[(index + 2) % length]; - } - - if (next.getInFlight() < current.getInFlight()) { - current = next; - } - - if (current.getInFlight() < maxRequests) { - // Check as few connections as possible, as long as the amount of in-flight - // requests is lower than maxRequests - break; - } - } - return current; - } - - /** - * Creates all the connections in the pool and switches the keyspace of each connection if needed. - * @param {string} keyspace - */ - async warmup(keyspace) { - if (this.connections.length < this.coreConnectionsLength) { - while (this.connections.length < this.coreConnectionsLength) { - await this._attemptNewConnection(); - } - - this.log('info', - `Connection pool to host ${this._address} created with ${this.connections.length} connection(s)`); - } else { - this.log('info', `Connection pool to host ${this._address} contains ${this.connections.length} connection(s)`); - } - - if (keyspace) { - try { - for (const connection of this.connections) { - await connection.changeKeyspace(keyspace); - } - } catch (err) { - // Log it and move on, it could be a momentary schema mismatch failure - this.log('warning', `Connection(s) to host ${this._address} could not be switched to keyspace ${keyspace}`); - } - } - } - - /** @returns {Connection} */ - _createConnection() { - const endpointOrServerName = !this.options.sni - ? this._address : this._host.hostId.toString(); - - const c = new Connection(endpointOrServerName, this.protocolVersion, this.options); - this._addListeners(c); - return c; - } - - /** @param {Connection} c */ - _addListeners(c) { - c.on('responseDequeued', () => this.responseCounter++); - - const self = this; - function connectionErrorCallback() { - // The socket is not fully open / can not send heartbeat - self.remove(c); - } - c.on('idleRequestError', connectionErrorCallback); - c.on('socketClose', connectionErrorCallback); - } - - addExistingConnection(c) { - this._addListeners(c); - // Use a copy of the connections array - this.connections = this.connections.slice(0); - this.connections.push(c); - } - - /** - * Prevents reconnection timeout from triggering - */ - clearNewConnectionAttempt() { - if (!this._newConnectionTimeout) { - return; - } - clearTimeout(this._newConnectionTimeout); - this._newConnectionTimeout = null; - } - - /** - * Tries to open a new connection. - * If a connection is being opened, it will resolve when the existing open task completes. - * @returns {Promise} - */ - async _attemptNewConnection() { - if (this._opening) { - // Wait for the event to fire - return await promiseUtils.fromEvent(this, 'open'); - } - - this._opening = true; - - const c = this._createConnection(); - let err; - - try { - await c.openAsync(); - } catch (e) { - err = e; - this.log('warning', `Connection to ${this._address} could not be created: ${err}`, err); - } - - if (this.isClosing()) { - this.log('info', `Connection to ${this._address} opened successfully but pool was being closed`); - err = new Error('Connection closed'); - } - - if (!err) { - // Append the connection to the pool. - // Use a copy of the connections array. - const newConnections = this.connections.slice(0); - newConnections.push(c); - this.connections = newConnections; - this.log('info', `Connection to ${this._address} opened successfully`); - } else { - promiseUtils.toBackground(c.closeAsync()); - } - - // Notify that creation finished by setting the flag and emitting the event - this._opening = false; - this.emit('open', err, c); - - if (err) { - // Opening failed - throw err; - } - } - - attemptNewConnectionImmediate() { - const self = this; - function openConnection() { - self.clearNewConnectionAttempt(); - self.scheduleNewConnectionAttempt(0); - } - - if (this._state === state.initial) { - return openConnection(); - } - - if (this._state === state.closing) { - return this.once('close', openConnection); - } - // In the case the pool its being / has been shutdown for good - // Do not attempt to create a new connection. - } - - /** - * Closes the connection and removes a connection from the pool. - * @param {Connection} connection - */ - remove(connection) { - // locating an object by position in the array is O(n), but normally there should be between 1 to 8 connections. - const index = this.connections.indexOf(connection); - if (index < 0) { - // it was already removed from the connections and it's closing - return; - } - // remove the connection from the pool, using an pool copy - const newConnections = this.connections.slice(0); - newConnections.splice(index, 1); - this.connections = newConnections; - // close the connection - setImmediate(function removeClose() { - connection.close(); - }); - this.emit('remove'); - } - - /** - * @param {Number} delay - */ - scheduleNewConnectionAttempt(delay) { - if (this.isClosing()) { - return; - } - - const self = this; - - this._newConnectionTimeout = setTimeout(function newConnectionTimeoutExpired() { - self._newConnectionTimeout = null; - if (self.connections.length >= self.coreConnectionsLength) { - // new connection can be scheduled while a new connection is being opened - // the pool has the appropriate size - return; - } - - if (delay > 0 && self.options.sni) { - // We use delay > 0 as an indication that it's a reconnection. - // A reconnection schedule can use delay = 0 as well, but it's a good enough signal. - promiseUtils.toBackground(self.options.sni.addressResolver.refresh().then(() => self._attemptNewConnection())); - return; - } - - promiseUtils.toBackground(self._attemptNewConnection()); - }, delay); - } - - hasScheduledNewConnection() { - return !!this._newConnectionTimeout || this._opening; - } - - /** - * Increases the size of the connection pool in the background, if needed. - */ - increaseSize() { - if (this.connections.length < this.coreConnectionsLength && !this.hasScheduledNewConnection()) { - // schedule the next connection in the background - this.scheduleNewConnectionAttempt(0); - } - } - - /** - * Gets the amount of responses and resets the internal counter. - * @returns {number} - */ - getAndResetResponseCounter() { - const temp = this.responseCounter; - this.responseCounter = 0; - return temp; - } - - /** - * Gets a boolean indicating if the pool is being closed / shutting down or has been shutdown. - */ - isClosing() { - return this._state !== state.initial; - } - - /** - * Gracefully waits for all in-flight requests to finish and closes the pool. - */ - drainAndShutdown() { - if (this.isClosing()) { - // Its already closing / shutting down - return; - } - - this._state = state.closing; - this.clearNewConnectionAttempt(); - - if (this.connections.length === 0) { - return this._afterClosing(); - } - - const self = this; - const connections = this.connections; - this.connections = utils.emptyArray; - let closedConnections = 0; - this.log('info', util.format('Draining and closing %d connections to %s', connections.length, this._address)); - let wasClosed = false; - // eslint-disable-next-line prefer-const - let checkShutdownTimeout; - - for (let i = 0; i < connections.length; i++) { - const c = connections[i]; - if (c.getInFlight() === 0) { - getDelayedClose(c)(); - continue; - } - c.emitDrain = true; - c.once('drain', getDelayedClose(c)); - } - - function getDelayedClose(connection) { - return (function delayedClose() { - connection.close(); - if (++closedConnections < connections.length) { - return; - } - if (wasClosed) { - return; - } - wasClosed = true; - if (checkShutdownTimeout) { - clearTimeout(checkShutdownTimeout); - } - self._afterClosing(); - }); - } - - // Check that after sometime (readTimeout + 100ms) the connections have been drained - const delay = (this.options.socketOptions.readTimeout || getDefaultOptions().socketOptions.readTimeout) + 100; - checkShutdownTimeout = setTimeout(function checkShutdown() { - wasClosed = true; - connections.forEach(function connectionEach(c) { - c.close(); - }); - self._afterClosing(); - }, delay); - } - - _afterClosing() { - const self = this; - - function resetState() { - if (self._state === state.shuttingDown) { - self._state = state.shutDown; - } else { - self._state = state.initial; - } - - self.emit('close'); - - if (self._state === state.shutDown) { - self.emit('shutdown'); - } - } - - if (this._opening) { - // The pool is growing, reset the state back to init once the open finished (without any new connection) - return this.once('open', resetState); - } - - resetState(); - } - - /** - * @returns {Promise} - */ - async shutdown() { - this.clearNewConnectionAttempt(); - - if (!this.connections.length) { - this._state = state.shutDown; - return; - } - - const previousState = this._state; - this._state = state.shuttingDown; - - if (previousState === state.closing || previousState === state.shuttingDown) { - // When previous state was closing, it will drain all connections and close them - // When previous state was "shuttingDown", it will close all the connections - // Once it's completed, shutdown event will be emitted - return promiseUtils.fromEvent(this, 'shutdown'); - } - - await this._closeAllConnections(); - - this._state = state.shutDown; - this.emit('shutdown'); - } - - async _closeAllConnections() { - const connections = this.connections; - // point to an empty array - this.connections = utils.emptyArray; - if (connections.length === 0) { - return; - } - - this.log('info', util.format('Closing %d connections to %s', connections.length, this._address)); - - await Promise.all(connections.map(c => c.closeAsync())); - } -} - -/** Lazily loads the default options */ -function getDefaultOptions() { - if (defaultOptions === undefined) { - defaultOptions = clientOptions.defaultOptions(); - } - return defaultOptions; -} - -module.exports = HostConnectionPool; \ No newline at end of file diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/host.js b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/host.js deleted file mode 100644 index 56c128f5b8..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/host.js +++ /dev/null @@ -1,658 +0,0 @@ -/* - * Copyright DataStax, Inc. - * - * 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 events = require('events'); - -const utils = require('./utils'); -const types = require('./types'); -const HostConnectionPool = require('./host-connection-pool'); -const PrepareHandler = require('./prepare-handler'); -const promiseUtils = require('./promise-utils'); - -const healthResponseCountInterval = 200; - -/** - * Represents a Cassandra node. - * @extends EventEmitter - */ -class Host extends events.EventEmitter { - - /** - * Creates a new Host instance. - */ - constructor(address, protocolVersion, options, metadata) { - super(); - /** - * Gets ip address and port number of the node separated by `:`. - * @type {String} - */ - this.address = address; - this.setDownAt = 0; - this.log = utils.log; - - /** - * Gets the timestamp of the moment when the Host was marked as UP. - * @type {Number|null} - * @ignore - * @internal - */ - this.isUpSince = null; - Object.defineProperty(this, 'options', { value: options, enumerable: false, writable: false }); - - /** - * The host pool. - * @internal - * @ignore - * @type {HostConnectionPool} - */ - Object.defineProperty(this, 'pool', { value: new HostConnectionPool(this, protocolVersion), enumerable: false }); - - this.pool.on('open', err => promiseUtils.toBackground(this._onNewConnectionOpen(err))); - this.pool.on('remove', () => this._checkPoolState()); - - /** - * Gets string containing the Cassandra version. - * @type {String} - */ - this.cassandraVersion = null; - - /** - * Gets data center name of the node. - * @type {String} - */ - this.datacenter = null; - - /** - * Gets rack name of the node. - * @type {String} - */ - this.rack = null; - - /** - * Gets the tokens assigned to the node. - * @type {Array} - */ - this.tokens = null; - - /** - * Gets the id of the host. - *

This identifier is used by the server for internal communication / gossip.

- * @type {Uuid} - */ - this.hostId = null; - - /** - * Gets string containing the DSE version or null if not set. - * @type {String} - */ - this.dseVersion = null; - - /** - * Gets the DSE Workloads the host is running. - *

- * This is based on the "workload" or "workloads" columns in {@code system.local} and {@code system.peers}. - *

- *

- * Workload labels may vary depending on the DSE version in use;e.g. DSE 5.1 may report two distinct workloads: - * Search and Analytics, while DSE 5.0 would report a single - * SearchAnalytics workload instead. The driver simply returns the workload labels as reported by - * DSE, without any form of pre-processing. - *

- *

When the information is unavailable, this property returns an empty array.

- * @type {Array} - */ - this.workloads = utils.emptyArray; - - // the distance as last set using the load balancing policy - this._distance = types.distance.ignored; - this._healthResponseCounter = 0; - - // Make some of the private instance variables not enumerable to prevent from showing when inspecting - Object.defineProperty(this, '_metadata', { value: metadata, enumerable: false }); - Object.defineProperty(this, '_healthResponseCountTimer', { value: null, enumerable: false, writable: true }); - - this.reconnectionSchedule = this.options.policies.reconnection.newSchedule(); - this.reconnectionDelay = 0; - } - - /** - * Marks this host as not available for query coordination, when the host was previously marked as UP, otherwise its - * a no-op. - * @internal - * @ignore - */ - setDown() { - // Multiple events signaling that a host is failing could cause multiple calls to this method - if (this.setDownAt !== 0) { - // the host is already marked as Down - return; - } - if (this.pool.isClosing()) { - // the pool is being closed/shutdown, don't mind - return; - } - this.setDownAt = Date.now(); - if (this.pool.coreConnectionsLength > 0) { - // According to the distance, there should be connections open to it => issue a warning - this.log('warning', `Host ${this.address} considered as DOWN. Reconnection delay ${this.reconnectionDelay}ms.`); - } - else { - this.log('info', `Host ${this.address} considered as DOWN.`); - } - this.emit('down'); - this._checkPoolState(); - } - - /** - * Marks this host as available for querying. - * @param {Boolean} [clearReconnection] - * @internal - * @ignore - */ - setUp(clearReconnection) { - if (!this.setDownAt) { - //The host is already marked as UP - return; - } - this.log('info', `Setting host ${this.address} as UP`); - this.setDownAt = 0; - this.isUpSince = Date.now(); - //if it was unhealthy and now it is not, lets reset the reconnection schedule. - this.reconnectionSchedule = this.options.policies.reconnection.newSchedule(); - if (clearReconnection) { - this.pool.clearNewConnectionAttempt(); - } - this.emit('up'); - } - - /** - * Resets the reconnectionSchedule and tries to issue a reconnection immediately. - * @internal - * @ignore - */ - checkIsUp() { - if (this.isUp()) { - return; - } - this.reconnectionSchedule = this.options.policies.reconnection.newSchedule(); - this.reconnectionDelay = 0; - this.pool.attemptNewConnectionImmediate(); - } - - /** - * @param {Boolean} [waitForPending] When true, it waits for in-flight operations to be finish before closing the - * connections. - * @returns {Promise} - * @internal - * @ignore - */ - shutdown(waitForPending) { - if (this._healthResponseCountTimer) { - clearInterval(this._healthResponseCountTimer); - } - if (waitForPending) { - this.pool.drainAndShutdown(); - // Gracefully draining and shutting down the pool is being done in the background - return Promise.resolve(); - } - return this.pool.shutdown(); - } - - /** - * Determines if the node is UP now (seen as UP by the driver). - * @returns {boolean} - */ - isUp() { - return !this.setDownAt; - } - - /** - * Determines if the host can be considered as UP. - * Deprecated: Use {@link Host#isUp()} instead. - * @returns {boolean} - */ - canBeConsideredAsUp() { - const self = this; - function hasTimePassed() { - return new Date().getTime() - self.setDownAt >= self.reconnectionDelay; - } - return !this.setDownAt || hasTimePassed(); - } - - /** - * Sets the distance of the host relative to the client using the load balancing policy. - * @param {Number} distance - * @internal - * @ignore - */ - setDistance(distance) { - const previousDistance = this._distance; - this._distance = distance || types.distance.local; - if (this.options.pooling.coreConnectionsPerHost) { - this.pool.coreConnectionsLength = this.options.pooling.coreConnectionsPerHost[this._distance] || 0; - } - else { - this.pool.coreConnectionsLength = 1; - } - if (this._distance === previousDistance) { - return this._distance; - } - if (this._healthResponseCountTimer) { - clearInterval(this._healthResponseCountTimer); - } - if (this._distance === types.distance.ignored) { - // this host was local/remote and now must be ignored - this.emit('ignore'); - this.pool.drainAndShutdown(); - } - else { - if (!this.isUp()) { - this.checkIsUp(); - } - // Reset the health check timer - this._healthResponseCountTimer = setInterval(() => { - this._healthResponseCounter = this.pool.getAndResetResponseCounter(); - }, healthResponseCountInterval); - } - return this._distance; - } - - /** - * Changes the protocol version of a given host - * @param {Number} value - * @internal - * @ignore - */ - setProtocolVersion(value) { - this.pool.protocolVersion = value; - } - - /** - * Gets the least busy connection from the pool. - * @param {Connection} [previousConnection] When provided, the pool should attempt to obtain a different connection. - * @returns {Connection!} - * @throws {Error} - * @throws {BusyConnectionError} - * @internal - * @ignore - */ - borrowConnection(previousConnection) { - return this.pool.borrowConnection(previousConnection); - } - - /** - * Creates all the connection in the pool. - * @param {string} keyspace - * @internal - * @ignore - */ - warmupPool(keyspace) { - return this.pool.warmup(keyspace); - } - - /** - * Starts creating the pool in the background. - * @internal - * @ignore - */ - initializePool() { - this.pool.increaseSize(); - } - /** - * Gets any connection that is already opened or null if not found. - * @returns {Connection} - * @internal - * @ignore - */ - getActiveConnection() { - if (!this.isUp() || !this.pool.connections.length) { - return null; - } - return this.pool.connections[0]; - } - - /** - * Internal method to get the amount of responses dequeued in the last interval (between 200ms and 400ms) on all - * connections to the host. - * @returns {Number} - * @internal - * @ignore - */ - getResponseCount() { - // Last interval plus the current count - return this._healthResponseCounter + this.pool.responseCounter; - } - - /** - * Checks the health of a connection in the pool - * @param {Connection} connection - * @internal - * @ignore - */ - checkHealth(connection) { - if (connection.timedOutOperations <= this.options.socketOptions.defunctReadTimeoutThreshold) { - return; - } - this.removeFromPool(connection); - } - - /** - * @param {Connection} connection - * @internal - * @ignore - */ - removeFromPool(connection) { - this.pool.remove(connection); - this._checkPoolState(); - } - - /** - * Internal method that gets the amount of in-flight requests on all connections to the host. - * @internal - * @ignore - */ - getInFlight() { - return this.pool.getInFlight(); - } - - /** - * Validates that the internal state of the connection pool. - * If the pool size is smaller than expected, schedule a new connection attempt. - * If the amount of connections is 0 for not ignored hosts, the host must be down. - * @private - */ - _checkPoolState() { - if (this.pool.isClosing()) { - return; - } - if (this.pool.connections.length < this.pool.coreConnectionsLength) { - // the pool needs to grow / reconnect - if (!this.pool.hasScheduledNewConnection()) { - this.reconnectionDelay = this.reconnectionSchedule.next().value; - this.pool.scheduleNewConnectionAttempt(this.reconnectionDelay); - } - } - const shouldHaveConnections = this._distance !== types.distance.ignored && this.pool.coreConnectionsLength > 0; - if (shouldHaveConnections && this.pool.connections.length === 0) { - // Mark as DOWN, if its UP - this.setDown(); - } - } - - /** - * Executed after an scheduled new connection attempt finished - * @private - */ - async _onNewConnectionOpen(err) { - if (err) { - this._checkPoolState(); - return; - } - if (!this.isUp() && this.options.rePrepareOnUp) { - this.log('info', `Re-preparing all queries on host ${this.address} before setting it as UP`); - const allPrepared = this._metadata.getAllPrepared(); - try { - await PrepareHandler.prepareAllQueries(this, allPrepared); - } - catch (err) { - this.log('warning', `Failed re-preparing on host ${this.address}: ${err}`, err); - } - } - this.setUp(); - this.pool.increaseSize(); - } - - /** - * Returns an array containing the Cassandra Version as an Array of Numbers having the major version in the first - * position. - * @returns {Array.} - */ - getCassandraVersion() { - if (!this.cassandraVersion) { - return utils.emptyArray; - } - return this.cassandraVersion.split('-')[0].split('.').map(x => parseInt(x, 10)); - } - - /** - * Gets the DSE version of the host as an Array, containing the major version in the first position. - * In case the cluster is not a DSE cluster, it returns an empty Array. - * @returns {Array} - */ - getDseVersion() { - if (!this.dseVersion) { - return utils.emptyArray; - } - return this.dseVersion.split('-')[0].split('.').map(x => parseInt(x, 10)); - } -} - -/** - * Represents an associative-array of {@link Host hosts} that can be iterated. - * It creates an internal copy when adding or removing, making it safe to iterate using the values() - * method within async operations. - * @extends events.EventEmitter - * @constructor - */ -class HostMap extends events.EventEmitter{ - constructor() { - super(); - - this._items = new Map(); - this._values = null; - - Object.defineProperty(this, 'length', { get: () => this.values().length, enumerable: true }); - - /** - * Emitted when a host is added to the map - * @event HostMap#add - */ - /** - * Emitted when a host is removed from the map - * @event HostMap#remove - */ - } - - /** - * Executes a provided function once per map element. - * @param callback - */ - forEach(callback) { - const items = this._items; - for (const [ key, value ] of items) { - callback(value, key); - } - } - - /** - * Gets a {@link Host host} by key or undefined if not found. - * @param {String} key - * @returns {Host} - */ - get(key) { - return this._items.get(key); - } - - /** - * Returns an array of host addresses. - * @returns {Array.} - */ - keys() { - return Array.from(this._items.keys()); - } - - /** - * Removes an item from the map. - * @param {String} key The key of the host - * @fires HostMap#remove - */ - remove(key) { - const value = this._items.get(key); - if (value === undefined) { - return; - } - - // Clear cache - this._values = null; - - // Copy the values - const copy = new Map(this._items); - copy.delete(key); - - this._items = copy; - this.emit('remove', value); - } - - /** - * Removes multiple hosts from the map. - * @param {Array.} keys - * @fires HostMap#remove - */ - removeMultiple(keys) { - // Clear value cache - this._values = null; - - // Copy the values - const copy = new Map(this._items); - const removedHosts = []; - - for (const key of keys) { - const h = copy.get(key); - - if (!h) { - continue; - } - - removedHosts.push(h); - copy.delete(key); - } - - this._items = copy; - removedHosts.forEach(h => this.emit('remove', h)); - } - - /** - * Adds a new item to the map. - * @param {String} key The key of the host - * @param {Host} value The host to be added - * @fires HostMap#remove - * @fires HostMap#add - */ - set(key, value) { - // Clear values cache - this._values = null; - - const originalValue = this._items.get(key); - if (originalValue) { - //The internal structure does not change - this._items.set(key, value); - //emit a remove followed by a add - this.emit('remove', originalValue); - this.emit('add', value); - return; - } - - // Copy the values - const copy = new Map(this._items); - copy.set(key, value); - this._items = copy; - this.emit('add', value); - return value; - } - - /** - * Returns a shallow copy of a portion of the items into a new array object. - * Backward-compatibility. - * @param {Number} [begin] - * @param {Number} [end] - * @returns {Array} - * @ignore - */ - slice(begin, end) { - if (!begin && !end) { - // Avoid making a copy of the copy - return this.values(); - } - - return this.values().slice(begin || 0, end); - } - - /** - * Deprecated: Use set() instead. - * @ignore - * @deprecated - */ - push(k, v) { - this.set(k, v); - } - - /** - * Returns a shallow copy of the values of the map. - * @returns {Array.} - */ - values() { - if (!this._values) { - // Cache the values - this._values = Object.freeze(Array.from(this._items.values())); - } - - return this._values; - } - - /** - * Removes all items from the map. - * @returns {Array.} The previous items - */ - clear() { - const previousItems = this.values(); - - // Clear cache - this._values = null; - - // Clear items - this._items = new Map(); - - // Emit events - previousItems.forEach(h => this.emit('remove', h)); - - return previousItems; - } - - inspect() { - return this._items; - } - - toJSON() { - // Node.js 10 and below don't support Object.fromEntries() - if (Object.fromEntries) { - return Object.fromEntries(this._items); - } - - const obj = {}; - for (const [ key, value ] of this._items) { - obj[key] = value; - } - - return obj; - } -} - -module.exports = { - Host, - HostMap -}; \ No newline at end of file diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/insights-client.js b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/insights-client.js deleted file mode 100644 index 4c9207d4d2..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/insights-client.js +++ /dev/null @@ -1,492 +0,0 @@ -/* - * Copyright DataStax, Inc. - * - * 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 os = require('os'); -const path = require('path'); -const fs = require('fs'); -const utils = require('./utils'); -const promiseUtils = require('./promise-utils'); -const types = require('./types'); -const requests = require('./requests'); -const { ExecutionOptions } = require('./execution-options'); -const packageInfo = require('../package.json'); -const VersionNumber = require('./types/version-number'); -const { NoAuthProvider } = require('./auth'); - -let kerberosModule; - -try { - // eslint-disable-next-line - kerberosModule = require('kerberos'); -} -catch (err) { - // Kerberos is an optional dependency -} - -const minDse6Version = new VersionNumber(6, 0, 5); -const minDse51Version = new VersionNumber(5, 1, 13); -const dse600Version = new VersionNumber(6, 0, 0); -const rpc = "CALL InsightsRpc.reportInsight(?)"; -const maxStatusErrorLogs = 5; - -/** - * Contains methods and functionality to send events to DSE Insights. - */ -class InsightsClient { - - /** - * Creates a new instance of the {@link InsightsClient} using the driver {@link Client}. - * @param {Client} client - * @param {Object} [options] - * @param {Number} [options.statusEventDelay] - * @param {Function} [options.errorCallback] - */ - constructor(client, options) { - this._client = client; - this._sessionId = types.Uuid.random().toString(); - this._enabled = false; - this._closed = false; - this._firstTimeout = null; - this._recurrentTimeout = null; - this._statusErrorLogs = 0; - - options = options || {}; - - this._statusEventDelay = options.statusEventDelay || 300000; - this._errorCallback = options.errorCallback || utils.noop; - } - - /** - * Initializes the insights client in the background by sending the startup event and scheduling status events at - * regular intervals. - * @returns {undefined} - */ - init() { - this._enabled = this._client.options.monitorReporting.enabled && this._dseSupportsInsights(); - if (!this._enabled) { - return; - } - - promiseUtils.toBackground(this._init()); - } - - async _init() { - try { - await this._sendStartupEvent(); - - if (this._closed) { - // The client was shutdown - return; - } - - // Send the status event the first time with a delay containing some random portion - // Initial delay should be statusEventDelay - (0 to 10%) - const firstDelay = Math.floor(this._statusEventDelay - 0.1 * this._statusEventDelay * Math.random()); - // Schedule the first timer - this._firstTimeout = setTimeout(() => { - // Send the first status event, the promise will never be rejected - this._sendStatusEvent(); - // The following status events are sent at regular intervals - this._recurrentTimeout = setInterval(() => this._sendStatusEvent(), this._statusEventDelay); - }, firstDelay); - } catch (err) { - if (this._closed) { - // Sending failed because the Client was shutdown - return; - } - // We shouldn't try to recover - this._client.log('verbose', `Insights startup message could not be sent (${err})`, err); - this._errorCallback(err); - } - } - - /** - * Sends the startup event. - * @returns {Promise} - * @private - */ - async _sendStartupEvent() { - const message = await this._getStartupMessage(); - const request = new requests.QueryRequest(rpc, [message], ExecutionOptions.empty()); - await this._client.controlConnection.query(request, false); - } - - /** - * Sends the status event. - * @returns {Promise} A promise that is never rejected. - * @private - */ - async _sendStatusEvent() { - const request = new requests.QueryRequest(rpc, [ this._getStatusEvent() ], ExecutionOptions.empty()); - - try { - await this._client.controlConnection.query(request, false); - } catch (err) { - if (this._closed) { - // Sending failed because the Client was shutdown - return; - } - - if (this._statusErrorLogs < maxStatusErrorLogs) { - this._client.log('warning', `Insights status message could not be sent (${err})`, err); - this._statusErrorLogs++; - } - - this._errorCallback(err); - } - } - - /** - * Validates the minimum server version for all nodes in the cluster. - * @private - */ - _dseSupportsInsights() { - if (this._client.hosts.length === 0) { - return false; - } - - return this._client.hosts.values().reduce((acc, host) => { - if (!acc) { - return acc; - } - - const versionArr = host.getDseVersion(); - - if (versionArr.length === 0) { - return false; - } - - const version = new VersionNumber(...versionArr); - - return version.compare(minDse6Version) >= 0 || - (version.compare(dse600Version) < 0 && version.compare(minDse51Version) >= 0); - - }, true); - } - - /** - * @returns {Promise} Returns a json string with the startup message. - * @private - */ - async _getStartupMessage() { - const cc = this._client.controlConnection; - const options = this._client.options; - - - const appInfo = await this._getAppInfo(options); - const message = { - metadata: { - name: 'driver.startup', - insightMappingId: 'v1', - insightType: 'EVENT', - timestamp: Date.now(), - tags: { language: 'nodejs' } - }, - data: { - driverName: packageInfo.description, - driverVersion: packageInfo.version, - clientId: options.id, - sessionId: this._sessionId, - applicationName: appInfo.applicationName, - applicationVersion: appInfo.applicationVersion, - applicationNameWasGenerated: appInfo.applicationNameWasGenerated, - contactPoints: mapToObject(cc.getResolvedContactPoints()), - dataCenters: this._getDataCenters(), - initialControlConnection: cc.host ? cc.host.address : undefined, - protocolVersion: cc.protocolVersion, - localAddress: cc.getLocalAddress(), - hostName: os.hostname(), - executionProfiles: getExecutionProfiles(this._client), - poolSizeByHostDistance: { - local: options.pooling.coreConnectionsPerHost[types.distance.local], - remote: options.pooling.coreConnectionsPerHost[types.distance.remote] - }, - heartbeatInterval: options.pooling.heartBeatInterval, - compression: 'NONE', - reconnectionPolicy: getPolicyInfo(options.policies.reconnection), - ssl: { - enabled: !!options.sslOptions, - certValidation: options.sslOptions ? !!options.sslOptions.rejectUnauthorized : undefined - }, - authProvider: { - type: !(options.authProvider instanceof NoAuthProvider) ? getConstructor(options.authProvider) : undefined, - }, - otherOptions: { - coalescingThreshold: options.socketOptions.coalescingThreshold, - }, - platformInfo: { - os: { - name: os.platform(), - version: os.release(), - arch: os.arch() - }, - cpus: { - length: os.cpus().length, - model: os.cpus()[0].model - }, - runtime: { - node: process.versions['node'], - v8: process.versions['v8'], - uv: process.versions['uv'], - openssl: process.versions['openssl'], - kerberos: kerberosModule ? kerberosModule.version : undefined - } - }, - configAntiPatterns: this._getConfigAntiPatterns(), - periodicStatusInterval: Math.floor(this._statusEventDelay / 1000) - } - }; - - return JSON.stringify(message); - } - - _getConfigAntiPatterns() { - const options = this._client.options; - const result = {}; - - if (options.sslOptions && !options.sslOptions.rejectUnauthorized) { - result.sslWithoutCertValidation = - 'Client-to-node encryption is enabled but server certificate validation is disabled'; - } - - return result; - } - - /** - * Gets an array of data centers the driver connects to. - * Whether the driver connects to a certain host is determined by the host distance (local and remote hosts) - * and the pooling options (whether connection length for remote hosts is greater than 0). - * @returns {Array} - * @private - */ - _getDataCenters() { - const remoteConnectionsLength = this._client.options.pooling.coreConnectionsPerHost[types.distance.remote]; - const dataCenters = new Set(); - - this._client.hosts.values().forEach(h => { - const distance = this._client.profileManager.getDistance(h); - if (distance === types.distance.local || (distance === types.distance.remote && remoteConnectionsLength > 0)) { - dataCenters.add(h.datacenter); - } - }); - - return Array.from(dataCenters); - } - - /** - * Tries to obtain the application name and version from - * @param {DseClientOptions} options - * @returns {Promise} - * @private - */ - async _getAppInfo(options) { - if (typeof options.applicationName === 'string') { - return Promise.resolve({ - applicationName: options.applicationName, - applicationVersion: options.applicationVersion, - applicationNameWasGenerated: false - }); - } - - let readPromise = Promise.resolve(); - - if (require.main && require.main.filename) { - const packageInfoPath = path.dirname(require.main.filename); - readPromise = this._readPackageInfoFile(packageInfoPath); - } - - const text = await readPromise; - let applicationName = 'Default Node.js Application'; - let applicationVersion; - - if (text) { - try { - const packageInfo = JSON.parse(text); - if (packageInfo.name) { - applicationName = packageInfo.name; - applicationVersion = packageInfo.version; - } - } - catch (err) { - // The package.json file could not be parsed - // Use the default name - } - } - - return { - applicationName, - applicationVersion, - applicationNameWasGenerated: true - }; - } - - /** - * @private - * @returns {Promise} A Promise that will never be rejected - */ - _readPackageInfoFile(packageInfoPath) { - return new Promise(resolve => { - fs.readFile(path.join(packageInfoPath, 'package.json'), 'utf8', (err, data) => { - // Swallow error - resolve(data); - }); - }); - } - - /** - * @returns {String} Returns a json string with the startup message. - * @private - */ - _getStatusEvent() { - const cc = this._client.controlConnection; - const options = this._client.options; - const state = this._client.getState(); - const connectedNodes = {}; - - state.getConnectedHosts().forEach(h => { - connectedNodes[h.address] = { - connections: state.getOpenConnections(h), - inFlightQueries: state.getInFlightQueries(h) - }; - }); - - const message = { - metadata: { - name: 'driver.status', - insightMappingId: 'v1', - insightType: 'EVENT', - timestamp: Date.now(), - tags: { language: 'nodejs' } - }, - data: { - clientId: options.id, - sessionId: this._sessionId, - controlConnection: cc.host ? cc.host.address : undefined, - connectedNodes - } - }; - - return JSON.stringify(message); - } - - /** - * Cleans any timer used internally and sets the client as closed. - */ - shutdown() { - if (!this._enabled) { - return; - } - - this._closed = true; - - if (this._firstTimeout !== null) { - clearTimeout(this._firstTimeout); - } - - if (this._recurrentTimeout !== null) { - clearInterval(this._recurrentTimeout); - } - } -} - -module.exports = InsightsClient; - -function mapToObject(map) { - const result = {}; - map.forEach((value, key) => result[key] = value); - return result; -} - -function getPolicyInfo(policy) { - if (!policy) { - return undefined; - } - - const options = policy.getOptions && policy.getOptions(); - - return { - type: policy.constructor.name, - options: (options instanceof Map) ? mapToObject(options) : utils.emptyObject - }; -} - -function getConsistencyString(c) { - if (typeof c !== 'number') { - return undefined; - } - - return types.consistencyToString[c]; -} - -function getConstructor(instance) { - return instance ? instance.constructor.name : undefined; -} - -function getExecutionProfiles(client) { - const executionProfiles = {}; - - const defaultProfile = client.profileManager.getDefault(); - setExecutionProfileProperties(client, executionProfiles, defaultProfile, defaultProfile); - - client.profileManager.getAll() - .filter(p => p !== defaultProfile) - .forEach(profile => setExecutionProfileProperties(client, executionProfiles, profile, defaultProfile)); - - return executionProfiles; -} - -function setExecutionProfileProperties(client, parent, profile, defaultProfile) { - const output = parent[profile.name] = {}; - setExecutionProfileItem(output, profile, defaultProfile, 'readTimeout'); - setExecutionProfileItem(output, profile, defaultProfile, 'loadBalancing', getPolicyInfo); - setExecutionProfileItem(output, profile, defaultProfile, 'retry', getPolicyInfo); - setExecutionProfileItem(output, profile, defaultProfile, 'consistency', getConsistencyString); - setExecutionProfileItem(output, profile, defaultProfile, 'serialConsistency', getConsistencyString); - - if (profile === defaultProfile) { - // Speculative execution policy is included in the profiles as some drivers support - // different spec exec policy per profile, in this case is fixed for all profiles - output.speculativeExecution = getPolicyInfo(client.options.policies.speculativeExecution); - } - - if (profile.graphOptions) { - output.graphOptions = {}; - const defaultGraphOptions = defaultProfile.graphOptions || utils.emptyObject; - setExecutionProfileItem(output.graphOptions, profile.graphOptions, defaultGraphOptions, 'language'); - setExecutionProfileItem(output.graphOptions, profile.graphOptions, defaultGraphOptions, 'name'); - setExecutionProfileItem(output.graphOptions, profile.graphOptions, defaultGraphOptions, 'readConsistency', - getConsistencyString); - setExecutionProfileItem(output.graphOptions, profile.graphOptions, defaultGraphOptions, 'source'); - setExecutionProfileItem(output.graphOptions, profile.graphOptions, defaultGraphOptions, 'writeConsistency', - getConsistencyString); - - if (Object.keys(output.graphOptions).length === 0) { - // Properties that are undefined will not be included in the JSON - output.graphOptions = undefined; - } - } -} - -function setExecutionProfileItem(output, profile, defaultProfile, prop, valueGetter) { - const value = profile[prop]; - valueGetter = valueGetter || (x => x); - - if ((profile === defaultProfile && value !== undefined) || value !== defaultProfile[prop]) { - output[prop] = valueGetter(value); - } -} \ No newline at end of file diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/mapping/cache.js b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/mapping/cache.js deleted file mode 100644 index ffc4777da9..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/mapping/cache.js +++ /dev/null @@ -1,207 +0,0 @@ -/* - * Copyright DataStax, Inc. - * - * 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 qModule = require('./q'); -const QueryOperator = qModule.QueryOperator; -const QueryAssignment = qModule.QueryAssignment; - -/** - * Provides utility methods for obtaining a caching keys based on the specifics of the Mapper methods. - * @ignore - */ -class Cache { - /** - * Gets an iterator of keys to uniquely identify a document shape for a select query. - * @param {Array} docKeys - * @param {Object} doc - * @param {{fields, limit, orderBy}} docInfo - * @returns {Iterator} - */ - static *getSelectKey(docKeys, doc, docInfo) { - yield* Cache._yieldKeyAndOperators(docKeys, doc); - - yield* Cache._getSelectDocInfo(docInfo); - } - /** - * Gets an iterator of keys to uniquely identify a shape for a select all query. - * @param {{fields, limit, orderBy}} docInfo - * @returns {Iterator} - */ - static *getSelectAllKey(docInfo) { - yield 'root'; - - yield* Cache._getSelectDocInfo(docInfo); - } - - /** - * Gets the parts of the key for a select query related to the docInfo. - * @param {{fields, limit, orderBy}} docInfo - * @private - */ - static *_getSelectDocInfo(docInfo) { - if (docInfo) { - if (docInfo.fields && docInfo.fields.length > 0) { - // Use a separator from properties - yield '|f|'; - yield* docInfo.fields; - } - - if (typeof docInfo.limit === 'number') { - yield '|l|'; - } - - if (docInfo.orderBy) { - yield '|o|'; - - // orderBy is uses property names as keys and 'asc'/'desc' as values - const keys = Object.keys(docInfo.orderBy); - for (let i = 0; i < keys.length; i++) { - const key = keys[i]; - yield key; - yield docInfo.orderBy[key]; - } - } - } - } - - /** - * Gets an iterator of keys to uniquely identify a document shape for an insert query. - * @param {Array} docKeys - * @param {{ifNotExists, ttl, fields}} docInfo - * @returns {Iterator} - */ - static *getInsertKey(docKeys, docInfo) { - // No operator supported on INSERT values - yield* docKeys; - - if (docInfo) { - if (docInfo.fields && docInfo.fields.length > 0) { - // Use a separator from properties - yield '|f|'; - yield* docInfo.fields; - } - - if (typeof docInfo.ttl === 'number') { - yield '|t|'; - } - - if (docInfo.ifNotExists) { - yield '|e|'; - } - } - } - - /** - * Gets an iterator of keys to uniquely identify a document shape for an UPDATE query. - * @param {Array} docKeys - * @param {Object} doc - * @param {{ifExists, when, ttl, fields}} docInfo - */ - static *getUpdateKey(docKeys, doc, docInfo) { - yield* Cache._yieldKeyAndAllQs(docKeys, doc); - - if (docInfo) { - if (docInfo.fields && docInfo.fields.length > 0) { - // Use a separator from properties - yield '|f|'; - yield* docInfo.fields; - } - - if (typeof docInfo.ttl === 'number') { - yield '|t|'; - } - - if (docInfo.ifExists) { - yield '|e|'; - } - - if (docInfo.when) { - yield* Cache._yieldKeyAndOperators(Object.keys(docInfo.when), docInfo.when); - } - } - } - - /** - * Gets an iterator of keys to uniquely identify a document shape for a DELETE query. - * @param {Array} docKeys - * @param {Object} doc - * @param {{ifExists, when, fields, deleteOnlyColumns}} docInfo - * @returns {Iterator} - */ - static *getRemoveKey(docKeys, doc, docInfo) { - yield* Cache._yieldKeyAndOperators(docKeys, doc); - - if (docInfo) { - if (docInfo.fields && docInfo.fields.length > 0) { - // Use a separator from properties - yield '|f|'; - yield* docInfo.fields; - } - - if (docInfo.ifExists) { - yield '|e|'; - } - - if (docInfo.deleteOnlyColumns) { - yield '|dc|'; - } - - if (docInfo.when) { - yield* Cache._yieldKeyAndOperators(Object.keys(docInfo.when), docInfo.when); - } - } - } - - static *_yieldKeyAndOperators(keys, obj) { - for (let i = 0; i < keys.length; i++) { - const key = keys[i]; - yield key; - yield* Cache._yieldOperators(obj[key]); - } - } - - static *_yieldOperators(value) { - if (value !== null && value !== undefined && value instanceof QueryOperator) { - yield value.key; - if (value.hasChildValues) { - yield* Cache._yieldOperators(value.value[0]); - yield '|/|'; - yield* Cache._yieldOperators(value.value[1]); - } - } - } - - static *_yieldKeyAndAllQs(keys, obj) { - for (let i = 0; i < keys.length; i++) { - const key = keys[i]; - yield key; - const value = obj[key]; - if (value !== null && value !== undefined) { - if (value instanceof QueryOperator) { - yield* Cache._yieldOperators(value); - } - else if (value instanceof QueryAssignment) { - yield value.sign; - yield value.inverted; - } - } - } - } -} - -module.exports = Cache; \ No newline at end of file diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/mapping/doc-info-adapter.js b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/mapping/doc-info-adapter.js deleted file mode 100644 index 32deead547..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/mapping/doc-info-adapter.js +++ /dev/null @@ -1,162 +0,0 @@ -/* - * Copyright DataStax, Inc. - * - * 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 errors = require('../errors'); -const utils = require('../utils'); - -/** - * Provides utility methods to adapt and map user provided docInfo and executionOptions to a predictable object format. - * @ignore - */ -class DocInfoAdapter { - /** - * Returns an Array where each item contains the property name, the column name and the property value (to obtain - * the operator). - * When docInfo.fields is specified, it uses that array to obtain the information. - * @param {Array} docKeys - * @param {null|{fields}} docInfo - * @param {Object} doc - * @param {ModelMappingInfo} mappingInfo - * @returns {Array} - */ - static getPropertiesInfo(docKeys, docInfo, doc, mappingInfo) { - let propertyKeys = docKeys; - if (docInfo && docInfo.fields && docInfo.fields.length > 0) { - propertyKeys = docInfo.fields; - } - - return propertyKeys.map(propertyName => ({ - propertyName, - columnName: mappingInfo.getColumnName(propertyName), - value: doc[propertyName], - fromModel: mappingInfo.getFromModelFn(propertyName) - })); - } - - /** - * @param {{orderBy}} docInfo - * @param {ModelMappingInfo} mappingInfo - * @returns {Array} - */ - static adaptOrderBy(docInfo, mappingInfo){ - if (!docInfo || !docInfo.orderBy) { - return utils.emptyArray; - } - return Object.keys(docInfo.orderBy).map(key => { - const value = docInfo.orderBy[key]; - const ordering = typeof value === 'string' ? value.toUpperCase() : value; - if (ordering !== 'ASC' && ordering !== 'DESC') { - throw new errors.ArgumentError('Order must be either "ASC" or "DESC", obtained: ' + value); - } - return [ mappingInfo.getColumnName(key), ordering ]; - }); - } - - /** - * Returns the QueryOptions for an INSERT/UPDATE/DELETE statement. - * @param {Object|String|undefined} executionOptions - * @param {Boolean} isIdempotent - */ - static adaptOptions(executionOptions, isIdempotent) { - const options = { - prepare: true, - executionProfile: undefined, - timestamp: undefined, - isIdempotent: isIdempotent - }; - - if (typeof executionOptions === 'string') { - options.executionProfile = executionOptions; - } - else if (executionOptions !== null && executionOptions !== undefined) { - options.executionProfile = executionOptions.executionProfile; - options.timestamp = executionOptions.timestamp; - - if (executionOptions.isIdempotent !== undefined) { - options.isIdempotent = executionOptions.isIdempotent; - } - } - return options; - } - - /** - * Returns the QueryOptions for a SELECT statement. - * @param {Object|String|undefined} executionOptions - * @param {Boolean} [overrideIdempotency] - */ - static adaptAllOptions(executionOptions, overrideIdempotency) { - const options = { - prepare: true, - executionProfile: undefined, - fetchSize: undefined, - pageState: undefined, - timestamp: undefined, - isIdempotent: undefined - }; - - if (typeof executionOptions === 'string') { - options.executionProfile = executionOptions; - } - else if (executionOptions !== null && executionOptions !== undefined) { - options.executionProfile = executionOptions.executionProfile; - options.fetchSize = executionOptions.fetchSize; - options.pageState = executionOptions.pageState; - options.timestamp = executionOptions.timestamp; - options.isIdempotent = executionOptions.isIdempotent; - } - - if (overrideIdempotency) { - options.isIdempotent = true; - } - - return options; - } - - /** - * Returns the QueryOptions for a batch statement. - * @param {Object|String|undefined} executionOptions - * @param {Boolean} isIdempotent - * @param {Boolean} isCounter - */ - static adaptBatchOptions(executionOptions, isIdempotent, isCounter) { - const options = { - prepare: true, - executionProfile: undefined, - timestamp: undefined, - logged: undefined, - isIdempotent: isIdempotent, - counter: isCounter - }; - - if (typeof executionOptions === 'string') { - options.executionProfile = executionOptions; - } - else if (executionOptions !== null && executionOptions !== undefined) { - options.executionProfile = executionOptions.executionProfile; - options.timestamp = executionOptions.timestamp; - options.logged = executionOptions.logged !== false; - - if (executionOptions.isIdempotent !== undefined) { - options.isIdempotent = executionOptions.isIdempotent; - } - } - return options; - } -} - -module.exports = DocInfoAdapter; \ No newline at end of file diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/mapping/index.d.ts b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/mapping/index.d.ts deleted file mode 100644 index 694e789cf7..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/mapping/index.d.ts +++ /dev/null @@ -1,189 +0,0 @@ -/* - * Copyright DataStax, Inc. - * - * 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. - */ - -import { types } from '../types'; -import { Client } from '../../'; -import Long = types.Long; - -export namespace mapping { - interface TableMappings { - getColumnName(propName: string): string; - - getPropertyName(columnName: string): string; - - newObjectInstance(): any; - } - - class DefaultTableMappings implements TableMappings { - getColumnName(propName: string): string; - - getPropertyName(columnName: string): string; - - newObjectInstance(): any; - } - - class UnderscoreCqlToCamelCaseMappings implements TableMappings { - getColumnName(propName: string): string; - - getPropertyName(columnName: string): string; - - newObjectInstance(): any; - } - - interface Result extends Iterator { - wasApplied(): boolean; - - first(): T | null; - - forEach(callback: (currentValue: T, index: number) => void, thisArg?: any): void; - - toArray(): T[]; - } - - type MappingExecutionOptions = { - executionProfile?: string; - isIdempotent?: boolean; - logged?: boolean; - timestamp?: number | Long; - fetchSize?: number; - pageState?: number; - } - - interface ModelTables { - name: string; - isView: boolean; - } - - class Mapper { - constructor(client: Client, options?: MappingOptions); - - batch(items: ModelBatchItem[], executionOptions?: string | MappingExecutionOptions): Promise; - - forModel(name: string): ModelMapper; - } - - type MappingOptions = { - models: { [key: string]: ModelOptions }; - } - - type FindDocInfo = { - fields?: string[]; - orderBy?: { [key: string]: string }; - limit?: number; - } - - type InsertDocInfo = { - fields?: string[]; - ttl?: number; - ifNotExists?: boolean; - } - - type UpdateDocInfo = { - fields?: string[]; - ttl?: number; - ifExists?: boolean; - when?: { [key: string]: any }; - orderBy?: { [key: string]: string }; - limit?: number; - deleteOnlyColumns?: boolean; - } - - type RemoveDocInfo = { - fields?: string[]; - ttl?: number; - ifExists?: boolean; - when?: { [key: string]: any }; - deleteOnlyColumns?: boolean; - } - - type ModelOptions = { - tables?: string[] | ModelTables[]; - mappings?: TableMappings; - columns?: { [key: string]: string|ModelColumnOptions }; - keyspace?: string; - } - - type ModelColumnOptions = { - name: string; - toModel?: (columnValue: any) => any; - fromModel?: (modelValue: any) => any; - }; - - interface ModelBatchItem { - - } - - interface ModelBatchMapper { - insert(doc: any, docInfo?: InsertDocInfo): ModelBatchItem; - - remove(doc: any, docInfo?: RemoveDocInfo): ModelBatchItem; - - update(doc: any, docInfo?: UpdateDocInfo): ModelBatchItem; - } - - interface ModelMapper { - name: string; - batching: ModelBatchMapper; - - get(doc: { [key: string]: any }, docInfo?: { fields?: string[] }, executionOptions?: string | MappingExecutionOptions): Promise; - - find(doc: { [key: string]: any }, docInfo?: FindDocInfo, executionOptions?: string | MappingExecutionOptions): Promise>; - - findAll(docInfo?: FindDocInfo, executionOptions?: string | MappingExecutionOptions): Promise>; - - insert(doc: { [key: string]: any }, docInfo?: InsertDocInfo, executionOptions?: string | MappingExecutionOptions): Promise>; - - update(doc: { [key: string]: any }, docInfo?: UpdateDocInfo, executionOptions?: string | MappingExecutionOptions): Promise>; - - remove(doc: { [key: string]: any }, docInfo?: RemoveDocInfo, executionOptions?: string | MappingExecutionOptions): Promise>; - - mapWithQuery( - query: string, - paramsHandler: (doc: any) => any[], - executionOptions?: string | MappingExecutionOptions - ): (doc: any, executionOptions?: string | MappingExecutionOptions) => Promise>; - } - - namespace q { - interface QueryOperator { - - } - - function in_(arr: any): QueryOperator; - - function gt(value: any): QueryOperator; - - function gte(value: any): QueryOperator; - - function lt(value: any): QueryOperator; - - function lte(value: any): QueryOperator; - - function notEq(value: any): QueryOperator; - - function and(condition1: any, condition2: any): QueryOperator; - - function incr(value: any): QueryOperator; - - function decr(value: any): QueryOperator; - - function append(value: any): QueryOperator; - - function prepend(value: any): QueryOperator; - - function remove(value: any): QueryOperator; - } -} \ No newline at end of file diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/mapping/index.js b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/mapping/index.js deleted file mode 100644 index e1de6c93b3..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/mapping/index.js +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Copyright DataStax, Inc. - * - * 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'; - -/** - * Module containing classes and fields related to the Mapper. - * @module mapping - */ - -exports.Mapper = require('./mapper'); -exports.ModelMapper = require('./model-mapper'); -exports.ModelBatchMapper = require('./model-batch-mapper'); -exports.ModelBatchItem = require('./model-batch-item').ModelBatchItem; -exports.Result = require('./result'); -const tableMappingsModule = require('./table-mappings'); -exports.TableMappings = tableMappingsModule.TableMappings; -exports.DefaultTableMappings = tableMappingsModule.DefaultTableMappings; -exports.UnderscoreCqlToCamelCaseMappings = tableMappingsModule.UnderscoreCqlToCamelCaseMappings; -exports.q = require('./q').q; \ No newline at end of file diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/mapping/mapper.js b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/mapping/mapper.js deleted file mode 100644 index 329c87f1c5..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/mapping/mapper.js +++ /dev/null @@ -1,193 +0,0 @@ -/* - * Copyright DataStax, Inc. - * - * 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 ModelMapper = require('./model-mapper'); -const MappingHandler = require('./mapping-handler'); -const DocInfoAdapter = require('./doc-info-adapter'); -const errors = require('../errors'); -const Result = require('./result'); -const ResultMapper = require('./result-mapper'); -const ModelMappingInfo = require('./model-mapping-info'); -const { ModelBatchItem } = require('./model-batch-item'); - -/** - * Represents an object mapper for Apache Cassandra and DataStax Enterprise. - * @alias module:mapping~Mapper - * @example Creating a Mapper instance with some options for the model 'User' - * const mappingOptions = { - * models: { - * 'User': { - * tables: ['users'], - * mappings: new UnderscoreCqlToCamelCaseMappings(), - * columnNames: { - * 'userid': 'id' - * } - * } - * } - * }; - * const mapper = new Mapper(client, mappingOptions); - * @example Creating a Mapper instance with other possible options for a model - * const mappingOptions = { - * models: { - * 'Video': { - * tables: ['videos', 'user_videos', 'latest_videos', { name: 'my_videos_view', isView: true }], - * mappings: new UnderscoreCqlToCamelCaseMappings(), - * columnNames: { - * 'videoid': 'id' - * }, - * keyspace: 'ks1' - * } - * } - * }; - * const mapper = new Mapper(client, mappingOptions); - */ -class Mapper { - /** - * Creates a new instance of Mapper. - * @param {Client} client The Client instance to use to execute the queries and fetch the metadata. - * @param {MappingOptions} [options] The [MappingOptions]{@link module:mapping~MappingOptions} containing the - * information of the models and table mappings. - */ - constructor(client, options) { - if (!client) { - throw new Error('client must be defined'); - } - - /** - * The Client instance used to create this Mapper instance. - * @type {Client} - */ - this.client = client; - - this._modelMappingInfos = ModelMappingInfo.parse(options, client.keyspace); - this._modelMappers = new Map(); - } - - /** - * Gets a [ModelMapper]{@link module:mapping~ModelMapper} that is able to map documents of a certain model into - * CQL rows. - * @param {String} name The name to identify the model. Note that the name is case-sensitive. - * @returns {ModelMapper} A [ModelMapper]{@link module:mapping~ModelMapper} instance. - */ - forModel(name) { - let modelMapper = this._modelMappers.get(name); - - if (modelMapper === undefined) { - let mappingInfo = this._modelMappingInfos.get(name); - - if (mappingInfo === undefined) { - if (!this.client.keyspace) { - throw new Error(`No mapping information found for model '${name}'. ` + - `Mapper is unable to create default mappings without setting the keyspace`); - } - - mappingInfo = ModelMappingInfo.createDefault(name, this.client.keyspace); - this.client.log('info', `Mapping information for model '${name}' not found, creating default mapping. ` + - `Keyspace: ${mappingInfo.keyspace}; Table: ${mappingInfo.tables[0].name}.`); - } else { - this.client.log('info', `Creating model mapper for '${name}' using mapping information. Keyspace: ${ - mappingInfo.keyspace}; Table${mappingInfo.tables.length > 1? 's' : ''}: ${ - mappingInfo.tables.map(t => t.name)}.`); - } - - modelMapper = new ModelMapper(name, new MappingHandler(this.client, mappingInfo)); - this._modelMappers.set(name, modelMapper); - } - - return modelMapper; - } - - /** - * Executes a batch of queries represented in the items. - * @param {Array} items - * @param {Object|String} [executionOptions] An object containing the options to be used for the requests - * execution or a string representing the name of the execution profile. - * @param {String} [executionOptions.executionProfile] The name of the execution profile. - * @param {Boolean} [executionOptions.isIdempotent] Defines whether the query can be applied multiple times without - * changing the result beyond the initial application. - *

- * The mapper uses the generated queries to determine the default value. When an UPDATE is generated with a - * counter column or appending/prepending to a list column, the execution is marked as not idempotent. - *

- *

- * Additionally, the mapper uses the safest approach for queries with lightweight transactions (Compare and - * Set) by considering them as non-idempotent. Lightweight transactions at client level with transparent retries can - * break linearizability. If that is not an issue for your application, you can manually set this field to true. - *

- * @param {Boolean} [executionOptions.logged=true] Determines whether the batch should be written to the batchlog. - * @param {Number|Long} [executionOptions.timestamp] The default timestamp for the query in microseconds from the - * unix epoch (00:00:00, January 1st, 1970). - * @returns {Promise} A Promise that resolves to a [Result]{@link module:mapping~Result}. - */ - batch(items, executionOptions) { - if (!Array.isArray(items) || !(items.length > 0)) { - return Promise.reject( - new errors.ArgumentError('First parameter items should be an Array with 1 or more ModelBatchItem instances')); - } - - const queries = []; - let isIdempotent = true; - let isCounter; - - return Promise - .all(items - .map(item => { - if (!(item instanceof ModelBatchItem)) { - return Promise.reject(new Error( - 'Batch items must be instances of ModelBatchItem, use modelMapper.batching object to create each item')); - } - - return item.pushQueries(queries) - .then(options => { - // The batch is idempotent when all the queries contained are idempotent - isIdempotent = isIdempotent && options.isIdempotent; - - // Let it fail at server level when there is a mix of counter and normal mutations - isCounter = options.isCounter; - }); - })) - .then(() => - this.client.batch(queries, DocInfoAdapter.adaptBatchOptions(executionOptions, isIdempotent, isCounter))) - .then(rs => { - // Results should only be adapted when the batch contains LWT (single table) - const info = items[0].getMappingInfo(); - return new Result(rs, info, ResultMapper.getMutationAdapter(rs)); - }); - } -} - -/** - * Represents the mapping options. - * @typedef {Object} module:mapping~MappingOptions - * @property {Object} models An associative array containing the - * name of the model as key and the table and column information as value. - */ - -/** - * Represents a set of options that applies to a certain model. - * @typedef {Object} module:mapping~ModelOptions - * @property {Array|Array<{name, isView}>} tables An Array containing the name of the tables or An Array - * containing the name and isView property to describe the table. - * @property {TableMappings} mappings The TableMappings implementation instance that is used to convert from column - * names to property names and the other way around. - * @property {Object.} [columnNames] An associative array containing the name of the columns and - * properties that doesn't follow the convention defined in the TableMappings. - * @property {String} [keyspace] The name of the keyspace. Only mandatory when the Client is not using a keyspace. - */ - -module.exports = Mapper; \ No newline at end of file diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/mapping/mapping-handler.js b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/mapping/mapping-handler.js deleted file mode 100644 index f5bd83177a..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/mapping/mapping-handler.js +++ /dev/null @@ -1,412 +0,0 @@ -/* - * Copyright DataStax, Inc. - * - * 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 utils = require('../utils'); -const QueryGenerator = require('./query-generator'); -const ResultMapper = require('./result-mapper'); -const Result = require('./result'); -const Cache = require('./cache'); -const Tree = require('./tree'); -const ObjectSelector = require('./object-selector'); -const DocInfoAdapter = require('./doc-info-adapter'); - -const cacheHighWaterMark = 100; - -/** - * @ignore - */ -class MappingHandler { - /** - * @param {Client} client - * @param {ModelMappingInfo} mappingInfo - */ - constructor(client, mappingInfo) { - this._client = client; - this._cache = { - select: new Tree().on('add', length => this._validateCacheLength(length)), - selectAll: new Tree().on('add', length => this._validateCacheLength(length)), - insert: new Tree().on('add', length => this._validateCacheLength(length)), - update: new Tree().on('add', length => this._validateCacheLength(length)), - remove: new Tree().on('add', length => this._validateCacheLength(length)), - customQueries: new Map() - }; - - /** - * Gets the mapping information of the document. - * @type {ModelMappingInfo} - */ - this.info = mappingInfo; - } - - /** - * Gets a function to be used to execute SELECT the query using the document. - * @param {Object} doc - * @param {{fields, orderBy, limit}} docInfo - * @param {Boolean} allPKsDefined Determines whether all primary keys must be defined in the doc for the query to - * be valid. - * @return {Promise} - */ - getSelectExecutor(doc, docInfo, allPKsDefined) { - const docKeys = Object.keys(doc); - if (docKeys.length === 0) { - return Promise.reject(new Error('Expected object with keys')); - } - - const cacheKey = Cache.getSelectKey(docKeys, doc, docInfo); - // Cache the executor and the result mapper under the same key - // That way, those can get evicted together - const cacheItem = this._cache.select.getOrCreate(cacheKey, () => ({ executor: null, resultAdapter: null })); - - if (cacheItem.executor !== null) { - return Promise.resolve(cacheItem.executor); - } - - const propertiesInfo = DocInfoAdapter.getPropertiesInfo(docKeys, null, doc, this.info); - const fieldsInfo = DocInfoAdapter.getPropertiesInfo(utils.emptyArray, docInfo, doc, this.info); - const orderByColumns = DocInfoAdapter.adaptOrderBy(docInfo, this.info); - const limit = docInfo && docInfo.limit; - - return this._client.connect() - .then(() => - ObjectSelector.getForSelect(this._client, this.info, allPKsDefined, propertiesInfo, fieldsInfo, orderByColumns)) - .then(tableName => { - // Part of the closure - const query = QueryGenerator.getSelect(tableName, this.info.keyspace, propertiesInfo, fieldsInfo, - orderByColumns, limit); - const paramsGetter = QueryGenerator.selectParamsGetter(propertiesInfo, limit); - const self = this; - - cacheItem.executor = function selectExecutor(doc, docInfo, executionOptions) { - return self._executeSelect(query, paramsGetter, doc, docInfo, executionOptions, cacheItem); - }; - - return cacheItem.executor; - }); - } - - getSelectAllExecutor(docInfo) { - const cacheKey = Cache.getSelectAllKey(docInfo); - const cacheItem = this._cache.selectAll.getOrCreate(cacheKey, () => ({ executor: null, resultAdapter: null })); - - if (cacheItem.executor !== null) { - return cacheItem.executor; - } - - const fieldsInfo = DocInfoAdapter.getPropertiesInfo(utils.emptyArray, docInfo, utils.emptyObject, this.info); - const orderByColumns = DocInfoAdapter.adaptOrderBy(docInfo, this.info); - const limit = docInfo && docInfo.limit; - - const tableName = ObjectSelector.getForSelectAll(this.info); - - // Part of the closure - const query = QueryGenerator.getSelect( - tableName, this.info.keyspace, utils.emptyArray, fieldsInfo, orderByColumns, limit); - const paramsGetter = QueryGenerator.selectParamsGetter(utils.emptyArray, limit); - const self = this; - - cacheItem.executor = function selectAllExecutor(docInfo, executionOptions) { - return self._executeSelect(query, paramsGetter, null, docInfo, executionOptions, cacheItem); - }; - - return cacheItem.executor; - } - - /** - * Executes a SELECT query and returns the adapted results. - * When a result adapter is not yet created, it gets a new one and caches it. - * @private - */ - _executeSelect(query, paramsGetter, doc, docInfo, executionOptions, cacheItem) { - const options = DocInfoAdapter.adaptAllOptions(executionOptions, true); - - return this._client.execute(query, paramsGetter(doc, docInfo, this.info), options) - .then(rs => { - if (cacheItem.resultAdapter === null) { - cacheItem.resultAdapter = ResultMapper.getSelectAdapter(this.info, rs); - } - return new Result(rs, this.info, cacheItem.resultAdapter); - }); - } - - /** - * Gets a function to be used to execute INSERT the query using the document. - * @param {Object} doc - * @param {{ifNotExists, ttl, fields}} docInfo - * @return {Promise} - */ - getInsertExecutor(doc, docInfo) { - const docKeys = Object.keys(doc); - if (docKeys.length === 0) { - return Promise.reject(new Error('Expected object with keys')); - } - - const cacheKey = Cache.getInsertKey(docKeys, docInfo); - const cacheItem = this._cache.insert.getOrCreate(cacheKey, () => ({ executor: null })); - - if (cacheItem.executor !== null) { - return Promise.resolve(cacheItem.executor); - } - - return this.createInsertQueries(docKeys, doc, docInfo) - .then(queries => { - if (queries.length === 1) { - return this._setSingleExecutor(cacheItem, queries[0]); - } - - return this._setBatchExecutor(cacheItem, queries); - }); - } - - /** - * Creates an Array containing the query and the params getter function for each table affected by the INSERT. - * @param {Array} docKeys - * @param {Object} doc - * @param {{ifNotExists, ttl, fields}} docInfo - * @returns {Promise>} - */ - createInsertQueries(docKeys, doc, docInfo) { - const propertiesInfo = DocInfoAdapter.getPropertiesInfo(docKeys, docInfo, doc, this.info); - const ifNotExists = docInfo && docInfo.ifNotExists; - - // Get all the tables affected - return this._client.connect() - .then(() => ObjectSelector.getForInsert(this._client, this.info, propertiesInfo)) - .then(tables => { - - if (tables.length > 1 && ifNotExists) { - throw new Error('Batch with ifNotExists conditions cannot span multiple tables'); - } - - // For each tables affected, Generate query and parameter getters - return tables.map(table => - QueryGenerator.getInsert(table, this.info.keyspace, propertiesInfo, docInfo,ifNotExists)); - }); - } - - /** - * Gets a function to be used to execute the UPDATE queries with the provided document. - * @param {Object} doc - * @param {{ifExists, when, ttl, fields}} docInfo - * @return {Promise} - */ - getUpdateExecutor(doc, docInfo) { - const docKeys = Object.keys(doc); - if (docKeys.length === 0) { - return Promise.reject(new Error('Expected object with keys')); - } - - const cacheKey = Cache.getUpdateKey(docKeys, doc, docInfo); - const cacheItem = this._cache.update.getOrCreate(cacheKey, () => ({ executor: null })); - - if (cacheItem.executor !== null) { - return Promise.resolve(cacheItem.executor); - } - - return this.createUpdateQueries(docKeys, doc, docInfo) - .then(queries => { - if (queries.length === 1) { - return this._setSingleExecutor(cacheItem, queries[0]); - } - - return this._setBatchExecutor(cacheItem, queries); - }); - } - - /** - * Creates an Array containing the query and the params getter function for each table affected by the UPDATE. - * @param {Array} docKeys - * @param {Object} doc - * @param {Object} docInfo - * @returns {Promise>} - */ - createUpdateQueries(docKeys, doc, docInfo) { - const propertiesInfo = DocInfoAdapter.getPropertiesInfo(docKeys, docInfo, doc, this.info); - const ifExists = docInfo && docInfo.ifExists; - const when = docInfo && docInfo.when - ? DocInfoAdapter.getPropertiesInfo(Object.keys(docInfo.when), null, docInfo.when, this.info) - : utils.emptyArray; - - if (when.length > 0 && ifExists) { - throw new Error('Both when and ifExists conditions can not be applied to the same statement'); - } - - // Get all the tables affected - return this._client.connect() - .then(() => ObjectSelector.getForUpdate(this._client, this.info, propertiesInfo, when)) - .then(tables => { - - if (tables.length > 1 && (when.length > 0 || ifExists)) { - throw new Error('Batch with when or ifExists conditions cannot span multiple tables'); - } - - // For each table affected, Generate query and parameter getters - return tables.map(table => - QueryGenerator.getUpdate(table, this.info.keyspace, propertiesInfo, docInfo, when, ifExists)); - }); - } - - /** - * Gets a function to be used to execute the DELETE queries with the provided document. - * @param {Object} doc - * @param {{when, ifExists, fields, deleteOnlyColumns}} docInfo - * @return {Promise} - */ - getDeleteExecutor(doc, docInfo) { - const docKeys = Object.keys(doc); - if (docKeys.length === 0) { - return Promise.reject(new Error('Expected object with keys')); - } - - const cacheKey = Cache.getRemoveKey(docKeys, doc, docInfo); - const cacheItem = this._cache.remove.getOrCreate(cacheKey, () => ({ executor: null })); - - if (cacheItem.executor !== null) { - return Promise.resolve(cacheItem.executor); - } - - return this.createDeleteQueries(docKeys, doc, docInfo) - .then(queries => { - if (queries.length === 1) { - return this._setSingleExecutor(cacheItem, queries[0]); - } - - return this._setBatchExecutor(cacheItem, queries); - }); - } - - /** - * Creates an Array containing the query and the params getter function for each table affected by the DELETE. - * @param {Array} docKeys - * @param {Object} doc - * @param {{when, ifExists, fields, deleteOnlyColumns}} docInfo - * @returns {Promise>} - */ - createDeleteQueries(docKeys, doc, docInfo) { - const propertiesInfo = DocInfoAdapter.getPropertiesInfo(docKeys, docInfo, doc, this.info); - const ifExists = docInfo && docInfo.ifExists; - const when = docInfo && docInfo.when - ? DocInfoAdapter.getPropertiesInfo(Object.keys(docInfo.when), null, docInfo.when, this.info) - : utils.emptyArray; - - if (when.length > 0 && ifExists) { - throw new Error('Both when and ifExists conditions can not be applied to the same statement'); - } - - // Get all the tables affected - return this._client.connect() - .then(() => ObjectSelector.getForDelete(this._client, this.info, propertiesInfo, when)) - .then(tables => { - - if (tables.length > 1 && (when.length > 0 || ifExists)) { - throw new Error('Batch with when or ifExists conditions cannot span multiple tables'); - } - - // For each tables affected, Generate query and parameter getters - return tables.map(table => - QueryGenerator.getDelete(table, this.info.keyspace, propertiesInfo, docInfo, when, ifExists)); - }); - } - - getExecutorFromQuery(query, paramsHandler, commonExecutionOptions) { - // Use the current instance in the closure - // as there is no guarantee of how the returned function will be invoked - const self = this; - const commonOptions = commonExecutionOptions ? DocInfoAdapter.adaptAllOptions(commonExecutionOptions) : null; - - return (function queryMappedExecutor(doc, executionOptions) { - // When the executionOptions were already specified, - // use it and skip the ones provided in each invocation - const options = commonOptions - ? commonOptions - : DocInfoAdapter.adaptAllOptions(executionOptions); - - return self._client.execute(query, paramsHandler(doc), options).then(rs => { - // Cache the resultAdapter based on the query - let resultAdapter = self._cache.customQueries.get(query); - - if (resultAdapter === undefined) { - const resultAdapterInfo = ResultMapper.getCustomQueryAdapter(self.info, rs); - resultAdapter = resultAdapterInfo.fn; - if (resultAdapterInfo.canCache) { - // Avoid caching conditional updates results as the amount of columns change - // depending on the parameter values. - self._cache.customQueries.set(query, resultAdapter); - - if (self._cache.customQueries.size === cacheHighWaterMark) { - self._client.log('warning', - `Custom queries cache reached ${cacheHighWaterMark} items, this could be caused by ` + - `hard-coding parameter values inside the query, which should be avoided`); - } - } - } - - return new Result(rs, self.info, resultAdapter); - }); - }); - } - - _setSingleExecutor(cacheItem, queryInfo) { - // Parameters and this instance are part of the closure - const self = this; - - // Set the function to execute the request in the cache - cacheItem.executor = function singleExecutor(doc, docInfo, executionOptions) { - const options = DocInfoAdapter.adaptOptions(executionOptions, queryInfo.isIdempotent); - - return self._client.execute(queryInfo.query, queryInfo.paramsGetter(doc, docInfo, self.info), options) - .then(rs => new Result(rs, self.info, ResultMapper.getMutationAdapter(rs))); - }; - - return cacheItem.executor; - } - - _setBatchExecutor(cacheItem, queries) { - // Parameters and the following fields are part of the closure - const self = this; - const isIdempotent = queries.reduce((acc, q) => acc && q.isIdempotent, true); - - // Set the function to execute the batch request in the cache - cacheItem.executor = function batchExecutor(doc, docInfo, executionOptions) { - // Use the params getter function to obtain the parameters each time - const queryAndParams = queries.map(q => ({ - query: q.query, - params: q.paramsGetter(doc, docInfo, self.info) - })); - - const options = DocInfoAdapter.adaptOptions(executionOptions, isIdempotent); - - // Execute using a Batch - return self._client.batch(queryAndParams, options) - .then(rs => new Result(rs, self.info, ResultMapper.getMutationAdapter(rs))); - }; - - return cacheItem.executor; - } - - _validateCacheLength(length) { - if (length !== cacheHighWaterMark) { - return; - } - - this._client.log('warning', `ModelMapper cache reached ${cacheHighWaterMark} items, this could be caused by ` + - `building the object to map in different ways (with different shapes) each time. Use the same or few object ` + - `structures for a model and represent unset values with undefined or types.unset`); - } -} - -module.exports = MappingHandler; \ No newline at end of file diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/mapping/model-batch-item.js b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/mapping/model-batch-item.js deleted file mode 100644 index 6a51591d3a..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/mapping/model-batch-item.js +++ /dev/null @@ -1,191 +0,0 @@ -/* - * Copyright DataStax, Inc. - * - * 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 Cache = require('./cache'); - -/** - * Represents a query or a set of queries used to perform a mutation in a batch. - * @alias module:mapping~ModelBatchItem - */ -class ModelBatchItem { - /** - * @param {Object} doc - * @param {Object} docInfo - * @param {MappingHandler} handler - * @param {Tree} cache - */ - constructor(doc, docInfo, handler, cache) { - this.doc = doc; - this.docInfo = docInfo; - this.handler = handler; - this.cache = cache; - } - - /** - * @ignore - * @returns > - */ - getQueries() { - const docKeys = Object.keys(this.doc); - const cacheItem = this.cache.getOrCreate(this.getCacheKey(docKeys), () => ({ queries: null })); - - if (cacheItem.queries === null) { - cacheItem.queries = this.createQueries(docKeys); - } - - return cacheItem.queries; - } - - /** - * Gets the cache key for this item. - * @abstract - * @param {Array} docKeys - * @returns {Iterator} - */ - getCacheKey(docKeys) { - throw new Error('getCacheKey must be implemented'); - } - - /** - * Gets the Promise to create the queries. - * @abstract - * @param {Array} docKeys - * @returns {Promise} - */ - createQueries(docKeys) { - throw new Error('getCacheKey must be implemented'); - } - - /** - * Pushes the queries and parameters represented by this instance to the provided array. - * @internal - * @ignore - * @param {Array} arr - * @return {Promise<{isIdempotent, isCounter}>} - */ - pushQueries(arr) { - let isIdempotent = true; - let isCounter; - - return this.getQueries().then(queries => { - queries.forEach(q => { - // It's idempotent if all the queries contained are idempotent - isIdempotent = isIdempotent && q.isIdempotent; - - // Either all queries are counter mutation or we let it fail at server level - isCounter = q.isCounter; - - arr.push({ query: q.query, params: q.paramsGetter(this.doc, this.docInfo) }); - }); - - return { isIdempotent, isCounter }; - }); - } - - /** - * Gets the mapping information for this batch item. - * @internal - * @ignore - */ - getMappingInfo() { - return this.handler.info; - } -} - -/** - * Represents a single or a set of INSERT queries in a batch. - * @ignore - * @internal - */ -class InsertModelBatchItem extends ModelBatchItem { - /** - * @param {Object} doc - * @param {Object} docInfo - * @param {MappingHandler} handler - * @param {Tree} cache - */ - constructor(doc, docInfo, handler, cache) { - super(doc, docInfo, handler, cache); - } - - /** @override */ - getCacheKey(docKeys) { - return Cache.getInsertKey(docKeys, this.docInfo); - } - - /** @override */ - createQueries(docKeys) { - return this.handler.createInsertQueries(docKeys, this.doc, this.docInfo); - } -} - -/** - * Represents a single or a set of UPDATE queries in a batch. - * @ignore - * @internal - */ -class UpdateModelBatchItem extends ModelBatchItem { - /** - * @param {Object} doc - * @param {Object} docInfo - * @param {MappingHandler} handler - * @param {Tree} cache - */ - constructor(doc, docInfo, handler, cache) { - super(doc, docInfo, handler, cache); - } - - /** @override */ - getCacheKey(docKeys) { - return Cache.getUpdateKey(docKeys, this.doc, this.docInfo); - } - - /** @override */ - createQueries(docKeys) { - return this.handler.createUpdateQueries(docKeys, this.doc, this.docInfo); - } -} - -/** - * Represents a single or a set of DELETE queries in a batch. - * @ignore - * @internal - */ -class RemoveModelBatchItem extends ModelBatchItem { - /** - * @param {Object} doc - * @param {Object} docInfo - * @param {MappingHandler} handler - * @param {Tree} cache - */ - constructor(doc, docInfo, handler, cache) { - super(doc, docInfo, handler, cache); - } - - /** @override */ - getCacheKey(docKeys) { - return Cache.getRemoveKey(docKeys, this.doc, this.docInfo); - } - - /** @override */ - createQueries(docKeys) { - return this.handler.createDeleteQueries(docKeys, this.doc, this.docInfo); - } -} - -module.exports = { ModelBatchItem, InsertModelBatchItem, UpdateModelBatchItem, RemoveModelBatchItem }; \ No newline at end of file diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/mapping/model-batch-mapper.js b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/mapping/model-batch-mapper.js deleted file mode 100644 index 4928072c8c..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/mapping/model-batch-mapper.js +++ /dev/null @@ -1,125 +0,0 @@ -/* - * Copyright DataStax, Inc. - * - * 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 Tree = require('./tree'); -const moduleBatchItemModule = require('./model-batch-item'); -const InsertModelBatchItem = moduleBatchItemModule.InsertModelBatchItem; -const UpdateModelBatchItem = moduleBatchItemModule.UpdateModelBatchItem; -const RemoveModelBatchItem = moduleBatchItemModule.RemoveModelBatchItem; - -/** - * Provides utility methods to group multiple mutations on a single batch. - * @alias module:mapping~ModelBatchMapper - */ -class ModelBatchMapper { - /** - * Creates a new instance of model batch mapper. - *

- * An instance of this class is exposed as a singleton in the batching field of the - * [ModelMapper]{@link module:mapping~ModelMapper}. Note that new instances should not be create with this - * constructor. - *

- * @param {MappingHandler} handler - * @ignore - */ - constructor(handler) { - this._handler = handler; - this._cache = { - insert: new Tree(), - update: new Tree(), - remove: new Tree() - }; - } - - /** - * Gets a [ModelBatchItem]{@link module:mapping~ModelBatchItem} containing the queries for the INSERT mutation to be - * used in a batch execution. - * @param {Object} doc An object containing the properties to insert. - * @param {Object} [docInfo] An object containing the additional document information. - * @param {Array} [docInfo.fields] An Array containing the name of the properties that will be used in the - * INSERT cql statements generated. If specified, it must include the columns to insert and the primary keys. - * @param {Number} [docInfo.ttl] Specifies an optional Time To Live (in seconds) for the inserted values. - * @param {Boolean} [docInfo.ifNotExists] When set, it only inserts if the row does not exist prior to the insertion. - *

Please note that using IF NOT EXISTS will incur a non negligible performance cost so this should be used - * sparingly.

- * @returns {ModelBatchItem} A [ModelBatchItem]{@link module:mapping~ModelBatchItem} instance representing a query - * or a set of queries to be included in a batch. - */ - insert(doc, docInfo) { - return new InsertModelBatchItem(doc, docInfo, this._handler, this._cache.insert); - } - - /** - * Gets a [ModelBatchItem]{@link module:mapping~ModelBatchItem} containing the queries for the UPDATE mutation to be - * used in a batch execution. - * @param {Object} doc An object containing the properties to update. - * @param {Object} [docInfo] An object containing the additional document information. - * @param {Array} [docInfo.fields] An Array containing the name of the properties that will be used in the - * UPDATE cql statements generated. If specified, it must include the columns to update and the primary keys. - * @param {Number} [docInfo.ttl] Specifies an optional Time To Live (in seconds) for the inserted values. - * @param {Boolean} [docInfo.ifExists] When set, it only updates if the row already exists on the server. - *

- * Please note that using IF conditions will incur a non negligible performance cost on the server-side so this - * should be used sparingly. - *

- * @param {Object} [docInfo.when] A document that act as the condition that has to be met for the UPDATE to occur. - * Use this property only in the case you want to specify a conditional clause for lightweight transactions (CAS). - *

- * Please note that using IF conditions will incur a non negligible performance cost on the server-side so this - * should be used sparingly. - *

- * @returns {ModelBatchItem} A [ModelBatchItem]{@link module:mapping~ModelBatchItem} instance representing a query - * or a set of queries to be included in a batch. - */ - update(doc, docInfo) { - return new UpdateModelBatchItem(doc, docInfo, this._handler, this._cache.update); - } - - /** - * Gets a [ModelBatchItem]{@link module:mapping~ModelBatchItem} containing the queries for the DELETE mutation to be - * used in a batch execution. - * @param {Object} doc A document containing the primary keys values of the document to delete. - * @param {Object} [docInfo] An object containing the additional doc information. - * @param {Object} [docInfo.when] A document that act as the condition that has to be met for the DELETE to occur. - * Use this property only in the case you want to specify a conditional clause for lightweight transactions (CAS). - * When the CQL query is generated, this would be used to generate the `IF` clause. - *

- * Please note that using IF conditions will incur a non negligible performance cost on the server-side so this - * should be used sparingly. - *

- * @param {Boolean} [docInfo.ifExists] When set, it only issues the DELETE command if the row already exists on the - * server. - *

- * Please note that using IF conditions will incur a non negligible performance cost on the server-side so this - * should be used sparingly. - *

- * @param {Array} [docInfo.fields] An Array containing the name of the properties that will be used in the - * DELETE cql statement generated. If specified, it must include the columns to delete and the primary keys. - * @param {Boolean} [docInfo.deleteOnlyColumns] Determines that, when more document properties are specified - * besides the primary keys, the generated DELETE statement should be used to delete some column values but leave - * the row. When this is enabled and more properties are specified, a DELETE statement will have the following form: - * "DELETE col1, col2 FROM table1 WHERE pk1 = ? AND pk2 = ?" - * @returns {ModelBatchItem} A [ModelBatchItem]{@link module:mapping~ModelBatchItem} instance representing a query - * or a set of queries to be included in a batch. - */ - remove(doc, docInfo) { - return new RemoveModelBatchItem(doc, docInfo, this._handler, this._cache.update); - } -} - -module.exports = ModelBatchMapper; \ No newline at end of file diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/mapping/model-mapper.js b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/mapping/model-mapper.js deleted file mode 100644 index 8a4d041945..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/mapping/model-mapper.js +++ /dev/null @@ -1,306 +0,0 @@ -/* - * Copyright DataStax, Inc. - * - * 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 ModelBatchMapper = require('./model-batch-mapper'); - -/** - * Represents an object mapper for a specific model. - * @alias module:mapping~ModelMapper - */ -class ModelMapper { - constructor(name, handler) { - /** - * Gets the name identifier of the model. - * @type {String} - */ - this.name = name; - this._handler = handler; - /** - * Gets a [ModelBatchMapper]{@link module:mapping~ModelBatchMapper} instance containing utility methods to group - * multiple doc mutations in a single batch. - * @type {ModelBatchMapper} - */ - this.batching = new ModelBatchMapper(this._handler); - } - - /** - * Gets the first document matching the provided filter or null when not found. - *

- * Note that all partition and clustering keys must be defined in order to use this method. - *

- * @param {Object} doc The object containing the properties that map to the primary keys. - * @param {Object} [docInfo] An object containing the additional document information. - * @param {Array} [docInfo.fields] An Array containing the name of the properties that will be used in the - * SELECT cql statement generated, in order to restrict the amount of columns retrieved. - * @param {Object|String} [executionOptions] An object containing the options to be used for the requests - * execution or a string representing the name of the execution profile. - * @param {String} [executionOptions.executionProfile] The name of the execution profile. - * @return {Promise} - * @example Get a video by id - * videoMapper.get({ id }) - * @example Get a video by id, selecting specific columns - * videoMapper.get({ id }, fields: ['name', 'description']) - */ - get(doc, docInfo, executionOptions) { - if (executionOptions === undefined && typeof docInfo === 'string') { - executionOptions = docInfo; - docInfo = null; - } - - return this._handler.getSelectExecutor(doc, docInfo, true) - .then(executor => executor(doc, docInfo, executionOptions)) - .then(result => result.first()); - } - - /** - * Executes a SELECT query based on the filter and returns the result as an iterable of documents. - * @param {Object} doc An object containing the properties that map to the primary keys to filter. - * @param {Object} [docInfo] An object containing the additional document information. - * @param {Array} [docInfo.fields] An Array containing the name of the properties that will be used in the - * SELECT cql statement generated, in order to restrict the amount of columns retrieved. - * @param {Object} [docInfo.orderBy] An associative array containing the column names as key and - * the order string (asc or desc) as value used to set the order of the results server-side. - * @param {Number} [docInfo.limit] Restricts the result of the query to a maximum number of rows on the - * server. - * @param {Object|String} [executionOptions] An object containing the options to be used for the requests - * execution or a string representing the name of the execution profile. - * @param {String} [executionOptions.executionProfile] The name of the execution profile. - * @param {Number} [executionOptions.fetchSize] The amount of rows to retrieve per page. - * @param {Number} [executionOptions.pageState] A Buffer instance or a string token representing the paging state. - *

When provided, the query will be executed starting from a given paging state.

- * @return {Promise} A Promise that resolves to a [Result]{@link module:mapping~Result} instance. - * @example Get user's videos - * const result = await videoMapper.find({ userId }); - * for (let video of result) { - * console.log(video.name); - * } - * @example Get user's videos from a certain date - * videoMapper.find({ userId, addedDate: q.gte(date)}); - * @example Get user's videos in reverse order - * videoMapper.find({ userId }, { orderBy: { addedDate: 'desc' }}); - */ - find(doc, docInfo, executionOptions) { - if (executionOptions === undefined && typeof docInfo === 'string') { - executionOptions = docInfo; - docInfo = null; - } - - return this._handler.getSelectExecutor(doc, docInfo, false) - .then(executor => executor(doc, docInfo, executionOptions)); - } - - /** - * Executes a SELECT query without a filter and returns the result as an iterable of documents. - *

- * This is only recommended to be used for tables with a limited amount of results. Otherwise, breaking up the - * token ranges on the client side should be used. - *

- * @param {Object} [docInfo] An object containing the additional document information. - * @param {Array} [docInfo.fields] An Array containing the name of the properties that will be used in the - * SELECT cql statement generated, in order to restrict the amount of columns retrieved. - * @param {Object} [docInfo.orderBy] An associative array containing the column names as key and - * the order string (asc or desc) as value used to set the order of the results server-side. - * @param {Number} [docInfo.limit] Restricts the result of the query to a maximum number of rows on the - * server. - * @param {Object|String} [executionOptions] An object containing the options to be used for the requests - * execution or a string representing the name of the execution profile. - * @param {String} [executionOptions.executionProfile] The name of the execution profile. - * @param {Number} [executionOptions.fetchSize] The mount of rows to retrieve per page. - * @param {Number} [executionOptions.pageState] A Buffer instance or a string token representing the paging state. - *

When provided, the query will be executed starting from a given paging state.

- * @return {Promise} A Promise that resolves to a [Result]{@link module:mapping~Result} instance. - */ - findAll(docInfo, executionOptions) { - if (executionOptions === undefined && typeof docInfo === 'string') { - executionOptions = docInfo; - docInfo = null; - } - - const executor = this._handler.getSelectAllExecutor(docInfo); - return executor(docInfo, executionOptions); - } - - /** - * Inserts a document. - *

- * When the model is mapped to multiple tables, it will insert a row in each table when all the primary keys - * are specified. - *

- * @param {Object} doc An object containing the properties to insert. - * @param {Object} [docInfo] An object containing the additional document information. - * @param {Array} [docInfo.fields] An Array containing the name of the properties that will be used in the - * INSERT cql statements generated. If specified, it must include the columns to insert and the primary keys. - * @param {Number} [docInfo.ttl] Specifies an optional Time To Live (in seconds) for the inserted values. - * @param {Boolean} [docInfo.ifNotExists] When set, it only inserts if the row does not exist prior to the insertion. - *

Please note that using IF NOT EXISTS will incur a non negligible performance cost so this should be used - * sparingly.

- * @param {Object|String} [executionOptions] An object containing the options to be used for the requests - * execution or a string representing the name of the execution profile. - * @param {String} [executionOptions.executionProfile] The name of the execution profile. - * @param {Boolean} [executionOptions.isIdempotent] Defines whether the query can be applied multiple times without - * changing the result beyond the initial application. - *

- * By default all generated INSERT statements are considered idempotent, except in the case of lightweight - * transactions. Lightweight transactions at client level with transparent retries can - * break linearizability. If that is not an issue for your application, you can manually set this field to true. - *

- * @param {Number|Long} [executionOptions.timestamp] The default timestamp for the query in microseconds from the - * unix epoch (00:00:00, January 1st, 1970). - *

When provided, this will replace the client generated and the server side assigned timestamp.

- * @return {Promise} A Promise that resolves to a [Result]{@link module:mapping~Result} instance. - * @example Insert a video - * videoMapper.insert({ id, name }); - */ - insert(doc, docInfo, executionOptions) { - if (executionOptions === undefined && typeof docInfo === 'string') { - executionOptions = docInfo; - docInfo = null; - } - - return this._handler.getInsertExecutor(doc, docInfo) - .then(executor => executor(doc, docInfo, executionOptions)); - } - - /** - * Updates a document. - *

- * When the model is mapped to multiple tables, it will update a row in each table when all the primary keys - * are specified. - *

- * @param {Object} doc An object containing the properties to update. - * @param {Object} [docInfo] An object containing the additional document information. - * @param {Array} [docInfo.fields] An Array containing the name of the properties that will be used in the - * UPDATE cql statements generated. If specified, it must include the columns to update and the primary keys. - * @param {Number} [docInfo.ttl] Specifies an optional Time To Live (in seconds) for the inserted values. - * @param {Boolean} [docInfo.ifExists] When set, it only updates if the row already exists on the server. - *

- * Please note that using IF conditions will incur a non negligible performance cost on the server-side so this - * should be used sparingly. - *

- * @param {Object} [docInfo.when] A document that act as the condition that has to be met for the UPDATE to occur. - * Use this property only in the case you want to specify a conditional clause for lightweight transactions (CAS). - *

- * Please note that using IF conditions will incur a non negligible performance cost on the server-side so this - * should be used sparingly. - *

- * @param {Object|String} [executionOptions] An object containing the options to be used for the requests - * execution or a string representing the name of the execution profile. - * @param {String} [executionOptions.executionProfile] The name of the execution profile. - * @param {Boolean} [executionOptions.isIdempotent] Defines whether the query can be applied multiple times without - * changing the result beyond the initial application. - *

- * The mapper uses the generated queries to determine the default value. When an UPDATE is generated with a - * counter column or appending/prepending to a list column, the execution is marked as not idempotent. - *

- *

- * Additionally, the mapper uses the safest approach for queries with lightweight transactions (Compare and - * Set) by considering them as non-idempotent. Lightweight transactions at client level with transparent retries can - * break linearizability. If that is not an issue for your application, you can manually set this field to true. - *

- * @param {Number|Long} [executionOptions.timestamp] The default timestamp for the query in microseconds from the - * unix epoch (00:00:00, January 1st, 1970). - *

When provided, this will replace the client generated and the server side assigned timestamp.

- * @return {Promise} A Promise that resolves to a [Result]{@link module:mapping~Result} instance. - * @example Update the name of a video - * videoMapper.update({ id, name }); - */ - update(doc, docInfo, executionOptions) { - if (executionOptions === undefined && typeof docInfo === 'string') { - executionOptions = docInfo; - docInfo = null; - } - - return this._handler.getUpdateExecutor(doc, docInfo) - .then(executor => executor(doc, docInfo, executionOptions)); - } - - /** - * Deletes a document. - * @param {Object} doc A document containing the primary keys values of the document to delete. - * @param {Object} [docInfo] An object containing the additional doc information. - * @param {Object} [docInfo.when] A document that act as the condition that has to be met for the DELETE to occur. - * Use this property only in the case you want to specify a conditional clause for lightweight transactions (CAS). - * When the CQL query is generated, this would be used to generate the `IF` clause. - *

- * Please note that using IF conditions will incur a non negligible performance cost on the server-side so this - * should be used sparingly. - *

- * @param {Boolean} [docInfo.ifExists] When set, it only issues the DELETE command if the row already exists on the - * server. - *

- * Please note that using IF conditions will incur a non negligible performance cost on the server-side so this - * should be used sparingly. - *

- * @param {Array} [docInfo.fields] An Array containing the name of the properties that will be used in the - * DELETE cql statement generated. If specified, it must include the columns to delete and the primary keys. - * @param {Boolean} [docInfo.deleteOnlyColumns] Determines that, when more document properties are specified - * besides the primary keys, the generated DELETE statement should be used to delete some column values but leave - * the row. When this is enabled and more properties are specified, a DELETE statement will have the following form: - * "DELETE col1, col2 FROM table1 WHERE pk1 = ? AND pk2 = ?" - * @param {Object|String} [executionOptions] An object containing the options to be used for the requests - * execution or a string representing the name of the execution profile. - * @param {String} [executionOptions.executionProfile] The name of the execution profile. - * @param {Boolean} [executionOptions.isIdempotent] Defines whether the query can be applied multiple times without - * changing the result beyond the initial application. - *

- * By default all generated DELETE statements are considered idempotent, except in the case of lightweight - * transactions. Lightweight transactions at client level with transparent retries can - * break linearizability. If that is not an issue for your application, you can manually set this field to true. - *

- * @param {Number|Long} [executionOptions.timestamp] The default timestamp for the query in microseconds from the - * unix epoch (00:00:00, January 1st, 1970). - *

When provided, this will replace the client generated and the server side assigned timestamp.

- * @return {Promise} A Promise that resolves to a [Result]{@link module:mapping~Result} instance. - * @example Delete a video - * videoMapper.remove({ id }); - */ - remove(doc, docInfo, executionOptions) { - if (executionOptions === undefined && typeof docInfo === 'string') { - executionOptions = docInfo; - docInfo = null; - } - - return this._handler.getDeleteExecutor(doc, docInfo) - .then(executor => executor(doc, docInfo, executionOptions)); - } - - /** - * Uses the provided query and param getter function to execute a query and map the results. - * Gets a function that takes the document, executes the query and returns the mapped results. - * @param {String} query The query to execute. - * @param {Function} paramsHandler The function to execute to extract the parameters of a document. - * @param {Object|String} [executionOptions] When provided, the options for all executions generated with this - * method will use the provided options and it will not consider the executionOptions per call. - * @param {String} [executionOptions.executionProfile] The name of the execution profile. - * @param {Number} [executionOptions.fetchSize] Amount of rows to retrieve per page. - * @param {Boolean} [executionOptions.isIdempotent] Defines whether the query can be applied multiple times - * without changing the result beyond the initial application. - * @param {Number} [executionOptions.pageState] Buffer or string token representing the paging state. - *

When provided, the query will be executed starting from a given paging state.

- * @param {Number|Long} [executionOptions.timestamp] The default timestamp for the query in microseconds from the - * unix epoch (00:00:00, January 1st, 1970). - *

When provided, this will replace the client generated and the server side assigned timestamp.

- * @return {Function} Returns a function that takes the document and execution options as parameters and returns a - * Promise the resolves to a [Result]{@link module:mapping~Result} instance. - */ - mapWithQuery(query, paramsHandler, executionOptions) { - return this._handler.getExecutorFromQuery(query, paramsHandler, executionOptions); - } -} - -module.exports = ModelMapper; \ No newline at end of file diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/mapping/model-mapping-info.js b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/mapping/model-mapping-info.js deleted file mode 100644 index 23be0408d3..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/mapping/model-mapping-info.js +++ /dev/null @@ -1,194 +0,0 @@ -/* - * Copyright DataStax, Inc. - * - * 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 tableMappingsModule = require('./table-mappings'); -const TableMappings = tableMappingsModule.TableMappings; -const DefaultTableMappings = tableMappingsModule.DefaultTableMappings; - -/** - * Represents the parsed user information of the table mappings of a model. - * @ignore - */ -class ModelMappingInfo { - /** - * @param {String} keyspace - * @param {Array<{name, isView}>} tables - * @param {TableMappings} mappings - * @param {Map} columns - */ - constructor(keyspace, tables, mappings, columns) { - this.keyspace = keyspace; - this.tables = tables; - this._mappings = mappings; - this._columns = columns; - - // Define a map of column information per property name - /** @type {Map} */ - this._documentProperties = new Map(); - for (const modelColumnInfo of columns.values()) { - this._documentProperties.set(modelColumnInfo.propertyName, modelColumnInfo); - } - } - - getColumnName(propName) { - const modelColumnInfo = this._documentProperties.get(propName); - if (modelColumnInfo !== undefined) { - // There is an specific name transformation between the column name and the property name - return modelColumnInfo.columnName; - } - // Rely on the TableMappings (i.e. maybe there is a convention defined for this property) - return this._mappings.getColumnName(propName); - } - - getPropertyName(columnName) { - const modelColumnInfo = this._columns.get(columnName); - if (modelColumnInfo !== undefined) { - // There is an specific name transformation between the column name and the property name - return modelColumnInfo.propertyName; - } - // Rely on the TableMappings (i.e. maybe there is a convention defined for this column) - return this._mappings.getPropertyName(columnName); - } - - getFromModelFn(propName) { - const modelColumnInfo = this._documentProperties.get(propName); - return modelColumnInfo !== undefined ? modelColumnInfo.fromModel : null; - } - - getToModelFn(columnName) { - const modelColumnInfo = this._columns.get(columnName); - return modelColumnInfo !== undefined ? modelColumnInfo.toModel : null; - } - - newInstance() { - return this._mappings.newObjectInstance(); - } - - /** - * Parses the user options into a map of model names and ModelMappingInfo. - * @param {MappingOptions} options - * @param {String} currentKeyspace - * @returns {Map} - */ - static parse(options, currentKeyspace) { - const result = new Map(); - if (!options || !options.models) { - return result; - } - - Object.keys(options.models).forEach(modelName => { - const modelOptions = options.models[modelName]; - result.set(modelName, ModelMappingInfo._create(modelName, currentKeyspace, modelOptions)); - }); - - return result; - } - - static _create(modelName, currentKeyspace, modelOptions) { - if (!currentKeyspace && (!modelOptions || !modelOptions.keyspace)) { - throw new Error( - 'You should specify the keyspace of the model in the MappingOptions when the Client is not using a keyspace'); - } - - if (!modelOptions) { - return ModelMappingInfo.createDefault(modelName, currentKeyspace); - } - - let tables; - - if (modelOptions.tables && modelOptions.tables.length > 0) { - tables = modelOptions.tables.map(item => { - const table = { name: null, isView: false }; - if (typeof item === 'string') { - table.name = item; - } else if (item) { - table.name = item.name; - table.isView = !!item.isView; - } - - if (!table.name) { - throw new Error(`Table name not specified for model '${modelName}'`); - } - - return table; - }); - } else { - tables = [ { name: modelName, isView: false }]; - } - - if (modelOptions.mappings && !(modelOptions.mappings instanceof TableMappings)) { - throw new Error('mappings should be an instance of TableMappings'); - } - - const columns = new Map(); - if (modelOptions.columns !== null && typeof modelOptions.columns === 'object') { - Object.keys(modelOptions.columns).forEach(columnName => { - columns.set(columnName, ModelColumnInfo.parse(columnName, modelOptions.columns[columnName])); - }); - } - - return new ModelMappingInfo( - modelOptions.keyspace || currentKeyspace, - tables, - modelOptions.mappings || new DefaultTableMappings(), - columns - ); - } - - static createDefault(modelName, currentKeyspace) { - return new ModelMappingInfo( - currentKeyspace, - [ { name: modelName, isView: false }], - new DefaultTableMappings(), - new Map()); - } -} - -class ModelColumnInfo { - constructor(columnName, propertyName, toModel, fromModel) { - this.columnName = columnName; - this.propertyName = propertyName; - - if (toModel && typeof toModel !== 'function') { - throw new TypeError(`toModel type for property '${propertyName}' should be a function (obtained ${ - typeof toModel})`); - } - - if (fromModel && typeof fromModel !== 'function') { - throw new TypeError(`fromModel type for property '${propertyName}' should be a function (obtained ${ - typeof fromModel})`); - } - - this.toModel = toModel; - this.fromModel = fromModel; - } - - static parse(columnName, value) { - if (!value) { - return new ModelColumnInfo(columnName, columnName); - } - - if (typeof value === 'string') { - return new ModelColumnInfo(columnName, value); - } - - return new ModelColumnInfo(columnName, value.name || columnName, value.toModel, value.fromModel); - } -} - -module.exports = ModelMappingInfo; \ No newline at end of file diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/mapping/object-selector.js b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/mapping/object-selector.js deleted file mode 100644 index de25df627a..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/mapping/object-selector.js +++ /dev/null @@ -1,321 +0,0 @@ -/* - * Copyright DataStax, Inc. - * - * 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 keyMatches = { - all: 1, - none: 0, - some: -1 -}; - -/** - * Provides utility methods to choose the correct tables and views that should be included in a statement. - * @ignore - */ -class ObjectSelector { - /** - * Gets the table/view that should be used to execute the SELECT query. - * @param {Client} client - * @param {ModelMappingInfo} info - * @param {Boolean} allPKsDefined - * @param {Array} propertiesInfo - * @param {Array} fieldsInfo - * @param {Array>} orderByColumns - * @return {Promise} A promise that resolves to a table names. - */ - static getForSelect(client, info, allPKsDefined, propertiesInfo, fieldsInfo, orderByColumns) { - return Promise.all( - info.tables.map(t => { - if (t.isView) { - return client.metadata.getMaterializedView(info.keyspace, t.name); - } - return client.metadata.getTable(info.keyspace, t.name); - })) - .then(tables => { - for (let i = 0; i < tables.length; i++) { - const table = tables[i]; - if (table === null) { - throw new Error(`Table "${info.tables[i].name}" could not be retrieved`); - } - - if (keysAreIncluded(table.partitionKeys, propertiesInfo) !== keyMatches.all) { - // Not all the partition keys are covered - continue; - } - - - if (allPKsDefined) { - if (keysAreIncluded(table.clusteringKeys, propertiesInfo) !== keyMatches.all) { - // All clustering keys should be included as allPKsDefined flag is set - continue; - } - } - - if (propertiesInfo.length > table.partitionKeys.length) { - // Check that the Where clause is composed by partition and clustering keys - const allPropertiesArePrimaryKeys = propertiesInfo - .reduce( - (acc, p) => acc && ( - contains(table.partitionKeys, c => c.name === p.columnName) || - contains(table.clusteringKeys, c => c.name === p.columnName) - ), - true); - - if (!allPropertiesArePrimaryKeys) { - continue; - } - } - - // All fields must be contained - const containsAllFields = fieldsInfo - .reduce((acc, p) => acc && table.columnsByName[p.columnName] !== undefined, true); - - if (!containsAllFields) { - continue; - } - - // CQL: - // - "ORDER BY" is currently only supported on the clustered columns of the PRIMARY KEY - // - "ORDER BY" currently only support the ordering of columns following their declared order in - // the PRIMARY KEY - // - // In the mapper, we validate that the ORDER BY columns appear in the same order as in the clustering keys - const containsAllOrderByColumns = orderByColumns - .reduce((acc, order, index) => { - if (!acc) { - return false; - } - - const ck = table.clusteringKeys[index]; - - return ck && ck.name === order[0]; - }, true); - - if (!containsAllOrderByColumns) { - continue; - } - - return table.name; - } - - let message = `No table matches the filter (${allPKsDefined ? 'all PKs have to be specified' : 'PKs'}): [${ - propertiesInfo.map(p => p.columnName)}]`; - - if (fieldsInfo.length > 0) { - message += `; fields: [${fieldsInfo.map(p => p.columnName)}]`; - } - if (orderByColumns.length > 0) { - message += `; orderBy: [${orderByColumns.map(item => item[0])}]`; - } - - throw new Error(message); - }); - } - - /** Returns the name of the first table */ - static getForSelectAll(info) { - return info.tables[0].name; - } - - /** - * Gets the tables that should be used to execute the INSERT query. - * @param {Client} client - * @param {ModelMappingInfo} info - * @param {Array} propertiesInfo - * @return {Promise>} A promise that resolves to an Array of tables. - */ - static getForInsert(client, info, propertiesInfo) { - return Promise.all(info.tables.filter(t => !t.isView).map(t => client.metadata.getTable(info.keyspace, t.name))) - .then(tables => { - const filteredTables = tables - .filter((table, i) => { - if (table === null) { - throw new Error(`Table "${info.tables[i].name}" could not be retrieved`); - } - - if (keysAreIncluded(table.partitionKeys, propertiesInfo) !== keyMatches.all) { - // Not all the partition keys are covered - return false; - } - - const clusteringKeyMatches = keysAreIncluded(table.clusteringKeys, propertiesInfo); - - // All clustering keys should be included or it can be inserting a static column value - if (clusteringKeyMatches === keyMatches.all) { - return true; - } - - if (clusteringKeyMatches === keyMatches.some) { - return false; - } - - const staticColumns = staticColumnCount(table); - return propertiesInfo.length === table.partitionKeys.length + staticColumns && staticColumns > 0; - }); - - if (filteredTables.length === 0) { - throw new Error(`No table matches (all PKs have to be specified) fields: [${ - propertiesInfo.map(p => p.columnName)}]`); - } - - return filteredTables; - }); - } - - /** - * Gets the tables that should be used to execute the UPDATE query. - * @param {Client} client - * @param {ModelMappingInfo} info - * @param {Array} propertiesInfo - * @param {Array} when - * @return {Promise>} A promise that resolves to an Array of tables. - */ - static getForUpdate(client, info, propertiesInfo, when) { - return Promise.all(info.tables.filter(t => !t.isView).map(t => client.metadata.getTable(info.keyspace, t.name))) - .then(tables => { - const filteredTables = tables - .filter((table, i) => { - if (table === null) { - throw new Error(`Table "${info.tables[i].name}" could not be retrieved`); - } - - if (keysAreIncluded(table.partitionKeys, propertiesInfo) !== keyMatches.all) { - // Not all the partition keys are covered - return false; - } - - const clusteringKeyMatches = keysAreIncluded(table.clusteringKeys, propertiesInfo); - - // All clustering keys should be included or it can be updating a static column value - if (clusteringKeyMatches === keyMatches.some) { - return false; - } - - if (clusteringKeyMatches === keyMatches.none && !hasStaticColumn(table)) { - return false; - } - - const applicableColumns = propertiesInfo - .reduce((acc, p) => acc + (table.columnsByName[p.columnName] !== undefined ? 1 : 0), 0); - - if (applicableColumns <= table.partitionKeys.length + table.clusteringKeys.length) { - if (!hasStaticColumn(table) || applicableColumns <= table.partitionKeys.length) { - // UPDATE statement does not contain columns to SET - return false; - } - } - - // "when" conditions should be contained in the table - return when.reduce((acc, p) => acc && table.columnsByName[p.columnName] !== undefined, true); - }); - - if (filteredTables.length === 0) { - let message = `No table matches (all PKs and columns to set have to be specified) fields: [${ - propertiesInfo.map(p => p.columnName)}]`; - - if (when.length > 0) { - message += `; condition: [${when.map(p => p.columnName)}]`; - } - - throw new Error(message); - } - - return filteredTables; - }); - } - - /** - * Gets the tables that should be used to execute the DELETE query. - * @param {Client} client - * @param {ModelMappingInfo} info - * @param {Array} propertiesInfo - * @param {Array} when - * @return {Promise>} A promise that resolves to an Array of tables. - */ - static getForDelete(client, info, propertiesInfo, when) { - return Promise.all(info.tables.filter(t => !t.isView).map(t => client.metadata.getTable(info.keyspace, t.name))) - .then(tables => { - const filteredTables = tables - .filter((table, i) => { - if (table === null) { - throw new Error(`Table "${info.tables[i].name}" could not be retrieved`); - } - - // All partition and clustering keys from the table should be included in the document - const keyNames = table.partitionKeys.concat(table.clusteringKeys).map(k => k.name); - const columns = propertiesInfo.map(p => p.columnName); - - for (let i = 0; i < keyNames.length; i++) { - if (columns.indexOf(keyNames[i]) === -1) { - return false; - } - } - - // "when" conditions should be contained in the table - return when.reduce((acc, p) => acc && table.columnsByName[p.columnName] !== undefined, true); - }); - - if (filteredTables.length === 0) { - let message = `No table matches (all PKs have to be specified) fields: [${ - propertiesInfo.map(p => p.columnName)}]`; - - if (when.length > 0) { - message += `; condition: [${when.map(p => p.columnName)}]`; - } - - throw new Error(message); - } - - return filteredTables; - }); - } -} - -function contains(arr, fn) { - return arr.filter(fn).length > 0; -} - -/** - * Returns the amount of matches for a given key - * @private - * @param {Array} keys - * @param {Array} propertiesInfo - */ -function keysAreIncluded(keys, propertiesInfo) { - if (keys.length === 0) { - return keyMatches.all; - } - - // Filtering by name might look slow / ineffective to using hash maps - // but we expect `keys` and `propertiesInfo` to contain only few items - const matches = propertiesInfo.reduce((acc, p) => acc + (contains(keys, k => p.columnName === k.name) ? 1 : 0), 0); - if (matches === 0) { - return keyMatches.none; - } - - return matches === keys.length ? keyMatches.all : keyMatches.some; -} - -function hasStaticColumn(table) { - return staticColumnCount(table) > 0; -} - -function staticColumnCount(table) { - return table.columns.reduce((acc, column) => acc + (column.isStatic ? 1 : 0), 0); -} - -module.exports = ObjectSelector; diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/mapping/q.js b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/mapping/q.js deleted file mode 100644 index 7e4c8ce2d8..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/mapping/q.js +++ /dev/null @@ -1,154 +0,0 @@ -/* - * Copyright DataStax, Inc. - * - * 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 errors = require('../errors'); - -/** - * Represents a CQL query operator, like >=, IN, <, ... - * @ignore - */ -class QueryOperator { - /** - * Creates a new instance of QueryOperator. - * @param {String} key - * @param value - * @param [hasChildValues] - * @param [isInOperator] - */ - constructor(key, value, hasChildValues, isInOperator) { - /** - * The CQL key representing the operator - * @type {string} - */ - this.key = key; - - /** - * The value to be used as parameter. - */ - this.value = value; - - /** - * Determines whether a query operator can have child values or operators (AND, OR) - */ - this.hasChildValues = hasChildValues; - - /** - * Determines whether this instance represents CQL "IN" operator. - */ - this.isInOperator = isInOperator; - } -} - -/** - * Represents a CQL assignment operation, like col = col + x. - * @ignore - */ -class QueryAssignment { - constructor(sign, value, inverted) { - /** - * Gets the sign of the assignment operation. - */ - this.sign = sign; - - /** - * Gets the value to be assigned. - */ - this.value = value; - - /** - * Determines whether the assignment should be inverted (prepends), e.g: col = x + col - * @type {boolean} - */ - this.inverted = !!inverted; - } -} - -/** - * Contains functions that represents operators in a query. - * @alias module:mapping~q - * @type {Object} - * @property {function} in_ Represents the CQL operator "IN". - * @property {function} gt Represents the CQL operator greater than ">". - * @property {function} gte Represents the CQL operator greater than or equals to ">=" . - * @property {function} lt Represents the CQL operator less than "<" . - * @property {function} lte Represents the CQL operator less than or equals to "<=" . - * @property {function} notEq Represents the CQL operator not equals to "!=" . - * @property {function} and When applied to a property, it represents two CQL conditions on the same column separated - * by the logical AND operator, e.g: "col1 >= x col < y" - * @property {function} incr Represents the CQL increment assignment used for counters, e.g: "col = col + x" - * @property {function} decr Represents the CQL decrement assignment used for counters, e.g: "col = col - x" - * @property {function} append Represents the CQL append assignment used for collections, e.g: "col = col + x" - * @property {function} prepend Represents the CQL prepend assignment used for lists, e.g: "col = x + col" - * @property {function} remove Represents the CQL remove assignment used for collections, e.g: "col = col - x" - */ -const q = { - in_: function in_(arr) { - if (!Array.isArray(arr)) { - throw new errors.ArgumentError('IN operator supports only Array values'); - } - return new QueryOperator('IN', arr, false, true); - }, - - gt: function gt(value) { - return new QueryOperator('>', value); - }, - - gte: function gte(value) { - return new QueryOperator('>=', value); - }, - - lt: function lt(value) { - return new QueryOperator('<', value); - }, - - lte: function lte(value) { - return new QueryOperator('<=', value); - }, - - notEq: function notEq(value) { - return new QueryOperator('!=', value); - }, - - and: function (condition1, condition2) { - return new QueryOperator('AND', [ condition1, condition2 ], true); - }, - - incr: function incr(value) { - return new QueryAssignment('+', value); - }, - - decr: function decr(value) { - return new QueryAssignment('-', value); - }, - - append: function append(value) { - return new QueryAssignment('+', value); - }, - - prepend: function prepend(value) { - return new QueryAssignment('+', value, true); - }, - - remove: function remove(value) { - return new QueryAssignment('-', value); - } -}; - -exports.q = q; -exports.QueryAssignment = QueryAssignment; -exports.QueryOperator = QueryOperator; \ No newline at end of file diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/mapping/query-generator.js b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/mapping/query-generator.js deleted file mode 100644 index daf5221699..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/mapping/query-generator.js +++ /dev/null @@ -1,446 +0,0 @@ -/* - * Copyright DataStax, Inc. - * - * 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 vm = require('vm'); -const qModule = require('./q'); -const QueryOperator = qModule.QueryOperator; -const QueryAssignment = qModule.QueryAssignment; -const types = require('../types'); -const dataTypes = types.dataTypes; - -const vmFileName = 'gen-param-getter.js'; - -/** - * Provides methods to generate a query and parameter handlers. - * @ignore - */ -class QueryGenerator { - /** - * Gets the SELECT query given the doc. - * @param {String} tableName - * @param {String} keyspace - * @param {Array} propertiesInfo - * @param {Array} fieldsInfo - * @param {Array} orderByColumns - * @param {Number|undefined} limit - * @return {string} - */ - static getSelect(tableName, keyspace, propertiesInfo, fieldsInfo, orderByColumns, limit) { - let query = 'SELECT '; - query += fieldsInfo.length > 0 ? fieldsInfo.map(p => p.columnName).join(', ') : '*'; - query += ` FROM ${keyspace}.${tableName}`; - - if (propertiesInfo.length > 0) { - query += ' WHERE '; - query += QueryGenerator._getConditionWithOperators(propertiesInfo); - } - - if (orderByColumns.length > 0) { - query += ' ORDER BY '; - query += orderByColumns.map(order => order[0] + ' ' + order[1]).join(', '); - } - - if (typeof limit === 'number') { - query += ' LIMIT ?'; - } - - return query; - } - - static selectParamsGetter(propertiesInfo, limit) { - let scriptText = '(function getParametersSelect(doc, docInfo, mappingInfo) {\n'; - scriptText += ' return ['; - - scriptText += QueryGenerator._valueGetterExpression(propertiesInfo); - - if (typeof limit === 'number') { - if (propertiesInfo.length > 0) { - scriptText += ', '; - } - scriptText += `docInfo['limit']`; - } - - // Finish return statement - scriptText += '];\n})'; - - const script = new vm.Script(scriptText, { filename: vmFileName }); - return script.runInThisContext(); - } - - /** - * Gets the INSERT query and function to obtain the parameters, given the doc. - * @param {TableMetadata} table - * @param {String} keyspace - * @param {Array} propertiesInfo - * @param {Object} docInfo - * @param {Boolean|undefined} ifNotExists - * @return {{query: String, paramsGetter: Function, isIdempotent: Boolean}} - */ - static getInsert(table, keyspace, propertiesInfo, docInfo, ifNotExists) { - const ttl = docInfo && docInfo.ttl; - - // Not all columns are contained in the table - const filteredPropertiesInfo = propertiesInfo - .filter(pInfo => table.columnsByName[pInfo.columnName] !== undefined); - - return ({ - query: QueryGenerator._getInsertQuery(table.name, keyspace, filteredPropertiesInfo, ifNotExists, ttl), - paramsGetter: QueryGenerator._insertParamsGetter(filteredPropertiesInfo, docInfo), - isIdempotent: !ifNotExists - }); - } - - /** - * Gets the query for an insert statement. - * @param {String} tableName - * @param {String} keyspace - * @param {Array} propertiesInfo - * @param {Boolean} ifNotExists - * @param {Number|undefined} ttl - * @return {String} - */ - static _getInsertQuery(tableName, keyspace, propertiesInfo, ifNotExists, ttl) { - let query = `INSERT INTO ${keyspace}.${tableName} (`; - query += propertiesInfo.map(pInfo => pInfo.columnName).join(', '); - query += ') VALUES ('; - query += propertiesInfo.map(() => '?').join(', '); - query += ')'; - - if (ifNotExists === true) { - query += ' IF NOT EXISTS'; - } - - if (typeof ttl === 'number') { - query += ' USING TTL ?'; - } - return query; - } - - static _insertParamsGetter(propertiesInfo, docInfo) { - let scriptText = '(function getParametersInsert(doc, docInfo, mappingInfo) {\n'; - scriptText += ' return ['; - - scriptText += QueryGenerator._valueGetterExpression(propertiesInfo); - - if (docInfo && typeof docInfo.ttl === 'number') { - scriptText += `, docInfo['ttl']`; - } - - // Finish return statement - scriptText += '];\n})'; - - const script = new vm.Script(scriptText, { filename: vmFileName }); - return script.runInThisContext(); - } - - /** - * Gets the UPDATE query and function to obtain the parameters, given the doc. - * @param {TableMetadata} table - * @param {String} keyspace - * @param {Array} propertiesInfo - * @param {Object} docInfo - * @param {Array} when - * @param {Boolean|undefined} ifExists - * @return {{query: String, paramsGetter: Function, isIdempotent: Boolean, isCounter}} - */ - static getUpdate(table, keyspace, propertiesInfo, docInfo, when, ifExists) { - const ttl = docInfo && docInfo.ttl; - const primaryKeys = new Set(table.partitionKeys.concat(table.clusteringKeys).map(c => c.name)); - let isIdempotent = true; - let isCounter = false; - - // Not all columns are contained in the table - const filteredPropertiesInfo = propertiesInfo.filter(pInfo => { - const column = table.columnsByName[pInfo.columnName]; - if (column === undefined) { - return false; - } - - if (column.type.code === dataTypes.list && pInfo.value instanceof QueryAssignment) { - // Its not idempotent when list append/prepend - isIdempotent = false; - } else if (column.type.code === dataTypes.counter) { - // Any update on a counter table is not idempotent - isIdempotent = false; - isCounter = true; - } - - return true; - }); - - return { - query: QueryGenerator._getUpdateQuery( - table.name, keyspace, primaryKeys, filteredPropertiesInfo, when, ifExists, ttl), - isIdempotent: isIdempotent && when.length === 0 && !ifExists, - paramsGetter: QueryGenerator._updateParamsGetter(primaryKeys, filteredPropertiesInfo, when, ttl), - isCounter - }; - } - - /** - * Gets the query for an UPDATE statement. - * @param {String} tableName - * @param {String} keyspace - * @param {Set} primaryKeys - * @param {Array} propertiesInfo - * @param {Object} when - * @param {Boolean} ifExists - * @param {Number|undefined} ttl - */ - static _getUpdateQuery(tableName, keyspace, primaryKeys, propertiesInfo, when, ifExists, ttl) { - let query = `UPDATE ${keyspace}.${tableName} `; - - if (typeof ttl === 'number') { - query += 'USING TTL ? '; - } - - query += 'SET '; - - query += propertiesInfo - .filter(p => !primaryKeys.has(p.columnName)) - .map(p => { - if (p.value instanceof QueryAssignment) { - if (p.value.inverted) { - // e.g: prepend "col1 = ? + col1" - return `${p.columnName} = ? ${p.value.sign} ${p.columnName}`; - } - // e.g: increment "col1 = col1 + ?" - return `${p.columnName} = ${p.columnName} ${p.value.sign} ?`; - } - - return p.columnName + ' = ?'; - }) - .join(', '); - - query += ' WHERE '; - query += propertiesInfo.filter(p => primaryKeys.has(p.columnName)).map(p => p.columnName + ' = ?').join(' AND '); - - if (ifExists === true) { - query += ' IF EXISTS'; - } - else if (when.length > 0) { - query += ' IF ' + QueryGenerator._getConditionWithOperators(when); - } - - return query; - } - - /** - * Returns a function to obtain the parameter values from a doc for an UPDATE statement. - * @param {Set} primaryKeys - * @param {Array} propertiesInfo - * @param {Array} when - * @param {Number|undefined} ttl - * @returns {Function} - */ - static _updateParamsGetter(primaryKeys, propertiesInfo, when, ttl) { - let scriptText = '(function getParametersUpdate(doc, docInfo, mappingInfo) {\n'; - scriptText += ' return ['; - - if (typeof ttl === 'number') { - scriptText += `docInfo['ttl'], `; - } - - // Assignment clause - scriptText += QueryGenerator._assignmentGetterExpression(propertiesInfo.filter(p => !primaryKeys.has(p.columnName))); - scriptText += ', '; - - // Where clause - scriptText += QueryGenerator._valueGetterExpression(propertiesInfo.filter(p => primaryKeys.has(p.columnName))); - - // Condition clause - if (when.length > 0) { - scriptText += ', ' + QueryGenerator._valueGetterExpression(when, 'docInfo.when'); - } - - // Finish return statement - scriptText += '];\n})'; - - const script = new vm.Script(scriptText, { filename: vmFileName }); - return script.runInThisContext(); - } - - /** - * Gets the DELETE query and function to obtain the parameters, given the doc. - * @param {TableMetadata} table - * @param {String} keyspace - * @param {Array} propertiesInfo - * @param {Object} docInfo - * @param {Array} when - * @param {Boolean|undefined} ifExists - * @return {{query: String, paramsGetter: Function, isIdempotent}} - */ - static getDelete(table, keyspace, propertiesInfo, docInfo, when, ifExists) { - const deleteOnlyColumns = docInfo && docInfo.deleteOnlyColumns; - const primaryKeys = new Set(table.partitionKeys.concat(table.clusteringKeys).map(c => c.name)); - - const filteredPropertiesInfo = propertiesInfo - .filter(pInfo => table.columnsByName[pInfo.columnName] !== undefined); - - - return ({ - query: QueryGenerator._getDeleteQuery( - table.name, keyspace, primaryKeys, filteredPropertiesInfo, when, ifExists, deleteOnlyColumns), - paramsGetter: QueryGenerator._deleteParamsGetter(primaryKeys, filteredPropertiesInfo, when), - isIdempotent: when.length === 0 && !ifExists - }); - } - - /** - * Gets the query for an UPDATE statement. - * @param {String} tableName - * @param {String} keyspace - * @param {Set} primaryKeys - * @param {Array} propertiesInfo - * @param {Array} when - * @param {Boolean} ifExists - * @param {Boolean} deleteOnlyColumns - * @private - * @return {String} - */ - static _getDeleteQuery(tableName, keyspace, primaryKeys, propertiesInfo, when, ifExists, deleteOnlyColumns) { - let query = 'DELETE'; - - if (deleteOnlyColumns) { - const columnsToDelete = propertiesInfo.filter(p => !primaryKeys.has(p.columnName)) - .map(p => p.columnName) - .join(', '); - - if (columnsToDelete !== '') { - query += ' ' + columnsToDelete; - } - } - - query += ` FROM ${keyspace}.${tableName} WHERE `; - query += propertiesInfo.filter(p => primaryKeys.has(p.columnName)).map(p => p.columnName + ' = ?').join(' AND '); - - if (ifExists === true) { - query += ' IF EXISTS'; - } - else if (when.length > 0) { - query += ' IF ' + QueryGenerator._getConditionWithOperators(when); - } - - return query; - } - /** - * Returns a function to obtain the parameter values from a doc for an UPDATE statement. - * @param {Set} primaryKeys - * @param {Array} propertiesInfo - * @param {Array} when - * @returns {Function} - */ - static _deleteParamsGetter(primaryKeys, propertiesInfo, when) { - let scriptText = '(function getParametersDelete(doc, docInfo, mappingInfo) {\n'; - scriptText += ' return ['; - - // Where clause - scriptText += QueryGenerator._valueGetterExpression(propertiesInfo.filter(p => primaryKeys.has(p.columnName))); - - // Condition clause - if (when.length > 0) { - scriptText += ', ' + QueryGenerator._valueGetterExpression(when, 'docInfo.when'); - } - - // Finish return statement - scriptText += '];\n})'; - - const script = new vm.Script(scriptText, { filename: vmFileName }); - return script.runInThisContext(); - } - - /** - * Gets a string containing the doc properties to get. - * @param {Array} propertiesInfo - * @param {String} [objectName='doc'] - * @return {string} - * @private - */ - static _valueGetterExpression(propertiesInfo, objectName) { - objectName = objectName || 'doc'; - - return propertiesInfo - .map(p => - QueryGenerator._valueGetterSingle(`${objectName}['${p.propertyName}']`, p.propertyName, p.value, p.fromModel)) - .join(', '); - } - - static _valueGetterSingle(prefix, propName, value, fromModelFn) { - let valueGetter = prefix; - - if (value instanceof QueryOperator) { - if (value.hasChildValues) { - return `${QueryGenerator._valueGetterSingle(`${prefix}.value[0]`, propName, value.value[0], fromModelFn)}` + - `, ${QueryGenerator._valueGetterSingle(`${prefix}.value[1]`, propName, value.value[1], fromModelFn)}`; - } - - valueGetter = `${prefix}.value`; - - if (value.isInOperator && fromModelFn) { - // Transform each individual value - return `${valueGetter}.map(v => ${QueryGenerator._getMappingFunctionCall(propName, 'v')})`; - } - } - - return !fromModelFn ? valueGetter : QueryGenerator._getMappingFunctionCall(propName, valueGetter); - } - - /** - * Gets a string containing the doc properties to SET, considering QueryAssignment instances. - * @param {Array} propertiesInfo - * @param {String} [prefix='doc'] - * @return {string} - * @private - */ - static _assignmentGetterExpression(propertiesInfo, prefix) { - prefix = prefix || 'doc'; - - return propertiesInfo - .map(p => { - const valueGetter = `${prefix}['${p.propertyName}']${p.value instanceof QueryAssignment ? '.value' : ''}`; - if (p.fromModel) { - return QueryGenerator._getMappingFunctionCall(p.propertyName, valueGetter); - } - return valueGetter; - }) - .join(', '); - } - - static _getConditionWithOperators(propertiesInfo) { - return propertiesInfo - .map(p => QueryGenerator._getSingleCondition(p.columnName, p.value)) - .join(' AND '); - } - - static _getMappingFunctionCall(propName, valueGetter) { - return `mappingInfo.getFromModelFn('${propName}')(${valueGetter})`; - } - - static _getSingleCondition(columnName, value) { - if (value instanceof QueryOperator) { - if (value.hasChildValues) { - return `${QueryGenerator._getSingleCondition(columnName, value.value[0])}` + - ` ${value.key} ${QueryGenerator._getSingleCondition(columnName, value.value[1])}`; - } - return `${columnName} ${value.key} ?`; - } - return `${columnName} = ?`; - } -} - -module.exports = QueryGenerator; \ No newline at end of file diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/mapping/result-mapper.js b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/mapping/result-mapper.js deleted file mode 100644 index c364e5a24a..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/mapping/result-mapper.js +++ /dev/null @@ -1,112 +0,0 @@ -/* - * Copyright DataStax, Inc. - * - * 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 vm = require('vm'); -const utils = require('../utils'); -const types = require('../types'); - -/** - * @ignore - */ -class ResultMapper { - /** - * Gets a generated function to adapt the row to a document. - * @param {ModelMappingInfo} info - * @param {ResultSet} rs - * @returns {Function} - */ - static getSelectAdapter(info, rs) { - const columns = rs.columns; - if (!columns) { - throw new Error('Expected ROWS result obtained VOID'); - } - - let scriptText = '(function rowAdapter(row, info) {\n' + - ' const item = info.newInstance();\n'; - - for (const c of columns) { - scriptText += ` item['${info.getPropertyName(c.name)}'] = `; - - if (!info.getToModelFn(c.name)) { - scriptText += `row['${c.name}'];\n`; - } else { - scriptText += `info.getToModelFn('${c.name}')(row['${c.name}']);\n`; - } - } - - scriptText += ' return item;\n})'; - - const script = new vm.Script(scriptText, { filename: 'gen-result-mapper.js'}); - return script.runInThisContext(); - } - - /** - * Gets a function used to adapt VOID results or conditional updates. - * @param {ResultSet} rs - * @returns {Function} - */ - static getMutationAdapter(rs) { - if (rs.columns === null) { - // VOID result - return utils.noop; - } - - if ( - rs.columns.length === 1 && rs.columns[0].name === '[applied]' && - rs.columns[0].type.code === types.dataTypes.boolean) { - return utils.noop; - } - - return ResultMapper._getConditionalRowAdapter(rs); - } - - static _getConditionalRowAdapter(rs) { - return (function conditionalRowAdapter(row, info) { - const item = info.newInstance(); - - // Skip the first column ("[applied]") - for (let i = 1; i < rs.columns.length; i++) { - const c = rs.columns[i]; - item[info.getPropertyName(c.name)] = row[c.name]; - } - - return item; - }); - } - - /** - * @param {ModelMappingInfo} info - * @param {ResultSet} rs - * @returns {{canCache: Boolean, fn: Function}} - */ - static getCustomQueryAdapter(info, rs) { - if (rs.columns === null || rs.columns.length === 0) { - // VOID result - return { canCache: true, fn: utils.noop }; - } - - if (rs.columns[0].name === '[applied]' && rs.columns[0].type.code === types.dataTypes.boolean) { - // Conditional update results adapter functions should not be cached - return { canCache: false, fn: ResultMapper._getConditionalRowAdapter(rs) }; - } - - return { canCache: true, fn: ResultMapper.getSelectAdapter(info, rs) }; - } -} - -module.exports = ResultMapper; \ No newline at end of file diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/mapping/result.js b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/mapping/result.js deleted file mode 100644 index 6f1ead4d6c..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/mapping/result.js +++ /dev/null @@ -1,136 +0,0 @@ -/* - * Copyright DataStax, Inc. - * - * 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 util = require('util'); -const utils = require('../utils'); -const inspectMethod = util.inspect.custom || 'inspect'; - -/** - * Represents the result of an execution as an iterable of objects in the Mapper. - * @alias module:mapping~Result - */ -class Result { - /** - * Creates a new instance of Result. - * @param {ResultSet} rs - * @param {ModelMappingInfo} info - * @param {Function} rowAdapter - */ - constructor(rs, info, rowAdapter) { - this._rs = rs; - this._info = info; - this._rowAdapter = rowAdapter; - - /** - * When there is a single cell containing the result of the a LWT operation, hide the result from the user. - * @private - */ - this._isEmptyLwt = (rs.columns !== null - && rs.columns.length === 1 && this._rs.rowLength === 1 && rs.columns[0].name === '[applied]'); - - /** - * Gets the amount of the documents contained in this Result instance. - *

- * When the results are paged, it returns the length of the current paged results not the total amount of - * rows in the table matching the query. - *

- * @type {Number} - */ - this.length = this._isEmptyLwt ? 0 : (rs.rowLength || 0); - - /** - * A string token representing the current page state of query. - *

- * When provided, it can be used in the following executions to continue paging and retrieve the remained of the - * result for the query. - *

- * @type {String} - * @default null - */ - this.pageState = rs.pageState; - } - - /** - * When this instance is the result of a conditional update query, it returns whether it was successful. - * Otherwise, it returns true. - *

- * For consistency, this method always returns true for non-conditional queries (although there is - * no reason to call the method in that case). This is also the case for conditional DDL statements - * (CREATE KEYSPACE... IF NOT EXISTS, CREATE TABLE... IF NOT EXISTS), for which the server doesn't return - * information whether it was applied or not. - *

- */ - wasApplied() { - return this._rs.wasApplied(); - } - - /** - * Gets the first document in this result or null when the result is empty. - */ - first() { - if (!this._rs.rowLength || this._isEmptyLwt) { - return null; - } - return this._rowAdapter(this._rs.rows[0], this._info); - } - - /** - * Returns a new Iterator object that contains the document values. - */ - *[Symbol.iterator]() { - if (this._isEmptyLwt) { - // Empty iterator - return; - } - - for (let i = 0; i < this._rs.rows.length; i++) { - yield this._rowAdapter(this._rs.rows[i], this._info); - } - } - - /** - * Converts the current instance to an Array of documents. - * @return {Array} - */ - toArray() { - if (this._isEmptyLwt || !this._rs.rows) { - return utils.emptyArray; - } - - return this._rs.rows.map(row => this._rowAdapter(row, this._info)); - } - - /** - * Executes a provided function once per result element. - * @param {Function} callback Function to execute for each element, taking two arguments: currentValue and index. - * @param {Object} [thisArg] Value to use as this when executing callback. - */ - forEach(callback, thisArg) { - let index = 0; - thisArg = thisArg || this; - for (const doc of this) { - callback.call(thisArg, doc, index++); - } - } - - [inspectMethod]() { - return this.toArray(); - } -} - -module.exports = Result; \ No newline at end of file diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/mapping/table-mappings.js b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/mapping/table-mappings.js deleted file mode 100644 index 06010a1c05..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/mapping/table-mappings.js +++ /dev/null @@ -1,122 +0,0 @@ -/* - * Copyright DataStax, Inc. - * - * 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'; - -/** - * Contains a set of methods to represent a row into a document and a document into a row. - * @alias module:mapping~TableMappings - * @interface - */ -class TableMappings { - /** - * Method that is called by the mapper to create the instance of the document. - * @return {Object} - */ - newObjectInstance() { - return {}; - } - - /** - * Gets the name of the column based on the document property name. - * @param {String} propName The name of the property. - * @returns {String} - */ - getColumnName(propName) { - return propName; - } - - /** - * Gets the name of the document property based on the column name. - * @param {String} columnName The name of the column. - * @returns {String} - */ - getPropertyName(columnName) { - return columnName; - } -} - -/** - * A [TableMappings]{@link module:mapping~TableMappings} implementation that converts CQL column names in all-lowercase - * identifiers with underscores (snake case) to camel case (initial lowercase letter) property names. - *

- * The conversion is performed without any checks for the source format, you should make sure that the source - * format is snake case for CQL identifiers and camel case for properties. - *

- * @alias module:mapping~UnderscoreCqlToCamelCaseMappings - * @implements {module:mapping~TableMappings} - */ -class UnderscoreCqlToCamelCaseMappings extends TableMappings { - /** - * Creates a new instance of {@link UnderscoreCqlToCamelCaseMappings} - */ - constructor() { - super(); - } - - /** - * Converts a property name in camel case to snake case. - * @param {String} propName Name of the property to convert to snake case. - * @return {String} - */ - getColumnName(propName) { - return propName.replace(/[a-z][A-Z]/g, (match, offset) => match.charAt(0) + '_' + match.charAt(1)).toLowerCase(); - } - - /** - * Converts a column name in snake case to camel case. - * @param {String} columnName The column name to convert to camel case. - * @return {String} - */ - getPropertyName(columnName) { - return columnName.replace(/_[a-z]/g, (match, offset) => ((offset === 0) ? match : match.substr(1).toUpperCase())); - } -} - -/** - * Default implementation of [TableMappings]{@link module:mapping~TableMappings} that doesn't perform any conversion. - * @alias module:mapping~DefaultTableMappings - * @implements {module:mapping~TableMappings} - */ -class DefaultTableMappings extends TableMappings { - /** - * Creates a new instance of {@link DefaultTableMappings}. - */ - constructor() { - super(); - } - - /** @override */ - getColumnName(propName) { - return super.getColumnName(propName); - } - - /** @override */ - getPropertyName(columnName) { - return super.getPropertyName(columnName); - } - - /** - * Creates a new object instance, using object initializer. - */ - newObjectInstance() { - return super.newObjectInstance(); - } -} - -exports.TableMappings = TableMappings; -exports.UnderscoreCqlToCamelCaseMappings = UnderscoreCqlToCamelCaseMappings; -exports.DefaultTableMappings = DefaultTableMappings; \ No newline at end of file diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/mapping/tree.js b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/mapping/tree.js deleted file mode 100644 index b16f7ed0e6..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/mapping/tree.js +++ /dev/null @@ -1,148 +0,0 @@ -/* - * Copyright DataStax, Inc. - * - * 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 EventEmitter = require('events'); - -/** - * Represents a tree node where the key is composed by 1 or more strings. - * @ignore - */ -class Node extends EventEmitter { - /** - * Creates a new instance of {@link Node}. - * @param {Array} key - * @param {Object} value - * @param {Array} [edges] - */ - constructor(key, value, edges) { - super(); - this.key = key; - this.value = value; - this.edges = edges || []; - } -} - -/** - * A radix tree where each node contains a key, a value and edges. - * @ignore - */ -class Tree extends Node { - constructor() { - super([], null); - this.length = 0; - } - - /** - * Gets the existing item in the tree or creates a new one with the value provided by valueHandler - * @param {Iterator} keyIterator - * @param {Function} valueHandler - * @return {Object} - */ - getOrCreate(keyIterator, valueHandler) { - if (typeof keyIterator.next !== 'function') { - keyIterator = keyIterator[Symbol.iterator](); - } - let node = this; - let isMatch = false; - let item = keyIterator.next(); - while (true) { - let newBranch; - // Check node keys at position 1 and above - for (let i = 1; i < node.key.length; i++) { - if (item.done || node.key[i] !== item.value) { - // We should branch out - newBranch = this._createBranch(node, i, item.done, valueHandler); - break; - } - item = keyIterator.next(); - } - - if (item.done) { - isMatch = true; - break; - } - - if (newBranch !== undefined) { - break; - } - - const edges = node.edges; - let nextNode; - for (let i = 0; i < edges.length; i++) { - const e = edges[i]; - if (e.key[0] === item.value) { - // its a match - nextNode = e; - item = keyIterator.next(); - break; - } - } - - if (nextNode === undefined) { - // Current node is the root for a new leaf - break; - } - else { - node = nextNode; - } - } - - if (!isMatch) { - // Create using "node" as the root - const value = valueHandler(); - node.edges.push(new Node(iteratorToArray(item.value, keyIterator), value)); - this._onItemAdded(); - return value; - } - return node.value; - } - - _createBranch(node, index, useNewValue, valueHandler) { - const newBranch = new Node(node.key.slice(index), node.value, node.edges); - node.key = node.key.slice(0, index); - node.edges = [ newBranch ]; - if (useNewValue) { - // The previous node value has moved to a leaf - // The node containing the new leaf should use the new value - node.value = valueHandler(); - this._onItemAdded(); - } - else { - // Clear the value as it was copied in the branch - node.value = null; - } - return newBranch; - } - - _onItemAdded() { - this.length++; - this.emit('add', this.length); - } -} - -function iteratorToArray(value, iterator) { - const values = [ value ]; - let item = iterator.next(); - while (!item.done) { - values.push(item.value); - item = iterator.next(); - } - return values; -} - -module.exports = Tree; \ No newline at end of file diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/metadata/aggregate.js b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/metadata/aggregate.js deleted file mode 100644 index 6677f5f6c1..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/metadata/aggregate.js +++ /dev/null @@ -1,78 +0,0 @@ -/* - * Copyright DataStax, Inc. - * - * 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'; - -/** - * Creates a new Aggregate. - * @classdesc Describes a CQL aggregate. - * @alias module:metadata~Aggregate - * @constructor - */ -function Aggregate() { - /** - * Name of the aggregate. - * @type {String} - */ - this.name = null; - /** - * Name of the keyspace where the aggregate is declared. - */ - this.keyspaceName = null; - /** - * Signature of the aggregate. - * @type {Array.} - */ - this.signature = null; - /** - * List of the CQL aggregate argument types. - * @type {Array.<{code, info}>} - */ - this.argumentTypes = null; - /** - * State Function. - * @type {String} - */ - this.stateFunction = null; - /** - * State Type. - * @type {{code, info}} - */ - this.stateType = null; - /** - * Final Function. - * @type {String} - */ - this.finalFunction = null; - this.initConditionRaw = null; - /** - * Initial state value of this aggregate. - * @type {String} - */ - this.initCondition = null; - /** - * Type of the return value. - * @type {{code: number, info: (Object|Array|null)}} - */ - this.returnType = null; - /** - * Indicates whether or not this aggregate is deterministic. This means that - * given a particular input, the aggregate will always produce the same output. - * @type {Boolean} - */ - this.deterministic = null; -} - -module.exports = Aggregate; \ No newline at end of file diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/metadata/client-state.js b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/metadata/client-state.js deleted file mode 100644 index 6bf7c372ac..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/metadata/client-state.js +++ /dev/null @@ -1,114 +0,0 @@ -/* - * Copyright DataStax, Inc. - * - * 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 util = require('util'); -const errors = require('../errors'); - -/** - * Represents the state of a {@link Client}. - *

- * Exposes information on the connections maintained by a Client at a specific time. - *

- * @alias module:metadata~ClientState - * @constructor - */ -class ClientState { - - /** - * Creates a new instance of ClientState. - * @param {Array} hosts - * @param {Object.} openConnections - * @param {Object.} inFlightQueries - */ - constructor(hosts, openConnections, inFlightQueries) { - this._hosts = hosts; - this._openConnections = openConnections; - this._inFlightQueries = inFlightQueries; - } - - /** - * Get an array of hosts to which the client is connected to. - * @return {Array} - */ - getConnectedHosts() { - return this._hosts; - } - - /** - * Gets the amount of open connections to a given host. - * @param {Host} host - * @return {Number} - */ - getOpenConnections(host) { - if (!host) { - throw new errors.ArgumentError('Host is not defined'); - } - - return this._openConnections[host.address] || 0; - } - - /** - * Gets the amount of queries that are currently being executed through a given host. - *

- * This corresponds to the number of queries that have been sent by the Client to server Host on one of its connections - * but haven't yet obtained a response. - *

- * @param {Host} host - * @return {Number} - */ - getInFlightQueries(host) { - if (!host) { - throw new errors.ArgumentError('Host is not defined'); - } - - return this._inFlightQueries[host.address] || 0; - } - - /** - * Returns the string representation of the instance. - */ - toString() { - return util.format('{"hosts": %j, "openConnections": %j, "inFlightQueries": %j}', - this._hosts.map(function (h) { return h.address; }), this._openConnections, this._inFlightQueries); - } - - /** - * Creates a new instance from the provided client. - * @param {Client} client - * @internal - * @ignore - */ - static from(client) { - const openConnections = {}; - const inFlightQueries = {}; - const hostArray = []; - - client.hosts.forEach(host => { - if (host.pool.connections.length === 0) { - return; - } - - hostArray.push(host); - openConnections[host.address] = host.pool.connections.length; - inFlightQueries[host.address] = host.getInFlight(); - }); - - return new ClientState(hostArray, openConnections, inFlightQueries); - } -} - -module.exports = ClientState; \ No newline at end of file diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/metadata/data-collection.js b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/metadata/data-collection.js deleted file mode 100644 index 1bab680a43..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/metadata/data-collection.js +++ /dev/null @@ -1,173 +0,0 @@ -/* - * Copyright DataStax, Inc. - * - * 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 util = require('util'); -const events = require('events'); -/** - * Creates a new instance of DataCollection - * @param {String} name Name of the data object. - * @classdesc Describes a table or a view - * @alias module:metadata~DataCollection - * @constructor - * @abstract - */ -function DataCollection(name) { - events.EventEmitter.call(this); - this.setMaxListeners(0); - //private - Object.defineProperty(this, 'loading', { value: false, enumerable: false, writable: true }); - Object.defineProperty(this, 'loaded', { value: false, enumerable: false, writable: true }); - /** - * Name of the object - * @type {String} - */ - this.name = name; - /** - * False-positive probability for SSTable Bloom filters. - * @type {number} - */ - this.bloomFilterFalsePositiveChance = 0; - /** - * Level of caching: all, keys_only, rows_only, none - * @type {String} - */ - this.caching = null; - /** - * A human readable comment describing the table. - * @type {String} - */ - this.comment = null; - /** - * Specifies the time to wait before garbage collecting tombstones (deletion markers) - * @type {number} - */ - this.gcGraceSeconds = 0; - /** - * Compaction strategy class used for the table. - * @type {String} - */ - this.compactionClass = null; - /** - * Associative-array containing the compaction options keys and values. - * @type {Object} - */ - this.compactionOptions = null; - /** - * Associative-array containing the compression options. - * @type {Object} - */ - this.compression = null; - /** - * Specifies the probability of read repairs being invoked over all replicas in the current data center. - * @type {number} - */ - this.localReadRepairChance = 0; - /** - * Specifies the probability with which read repairs should be invoked on non-quorum reads. The value must be - * between 0 and 1. - * @type {number} - */ - this.readRepairChance = 0; - /** - * An associative Array containing extra metadata for the table. - *

- * For Apache Cassandra versions prior to 3.0.0, this method always returns null. - *

- * @type {Object} - */ - this.extensions = null; - /** - * When compression is enabled, this option defines the probability - * with which checksums for compressed blocks are checked during reads. - * The default value for this options is 1.0 (always check). - *

- * For Apache Cassandra versions prior to 3.0.0, this method always returns null. - *

- * @type {Number|null} - */ - this.crcCheckChance = null; - /** - * Whether the populate I/O cache on flush is set on this table. - * @type {Boolean} - */ - this.populateCacheOnFlush = false; - /** - * Returns the default TTL for this table. - * @type {Number} - */ - this.defaultTtl = 0; - /** - * * Returns the speculative retry option for this table. - * @type {String} - */ - this.speculativeRetry = 'NONE'; - /** - * Returns the minimum index interval option for this table. - *

- * Note: this option is available in Apache Cassandra 2.1 and above, and will return null for - * earlier versions. - *

- * @type {Number|null} - */ - this.minIndexInterval = 128; - /** - * Returns the maximum index interval option for this table. - *

- * Note: this option is available in Apache Cassandra 2.1 and above, and will return null for - * earlier versions. - *

- * @type {Number|null} - */ - this.maxIndexInterval = 2048; - /** - * Array describing the table columns. - * @type {Array} - */ - this.columns = null; - /** - * An associative Array of columns by name. - * @type {Object} - */ - this.columnsByName = null; - /** - * Array describing the columns that are part of the partition key. - * @type {Array} - */ - this.partitionKeys = []; - /** - * Array describing the columns that form the clustering key. - * @type {Array} - */ - this.clusteringKeys = []; - /** - * Array describing the clustering order of the columns in the same order as the clusteringKeys. - * @type {Array} - */ - this.clusteringOrder = []; - /** - * An associative Array containing nodesync options for this table. - *

- * For DSE versions prior to 6.0.0, this method always returns {@code null}. If nodesync - * was not explicitly configured for this table this method will also return {@code null}. - *

- * @type {Object} - */ - this.nodesync = null; -} - -util.inherits(DataCollection, events.EventEmitter); - -module.exports = DataCollection; \ No newline at end of file diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/metadata/event-debouncer.js b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/metadata/event-debouncer.js deleted file mode 100644 index 4ea8ddc2ee..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/metadata/event-debouncer.js +++ /dev/null @@ -1,164 +0,0 @@ -/* - * Copyright DataStax, Inc. - * - * 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 util = require('util'); -const utils = require('../utils'); -const promiseUtils = require('../promise-utils'); - -const _queueOverflowThreshold = 1000; - -/** - * Debounce protocol events by acting on those events with a sliding delay. - * @ignore - * @constructor - */ -class EventDebouncer { - - /** - * Creates a new instance of the event debouncer. - * @param {Number} delay - * @param {Function} logger - */ - constructor(delay, logger) { - this._delay = delay; - this._logger = logger; - this._queue = null; - this._timeout = null; - } - - /** - * Adds a new event to the queue and moves the delay. - * @param {{ handler: Function, all: boolean|undefined, keyspace: String|undefined, - * cqlObject: String|null|undefined }} event - * @param {Boolean} processNow - * @returns {Promise} - */ - eventReceived(event, processNow) { - return new Promise((resolve, reject) => { - event.callback = promiseUtils.getCallback(resolve, reject); - this._queue = this._queue || { callbacks: [], keyspaces: {} }; - const delay = !processNow ? this._delay : 0; - if (event.all) { - // when an event marked with all is received, it supersedes all the rest of events - // a full update (hosts + keyspaces + tokens) is going to be made - this._queue.mainEvent = event; - } - if (this._queue.callbacks.length === _queueOverflowThreshold) { - // warn once - this._logger('warn', util.format('Event debouncer queue exceeded %d events', _queueOverflowThreshold)); - } - this._queue.callbacks.push(event.callback); - if (this._queue.mainEvent) { - // a full refresh is scheduled and the callback was added, nothing else to do. - return this._slideDelay(delay); - } - // Insert at keyspace level - let keyspaceEvents = this._queue.keyspaces[event.keyspace]; - if (!keyspaceEvents) { - keyspaceEvents = this._queue.keyspaces[event.keyspace] = { events: [] }; - } - if (event.cqlObject === undefined) { - // a full refresh of the keyspace, supersedes all child keyspace events - keyspaceEvents.mainEvent = event; - } - keyspaceEvents.events.push(event); - this._slideDelay(delay); - }); - } - - /** - * @param {Number} delay - * @private - * */ - _slideDelay(delay) { - const self = this; - function process() { - const q = self._queue; - self._queue = null; - self._timeout = null; - processQueue(q); - } - if (delay === 0) { - // no delay, process immediately - if (this._timeout) { - clearTimeout(this._timeout); - } - return process(); - } - const previousTimeout = this._timeout; - // Add the new timeout before removing the previous one performs better - this._timeout = setTimeout(process, delay); - if (previousTimeout) { - clearTimeout(previousTimeout); - } - } - - /** - * Clears the timeout and invokes all pending callback. - */ - shutdown() { - if (!this._queue) { - return; - } - this._queue.callbacks.forEach(function (cb) { - cb(); - }); - this._queue = null; - clearTimeout(this._timeout); - this._timeout = null; - } -} - -/** - * @param {{callbacks: Array, keyspaces: Object, mainEvent: Object}} q - * @private - */ -function processQueue (q) { - if (q.mainEvent) { - // refresh all by invoking 1 handler and invoke all pending callbacks - return promiseUtils.toCallback(q.mainEvent.handler(), (err) => { - for (let i = 0; i < q.callbacks.length; i++) { - q.callbacks[i](err); - } - }); - } - - utils.each(Object.keys(q.keyspaces), function eachKeyspace(name, next) { - const keyspaceEvents = q.keyspaces[name]; - if (keyspaceEvents.mainEvent) { - // refresh a keyspace - return promiseUtils.toCallback(keyspaceEvents.mainEvent.handler(), function mainEventCallback(err) { - for (let i = 0; i < keyspaceEvents.events.length; i++) { - keyspaceEvents.events[i].callback(err); - } - - next(); - }); - } - - // deal with individual handlers and callbacks - keyspaceEvents.events.forEach(event => { - // sync handlers - event.handler(); - event.callback(); - }); - - next(); - }); -} - -module.exports = EventDebouncer; \ No newline at end of file diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/metadata/index.d.ts b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/metadata/index.d.ts deleted file mode 100644 index 80c0d9673b..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/metadata/index.d.ts +++ /dev/null @@ -1,211 +0,0 @@ -/* - * Copyright DataStax, Inc. - * - * 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. - */ - -import { types } from '../types'; -import { EmptyCallback, Host, token, ValueCallback } from '../../'; -import dataTypes = types.dataTypes; -import Uuid = types.Uuid; -import InetAddress = types.InetAddress; - -export namespace metadata { - - interface Aggregate { - argumentTypes: Array<{ code: dataTypes, info: any }>; - finalFunction: string; - initCondition: string; - keyspaceName: string; - returnType: string; - signature: string[]; - stateFunction: string; - stateType: string; - } - - interface ClientState { - getConnectedHosts(): Host[]; - - getInFlightQueries(host: Host): number; - - getOpenConnections(host: Host): number; - - toString(): string; - } - - interface DataTypeInfo { - code: dataTypes; - info: string | DataTypeInfo | DataTypeInfo[]; - options: { - frozen: boolean; - reversed: boolean; - }; - } - - interface ColumnInfo { - name: string; - type: DataTypeInfo; - } - - enum IndexKind { - custom = 0, - keys, - composites - } - - interface Index { - kind: IndexKind; - name: string; - options: object; - target: string; - - isCompositesKind(): boolean; - - isCustomKind(): boolean; - - isKeysKind(): boolean; - } - - interface DataCollection { - bloomFilterFalsePositiveChance: number; - caching: string; - clusteringKeys: ColumnInfo[]; - clusteringOrder: string[]; - columns: ColumnInfo[]; - columnsByName: { [key: string]: ColumnInfo }; - comment: string; - compactionClass: string; - compactionOptions: { [option: string]: any; }; - compression: { - class?: string; - [option: string]: any; - }; - crcCheckChange?: number; - defaultTtl: number; - extensions: { [option: string]: any; }; - gcGraceSeconds: number; - localReadRepairChance: number; - maxIndexInterval?: number; - minIndexInterval?: number; - name: string; - partitionKeys: ColumnInfo[]; - populateCacheOnFlush: boolean; - readRepairChance: number; - speculativeRetry: string; - } - - interface MaterializedView extends DataCollection { - tableName: string; - whereClause: string; - includeAllColumns: boolean; - } - - interface TableMetadata extends DataCollection { - indexes: Index[]; - indexInterval?: number; - isCompact: boolean; - memtableFlushPeriod: number; - replicateOnWrite: boolean; - cdc?: boolean; - virtual: boolean; - } - - interface QueryTrace { - requestType: string; - coordinator: InetAddress; - parameters: { [key: string]: any }; - startedAt: number | types.Long; - duration: number; - clientAddress: string; - events: Array<{ id: Uuid; activity: any; source: any; elapsed: any; thread: any }>; - } - - interface SchemaFunction { - argumentNames: string[]; - argumentTypes: Array<{ code: dataTypes, info: any }>; - body: string; - calledOnNullInput: boolean; - keyspaceName: string; - language: string; - name: string; - returnType: string; - signature: string[]; - } - - interface Udt { - name: string; - fields: ColumnInfo[] - } - - interface Metadata { - keyspaces: { [name: string]: { name: string, strategy: string }}; - - clearPrepared(): void; - - getAggregate(keyspaceName: string, name: string, signature: string[] | Array<{ code: number, info: any }>, callback: ValueCallback): void; - - getAggregate(keyspaceName: string, name: string, signature: string[] | Array<{ code: number, info: any }>): Promise; - - getAggregates(keyspaceName: string, name: string, callback: ValueCallback): void; - - getAggregates(keyspaceName: string, name: string): Promise; - - getFunction(keyspaceName: string, name: string, signature: string[] | Array<{ code: number, info: any }>, callback: ValueCallback): void; - - getFunction(keyspaceName: string, name: string, signature: string[] | Array<{ code: number, info: any }>): Promise; - - getFunctions(keyspaceName: string, name: string, callback: ValueCallback): void; - - getFunctions(keyspaceName: string, name: string): Promise; - - getMaterializedView(keyspaceName: string, name: string, callback: ValueCallback): void; - - getMaterializedView(keyspaceName: string, name: string, callback: EmptyCallback): Promise; - - getReplicas(keyspaceName: string, token: Buffer | token.Token | token.TokenRange): Host[]; - - getTable(keyspaceName: string, name: string, callback: ValueCallback): void; - - getTable(keyspaceName: string, name: string): Promise; - - getTokenRanges(): Set; - - getTokenRangesForHost(keyspaceName: string, host: Host): Set | null; - - getTrace(traceId: Uuid, consistency: types.consistencies, callback: ValueCallback): void; - - getTrace(traceId: Uuid, consistency: types.consistencies): Promise; - - getTrace(traceId: Uuid, callback: ValueCallback): void; - - getTrace(traceId: Uuid): Promise; - - getUdt(keyspaceName: string, name: string, callback: ValueCallback): void; - - getUdt(keyspaceName: string, name: string): Promise; - - newToken(components: Buffer[] | Buffer | string): token.Token; - - newTokenRange(start: token.Token, end: token.Token): token.TokenRange; - - refreshKeyspace(name: string, callback: EmptyCallback): void; - - refreshKeyspace(name: string): Promise; - - refreshKeyspaces(waitReconnect: boolean, callback: EmptyCallback): void; - - refreshKeyspaces(waitReconnect?: boolean): Promise; - - refreshKeyspaces(callback: EmptyCallback): void; - } -} \ No newline at end of file diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/metadata/index.js b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/metadata/index.js deleted file mode 100644 index ec587fcaf3..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/metadata/index.js +++ /dev/null @@ -1,1024 +0,0 @@ -/* - * Copyright DataStax, Inc. - * - * 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 events = require('events'); -const util = require('util'); - -/** - * Module containing classes and fields related to metadata. - * @module metadata - */ - -const t = require('../tokenizer'); -const utils = require('../utils'); -const errors = require('../errors'); -const types = require('../types'); -const requests = require('../requests'); -const schemaParserFactory = require('./schema-parser'); -const promiseUtils = require('../promise-utils'); -const { TokenRange } = require('../token'); -const { ExecutionOptions } = require('../execution-options'); - -/** - * @const - * @private - */ -const _selectTraceSession = "SELECT * FROM system_traces.sessions WHERE session_id=%s"; -/** - * @const - * @private - */ -const _selectTraceEvents = "SELECT * FROM system_traces.events WHERE session_id=%s"; -/** - * @const - * @private - */ -const _selectSchemaVersionPeers = "SELECT schema_version FROM system.peers"; -/** - * @const - * @private - */ -const _selectSchemaVersionLocal = "SELECT schema_version FROM system.local"; -/** - * @const - * @private - */ -const _traceMaxAttemps = 5; -/** - * @const - * @private - */ -const _traceAttemptDelay = 400; - -/** - * Represents cluster and schema information. - * The metadata class acts as a internal state of the driver. - */ -class Metadata { - - /** - * Creates a new instance of {@link Metadata}. - * @param {ClientOptions} options - * @param {ControlConnection} controlConnection Control connection used to retrieve information. - */ - constructor(options, controlConnection) { - if (!options) { - throw new errors.ArgumentError('Options are not defined'); - } - - Object.defineProperty(this, 'options', { value: options, enumerable: false, writable: false }); - Object.defineProperty(this, 'controlConnection', { value: controlConnection, enumerable: false, writable: false }); - this.keyspaces = {}; - this.initialized = false; - this._isDbaas = false; - this._schemaParser = schemaParserFactory.getByVersion(options, controlConnection, this.getUdt.bind(this)); - this.log = utils.log; - this._preparedQueries = new PreparedQueries(options.maxPrepared, (...args) => this.log(...args)); - } - - /** - * Sets the cassandra version - * @internal - * @ignore - * @param {Array.} version - */ - setCassandraVersion(version) { - this._schemaParser = schemaParserFactory.getByVersion( - this.options, this.controlConnection, this.getUdt.bind(this), version, this._schemaParser); - } - - /** - * Determines whether the cluster is provided as a service. - * @returns {boolean} true when the cluster is provided as a service (DataStax Astra), false when it's a - * different deployment (on-prem). - */ - isDbaas() { - return this._isDbaas; - } - - /** - * Sets the product type as DBaaS. - * @internal - * @ignore - */ - setProductTypeAsDbaas() { - this._isDbaas = true; - } - - /** - * @ignore - * @param {String} partitionerName - */ - setPartitioner(partitionerName) { - if (/RandomPartitioner$/.test(partitionerName)) { - return this.tokenizer = new t.RandomTokenizer(); - } - if (/ByteOrderedPartitioner$/.test(partitionerName)) { - return this.tokenizer = new t.ByteOrderedTokenizer(); - } - return this.tokenizer = new t.Murmur3Tokenizer(); - } - - /** - * Populates the information regarding primary replica per token, datacenters (+ racks) and sorted token ring. - * @ignore - * @param {HostMap} hosts - */ - buildTokens(hosts) { - if (!this.tokenizer) { - return this.log('error', 'Tokenizer could not be determined'); - } - //Get a sorted array of tokens - const allSorted = []; - //Get a map of - const primaryReplicas = {}; - //Depending on the amount of tokens, this could be an expensive operation - const hostArray = hosts.values(); - const stringify = this.tokenizer.stringify; - const datacenters = {}; - hostArray.forEach((h) => { - if (!h.tokens) { - return; - } - h.tokens.forEach((tokenString) => { - const token = this.tokenizer.parse(tokenString); - utils.insertSorted(allSorted, token, (t1, t2) => t1.compare(t2)); - primaryReplicas[stringify(token)] = h; - }); - let dc = datacenters[h.datacenter]; - if (!dc) { - dc = datacenters[h.datacenter] = { - hostLength: 0, - racks: new utils.HashSet() - }; - } - dc.hostLength++; - dc.racks.add(h.rack); - }); - //Primary replica for given token - this.primaryReplicas = primaryReplicas; - //All the tokens in ring order - this.ring = allSorted; - // Build TokenRanges. - const tokenRanges = new Set(); - if (this.ring.length === 1) { - // If there is only one token, return the range ]minToken, minToken] - const min = this.tokenizer.minToken(); - tokenRanges.add(new TokenRange(min, min, this.tokenizer)); - } - else { - for (let i = 0; i < this.ring.length; i++) { - const start = this.ring[i]; - const end = this.ring[(i + 1) % this.ring.length]; - tokenRanges.add(new TokenRange(start, end, this.tokenizer)); - } - } - this.tokenRanges = tokenRanges; - //Compute string versions as it's potentially expensive and frequently reused later - this.ringTokensAsStrings = new Array(allSorted.length); - for (let i = 0; i < allSorted.length; i++) { - this.ringTokensAsStrings[i] = stringify(allSorted[i]); - } - //Datacenter metadata (host length and racks) - this.datacenters = datacenters; - } - - /** - * Gets the keyspace metadata information and updates the internal state of the driver. - *

- * If a callback is provided, the callback is invoked when the keyspaces metadata refresh completes. - * Otherwise, it returns a Promise. - *

- * @param {String} name Name of the keyspace. - * @param {Function} [callback] Optional callback. - */ - refreshKeyspace(name, callback) { - return promiseUtils.optionalCallback(this._refreshKeyspace(name), callback); - } - - /** - * @param {String} name - * @private - */ - async _refreshKeyspace(name) { - if (!this.initialized) { - throw this._uninitializedError(); - } - this.log('info', util.format('Retrieving keyspace %s metadata', name)); - try { - const ksInfo = await this._schemaParser.getKeyspace(name); - if (!ksInfo) { - // the keyspace was dropped - delete this.keyspaces[name]; - return null; - } - // Tokens are lazily init on the keyspace, once a replica from that keyspace is retrieved. - this.keyspaces[ksInfo.name] = ksInfo; - return ksInfo; - } - catch (err) { - this.log('error', 'There was an error while trying to retrieve keyspace information', err); - throw err; - } - } - - /** - * Gets the metadata information of all the keyspaces and updates the internal state of the driver. - *

- * If a callback is provided, the callback is invoked when the keyspace metadata refresh completes. - * Otherwise, it returns a Promise. - *

- * @param {Boolean|Function} [waitReconnect] Determines if it should wait for reconnection in case the control connection is not - * connected at the moment. Default: true. - * @param {Function} [callback] Optional callback. - */ - refreshKeyspaces(waitReconnect, callback) { - if (typeof waitReconnect === 'function' || typeof waitReconnect === 'undefined') { - callback = waitReconnect; - waitReconnect = true; - } - if (!this.initialized) { - const err = this._uninitializedError(); - if (callback) { - return callback(err); - } - return Promise.reject(err); - } - return promiseUtils.optionalCallback(this.refreshKeyspacesInternal(waitReconnect), callback); - } - - /** - * @param {Boolean} waitReconnect - * @returns {Promise>} - * @ignore - * @internal - */ - async refreshKeyspacesInternal(waitReconnect) { - this.log('info', 'Retrieving keyspaces metadata'); - try { - this.keyspaces = await this._schemaParser.getKeyspaces(waitReconnect); - return this.keyspaces; - } - catch (err) { - this.log('error', 'There was an error while trying to retrieve keyspaces information', err); - throw err; - } - } - - _getKeyspaceReplicas(keyspace) { - if (!keyspace.replicas) { - //Calculate replicas the first time for the keyspace - keyspace.replicas = - keyspace.tokenToReplica(this.tokenizer, this.ringTokensAsStrings, this.primaryReplicas, this.datacenters); - } - return keyspace.replicas; - } - - /** - * Gets the host list representing the replicas that contain the given partition key, token or token range. - *

- * It uses the pre-loaded keyspace metadata to retrieve the replicas for a token for a given keyspace. - * When the keyspace metadata has not been loaded, it returns null. - *

- * @param {String} keyspaceName - * @param {Buffer|Token|TokenRange} token Can be Buffer (serialized partition key), Token or TokenRange - * @returns {Array} - */ - getReplicas(keyspaceName, token) { - if (!this.ring) { - return null; - } - if (Buffer.isBuffer(token)) { - token = this.tokenizer.hash(token); - } - if (token instanceof TokenRange) { - token = token.end; - } - let keyspace; - if (keyspaceName) { - keyspace = this.keyspaces[keyspaceName]; - if (!keyspace) { - // the keyspace was not found, the metadata should be loaded beforehand - return null; - } - } - let i = utils.binarySearch(this.ring, token, (t1, t2) => t1.compare(t2)); - if (i < 0) { - i = ~i; - } - if (i >= this.ring.length) { - //it circled back - i = i % this.ring.length; - } - const closestToken = this.ringTokensAsStrings[i]; - if (!keyspaceName) { - return [this.primaryReplicas[closestToken]]; - } - const replicas = this._getKeyspaceReplicas(keyspace); - return replicas[closestToken]; - } - - /** - * Gets the token ranges that define data distribution in the ring. - * - * @returns {Set} The ranges of the ring or empty set if schema metadata is not enabled. - */ - getTokenRanges() { - return this.tokenRanges; - } - - /** - * Gets the token ranges that are replicated on the given host, for - * the given keyspace. - * - * @param {String} keyspaceName The name of the keyspace to get ranges for. - * @param {Host} host The host. - * @returns {Set|null} Ranges for the keyspace on this host or null if keyspace isn't found or hasn't been loaded. - */ - getTokenRangesForHost(keyspaceName, host) { - if (!this.ring) { - return null; - } - let keyspace; - if (keyspaceName) { - keyspace = this.keyspaces[keyspaceName]; - if (!keyspace) { - // the keyspace was not found, the metadata should be loaded beforehand - return null; - } - } - // If the ring has only 1 token, just return the ranges as we should only have a single node cluster. - if (this.ring.length === 1) { - return this.getTokenRanges(); - } - const replicas = this._getKeyspaceReplicas(keyspace); - const ranges = new Set(); - // for each range, find replicas for end token, if replicas include host, add range. - this.tokenRanges.forEach((tokenRange) => { - const replicasForToken = replicas[this.tokenizer.stringify(tokenRange.end)]; - if (replicasForToken.indexOf(host) !== -1) { - ranges.add(tokenRange); - } - }); - return ranges; - } - - /** - * Constructs a Token from the input buffer(s) or string input. If a string is passed in - * it is assumed this matches the token representation reported by cassandra. - * @param {Array|Buffer|String} components - * @returns {Token} constructed token from the input buffer. - */ - newToken(components) { - if (!this.tokenizer) { - throw new Error('Partitioner not established. This should only happen if metadata was disabled or you have not connected yet.'); - } - if (Array.isArray(components)) { - return this.tokenizer.hash(Buffer.concat(components)); - } - else if (util.isString(components)) { - return this.tokenizer.parse(components); - } - return this.tokenizer.hash(components); - } - - /** - * Constructs a TokenRange from the given start and end tokens. - * @param {Token} start - * @param {Token} end - * @returns TokenRange build range spanning from start (exclusive) to end (inclusive). - */ - newTokenRange(start, end) { - if (!this.tokenizer) { - throw new Error('Partitioner not established. This should only happen if metadata was disabled or you have not connected yet.'); - } - return new TokenRange(start, end, this.tokenizer); - } - - /** - * Gets the metadata information already stored associated to a prepared statement - * @param {String} keyspaceName - * @param {String} query - * @internal - * @ignore - */ - getPreparedInfo(keyspaceName, query) { - return this._preparedQueries.getOrAdd(keyspaceName, query); - } - - /** - * Clears the internal state related to the prepared statements. - * Following calls to the Client using the prepare flag will re-prepare the statements. - */ - clearPrepared() { - this._preparedQueries.clear(); - } - - /** @ignore */ - getPreparedById(id) { - return this._preparedQueries.getById(id); - } - - /** @ignore */ - setPreparedById(info) { - return this._preparedQueries.setById(info); - } - - /** @ignore */ - getAllPrepared() { - return this._preparedQueries.getAll(); - } - - /** @ignore */ - _uninitializedError() { - return new Error('Metadata has not been initialized. This could only happen if you have not connected yet.'); - } - - /** - * Gets the definition of an user-defined type. - *

- * If a callback is provided, the callback is invoked when the metadata retrieval completes. - * Otherwise, it returns a Promise. - *

- *

- * When trying to retrieve the same UDT definition concurrently, it will query once and invoke all callbacks - * with the retrieved information. - *

- * @param {String} keyspaceName Name of the keyspace. - * @param {String} name Name of the UDT. - * @param {Function} [callback] The callback to invoke when retrieval completes. - */ - getUdt(keyspaceName, name, callback) { - return promiseUtils.optionalCallback(this._getUdt(keyspaceName, name), callback); - } - - /** - * @param {String} keyspaceName - * @param {String} name - * @returns {Promise} - * @private - */ - async _getUdt(keyspaceName, name) { - if (!this.initialized) { - throw this._uninitializedError(); - } - let cache; - if (this.options.isMetadataSyncEnabled) { - const keyspace = this.keyspaces[keyspaceName]; - if (!keyspace) { - return null; - } - cache = keyspace.udts; - } - return await this._schemaParser.getUdt(keyspaceName, name, cache); - } - - /** - * Gets the definition of a table. - *

- * If a callback is provided, the callback is invoked when the metadata retrieval completes. - * Otherwise, it returns a Promise. - *

- *

- * When trying to retrieve the same table definition concurrently, it will query once and invoke all callbacks - * with the retrieved information. - *

- * @param {String} keyspaceName Name of the keyspace. - * @param {String} name Name of the Table. - * @param {Function} [callback] The callback with the err as a first parameter and the {@link TableMetadata} as - * second parameter. - */ - getTable(keyspaceName, name, callback) { - return promiseUtils.optionalCallback(this._getTable(keyspaceName, name), callback); - } - - /** - * @param {String} keyspaceName - * @param {String} name - * @private - */ - async _getTable(keyspaceName, name) { - if (!this.initialized) { - throw this._uninitializedError(); - } - let cache; - let virtual; - if (this.options.isMetadataSyncEnabled) { - const keyspace = this.keyspaces[keyspaceName]; - if (!keyspace) { - return null; - } - cache = keyspace.tables; - virtual = keyspace.virtual; - } - return await this._schemaParser.getTable(keyspaceName, name, cache, virtual); - } - - /** - * Gets the definition of CQL functions for a given name. - *

- * If a callback is provided, the callback is invoked when the metadata retrieval completes. - * Otherwise, it returns a Promise. - *

- *

- * When trying to retrieve the same function definition concurrently, it will query once and invoke all callbacks - * with the retrieved information. - *

- * @param {String} keyspaceName Name of the keyspace. - * @param {String} name Name of the Function. - * @param {Function} [callback] The callback with the err as a first parameter and the array of {@link SchemaFunction} - * as second parameter. - */ - getFunctions(keyspaceName, name, callback) { - return promiseUtils.optionalCallback(this._getFunctionsWrapper(keyspaceName, name), callback); - } - - /** - * @param {String} keyspaceName - * @param {String} name - * @private - */ - async _getFunctionsWrapper(keyspaceName, name) { - if (!keyspaceName || !name) { - throw new errors.ArgumentError('You must provide the keyspace name and cql function name to retrieve the metadata'); - } - const functionsMap = await this._getFunctions(keyspaceName, name, false); - return Array.from(functionsMap.values()); - } - - /** - * Gets a definition of CQL function for a given name and signature. - *

- * If a callback is provided, the callback is invoked when the metadata retrieval completes. - * Otherwise, it returns a Promise. - *

- *

- * When trying to retrieve the same function definition concurrently, it will query once and invoke all callbacks - * with the retrieved information. - *

- * @param {String} keyspaceName Name of the keyspace - * @param {String} name Name of the Function - * @param {Array.|Array.<{code, info}>} signature Array of types of the parameters. - * @param {Function} [callback] The callback with the err as a first parameter and the {@link SchemaFunction} as second - * parameter. - */ - getFunction(keyspaceName, name, signature, callback) { - return promiseUtils.optionalCallback(this._getSingleFunction(keyspaceName, name, signature, false), callback); - } - - /** - * Gets the definition of CQL aggregate for a given name. - *

- * If a callback is provided, the callback is invoked when the metadata retrieval completes. - * Otherwise, it returns a Promise. - *

- *

- * When trying to retrieve the same aggregates definition concurrently, it will query once and invoke all callbacks - * with the retrieved information. - *

- * @param {String} keyspaceName Name of the keyspace - * @param {String} name Name of the Function - * @param {Function} [callback] The callback with the err as a first parameter and the array of {@link Aggregate} as - * second parameter. - */ - getAggregates(keyspaceName, name, callback) { - return promiseUtils.optionalCallback(this._getAggregates(keyspaceName, name), callback); - } - - /** - * @param {String} keyspaceName - * @param {String} name - * @private - */ - async _getAggregates(keyspaceName, name) { - if (!keyspaceName || !name) { - throw new errors.ArgumentError('You must provide the keyspace name and cql aggregate name to retrieve the metadata'); - } - const functionsMap = await this._getFunctions(keyspaceName, name, true); - return Array.from(functionsMap.values()); - } - - /** - * Gets a definition of CQL aggregate for a given name and signature. - *

- * If a callback is provided, the callback is invoked when the metadata retrieval completes. - * Otherwise, it returns a Promise. - *

- *

- * When trying to retrieve the same aggregate definition concurrently, it will query once and invoke all callbacks - * with the retrieved information. - *

- * @param {String} keyspaceName Name of the keyspace - * @param {String} name Name of the aggregate - * @param {Array.|Array.<{code, info}>} signature Array of types of the parameters. - * @param {Function} [callback] The callback with the err as a first parameter and the {@link Aggregate} as second parameter. - */ - getAggregate(keyspaceName, name, signature, callback) { - return promiseUtils.optionalCallback(this._getSingleFunction(keyspaceName, name, signature, true), callback); - } - - /** - * Gets the definition of a CQL materialized view for a given name. - *

- * If a callback is provided, the callback is invoked when the metadata retrieval completes. - * Otherwise, it returns a Promise. - *

- *

- * Note that, unlike the rest of the {@link Metadata} methods, this method does not cache the result for following - * calls, as the current version of the Cassandra native protocol does not support schema change events for - * materialized views. Each call to this method will produce one or more queries to the cluster. - *

- * @param {String} keyspaceName Name of the keyspace - * @param {String} name Name of the materialized view - * @param {Function} [callback] The callback with the err as a first parameter and the {@link MaterializedView} as - * second parameter. - */ - getMaterializedView(keyspaceName, name, callback) { - return promiseUtils.optionalCallback(this._getMaterializedView(keyspaceName, name), callback); - } - - /** - * @param {String} keyspaceName - * @param {String} name - * @returns {Promise} - * @private - */ - async _getMaterializedView(keyspaceName, name) { - if (!this.initialized) { - throw this._uninitializedError(); - } - let cache; - if (this.options.isMetadataSyncEnabled) { - const keyspace = this.keyspaces[keyspaceName]; - if (!keyspace) { - return null; - } - cache = keyspace.views; - } - return await this._schemaParser.getMaterializedView(keyspaceName, name, cache); - } - - /** - * Gets a map of cql function definitions or aggregates based on signature. - * @param {String} keyspaceName - * @param {String} name Name of the function or aggregate - * @param {Boolean} aggregate - * @returns {Promise} - * @private - */ - async _getFunctions(keyspaceName, name, aggregate) { - if (!this.initialized) { - throw this._uninitializedError(); - } - let cache; - if (this.options.isMetadataSyncEnabled) { - const keyspace = this.keyspaces[keyspaceName]; - if (!keyspace) { - return new Map(); - } - cache = aggregate ? keyspace.aggregates : keyspace.functions; - } - return await this._schemaParser.getFunctions(keyspaceName, name, aggregate, cache); - } - - /** - * Gets a single cql function or aggregate definition - * @param {String} keyspaceName - * @param {String} name - * @param {Array} signature - * @param {Boolean} aggregate - * @returns {Promise} - * @private - */ - async _getSingleFunction(keyspaceName, name, signature, aggregate) { - if (!keyspaceName || !name) { - throw new errors.ArgumentError('You must provide the keyspace name and cql function name to retrieve the metadata'); - } - if (!Array.isArray(signature)) { - throw new errors.ArgumentError('Signature must be an array of types'); - } - signature = signature.map(item => { - if (typeof item === 'string') { - return item; - } - return types.getDataTypeNameByCode(item); - }); - const functionsMap = await this._getFunctions(keyspaceName, name, aggregate); - return functionsMap.get(signature.join(',')) || null; - } - - /** - * Gets the trace session generated by Cassandra when query tracing is enabled for the - * query. The trace itself is stored in Cassandra in the sessions and - * events table in the system_traces keyspace and can be - * retrieve manually using the trace identifier. - *

- * If a callback is provided, the callback is invoked when the metadata retrieval completes. - * Otherwise, it returns a Promise. - *

- * @param {Uuid} traceId Identifier of the trace session. - * @param {Number} [consistency] The consistency level to obtain the trace. - * @param {Function} [callback] The callback with the err as first parameter and the query trace as second parameter. - */ - getTrace(traceId, consistency, callback) { - if (!callback && typeof consistency === 'function') { - // Both callback and consistency are optional parameters - // In this case, the second parameter is the callback - callback = consistency; - consistency = null; - } - - return promiseUtils.optionalCallback(this._getTrace(traceId, consistency), callback); - } - - /** - * @param {Uuid} traceId - * @param {Number} consistency - * @returns {Promise} - * @private - */ - async _getTrace(traceId, consistency) { - if (!this.initialized) { - throw this._uninitializedError(); - } - - let trace; - let attempts = 0; - const info = ExecutionOptions.empty(); - info.getConsistency = () => consistency; - - const sessionRequest = new requests.QueryRequest(util.format(_selectTraceSession, traceId), null, info); - const eventsRequest = new requests.QueryRequest(util.format(_selectTraceEvents, traceId), null, info); - - while (!trace && (attempts++ < _traceMaxAttemps)) { - const sessionResponse = await this.controlConnection.query(sessionRequest); - const sessionRow = sessionResponse.rows[0]; - - if (!sessionRow || typeof sessionRow['duration'] !== 'number') { - await promiseUtils.delay(_traceAttemptDelay); - continue; - } - - trace = { - requestType: sessionRow['request'], - coordinator: sessionRow['coordinator'], - parameters: sessionRow['parameters'], - startedAt: sessionRow['started_at'], - duration: sessionRow['duration'], - clientAddress: sessionRow['client'], - events: null - }; - - const eventsResponse = await this.controlConnection.query(eventsRequest); - trace.events = eventsResponse.rows.map(row => ({ - id: row['event_id'], - activity: row['activity'], - source: row['source'], - elapsed: row['source_elapsed'], - thread: row['thread'] - })); - } - - if (!trace) { - throw new Error(`Trace ${traceId.toString()} could not fully retrieved after ${_traceMaxAttemps} attempts`); - } - - return trace; - } - - /** - * Checks whether hosts that are currently up agree on the schema definition. - *

- * This method performs a one-time check only, without any form of retry; therefore - * protocolOptions.maxSchemaAgreementWaitSeconds setting does not apply in this case. - *

- * @param {Function} [callback] A function that is invoked with a value - * true when all hosts agree on the schema and false when there is no agreement or when - * the check could not be performed (for example, if the control connection is down). - * @returns {Promise} Returns a Promise when a callback is not provided. The promise resolves to - * true when all hosts agree on the schema and false when there is no agreement or when - * the check could not be performed (for example, if the control connection is down). - */ - checkSchemaAgreement(callback) { - return promiseUtils.optionalCallback(this._checkSchemaAgreement(), callback); - } - - /** - * Async-only version of check schema agreement. - * @private - */ - async _checkSchemaAgreement() { - const connection = this.controlConnection.connection; - if (!connection) { - return false; - } - try { - return await this.compareSchemaVersions(connection); - } - catch (err) { - return false; - } - } - - /** - * Uses the metadata to fill the user provided parameter hints - * @param {String} keyspace - * @param {Array} hints - * @internal - * @ignore - */ - async adaptUserHints(keyspace, hints) { - if (!Array.isArray(hints)) { - return; - } - const udts = []; - // Check for udts and get the metadata - for (let i = 0; i < hints.length; i++) { - const hint = hints[i]; - if (typeof hint !== 'string') { - continue; - } - - const type = types.dataTypes.getByName(hint); - this._checkUdtTypes(udts, type, keyspace); - hints[i] = type; - } - - for (const type of udts) { - const udtInfo = await this.getUdt(type.info.keyspace, type.info.name); - if (!udtInfo) { - throw new TypeError('User defined type not found: ' + type.info.keyspace + '.' + type.info.name); - } - type.info = udtInfo; - } - } - - /** - * @param {Array} udts - * @param {{code, info}} type - * @param {string} keyspace - * @private - */ - _checkUdtTypes(udts, type, keyspace) { - if (type.code === types.dataTypes.udt) { - const udtName = type.info.split('.'); - type.info = { - keyspace: udtName[0], - name: udtName[1] - }; - if (!type.info.name) { - if (!keyspace) { - throw new TypeError('No keyspace specified for udt: ' + udtName.join('.')); - } - //use the provided keyspace - type.info.name = type.info.keyspace; - type.info.keyspace = keyspace; - } - udts.push(type); - return; - } - - if (!type.info) { - return; - } - if (type.code === types.dataTypes.list || type.code === types.dataTypes.set) { - return this._checkUdtTypes(udts, type.info, keyspace); - } - if (type.code === types.dataTypes.map) { - this._checkUdtTypes(udts, type.info[0], keyspace); - this._checkUdtTypes(udts, type.info[1], keyspace); - } - } - - /** - * Uses the provided connection to query the schema versions and compare them. - * @param {Connection} connection - * @internal - * @ignore - */ - async compareSchemaVersions(connection) { - const versions = new Set(); - const response1 = await connection.send(new requests.QueryRequest(_selectSchemaVersionLocal), null); - if (response1 && response1.rows && response1.rows.length === 1) { - versions.add(response1.rows[0]['schema_version'].toString()); - } - const response2 = await connection.send(new requests.QueryRequest(_selectSchemaVersionPeers), null); - if (response2 && response2.rows) { - for (const row of response2.rows) { - const value = row['schema_version']; - if (!value) { - continue; - } - versions.add(value.toString()); - } - } - return versions.size === 1; - } -} - -/** - * Allows to store prepared queries and retrieval by query or query id. - * @ignore - */ -class PreparedQueries { - - /** - * @param {Number} maxPrepared - * @param {Function} logger - */ - constructor(maxPrepared, logger) { - this.length = 0; - this._maxPrepared = maxPrepared; - this._mapByKey = new Map(); - this._mapById = new Map(); - this._logger = logger; - } - - _getKey(keyspace, query) { - return (keyspace || '') + query; - } - - getOrAdd(keyspace, query) { - const key = this._getKey(keyspace, query); - let info = this._mapByKey.get(key); - if (info) { - return info; - } - - this._validateOverflow(); - - info = new events.EventEmitter(); - info.setMaxListeners(0); - info.query = query; - // The keyspace in which it was prepared - info.keyspace = keyspace; - this._mapByKey.set(key, info); - this.length++; - return info; - } - - _validateOverflow() { - if (this.length < this._maxPrepared) { - return; - } - - const toRemove = []; - this._logger('warning', - 'Prepared statements exceeded maximum. This could be caused by preparing queries that contain parameters'); - - const toRemoveLength = this.length - this._maxPrepared + 1; - - for (const [key, info] of this._mapByKey) { - if (!info.queryId) { - // Only remove queries that contain queryId - continue; - } - - const length = toRemove.push([key, info]); - if (length >= toRemoveLength) { - break; - } - } - - for (const [key, info] of toRemove) { - this._mapByKey.delete(key); - this._mapById.delete(info.queryId.toString('hex')); - this.length--; - } - } - - setById(info) { - this._mapById.set(info.queryId.toString('hex'), info); - } - - getById(id) { - return this._mapById.get(id.toString('hex')); - } - - clear() { - this._mapByKey = new Map(); - this._mapById = new Map(); - this.length = 0; - } - - getAll() { - return Array.from(this._mapByKey.values()).filter(info => !!info.queryId); - } -} - -module.exports = Metadata; diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/metadata/materialized-view.js b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/metadata/materialized-view.js deleted file mode 100644 index 455a66a0ef..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/metadata/materialized-view.js +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright DataStax, Inc. - * - * 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 util = require('util'); -const DataCollection = require('./data-collection'); -/** - * Creates a new MaterializedView. - * @param {String} name Name of the View. - * @classdesc Describes a CQL materialized view. - * @alias module:metadata~MaterializedView - * @augments {module:metadata~DataCollection} - * @constructor - */ -function MaterializedView(name) { - DataCollection.call(this, name); - /** - * Name of the table. - * @type {String} - */ - this.tableName = null; - /** - * View where clause. - * @type {String} - */ - this.whereClause = null; - /** - * Determines if all the table columns where are included in the view. - * @type {boolean} - */ - this.includeAllColumns = false; -} - -util.inherits(MaterializedView, DataCollection); - -module.exports = MaterializedView; \ No newline at end of file diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/metadata/schema-function.js b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/metadata/schema-function.js deleted file mode 100644 index 40105c07f9..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/metadata/schema-function.js +++ /dev/null @@ -1,97 +0,0 @@ -/* - * Copyright DataStax, Inc. - * - * 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'; - -/** - * Creates a new SchemaFunction. - * @classdesc Describes a CQL function. - * @alias module:metadata~SchemaFunction - * @constructor - */ -function SchemaFunction() { - /** - * Name of the cql function. - * @type {String} - */ - this.name = null; - /** - * Name of the keyspace where the cql function is declared. - */ - this.keyspaceName = null; - /** - * Signature of the function. - * @type {Array.} - */ - this.signature = null; - /** - * List of the function argument names. - * @type {Array.} - */ - this.argumentNames = null; - /** - * List of the function argument types. - * @type {Array.<{code, info}>} - */ - this.argumentTypes = null; - /** - * Body of the function. - * @type {String} - */ - this.body = null; - /** - * Determines if the function is called when the input is null. - * @type {Boolean} - */ - this.calledOnNullInput = null; - /** - * Name of the programming language, for example: java, javascript, ... - * @type {String} - */ - this.language = null; - /** - * Type of the return value. - * @type {{code: number, info: (Object|Array|null)}} - */ - this.returnType = null; - /** - * Indicates whether or not this function is deterministic. This means that - * given a particular input, the function will always produce the same output. - * @type {Boolean} - */ - this.deterministic = null; - /** - * Indicates whether or not this function is monotonic on all of its - * arguments. This means that it is either entirely non-increasing or - * non-decreasing. Even if the function is not monotonic on all of its - * arguments, it's possible to specify that it is monotonic on one of - * its arguments, meaning that partial applications of the function over - * that argument will be monotonic. - * - * Monotonicity is required to use the function in a GROUP BY clause. - * @type {Boolean} - */ - this.monotonic = null; - /** - * The argument names that the function is monotonic on. - * - * If {@link monotonic} is true, this will return all argument names. - * Otherwise, this will return either one argument or an empty array. - * @type {Array.} - */ - this.monotonicOn = null; -} - -module.exports = SchemaFunction; \ No newline at end of file diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/metadata/schema-index.js b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/metadata/schema-index.js deleted file mode 100644 index 8787bad27f..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/metadata/schema-index.js +++ /dev/null @@ -1,149 +0,0 @@ -/* - * Copyright DataStax, Inc. - * - * 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 util = require('util'); -const utils = require('../utils'); -const types = require('../types'); - -/** @private */ -const kind = { - custom: 0, - keys: 1, - composites: 2 -}; -/** - * Creates a new Index instance. - * @classdesc Describes a CQL index. - * @param {String} name - * @param {String} target - * @param {Number|String} kind - * @param {Object} options - * @alias module:metadata~Index - * @constructor - */ -function Index(name, target, kind, options) { - /** - * Name of the index. - * @type {String} - */ - this.name = name; - /** - * Target of the index. - * @type {String} - */ - this.target = target; - /** - * A numeric value representing index kind (0: custom, 1: keys, 2: composite); - * @type {Number} - */ - this.kind = typeof kind === 'string' ? getKindByName(kind) : kind; - /** - * An associative array containing the index options - * @type {Object} - */ - this.options = options; -} - -/** - * Determines if the index is of composites kind - * @returns {Boolean} - */ -Index.prototype.isCompositesKind = function () { - return this.kind === kind.composites; -}; - -/** - * Determines if the index is of keys kind - * @returns {Boolean} - */ -Index.prototype.isKeysKind = function () { - return this.kind === kind.keys; -}; - -/** - * Determines if the index is of custom kind - * @returns {Boolean} - */ -Index.prototype.isCustomKind = function () { - return this.kind === kind.custom; -}; - -/** - * Parses Index information from rows in the 'system_schema.indexes' table - * @deprecated It will be removed in the next major version. - * @param {Array.} indexRows - * @returns {Array.} - */ -Index.fromRows = function (indexRows) { - if (!indexRows || indexRows.length === 0) { - return utils.emptyArray; - } - return indexRows.map(function (row) { - const options = row['options']; - return new Index(row['index_name'], options['target'], getKindByName(row['kind']), options); - }); -}; - -/** - * Parses Index information from rows in the legacy 'system.schema_columns' table. - * @deprecated It will be removed in the next major version. - * @param {Array.} columnRows - * @param {Object.} columnsByName - * @returns {Array.} - */ -Index.fromColumnRows = function (columnRows, columnsByName) { - const result = []; - for (let i = 0; i < columnRows.length; i++) { - const row = columnRows[i]; - const indexName = row['index_name']; - if (!indexName) { - continue; - } - const c = columnsByName[row['column_name']]; - let target; - const options = JSON.parse(row['index_options']); - if (options !== null && options['index_keys'] !== undefined) { - target = util.format("keys(%s)", c.name); - } - else if (options !== null && options['index_keys_and_values'] !== undefined) { - target = util.format("entries(%s)", c.name); - } - else if (c.type.options.frozen && (c.type.code === types.dataTypes.map || c.type.code === types.dataTypes.list || - c.type.code === types.dataTypes.set)) { - target = util.format("full(%s)", c.name); - } - else { - target = c.name; - } - result.push(new Index(indexName, target, getKindByName(row['index_type']), options)); - } - return result; -}; - -/** - * Gets the number representing the kind based on the name - * @param {String} name - * @returns {Number} - * @private - */ -function getKindByName(name) { - if (!name) { - return kind.custom; - } - return kind[name.toLowerCase()]; -} - -module.exports = Index; \ No newline at end of file diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/metadata/schema-parser.js b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/metadata/schema-parser.js deleted file mode 100644 index af05a3b69a..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/metadata/schema-parser.js +++ /dev/null @@ -1,1177 +0,0 @@ -/* - * Copyright DataStax, Inc. - * - * 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 util = require('util'); -const events = require('events'); -const types = require('../types'); -const utils = require('../utils'); -const errors = require('../errors'); -const promiseUtils = require('../promise-utils'); -const TableMetadata = require('./table-metadata'); -const Aggregate = require('./aggregate'); -const SchemaFunction = require('./schema-function'); -const Index = require('./schema-index'); -const MaterializedView = require('./materialized-view'); -const { format } = util; - -/** - * @module metadata/schemaParser - * @ignore - */ - -const _selectAllKeyspacesV1 = "SELECT * FROM system.schema_keyspaces"; -const _selectSingleKeyspaceV1 = "SELECT * FROM system.schema_keyspaces where keyspace_name = '%s'"; -const _selectAllKeyspacesV2 = "SELECT * FROM system_schema.keyspaces"; -const _selectSingleKeyspaceV2 = "SELECT * FROM system_schema.keyspaces where keyspace_name = '%s'"; -const _selectTableV1 = "SELECT * FROM system.schema_columnfamilies WHERE keyspace_name='%s' AND columnfamily_name='%s'"; -const _selectTableV2 = "SELECT * FROM system_schema.tables WHERE keyspace_name='%s' AND table_name='%s'"; -const _selectColumnsV1 = "SELECT * FROM system.schema_columns WHERE keyspace_name='%s' AND columnfamily_name='%s'"; -const _selectColumnsV2 = "SELECT * FROM system_schema.columns WHERE keyspace_name='%s' AND table_name='%s'"; -const _selectIndexesV2 = "SELECT * FROM system_schema.indexes WHERE keyspace_name='%s' AND table_name='%s'"; -const _selectUdtV1 = "SELECT * FROM system.schema_usertypes WHERE keyspace_name='%s' AND type_name='%s'"; -const _selectUdtV2 = "SELECT * FROM system_schema.types WHERE keyspace_name='%s' AND type_name='%s'"; -const _selectFunctionsV1 = "SELECT * FROM system.schema_functions WHERE keyspace_name = '%s' AND function_name = '%s'"; -const _selectFunctionsV2 = "SELECT * FROM system_schema.functions WHERE keyspace_name = '%s' AND function_name = '%s'"; -const _selectAggregatesV1 = "SELECT * FROM system.schema_aggregates WHERE keyspace_name = '%s' AND aggregate_name = '%s'"; -const _selectAggregatesV2 = "SELECT * FROM system_schema.aggregates WHERE keyspace_name = '%s' AND aggregate_name = '%s'"; -const _selectMaterializedViewV2 = "SELECT * FROM system_schema.views WHERE keyspace_name = '%s' AND view_name = '%s'"; - -const _selectAllVirtualKeyspaces = "SELECT * FROM system_virtual_schema.keyspaces"; -const _selectSingleVirtualKeyspace = "SELECT * FROM system_virtual_schema.keyspaces where keyspace_name = '%s'"; -const _selectVirtualTable = "SELECT * FROM system_virtual_schema.tables where keyspace_name = '%s' and table_name='%s'"; -const _selectVirtualColumns = "SELECT * FROM system_virtual_schema.columns where keyspace_name = '%s' and table_name='%s'"; - - -/** - * @abstract - * @param {ClientOptions} options The client options - * @param {ControlConnection} cc - * @constructor - * @ignore - */ -class SchemaParser { - constructor(options, cc) { - this.cc = cc; - this.encodingOptions = options.encoding; - this.selectTable = null; - this.selectColumns = null; - this.selectIndexes = null; - this.selectUdt = null; - this.selectAggregates = null; - this.selectFunctions = null; - this.supportsVirtual = false; - } - - /** - * @param name - * @param durableWrites - * @param strategy - * @param strategyOptions - * @param virtual - * @returns {{name, durableWrites, strategy, strategyOptions, tokenToReplica, udts, tables, functions, aggregates}} - * @protected - */ - _createKeyspace(name, durableWrites, strategy, strategyOptions, virtual) { - return { - name, - durableWrites, - strategy, - strategyOptions, - virtual: virtual === true, - udts: {}, - tables: {}, - functions: {}, - aggregates: {}, - views: {}, - tokenToReplica: getTokenToReplicaMapper(strategy, strategyOptions), - graphEngine: undefined - }; - } - - /** - * @abstract - * @param {String} name - * @returns {Promise} - */ - getKeyspace(name) { - } - - /** - * @abstract - * @param {Boolean} waitReconnect - * @returns {Promise>} - */ - getKeyspaces(waitReconnect) { - } - - /** - * @param {String} keyspaceName - * @param {String} name - * @param {Object} cache - * @param {Boolean} virtual - * @returns {Promise} - */ - async getTable(keyspaceName, name, cache, virtual) { - let tableInfo = cache && cache[name]; - if (!tableInfo) { - tableInfo = new TableMetadata(name); - if (cache) { - cache[name] = tableInfo; - } - } - if (tableInfo.loaded) { - return tableInfo; - } - if (tableInfo.loading) { - // Wait for it to emit - return promiseUtils.fromEvent(tableInfo, 'load'); - } - try { - // its not cached and not being retrieved - tableInfo.loading = true; - let indexRows; - let virtualTable = virtual; - const selectTable = virtualTable ? _selectVirtualTable : this.selectTable; - const query = util.format(selectTable, keyspaceName, name); - let tableRow = await this._getFirstRow(query); - // if we weren't sure if table was virtual or not, query virtual schema. - if (!tableRow && this.supportsVirtual && virtualTable === undefined) { - const query = util.format(_selectVirtualTable, keyspaceName, name); - try { - tableRow = await this._getFirstRow(query); - } - catch (err) { - // we can't error here as we can't be sure if the node - // supports virtual tables, in this case it is adequate - // to act as if there was no matching table. - } - if (tableRow) { - // We are fetching a virtual table - virtualTable = true; - } - } - if (!tableRow) { - tableInfo.loading = false; - tableInfo.emit('load', null, null); - return null; - } - const selectColumns = virtualTable ? _selectVirtualColumns : this.selectColumns; - const columnRows = await this._getRows(util.format(selectColumns, keyspaceName, name)); - if (this.selectIndexes && !virtualTable) { - indexRows = await this._getRows(util.format(this.selectIndexes, keyspaceName, name)); - } - await this._parseTableOrView(tableInfo, tableRow, columnRows, indexRows, virtualTable); - tableInfo.loaded = true; - tableInfo.emit('load', null, tableInfo); - return tableInfo; - } - catch (err) { - tableInfo.emit('load', err, null); - throw err; - } - finally { - tableInfo.loading = false; - } - } - - async _getFirstRow(query) { - const rows = await this._getRows(query); - return rows[0]; - } - - async _getRows(query) { - const response = await this.cc.query(query); - return response.rows; - } - - /** - * @param {String} keyspaceName - * @param {String} name - * @param {Object} cache - * @returns {Promise} - */ - async getUdt(keyspaceName, name, cache) { - let udtInfo = cache && cache[name]; - if (!udtInfo) { - udtInfo = new events.EventEmitter(); - if (cache) { - cache[name] = udtInfo; - } - udtInfo.setMaxListeners(0); - udtInfo.loading = false; - udtInfo.name = name; - udtInfo.keyspace = keyspaceName; - udtInfo.fields = null; - } - if (udtInfo.fields) { - return udtInfo; - } - if (udtInfo.loading) { - return promiseUtils.fromEvent(udtInfo, 'load'); - } - udtInfo.loading = true; - const query = format(this.selectUdt, keyspaceName, name); - try { - const row = await this._getFirstRow(query); - if (!row) { - udtInfo.loading = false; - udtInfo.emit('load', null, null); - return null; - } - await this._parseUdt(udtInfo, row); - udtInfo.emit('load', null, udtInfo); - return udtInfo; - } - catch (err) { - udtInfo.emit('load', err); - throw err; - } - finally { - udtInfo.loading = false; - } - } - - /** - * Parses the udt information from the row - * @param udtInfo - * @param {Row} row - * @returns {Promise} - * @abstract - */ - _parseUdt(udtInfo, row) { - } - - /** - * Builds the metadata based on the table and column rows - * @abstract - * @param {module:metadata~TableMetadata} tableInfo - * @param {Row} tableRow - * @param {Array.} columnRows - * @param {Array.} indexRows - * @param {Boolean} virtual - * @returns {Promise} - * @throws {Error} - */ - async _parseTableOrView(tableInfo, tableRow, columnRows, indexRows, virtual) { - } - - /** - * @abstract - * @param {String} keyspaceName - * @param {String} name - * @param {Object} cache - * @returns {Promise} - */ - getMaterializedView(keyspaceName, name, cache) { - } - - /** - * @param {String} keyspaceName - * @param {String} name - * @param {Boolean} aggregate - * @param {Object} cache - * @returns {Promise} - */ - async getFunctions(keyspaceName, name, aggregate, cache) { - /** @type {String} */ - let query = this.selectFunctions; - let parser = row => this._parseFunction(row); - if (aggregate) { - query = this.selectAggregates; - parser = row => this._parseAggregate(row); - } - // if it's not already loaded, get all functions with that name - // cache it by name and, within name, by signature - let functionsInfo = cache && cache[name]; - if (!functionsInfo) { - functionsInfo = new events.EventEmitter(); - if (cache) { - cache[name] = functionsInfo; - } - functionsInfo.setMaxListeners(0); - } - if (functionsInfo.values) { - return functionsInfo.values; - } - if (functionsInfo.loading) { - return promiseUtils.fromEvent(functionsInfo, 'load'); - } - functionsInfo.loading = true; - try { - const rows = await this._getRows(format(query, keyspaceName, name)); - const funcs = await Promise.all(rows.map(parser)); - const result = new Map(); - if (rows.length > 0) { - // Cache positive hits - functionsInfo.values = result; - } - - funcs.forEach(f => functionsInfo.values.set(f.signature.join(','), f)); - functionsInfo.emit('load', null, result); - return result; - } - catch (err) { - functionsInfo.emit('load', err); - throw err; - } - finally { - functionsInfo.loading = false; - } - } - - /** - * @abstract - * @param {Row} row - * @returns {Promise} - */ - _parseAggregate(row) { - } - - /** - * @abstract - * @param {Row} row - * @returns {Promise} - */ - _parseFunction(row) { - } - - /** @returns {Map} */ - _asMap(obj) { - if (!obj) { - return new Map(); - } - if (this.encodingOptions.map && obj instanceof this.encodingOptions.map) { - // Its already a Map or a polyfill of a Map - return obj; - } - return new Map(Object.keys(obj).map(k => [k, obj[k]])); - } - - _mapAsObject(map) { - if (!map) { - return map; - } - if (this.encodingOptions.map && map instanceof this.encodingOptions.map) { - const result = {}; - map.forEach((value, key) => result[key] = value); - return result; - } - return map; - } -} - -/** - * Used to parse schema information for Cassandra versions 1.2.x, and 2.x - * @ignore - */ -class SchemaParserV1 extends SchemaParser { - - /** - * @param {ClientOptions} options - * @param {ControlConnection} cc - */ - constructor(options, cc) { - super(options, cc); - this.selectTable = _selectTableV1; - this.selectColumns = _selectColumnsV1; - this.selectUdt = _selectUdtV1; - this.selectAggregates = _selectAggregatesV1; - this.selectFunctions = _selectFunctionsV1; - } - - async getKeyspaces(waitReconnect) { - const keyspaces = {}; - const result = await this.cc.query(_selectAllKeyspacesV1, waitReconnect); - for (let i = 0; i < result.rows.length; i++) { - const row = result.rows[i]; - const ksInfo = this._createKeyspace(row['keyspace_name'], row['durable_writes'], row['strategy_class'], JSON.parse(row['strategy_options'] || null)); - keyspaces[ksInfo.name] = ksInfo; - } - return keyspaces; - } - - async getKeyspace(name) { - const row = await this._getFirstRow(format(_selectSingleKeyspaceV1, name)); - if (!row) { - return null; - } - return this._createKeyspace(row['keyspace_name'], row['durable_writes'], row['strategy_class'], JSON.parse(row['strategy_options'])); - } - - // eslint-disable-next-line require-await - async _parseTableOrView(tableInfo, tableRow, columnRows, indexRows, virtual) { - // All the tableInfo parsing in V1 is sync, it uses a async function because the super class defines one - // to support other versions. - let c, name, types; - const encoder = this.cc.getEncoder(); - const columnsKeyed = {}; - let partitionKeys = []; - let clusteringKeys = []; - tableInfo.bloomFilterFalsePositiveChance = tableRow['bloom_filter_fp_chance']; - tableInfo.caching = tableRow['caching']; - tableInfo.comment = tableRow['comment']; - tableInfo.compactionClass = tableRow['compaction_strategy_class']; - tableInfo.compactionOptions = JSON.parse(tableRow['compaction_strategy_options']); - tableInfo.compression = JSON.parse(tableRow['compression_parameters']); - tableInfo.gcGraceSeconds = tableRow['gc_grace_seconds']; - tableInfo.localReadRepairChance = tableRow['local_read_repair_chance']; - tableInfo.readRepairChance = tableRow['read_repair_chance']; - tableInfo.populateCacheOnFlush = tableRow['populate_io_cache_on_flush'] || tableInfo.populateCacheOnFlush; - tableInfo.memtableFlushPeriod = tableRow['memtable_flush_period_in_ms'] || tableInfo.memtableFlushPeriod; - tableInfo.defaultTtl = tableRow['default_time_to_live'] || tableInfo.defaultTtl; - tableInfo.speculativeRetry = tableRow['speculative_retry'] || tableInfo.speculativeRetry; - tableInfo.indexInterval = tableRow['index_interval'] || tableInfo.indexInterval; - if (typeof tableRow['min_index_interval'] !== 'undefined') { - //Cassandra 2.1+ - tableInfo.minIndexInterval = tableRow['min_index_interval'] || tableInfo.minIndexInterval; - tableInfo.maxIndexInterval = tableRow['max_index_interval'] || tableInfo.maxIndexInterval; - } - else { - //set to null - tableInfo.minIndexInterval = null; - tableInfo.maxIndexInterval = null; - } - if (typeof tableRow['replicate_on_write'] !== 'undefined') { - //leave the default otherwise - tableInfo.replicateOnWrite = tableRow['replicate_on_write']; - } - tableInfo.columns = []; - for (let i = 0; i < columnRows.length; i++) { - const row = columnRows[i]; - const type = encoder.parseFqTypeName(row['validator']); - c = { - name: row['column_name'], - type: type, - isStatic: false - }; - tableInfo.columns.push(c); - columnsKeyed[c.name] = c; - switch (row['type']) { - case 'partition_key': - partitionKeys.push({ c: c, index: (row['component_index'] || 0) }); - break; - case 'clustering_key': - clusteringKeys.push({ - c: c, - index: (row['component_index'] || 0), - order: c.type.options.reversed ? 'DESC' : 'ASC' - }); - break; - case 'static': - // C* 2.0.6+ supports static columns - c.isStatic = true; - break; - } - } - if (partitionKeys.length > 0) { - tableInfo.partitionKeys = partitionKeys.sort(utils.propCompare('index')).map(item => item.c); - clusteringKeys.sort(utils.propCompare('index')); - tableInfo.clusteringKeys = clusteringKeys.map(item => item.c); - tableInfo.clusteringOrder = clusteringKeys.map(item => item.order); - } - // In C* 1.2, keys are not stored on the schema_columns table - const keysStoredInTableRow = (tableInfo.partitionKeys.length === 0); - if (keysStoredInTableRow && tableRow['key_aliases']) { - //In C* 1.2, keys are not stored on the schema_columns table - partitionKeys = JSON.parse(tableRow['key_aliases']); - types = encoder.parseKeyTypes(tableRow['key_validator']).types; - for (let i = 0; i < partitionKeys.length; i++) { - name = partitionKeys[i]; - c = columnsKeyed[name]; - if (!c) { - c = { - name: name, - type: types[i] - }; - tableInfo.columns.push(c); - } - tableInfo.partitionKeys.push(c); - } - } - const comparator = encoder.parseKeyTypes(tableRow['comparator']); - if (keysStoredInTableRow && tableRow['column_aliases']) { - clusteringKeys = JSON.parse(tableRow['column_aliases']); - for (let i = 0; i < clusteringKeys.length; i++) { - name = clusteringKeys[i]; - c = columnsKeyed[name]; - if (!c) { - c = { - name: name, - type: comparator.types[i] - }; - tableInfo.columns.push(c); - } - tableInfo.clusteringKeys.push(c); - tableInfo.clusteringOrder.push(c.type.options.reversed ? 'DESC' : 'ASC'); - } - } - tableInfo.isCompact = !!tableRow['is_dense']; - if (!tableInfo.isCompact) { - //is_dense column does not exist in previous versions of Cassandra - //also, compact pk, ck and val appear as is_dense false - // clusteringKeys != comparator types - 1 - // or not composite (comparator) - tableInfo.isCompact = ( - //clustering keys are not marked as composite - !comparator.isComposite || - //only 1 column not part of the partition or clustering keys - (!comparator.hasCollections && tableInfo.clusteringKeys.length !== comparator.types.length - 1)); - } - name = tableRow['value_alias']; - if (tableInfo.isCompact && name && !columnsKeyed[name]) { - //additional column in C* 1.2 as value_alias - c = { - name: name, - type: encoder.parseFqTypeName(tableRow['default_validator']) - }; - tableInfo.columns.push(c); - columnsKeyed[name] = c; - } - tableInfo.columnsByName = columnsKeyed; - tableInfo.indexes = Index.fromColumnRows(columnRows, tableInfo.columnsByName); - } - - getMaterializedView(keyspaceName, name, cache) { - return Promise.reject(new errors.NotSupportedError('Materialized views are not supported on Cassandra versions below 3.0')); - } - - // eslint-disable-next-line require-await - async _parseAggregate(row) { - const encoder = this.cc.getEncoder(); - const aggregate = new Aggregate(); - aggregate.name = row['aggregate_name']; - aggregate.keyspaceName = row['keyspace_name']; - aggregate.signature = row['signature'] || utils.emptyArray; - aggregate.stateFunction = row['state_func']; - aggregate.finalFunction = row['final_func']; - aggregate.initConditionRaw = row['initcond']; - aggregate.argumentTypes = (row['argument_types'] || utils.emptyArray).map(name => encoder.parseFqTypeName(name)); - aggregate.stateType = encoder.parseFqTypeName(row['state_type']); - const initConditionValue = encoder.decode(aggregate.initConditionRaw, aggregate.stateType); - if (initConditionValue !== null && typeof initConditionValue !== 'undefined') { - aggregate.initCondition = initConditionValue.toString(); - } - aggregate.returnType = encoder.parseFqTypeName(row['return_type']); - return aggregate; - } - - // eslint-disable-next-line require-await - async _parseFunction(row) { - const encoder = this.cc.getEncoder(); - const func = new SchemaFunction(); - func.name = row['function_name']; - func.keyspaceName = row['keyspace_name']; - func.signature = row['signature'] || utils.emptyArray; - func.argumentNames = row['argument_names'] || utils.emptyArray; - func.body = row['body']; - func.calledOnNullInput = row['called_on_null_input']; - func.language = row['language']; - func.argumentTypes = (row['argument_types'] || utils.emptyArray).map(name => encoder.parseFqTypeName(name)); - func.returnType = encoder.parseFqTypeName(row['return_type']); - return func; - } - - // eslint-disable-next-line require-await - async _parseUdt(udtInfo, row) { - const encoder = this.cc.getEncoder(); - const fieldNames = row['field_names']; - const fieldTypes = row['field_types']; - const fields = new Array(fieldNames.length); - for (let i = 0; i < fieldNames.length; i++) { - fields[i] = { - name: fieldNames[i], - type: encoder.parseFqTypeName(fieldTypes[i]) - }; - } - udtInfo.fields = fields; - return udtInfo; - } -} - - -/** - * Used to parse schema information for Cassandra versions 3.x and above - * @param {ClientOptions} options The client options - * @param {ControlConnection} cc The control connection to be used - * @param {Function} udtResolver The function to be used to retrieve the udts. - * @ignore - */ -class SchemaParserV2 extends SchemaParser { - - /** - * @param {ClientOptions} options The client options - * @param {ControlConnection} cc The control connection to be used - * @param {Function} udtResolver The function to be used to retrieve the udts. - */ - constructor(options, cc, udtResolver) { - super(options, cc); - this.udtResolver = udtResolver; - this.selectTable = _selectTableV2; - this.selectColumns = _selectColumnsV2; - this.selectUdt = _selectUdtV2; - this.selectAggregates = _selectAggregatesV2; - this.selectFunctions = _selectFunctionsV2; - this.selectIndexes = _selectIndexesV2; - } - - async getKeyspaces(waitReconnect) { - const keyspaces = {}; - const result = await this.cc.query(_selectAllKeyspacesV2, waitReconnect); - for (let i = 0; i < result.rows.length; i++) { - const ksInfo = this._parseKeyspace(result.rows[i]); - keyspaces[ksInfo.name] = ksInfo; - } - return keyspaces; - } - - async getKeyspace(name) { - const row = await this._getFirstRow(format(_selectSingleKeyspaceV2, name)); - if (!row) { - return null; - } - return this._parseKeyspace(row); - } - - async getMaterializedView(keyspaceName, name, cache) { - let viewInfo = cache && cache[name]; - if (!viewInfo) { - viewInfo = new MaterializedView(name); - if (cache) { - cache[name] = viewInfo; - } - } - if (viewInfo.loaded) { - return viewInfo; - } - if (viewInfo.loading) { - return promiseUtils.fromEvent(viewInfo, 'load'); - } - viewInfo.loading = true; - try { - const tableRow = await this._getFirstRow(format(_selectMaterializedViewV2, keyspaceName, name)); - if (!tableRow) { - viewInfo.emit('load', null, null); - viewInfo.loading = false; - return null; - } - const columnRows = await this._getRows(format(this.selectColumns, keyspaceName, name)); - await this._parseTableOrView(viewInfo, tableRow, columnRows, null, false); - viewInfo.loaded = true; - viewInfo.emit('load', null, viewInfo); - return viewInfo; - } - catch (err) { - viewInfo.emit('load', err); - throw err; - } - finally { - viewInfo.loading = false; - } - } - - _parseKeyspace(row, virtual) { - const replication = row['replication']; - let strategy; - let strategyOptions; - if (replication) { - strategy = replication['class']; - strategyOptions = {}; - for (const key in replication) { - if (!replication.hasOwnProperty(key) || key === 'class') { - continue; - } - strategyOptions[key] = replication[key]; - } - } - - const ks = this._createKeyspace(row['keyspace_name'], row['durable_writes'], strategy, strategyOptions, virtual); - ks.graphEngine = row['graph_engine']; - return ks; - } - - async _parseTableOrView(tableInfo, tableRow, columnRows, indexRows, virtual) { - const encoder = this.cc.getEncoder(); - const columnsKeyed = {}; - const partitionKeys = []; - const clusteringKeys = []; - tableInfo.columns = await Promise.all(columnRows.map(async (row) => { - const type = await encoder.parseTypeName(tableRow['keyspace_name'], row['type'], 0, null, this.udtResolver); - const c = { - name: row['column_name'], - type: type, - isStatic: false - }; - columnsKeyed[c.name] = c; - switch (row['kind']) { - case 'partition_key': - partitionKeys.push({ c, index: (row['position'] || 0) }); - break; - case 'clustering': - clusteringKeys.push({ - c, index: (row['position'] || 0), order: row['clustering_order'] === 'desc' ? 'DESC' : 'ASC' - }); - break; - case 'static': - c.isStatic = true; - break; - } - return c; - })); - tableInfo.columnsByName = columnsKeyed; - tableInfo.partitionKeys = partitionKeys.sort(utils.propCompare('index')).map(item => item.c); - clusteringKeys.sort(utils.propCompare('index')); - tableInfo.clusteringKeys = clusteringKeys.map(item => item.c); - tableInfo.clusteringOrder = clusteringKeys.map(item => item.order); - if (virtual) { - // When table is virtual, the only relevant information to parse are the columns - // as the table itself has no configuration - tableInfo.virtual = true; - return; - } - const isView = tableInfo instanceof MaterializedView; - tableInfo.bloomFilterFalsePositiveChance = tableRow['bloom_filter_fp_chance']; - tableInfo.caching = JSON.stringify(tableRow['caching']); - tableInfo.comment = tableRow['comment']; - // Regardless of the encoding options, use always an Object to represent an associative Array - const compaction = this._asMap(tableRow['compaction']); - if (compaction) { - // compactionOptions as an Object - tableInfo.compactionOptions = {}; - tableInfo.compactionClass = compaction.get('class'); - compaction.forEach((value, key) => { - if (key === 'class') { - return; - } - tableInfo.compactionOptions[key] = compaction.get(key); - }); - } - // Convert compression to an Object - tableInfo.compression = this._mapAsObject(tableRow['compression']); - tableInfo.gcGraceSeconds = tableRow['gc_grace_seconds']; - tableInfo.localReadRepairChance = tableRow['dclocal_read_repair_chance']; - tableInfo.readRepairChance = tableRow['read_repair_chance']; - tableInfo.extensions = this._mapAsObject(tableRow['extensions']); - tableInfo.crcCheckChance = tableRow['crc_check_chance']; - tableInfo.memtableFlushPeriod = tableRow['memtable_flush_period_in_ms'] || tableInfo.memtableFlushPeriod; - tableInfo.defaultTtl = tableRow['default_time_to_live'] || tableInfo.defaultTtl; - tableInfo.speculativeRetry = tableRow['speculative_retry'] || tableInfo.speculativeRetry; - tableInfo.minIndexInterval = tableRow['min_index_interval'] || tableInfo.minIndexInterval; - tableInfo.maxIndexInterval = tableRow['max_index_interval'] || tableInfo.maxIndexInterval; - tableInfo.nodesync = tableRow['nodesync'] || tableInfo.nodesync; - if (!isView) { - const cdc = tableRow['cdc']; - if (cdc !== undefined) { - tableInfo.cdc = cdc; - } - } - if (isView) { - tableInfo.tableName = tableRow['base_table_name']; - tableInfo.whereClause = tableRow['where_clause']; - tableInfo.includeAllColumns = tableRow['include_all_columns']; - return; - } - tableInfo.indexes = this._getIndexes(indexRows); - // flags can be an instance of Array or Set (real or polyfill) - let flags = tableRow['flags']; - if (Array.isArray(flags)) { - flags = new Set(flags); - } - const isDense = flags.has('dense'); - const isSuper = flags.has('super'); - const isCompound = flags.has('compound'); - tableInfo.isCompact = isSuper || isDense || !isCompound; - // Remove the columns related to Thrift - const isStaticCompact = !isSuper && !isDense && !isCompound; - if (isStaticCompact) { - pruneStaticCompactTableColumns(tableInfo); - } - else if (isDense) { - pruneDenseTableColumns(tableInfo); - } - } - - _getIndexes(indexRows) { - if (!indexRows || indexRows.length === 0) { - return utils.emptyArray; - } - return indexRows.map((row) => { - const options = this._mapAsObject(row['options']); - return new Index(row['index_name'], options['target'], row['kind'], options); - }); - } - - async _parseAggregate(row) { - const encoder = this.cc.getEncoder(); - const aggregate = new Aggregate(); - aggregate.name = row['aggregate_name']; - aggregate.keyspaceName = row['keyspace_name']; - aggregate.signature = row['argument_types'] || utils.emptyArray; - aggregate.stateFunction = row['state_func']; - aggregate.finalFunction = row['final_func']; - aggregate.initConditionRaw = row['initcond']; - aggregate.initCondition = aggregate.initConditionRaw; - aggregate.deterministic = row['deterministic'] || false; - aggregate.argumentTypes = await Promise.all(aggregate.signature.map(name => encoder.parseTypeName(row['keyspace_name'], name, 0, null, this.udtResolver))); - aggregate.stateType = await encoder.parseTypeName(row['keyspace_name'], row['state_type'], 0, null, this.udtResolver); - aggregate.returnType = await encoder.parseTypeName(row['keyspace_name'], row['return_type'], 0, null, this.udtResolver); - return aggregate; - } - - async _parseFunction(row) { - const encoder = this.cc.getEncoder(); - const func = new SchemaFunction(); - func.name = row['function_name']; - func.keyspaceName = row['keyspace_name']; - func.signature = row['argument_types'] || utils.emptyArray; - func.argumentNames = row['argument_names'] || utils.emptyArray; - func.body = row['body']; - func.calledOnNullInput = row['called_on_null_input']; - func.language = row['language']; - func.deterministic = row['deterministic'] || false; - func.monotonic = row['monotonic'] || false; - func.monotonicOn = row['monotonic_on'] || utils.emptyArray; - func.argumentTypes = await Promise.all(func.signature.map(name => encoder.parseTypeName(row['keyspace_name'], name, 0, null, this.udtResolver))); - func.returnType = await encoder.parseTypeName(row['keyspace_name'], row['return_type'], 0, null, this.udtResolver); - return func; - } - - async _parseUdt(udtInfo, row) { - const encoder = this.cc.getEncoder(); - const fieldTypes = row['field_types']; - const keyspace = row['keyspace_name']; - udtInfo.fields = await Promise.all(row['field_names'].map(async (name, i) => { - const type = await encoder.parseTypeName(keyspace, fieldTypes[i], 0, null, this.udtResolver); - return { name, type }; - })); - return udtInfo; - } -} - -/** - * Used to parse schema information for Cassandra versions 4.x and above. - * - * This parser similar to [SchemaParserV2] expect it also parses virtual - * keyspaces. - * @ignore - */ -class SchemaParserV3 extends SchemaParserV2 { - /** - * @param {ClientOptions} options The client options - * @param {ControlConnection} cc The control connection to be used - * @param {Function} udtResolver The function to be used to retrieve the udts. - */ - constructor(options, cc, udtResolver) { - super(options, cc, udtResolver); - this.supportsVirtual = true; - } - - async getKeyspaces(waitReconnect) { - const keyspaces = {}; - const queries = [ - { query: _selectAllKeyspacesV2, virtual: false }, - { query: _selectAllVirtualKeyspaces, virtual: true } - ]; - - await Promise.all(queries.map(async (q) => { - let result = null; - try { - result = await this.cc.query(q.query, waitReconnect); - } - catch (err) { - if (q.virtual) { - // Only throw error for non-virtual query as - // server reporting C* 4.0 may not actually implement - // virtual tables. - return; - } - throw err; - } - for (let i = 0; i < result.rows.length; i++) { - const ksInfo = this._parseKeyspace(result.rows[i], q.virtual); - keyspaces[ksInfo.name] = ksInfo; - } - })); - return keyspaces; - } - - async getKeyspace(name) { - const ks = await this._getKeyspace(_selectSingleKeyspaceV2, name, false); - if (!ks) { - // if not found, attempt to retrieve as virtual keyspace. - return this._getKeyspace(_selectSingleVirtualKeyspace, name, true); - } - return ks; - } - - async _getKeyspace(query, name, virtual) { - try { - const row = await this._getFirstRow(format(query, name)); - - if (!row) { - return null; - } - - return this._parseKeyspace(row, virtual); - } - catch (err) { - if (virtual) { - // only throw error for non-virtual query as - // server reporting C* 4.0 may not actually implement - // virtual tables. - return null; - } - throw err; - } - } -} - -/** - * Upon migration from thrift to CQL, we internally create a pair of surrogate clustering/regular columns - * for compact static tables. These columns shouldn't be exposed to the user but are currently returned by C*. - * We also need to remove the static keyword for all other columns in the table. - * @param {module:metadata~TableMetadata} tableInfo -*/ -function pruneStaticCompactTableColumns(tableInfo) { - let i; - let c; - //remove "column1 text" clustering column - for (i = 0; i < tableInfo.clusteringKeys.length; i++) { - c = tableInfo.clusteringKeys[i]; - const index = tableInfo.columns.indexOf(c); - tableInfo.columns.splice(index, 1); - delete tableInfo.columnsByName[c.name]; - } - tableInfo.clusteringKeys = utils.emptyArray; - tableInfo.clusteringOrder = utils.emptyArray; - //remove regular columns and set the static columns to non-static - i = tableInfo.columns.length; - while (i--) { - c = tableInfo.columns[i]; - if (!c.isStatic && tableInfo.partitionKeys.indexOf(c) === -1) { - // remove "value blob" regular column - tableInfo.columns.splice(i, 1); - delete tableInfo.columnsByName[c.name]; - continue; - } - c.isStatic = false; - } -} - -/** - * Upon migration from thrift to CQL, we internally create a surrogate column "value" of type custom. - * This column shouldn't be exposed to the user but is currently returned by C*. - * @param {module:metadata~TableMetadata} tableInfo - */ -function pruneDenseTableColumns(tableInfo) { - let i = tableInfo.columns.length; - while (i--) { - const c = tableInfo.columns[i]; - if (!c.isStatic && c.type.code === types.dataTypes.custom && c.type.info === 'empty') { - // remove "value blob" regular column - tableInfo.columns.splice(i, 1); - delete tableInfo.columnsByName[c.name]; - continue; - } - c.isStatic = false; - } -} - -function getTokenToReplicaMapper(strategy, strategyOptions) { - if (/SimpleStrategy$/.test(strategy)) { - const rf = parseInt(strategyOptions['replication_factor'], 10); - if (rf > 1) { - return getTokenToReplicaSimpleMapper(rf); - } - } - if (/NetworkTopologyStrategy$/.test(strategy)) { - return getTokenToReplicaNetworkMapper(strategyOptions); - } - //default, wrap in an Array - return (function noStrategy(tokenizer, ring, primaryReplicas) { - const replicas = {}; - for (const key in primaryReplicas) { - if (!primaryReplicas.hasOwnProperty(key)) { - continue; - } - replicas[key] = [primaryReplicas[key]]; - } - return replicas; - }); -} - -/** - * @param {Number} replicationFactor - * @returns {function} - */ -function getTokenToReplicaSimpleMapper(replicationFactor) { - return (function tokenSimpleStrategy(tokenizer, ringTokensAsStrings, primaryReplicas) { - const ringLength = ringTokensAsStrings.length; - const rf = Math.min(replicationFactor, ringLength); - const replicas = {}; - for (let i = 0; i < ringLength; i++) { - const key = ringTokensAsStrings[i]; - const tokenReplicas = [primaryReplicas[key]]; - for (let j = 1; j < ringLength && tokenReplicas.length < rf; j++) { - let nextReplicaIndex = i + j; - if (nextReplicaIndex >= ringLength) { - //circle back - nextReplicaIndex = nextReplicaIndex % ringLength; - } - const nextReplica = primaryReplicas[ringTokensAsStrings[nextReplicaIndex]]; - // In the case of vnodes, consecutive sections of the ring can be assigned to the same host. - if (tokenReplicas.indexOf(nextReplica) === -1) { - tokenReplicas.push(nextReplica); - } - } - replicas[key] = tokenReplicas; - } - return replicas; - }); -} - -/** - * @param {Object} replicationFactors - * @returns {Function} - * @private - */ -function getTokenToReplicaNetworkMapper(replicationFactors) { - // A(DC1) - // - // H B(DC2) - // | - // G --+-- C(DC1) - // | - // F D(DC2) - // - // E(DC1) - return (function tokenNetworkStrategy(tokenizer, ringTokensAsStrings, primaryReplicas, datacenters) { - const replicas = {}; - const ringLength = ringTokensAsStrings.length; - - for (let i = 0; i < ringLength; i++) { - const key = ringTokensAsStrings[i]; - const tokenReplicas = []; - const replicasByDc = {}; - const racksPlaced = {}; - const skippedHosts = []; - for (let j = 0; j < ringLength; j++) { - let nextReplicaIndex = i + j; - if (nextReplicaIndex >= ringLength) { - //circle back - nextReplicaIndex = nextReplicaIndex % ringLength; - } - const h = primaryReplicas[ringTokensAsStrings[nextReplicaIndex]]; - // In the case of vnodes, consecutive sections of the ring can be assigned to the same host. - if (tokenReplicas.indexOf(h) !== -1) { - continue; - } - const dc = h.datacenter; - //Check if the next replica belongs to one of the targeted dcs - let dcRf = parseInt(replicationFactors[dc], 10); - if (!dcRf) { - continue; - } - dcRf = Math.min(dcRf, datacenters[dc].hostLength); - let dcReplicas = replicasByDc[dc] || 0; - //Amount of replicas per dc is greater than rf or the amount of host in the datacenter - if (dcReplicas >= dcRf) { - continue; - } - let racksPlacedInDc = racksPlaced[dc]; - if (!racksPlacedInDc) { - racksPlacedInDc = racksPlaced[dc] = new utils.HashSet(); - } - if (h.rack && - racksPlacedInDc.contains(h.rack) && - racksPlacedInDc.length < datacenters[dc].racks.length) { - // We already selected a replica for this rack - // Skip until replicas in other racks are added - if (skippedHosts.length < dcRf - dcReplicas) { - skippedHosts.push(h); - } - continue; - } - replicasByDc[h.datacenter] = ++dcReplicas; - tokenReplicas.push(h); - if (h.rack && racksPlacedInDc.add(h.rack) && racksPlacedInDc.length === datacenters[dc].racks.length) { - // We finished placing all replicas for all racks in this dc - // Add the skipped hosts - replicasByDc[dc] += addSkippedHosts(dcRf, dcReplicas, tokenReplicas, skippedHosts); - } - if (isDoneForToken(replicationFactors, datacenters, replicasByDc)) { - break; - } - } - replicas[key] = tokenReplicas; - } - return replicas; - }); -} - -/** - * @returns {Number} The number of skipped hosts added. - */ -function addSkippedHosts(dcRf, dcReplicas, tokenReplicas, skippedHosts) { - let i; - for (i = 0; i < dcRf - dcReplicas && i < skippedHosts.length; i++) { - tokenReplicas.push(skippedHosts[i]); - } - return i; -} - -function isDoneForToken(replicationFactors, datacenters, replicasByDc) { - const keys = Object.keys(replicationFactors); - for (let i = 0; i < keys.length; i++) { - const dcName = keys[i]; - const dc = datacenters[dcName]; - if (!dc) { - // A DC is included in the RF but the DC does not exist in the topology - continue; - } - const rf = Math.min(parseInt(replicationFactors[dcName], 10), dc.hostLength); - if (rf > 0 && (!replicasByDc[dcName] || replicasByDc[dcName] < rf)) { - return false; - } - } - return true; -} - -/** - * Creates a new instance if the currentInstance is not valid for the - * provided Cassandra version - * @param {ClientOptions} options The client options - * @param {ControlConnection} cc The control connection to be used - * @param {Function} udtResolver The function to be used to retrieve the udts. - * @param {Array.} [version] The cassandra version - * @param {SchemaParser} [currentInstance] The current instance - * @returns {SchemaParser} - */ -function getByVersion(options, cc, udtResolver, version, currentInstance) { - let parserConstructor = SchemaParserV1; - if (version && version[0] === 3) { - parserConstructor = SchemaParserV2; - } else if (version && version[0] >= 4) { - parserConstructor = SchemaParserV3; - } - if (!currentInstance || !(currentInstance instanceof parserConstructor)){ - return new parserConstructor(options, cc, udtResolver); - } - return currentInstance; -} - -exports.getByVersion = getByVersion; -exports.isDoneForToken = isDoneForToken; \ No newline at end of file diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/metadata/table-metadata.js b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/metadata/table-metadata.js deleted file mode 100644 index 87e171ef2b..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/metadata/table-metadata.js +++ /dev/null @@ -1,77 +0,0 @@ -/* - * Copyright DataStax, Inc. - * - * 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 util = require('util'); -const DataCollection = require('./data-collection'); -/** - * Creates a new instance of TableMetadata - * @classdesc Describes a table - * @param {String} name Name of the Table - * @augments {module:metadata~DataCollection} - * @alias module:metadata~TableMetadata - * @constructor - */ -function TableMetadata(name) { - DataCollection.call(this, name); - /** - * Applies only to counter tables. - * When set to true, replicates writes to all affected replicas regardless of the consistency level specified by - * the client for a write request. For counter tables, this should always be set to true. - * @type {Boolean} - */ - this.replicateOnWrite = true; - /** - * Returns the memtable flush period (in milliseconds) option for this table. - * @type {Number} - */ - this.memtableFlushPeriod = 0; - /** - * Returns the index interval option for this table. - *

- * Note: this option is only available in Apache Cassandra 2.0. It is deprecated in Apache Cassandra 2.1 and - * above, and will therefore return null for 2.1 nodes. - *

- * @type {Number|null} - */ - this.indexInterval = null; - /** - * Determines whether the table uses the COMPACT STORAGE option. - * @type {Boolean} - */ - this.isCompact = false; - /** - * - * @type {Array.} - */ - this.indexes = null; - - /** - * Determines whether the Change Data Capture (CDC) flag is set for the table. - * @type {Boolean|null} - */ - this.cdc = null; - - /** - * Determines whether the table is a virtual table or not. - * @type {Boolean} - */ - this.virtual = false; -} - -util.inherits(TableMetadata, DataCollection); - -module.exports = TableMetadata; \ No newline at end of file diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/metrics/client-metrics.js b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/metrics/client-metrics.js deleted file mode 100644 index 88fe073e2b..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/metrics/client-metrics.js +++ /dev/null @@ -1,129 +0,0 @@ -/* - * Copyright DataStax, Inc. - * - * 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'; - -/** - * Represents a base class that is used to measure events from the server and the client as seen by the driver. - * @alias module:metrics~ClientMetrics - * @interface - */ -class ClientMetrics { - /** - * Method invoked when an authentication error is obtained from the server. - * @param {AuthenticationError|Error} e The error encountered. - */ - onAuthenticationError(e) {} - - /** - * Method invoked when an error (different than a server or client timeout, authentication or connection error) is - * encountered when executing a request. - * @param {OperationTimedOutError} e The timeout error. - */ - onClientTimeoutError(e) {} - - /** - * Method invoked when there is a connection error. - * @param {Error} e The error encountered. - */ - onConnectionError(e) {} - - /** - * Method invoked when an error (different than a server or client timeout, authentication or connection error) is - * encountered when executing a request. - * @param {Error} e The error encountered. - */ - onOtherError(e) {} - - /** - * Method invoked when a read timeout error is obtained from the server. - * @param {ResponseError} e The error encountered. - */ - onReadTimeoutError(e) {} - - /** - * Method invoked when a write timeout error is obtained from the server. - * @param {ResponseError} e The error encountered. - */ - onWriteTimeoutError(e) {} - - /** - * Method invoked when an unavailable error is obtained from the server. - * @param {ResponseError} e The error encountered. - */ - onUnavailableError(e) {} - - /** - * Method invoked when an execution is retried as a result of a client-level timeout. - * @param {Error} e The error that caused the retry. - */ - onClientTimeoutRetry(e) {} - - /** - * Method invoked when an error (other than a server or client timeout) is retried. - * @param {Error} e The error that caused the retry. - */ - onOtherErrorRetry(e) {} - - /** - * Method invoked when an execution is retried as a result of a read timeout from the server (coordinator to replica). - * @param {Error} e The error that caused the retry. - */ - onReadTimeoutRetry(e) {} - - /** - * Method invoked when an execution is retried as a result of an unavailable error from the server. - * @param {Error} e The error that caused the retry. - */ - onUnavailableRetry(e) {} - - /** - * Method invoked when an execution is retried as a result of a write timeout from the server (coordinator to - * replica). - * @param {Error} e The error that caused the retry. - */ - onWriteTimeoutRetry(e) {} - - /** - * Method invoked when an error is marked as ignored by the retry policy. - * @param {Error} e The error that was ignored by the retry policy. - */ - onIgnoreError(e) {} - - /** - * Method invoked when a speculative execution is started. - */ - onSpeculativeExecution() {} - - /** - * Method invoked when a response is obtained successfully. - * @param {Array} latency The latency represented in a [seconds, nanoseconds] tuple - * Array, where nanoseconds is the remaining part of the real time that can't be represented in second precision. - */ - onSuccessfulResponse(latency) {} - - /** - * Method invoked when any response is obtained, the response can be the result of a successful execution or a - * server-side error. - * @param {Array} latency The latency represented in a [seconds, nanoseconds] tuple - * Array, where nanoseconds is the remaining part of the real time that can't be represented in second precision. - */ - onResponse(latency) { - - } -} - -module.exports = ClientMetrics; \ No newline at end of file diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/metrics/default-metrics.js b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/metrics/default-metrics.js deleted file mode 100644 index 1df5dfaecd..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/metrics/default-metrics.js +++ /dev/null @@ -1,198 +0,0 @@ -/* - * Copyright DataStax, Inc. - * - * 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 ClientMetrics = require('./client-metrics'); -const EventEmitter = require('events'); - -/** - * A default implementation of [ClientMetrics]{@link module:metrics~ClientMetrics} that exposes the driver events as - * Node.js events. - *

- * An instance of [DefaultMetrics]{@link module:metrics~DefaultMetrics} is configured by default in the client, - * you can access this instance using [Client#metrics]{@link Client#metrics} property. - *

- * @implements {module:metrics~ClientMetrics} - * @alias module:metrics~DefaultMetrics - * @example Listening to events emitted - * defaultMetrics.errors.on('increment', err => totalErrors++); - * defaultMetrics.errors.clientTimeout.on('increment', () => clientTimeoutErrors++); - * defaultMetrics.speculativeRetries.on('increment', () => specExecsCount++); - * defaultMetrics.responses.on('increment', latency => myHistogram.record(latency)); - */ -class DefaultMetrics extends ClientMetrics { - /** - * Creates a new instance of [DefaultMetrics]{@link module:metrics~DefaultMetrics}. - */ - constructor() { - super(); - - /** - * Emits all the error events. - *

Use each of the properties to measure events of specific errors.

- * @type {EventEmitter} - * @property {EventEmitter} authentication Emits the authentication timeout error events. - * @property {EventEmitter} clientTimeout Emits the client timeout error events. - * @property {EventEmitter} connection Emits the connection error events. - * @property {EventEmitter} readTimeout Emits the read timeout error events obtained from the server. - * @property {EventEmitter} other Emits the error events, that are not part of the other categories. - * @property {EventEmitter} unavailable Emits the unavailable error events obtained from the server. - * @property {EventEmitter} writeTimeout Emits the write timeout error events obtained from the server - */ - this.errors = new EventEmitter(); - this.errors.authentication = new EventEmitter(); - this.errors.clientTimeout = new EventEmitter(); - this.errors.connection = new EventEmitter(); - this.errors.other = new EventEmitter(); - this.errors.readTimeout = new EventEmitter(); - this.errors.unavailable = new EventEmitter(); - this.errors.writeTimeout = new EventEmitter(); - - /** - * Emits all the retry events. - *

Use each of the properties to measure events of specific retries.

- * @type {EventEmitter} - * @property {EventEmitter} clientTimeout Emits when an execution is retried as a result of an client timeout. - * @property {EventEmitter} other Emits the error events, that are not part of the other categories. - * @property {EventEmitter} readTimeout Emits an execution is retried as a result of an read timeout error from the - * server (coordinator to replica). - * @property {EventEmitter} unavailable Emits an execution is retried as a result of an unavailable error from the - * server. - * @property {EventEmitter} writeTimeout Emits an execution is retried as a result of a write timeout error from the - * server (coordinator to replica). - */ - this.retries = new EventEmitter(); - this.retries.clientTimeout = new EventEmitter(); - this.retries.other = new EventEmitter(); - this.retries.readTimeout = new EventEmitter(); - this.retries.unavailable = new EventEmitter(); - this.retries.writeTimeout = new EventEmitter(); - - /** - * Emits events when a speculative execution is started. - * @type {EventEmitter} - */ - this.speculativeExecutions = new EventEmitter(); - - /** - * Emits events when an error is ignored by the retry policy. - * @type {EventEmitter} - */ - this.ignoredErrors = new EventEmitter(); - - /** - * Emits events when a response message is obtained. - * @type {EventEmitter} - * @property {EventEmitter} success Emits when a response was obtained as the result of a successful execution. - */ - this.responses = new EventEmitter(); - this.responses.success = new EventEmitter(); - } - - /** @override */ - onAuthenticationError(e) { - this.errors.authentication.emit('increment', e); - this.errors.emit('increment', e);} - - /** @override */ - onConnectionError(e) { - this.errors.connection.emit('increment', e); - this.errors.emit('increment', e); - } - - /** @override */ - onReadTimeoutError(e) { - this.errors.readTimeout.emit('increment', e); - this.errors.emit('increment', e); - } - - /** @override */ - onWriteTimeoutError(e) { - this.errors.writeTimeout.emit('increment', e); - this.errors.emit('increment', e); - } - - /** @override */ - onUnavailableError(e) { - this.errors.unavailable.emit('increment', e); - this.errors.emit('increment', e); - } - - /** @override */ - onClientTimeoutError(e) { - this.errors.clientTimeout.emit('increment', e); - this.errors.emit('increment', e); - } - - /** @override */ - onOtherError(e) { - this.errors.other.emit('increment', e); - this.errors.emit('increment', e); - } - - /** @override */ - onClientTimeoutRetry(e) { - this.retries.clientTimeout.emit('increment', e); - this.retries.emit('increment', e); - } - - /** @override */ - onOtherErrorRetry(e) { - this.retries.other.emit('increment', e); - this.retries.emit('increment', e); - } - - /** @override */ - onReadTimeoutRetry(e) { - this.retries.readTimeout.emit('increment', e); - this.retries.emit('increment', e); - } - - /** @override */ - onUnavailableRetry(e) { - this.retries.unavailable.emit('increment', e); - this.retries.emit('increment', e); - } - - /** @override */ - onWriteTimeoutRetry(e) { - this.retries.writeTimeout.emit('increment', e); - this.retries.emit('increment', e); - } - - /** @override */ - onIgnoreError(e) { - this.ignoredErrors.emit('increment', e); - } - - /** @override */ - onSpeculativeExecution() { - this.speculativeExecutions.emit('increment'); - } - - /** @override */ - onSuccessfulResponse(latency) { - this.responses.success.emit('increment', latency); - } - - /** @override */ - onResponse(latency) { - this.responses.emit('increment', latency); - } -} - -module.exports = DefaultMetrics; \ No newline at end of file diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/metrics/index.d.ts b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/metrics/index.d.ts deleted file mode 100644 index 4ad80054c3..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/metrics/index.d.ts +++ /dev/null @@ -1,89 +0,0 @@ -/* - * Copyright DataStax, Inc. - * - * 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. - */ - -import { errors } from '../../'; - -export namespace metrics { - interface ClientMetrics { - onAuthenticationError(e: Error | errors.AuthenticationError): void; - - onClientTimeoutError(e: errors.OperationTimedOutError): void; - - onClientTimeoutRetry(e: Error): void; - - onConnectionError(e: Error): void; - - onIgnoreError(e: Error): void; - - onOtherError(e: Error): void; - - onOtherErrorRetry(e: Error): void; - - onReadTimeoutError(e: errors.ResponseError): void; - - onReadTimeoutRetry(e: Error): void; - - onResponse(latency: number[]): void; - - onSpeculativeExecution(): void; - - onSuccessfulResponse(latency: number[]): void; - - onUnavailableError(e: errors.ResponseError): void; - - onUnavailableRetry(e: Error): void; - - onWriteTimeoutError(e: errors.ResponseError): void; - - onWriteTimeoutRetry(e: Error): void; - } - - class DefaultMetrics implements ClientMetrics { - constructor(); - - onAuthenticationError(e: Error | errors.AuthenticationError): void; - - onClientTimeoutError(e: errors.OperationTimedOutError): void; - - onClientTimeoutRetry(e: Error): void; - - onConnectionError(e: Error): void; - - onIgnoreError(e: Error): void; - - onOtherError(e: Error): void; - - onOtherErrorRetry(e: Error): void; - - onReadTimeoutError(e: errors.ResponseError): void; - - onReadTimeoutRetry(e: Error): void; - - onResponse(latency: number[]): void; - - onSpeculativeExecution(): void; - - onSuccessfulResponse(latency: number[]): void; - - onUnavailableError(e: errors.ResponseError): void; - - onUnavailableRetry(e: Error): void; - - onWriteTimeoutError(e: errors.ResponseError): void; - - onWriteTimeoutRetry(e: Error): void; - } -} \ No newline at end of file diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/metrics/index.js b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/metrics/index.js deleted file mode 100644 index 9afb03a05a..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/metrics/index.js +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Copyright DataStax, Inc. - * - * 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 ClientMetrics = require('./client-metrics'); -const DefaultMetrics = require('./default-metrics'); - -/** - * The metrics module contains interfaces and implementations used by the driver to expose - * measurements of its internal behavior and of the server as seen from the driver side. - * @module metrics - */ - -module.exports = { ClientMetrics, DefaultMetrics }; \ No newline at end of file diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/operation-state.js b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/operation-state.js deleted file mode 100644 index 8fe623d1d6..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/operation-state.js +++ /dev/null @@ -1,164 +0,0 @@ -/* - * Copyright DataStax, Inc. - * - * 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 util = require('util'); -const utils = require('./utils'); -const errors = require('./errors'); -const requests = require('./requests'); -const ExecuteRequest = requests.ExecuteRequest; -const QueryRequest = requests.QueryRequest; - -const state = { - init: 0, - completed: 1, - timedOut: 2, - cancelled: 3 -}; - -/** - * Maintains the state information of a request inside a Connection. - */ -class OperationState { - /** - * Creates a new instance of OperationState. - * @param {Request} request - * @param {Function} rowCallback - * @param {Function} callback - */ - constructor(request, rowCallback, callback) { - this.request = request; - this._rowCallback = rowCallback; - this._callback = callback; - this._timeout = null; - this._state = state.init; - this._rowIndex = 0; - /** - * Stream id that is set right before being written. - * @type {number} - */ - this.streamId = -1; - } - - /** - * Marks the operation as cancelled, clearing all callbacks and timeouts. - */ - cancel() { - if (this._state !== state.init) { - return; - } - if (this._timeout !== null) { - clearTimeout(this._timeout); - } - this._state = state.cancelled; - this._callback = utils.noop; - } - - /** - * Determines if the operation can be written to the wire (when it hasn't been cancelled or it hasn't timed out). - */ - canBeWritten() { - return this._state === state.init; - } - - /** - * Determines if the response is going to be yielded by row. - * @return {boolean} - */ - isByRow() { - return this._rowCallback && (this.request instanceof ExecuteRequest || this.request instanceof QueryRequest); - } - - /** - * Creates the timeout for the request. - * @param {ExecutionOptions} execOptions - * @param {Number} defaultReadTimeout - * @param {String} address - * @param {Function} onTimeout The callback to be invoked when it times out. - * @param {Function} onResponse The callback to be invoked if a response is obtained after it timed out. - */ - setRequestTimeout(execOptions, defaultReadTimeout, address, onTimeout, onResponse) { - if (this._state !== state.init) { - // No need to set the timeout - return; - } - const millis = execOptions.getReadTimeout() !== undefined ? execOptions.getReadTimeout() : defaultReadTimeout; - if (!(millis > 0)) { - // Read timeout disabled - return; - } - const self = this; - this._timeout = setTimeout(function requestTimedOut() { - onTimeout(); - const message = util.format('The host %s did not reply before timeout %d ms', address, millis); - self._markAsTimedOut(new errors.OperationTimedOutError(message, address), onResponse); - }, millis); - } - - setResultRow(row, meta, rowLength, flags, header) { - this._markAsCompleted(); - if (!this._rowCallback) { - return this.setResult(new errors.DriverInternalError('RowCallback not found for streaming frame handler')); - } - this._rowCallback(this._rowIndex++, row, rowLength); - if (this._rowIndex === rowLength) { - this._swapCallbackAndInvoke(null, { rowLength: rowLength, meta: meta, flags: flags }, header.bodyLength); - } - } - - /** - * Marks the current operation as timed out. - * @param {Error} err - * @param {Function} onResponse - * @private - */ - _markAsTimedOut(err, onResponse) { - if (this._state !== state.init) { - return; - } - this._state = state.timedOut; - this._swapCallbackAndInvoke(err, null, null, onResponse); - } - - _markAsCompleted() { - if (this._state !== state.init) { - return; - } - if (this._timeout !== null) { - clearTimeout(this._timeout); - } - this._state = state.completed; - } - - /** - * Sets the result of this operation, declaring that no further input will be processed for this operation. - * @param {Error} err - * @param {Object} [result] - * @param {Number} [length] - */ - setResult(err, result, length) { - this._markAsCompleted(); - this._swapCallbackAndInvoke(err, result, length); - } - - _swapCallbackAndInvoke(err, result, length, newCallback) { - const callback = this._callback; - this._callback = newCallback || utils.noop; - callback(err, result, length); - } -} - -module.exports = OperationState; \ No newline at end of file diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/policies/address-resolution.js b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/policies/address-resolution.js deleted file mode 100644 index e0a0fc0be1..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/policies/address-resolution.js +++ /dev/null @@ -1,139 +0,0 @@ -/* - * Copyright DataStax, Inc. - * - * 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 dns = require('dns'); -const util = require('util'); -const utils = require('../utils'); -/** @module policies/addressResolution */ -/** - * @class - * @classdesc - * Translates IP addresses received from Cassandra nodes into locally queryable - * addresses. - *

- * The driver auto-detects new Cassandra nodes added to the cluster through server - * side pushed notifications and through checking the system tables. For each - * node, the address received will correspond to the address set as - * rpc_address in the node yaml file. In most case, this is the correct - * address to use by the driver and that is what is used by default. However, - * sometimes the addresses received through this mechanism will either not be - * reachable directly by the driver or should not be the preferred address to use - * to reach the node (for instance, the rpc_address set on Cassandra nodes - * might be a private IP, but some clients may have to use a public IP, or - * pass by a router to reach that node). This interface allows to deal with - * such cases, by allowing to translate an address as sent by a Cassandra node - * to another address to be used by the driver for connection. - *

- * Please note that the contact points addresses provided while creating the - * {@link Client} instance are not "translated", only IP address retrieve from or sent - * by Cassandra nodes to the driver are. - * @constructor - */ -function AddressTranslator() { - -} - -/** - * Translates a Cassandra rpc_address to another address if necessary. - * @param {String} address the address of a node as returned by Cassandra. - *

- * Note that if the rpc_address of a node has been configured to 0.0.0.0 - * server side, then the provided address will be the node listen_address, - * *not* 0.0.0.0. - *

- * @param {Number} port The port number, as specified in the [protocolOptions]{@link ClientOptions} at Client instance creation (9042 by default). - * @param {Function} callback Callback to invoke with endpoint as first parameter. - * The endpoint is an string composed of the IP address and the port number in the format ipAddress:port. - */ -AddressTranslator.prototype.translate = function (address, port, callback) { - callback(address + ':' + port); -}; - -/** - * @class - * @classdesc - * {@link AddressTranslator} implementation for multi-region EC2 deployments where clients are also deployed in EC2. - *

- * Its distinctive feature is that it translates addresses according to the location of the Cassandra host: - *

- *
    - *
  • addresses in different EC2 regions (than the client) are unchanged
  • - *
  • addresses in the same EC2 region are translated to private IPs
  • - *
- *

- * This optimizes network costs, because Amazon charges more for communication over public IPs. - *

- * @constructor - */ -function EC2MultiRegionTranslator() { - -} - -util.inherits(EC2MultiRegionTranslator, AddressTranslator); - -/** - * Addresses in the same EC2 region are translated to private IPs and addresses in - * different EC2 regions (than the client) are unchanged - */ -EC2MultiRegionTranslator.prototype.translate = function (address, port, callback) { - let newAddress = address; - const self = this; - let name; - utils.series([ - function resolve(next) { - dns.reverse(address, function (err, hostNames) { - if (err) { - return next(err); - } - if (!hostNames) { - return next(); - } - name = hostNames[0]; - next(); - }); - }, - function lookup(next) { - if (!name) { - return next(); - } - dns.lookup(name, function (err, lookupAddress) { - if (err) { - return next(err); - } - newAddress = lookupAddress; - next(); - }); - }], function (err) { - if (err) { - //there was an issue while doing dns resolution - self.logError(address, err); - } - callback(newAddress + ':' + port); - }); -}; - -/** - * Log method called to log errors that occurred while performing dns resolution. - * You can assign your own method to the class instance to do proper logging. - * @param {String} address - * @param {Error} err - */ -EC2MultiRegionTranslator.prototype.logError = function (address, err) { - //Do nothing by default -}; - -exports.AddressTranslator = AddressTranslator; -exports.EC2MultiRegionTranslator = EC2MultiRegionTranslator; \ No newline at end of file diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/policies/index.d.ts b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/policies/index.d.ts deleted file mode 100644 index ffae185be5..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/policies/index.d.ts +++ /dev/null @@ -1,210 +0,0 @@ -/* - * Copyright DataStax, Inc. - * - * 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. - */ - -import { Client, EmptyCallback, ExecutionOptions, Host, HostMap } from '../../'; -import { types } from '../types'; - - -export namespace policies { - function defaultAddressTranslator(): addressResolution.AddressTranslator; - - function defaultLoadBalancingPolicy(localDc?: string): loadBalancing.LoadBalancingPolicy; - - function defaultReconnectionPolicy(): reconnection.ReconnectionPolicy; - - function defaultRetryPolicy(): retry.RetryPolicy; - - function defaultSpeculativeExecutionPolicy(): speculativeExecution.SpeculativeExecutionPolicy; - - function defaultTimestampGenerator(): timestampGeneration.TimestampGenerator; - - namespace addressResolution { - interface AddressTranslator { - translate(address: string, port: number, callback: Function): void; - } - - class EC2MultiRegionTranslator implements AddressTranslator { - translate(address: string, port: number, callback: Function): void; - } - } - - namespace loadBalancing { - abstract class LoadBalancingPolicy { - init(client: Client, hosts: HostMap, callback: EmptyCallback): void; - - getDistance(host: Host): types.distance; - - newQueryPlan( - keyspace: string, - executionOptions: ExecutionOptions, - callback: (error: Error, iterator: Iterator) => void): void; - - getOptions(): Map; - } - - class DCAwareRoundRobinPolicy extends LoadBalancingPolicy { - constructor(localDc: string); - } - - class TokenAwarePolicy extends LoadBalancingPolicy { - constructor(childPolicy: LoadBalancingPolicy); - } - - class AllowListPolicy extends LoadBalancingPolicy { - constructor(childPolicy: LoadBalancingPolicy, allowList: string[]); - } - - class WhiteListPolicy extends AllowListPolicy { - } - - class RoundRobinPolicy extends LoadBalancingPolicy { - constructor(); - } - - class DefaultLoadBalancingPolicy extends LoadBalancingPolicy { - constructor(options?: { localDc?: string, filter?: (host: Host) => boolean }); - } - } - - namespace reconnection { - class ConstantReconnectionPolicy implements ReconnectionPolicy { - constructor(delay: number); - - getOptions(): Map; - - newSchedule(): Iterator; - - } - - class ExponentialReconnectionPolicy implements ReconnectionPolicy { - constructor(baseDelay: number, maxDelay: number, startWithNoDelay?: boolean); - - getOptions(): Map; - - newSchedule(): Iterator; - } - - interface ReconnectionPolicy { - getOptions(): Map; - - newSchedule(): Iterator; - } - } - - namespace retry { - class DecisionInfo { - decision: number; - consistency: types.consistencies; - } - - class OperationInfo { - query: string; - executionOptions: ExecutionOptions; - nbRetry: number; - } - - class IdempotenceAwareRetryPolicy extends RetryPolicy { - constructor(childPolicy: RetryPolicy); - } - - class FallthroughRetryPolicy extends RetryPolicy { - constructor(); - } - - class RetryPolicy { - onReadTimeout( - info: OperationInfo, - consistency: types.consistencies, - received: number, - blockFor: number, - isDataPresent: boolean): DecisionInfo; - - onRequestError(info: OperationInfo, consistency: types.consistencies, err: Error): DecisionInfo; - - onUnavailable( - info: OperationInfo, consistency: types.consistencies, required: number, alive: boolean): DecisionInfo; - - onWriteTimeout( - info: OperationInfo, - consistency: types.consistencies, - received: number, - blockFor: number, - writeType: string): DecisionInfo; - - rethrowResult(): DecisionInfo; - - retryResult(consistency: types.consistencies, useCurrentHost?: boolean): DecisionInfo; - } - - namespace RetryDecision { - enum retryDecision { - ignore, - rethrow, - retry - } - } - } - - namespace speculativeExecution { - class ConstantSpeculativeExecutionPolicy implements SpeculativeExecutionPolicy { - constructor(delay: number, maxSpeculativeExecutions: number); - - getOptions(): Map; - - init(client: Client): void; - - newPlan(keyspace: string, queryInfo: string | Array): { nextExecution: Function }; - - shutdown(): void; - } - - class NoSpeculativeExecutionPolicy implements SpeculativeExecutionPolicy { - constructor(); - - getOptions(): Map; - - init(client: Client): void; - - newPlan(keyspace: string, queryInfo: string | Array): { nextExecution: Function }; - - shutdown(): void; - } - - interface SpeculativeExecutionPolicy { - getOptions(): Map; - - init(client: Client): void; - - newPlan(keyspace: string, queryInfo: string|Array): { nextExecution: Function }; - - shutdown(): void; - } - } - - namespace timestampGeneration { - class MonotonicTimestampGenerator implements TimestampGenerator { - constructor(warningThreshold: number, minLogInterval: number); - - getDate(): number; - - next(client: Client): types.Long | number; - } - - interface TimestampGenerator { - next(client: Client): types.Long|number; - } - } -} \ No newline at end of file diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/policies/index.js b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/policies/index.js deleted file mode 100644 index 9590d6b57d..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/policies/index.js +++ /dev/null @@ -1,84 +0,0 @@ -/* - * Copyright DataStax, Inc. - * - * 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'; - -/** - * Contains driver tuning policies to determine [load balancing]{@link module:policies/loadBalancing}, - * [retrying]{@link module:policies/retry} queries, [reconnecting]{@link module:policies/reconnection} to a node, - * [address resolution]{@link module:policies/addressResolution}, - * [timestamp generation]{@link module:policies/timestampGeneration} and - * [speculative execution]{@link module:policies/speculativeExecution}. - * @module policies - */ -const addressResolution = exports.addressResolution = require('./address-resolution'); -const loadBalancing = exports.loadBalancing = require('./load-balancing'); -const reconnection = exports.reconnection = require('./reconnection'); -const retry = exports.retry = require('./retry'); -const speculativeExecution = exports.speculativeExecution = require('./speculative-execution'); -const timestampGeneration = exports.timestampGeneration = require('./timestamp-generation'); - -/** - * Returns a new instance of the default address translator policy used by the driver. - * @returns {AddressTranslator} - */ -exports.defaultAddressTranslator = function () { - return new addressResolution.AddressTranslator(); -}; - -/** - * Returns a new instance of the default load-balancing policy used by the driver. - * @param {string} [localDc] When provided, it sets the data center that is going to be used as local for the - * load-balancing policy instance. - *

When localDc is undefined, the load-balancing policy instance will use the localDataCenter - * provided in the {@link ClientOptions}.

- * @returns {LoadBalancingPolicy} - */ -exports.defaultLoadBalancingPolicy = function (localDc) { - return new loadBalancing.DefaultLoadBalancingPolicy(localDc); -}; - -/** - * Returns a new instance of the default retry policy used by the driver. - * @returns {RetryPolicy} - */ -exports.defaultRetryPolicy = function () { - return new retry.RetryPolicy(); -}; - -/** - * Returns a new instance of the default reconnection policy used by the driver. - * @returns {ReconnectionPolicy} - */ -exports.defaultReconnectionPolicy = function () { - return new reconnection.ExponentialReconnectionPolicy(1000, 10 * 60 * 1000, false); -}; - - -/** - * Returns a new instance of the default speculative execution policy used by the driver. - * @returns {SpeculativeExecutionPolicy} - */ -exports.defaultSpeculativeExecutionPolicy = function () { - return new speculativeExecution.NoSpeculativeExecutionPolicy(); -}; - -/** - * Returns a new instance of the default timestamp generator used by the driver. - * @returns {TimestampGenerator} - */ -exports.defaultTimestampGenerator = function () { - return new timestampGeneration.MonotonicTimestampGenerator(); -}; diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/policies/load-balancing.js b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/policies/load-balancing.js deleted file mode 100644 index de56e0d5c3..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/policies/load-balancing.js +++ /dev/null @@ -1,883 +0,0 @@ -/* - * Copyright DataStax, Inc. - * - * 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 util = require('util'); -const types = require('../types'); -const utils = require('../utils.js'); -const errors = require('../errors.js'); - -const doneIteratorObject = Object.freeze({ done: true }); -const newlyUpInterval = 60000; - -/** @module policies/loadBalancing */ -/** - * Base class for Load Balancing Policies - * @constructor - */ -function LoadBalancingPolicy() { - -} - -/** - * Initializes the load balancing policy, called after the driver obtained the information of the cluster. - * @param {Client} client - * @param {HostMap} hosts - * @param {Function} callback - */ -LoadBalancingPolicy.prototype.init = function (client, hosts, callback) { - this.client = client; - this.hosts = hosts; - callback(); -}; - -/** - * Returns the distance assigned by this policy to the provided host. - * @param {Host} host - */ -LoadBalancingPolicy.prototype.getDistance = function (host) { - return types.distance.local; -}; - -/** - * Returns an iterator with the hosts for a new query. - * Each new query will call this method. The first host in the result will - * then be used to perform the query. - * @param {String} keyspace Name of currently logged keyspace at Client level. - * @param {ExecutionOptions|null} executionOptions The information related to the execution of the request. - * @param {Function} callback The function to be invoked with the error as first parameter and the host iterator as - * second parameter. - */ -LoadBalancingPolicy.prototype.newQueryPlan = function (keyspace, executionOptions, callback) { - callback(new Error('You must implement a query plan for the LoadBalancingPolicy class')); -}; - -/** - * Gets an associative array containing the policy options. - */ -LoadBalancingPolicy.prototype.getOptions = function () { - return new Map(); -}; - -/** - * This policy yield nodes in a round-robin fashion. - * @extends LoadBalancingPolicy - * @constructor - */ -function RoundRobinPolicy() { - this.index = 0; -} - -util.inherits(RoundRobinPolicy, LoadBalancingPolicy); - -/** - * Returns an iterator with the hosts to be used as coordinator for a query. - * @param {String} keyspace Name of currently logged keyspace at Client level. - * @param {ExecutionOptions|null} executionOptions The information related to the execution of the request. - * @param {Function} callback The function to be invoked with the error as first parameter and the host iterator as - * second parameter. - */ -RoundRobinPolicy.prototype.newQueryPlan = function (keyspace, executionOptions, callback) { - if (!this.hosts) { - return callback(new Error('Load balancing policy not initialized')); - } - const hosts = this.hosts.values(); - const self = this; - let counter = 0; - - let planIndex = self.index % hosts.length; - self.index += 1; - if (self.index >= utils.maxInt) { - self.index = 0; - } - - callback(null, { - next: function () { - if (++counter > hosts.length) { - return doneIteratorObject; - } - return {value: hosts[planIndex++ % hosts.length], done: false}; - } - }); -}; - -/** - * A data-center aware Round-robin load balancing policy. - * This policy provides round-robin queries over the nodes of the local - * data center. - * @param {?String} [localDc] local datacenter name. This value overrides the 'localDataCenter' Client option \ - * and is useful for cases where you have multiple execution profiles that you intend on using for routing - * requests to different data centers. - * @extends {LoadBalancingPolicy} - * @constructor - */ -function DCAwareRoundRobinPolicy(localDc) { - this.localDc = localDc; - this.index = 0; - /** @type {Array} */ - this.localHostsArray = null; -} - -util.inherits(DCAwareRoundRobinPolicy, LoadBalancingPolicy); - -/** - * Initializes the load balancing policy. - * @param {Client} client - * @param {HostMap} hosts - * @param {Function} callback - */ -DCAwareRoundRobinPolicy.prototype.init = function (client, hosts, callback) { - this.client = client; - this.hosts = hosts; - hosts.on('add', this._cleanHostCache.bind(this)); - hosts.on('remove', this._cleanHostCache.bind(this)); - - try { - setLocalDc(this, client, this.hosts); - } catch (err) { - return callback(err); - } - - callback(); -}; - -/** - * Returns the distance depending on the datacenter. - * @param {Host} host - */ -DCAwareRoundRobinPolicy.prototype.getDistance = function (host) { - if (host.datacenter === this.localDc) { - return types.distance.local; - } - - return types.distance.ignored; -}; - -DCAwareRoundRobinPolicy.prototype._cleanHostCache = function () { - this.localHostsArray = null; -}; - -DCAwareRoundRobinPolicy.prototype._resolveLocalHosts = function() { - const hosts = this.hosts.values(); - if (this.localHostsArray) { - //there were already calculated - return; - } - this.localHostsArray = []; - hosts.forEach(function (h) { - if (!h.datacenter) { - //not a remote dc node - return; - } - if (h.datacenter === this.localDc) { - this.localHostsArray.push(h); - } - }, this); -}; - -/** - * It returns an iterator that yields local nodes. - * @param {String} keyspace Name of currently logged keyspace at Client level. - * @param {ExecutionOptions|null} executionOptions The information related to the execution of the request. - * @param {Function} callback The function to be invoked with the error as first parameter and the host iterator as - * second parameter. - */ -DCAwareRoundRobinPolicy.prototype.newQueryPlan = function (keyspace, executionOptions, callback) { - if (!this.hosts) { - return callback(new Error('Load balancing policy not initialized')); - } - this.index += 1; - if (this.index >= utils.maxInt) { - this.index = 0; - } - this._resolveLocalHosts(); - // Use a local reference of hosts - const localHostsArray = this.localHostsArray; - let planLocalIndex = this.index; - let counter = 0; - callback(null, { - next: function () { - let host; - if (counter++ < localHostsArray.length) { - host = localHostsArray[planLocalIndex++ % localHostsArray.length]; - return { value: host, done: false }; - } - return doneIteratorObject; - } - }); -}; - -/** - * Gets an associative array containing the policy options. - */ -DCAwareRoundRobinPolicy.prototype.getOptions = function () { - return new Map([ - ['localDataCenter', this.localDc ] - ]); -}; - -/** - * A wrapper load balancing policy that add token awareness to a child policy. - * @param {LoadBalancingPolicy} childPolicy - * @extends LoadBalancingPolicy - * @constructor - */ -function TokenAwarePolicy (childPolicy) { - if (!childPolicy) { - throw new Error("You must specify a child load balancing policy"); - } - this.childPolicy = childPolicy; -} - -util.inherits(TokenAwarePolicy, LoadBalancingPolicy); - -TokenAwarePolicy.prototype.init = function (client, hosts, callback) { - this.client = client; - this.hosts = hosts; - this.childPolicy.init(client, hosts, callback); -}; - -TokenAwarePolicy.prototype.getDistance = function (host) { - return this.childPolicy.getDistance(host); -}; - -/** - * Returns the hosts to use for a new query. - * The returned plan will return local replicas first, if replicas can be determined, followed by the plan of the - * child policy. - * @param {String} keyspace Name of currently logged keyspace at Client level. - * @param {ExecutionOptions|null} executionOptions The information related to the execution of the request. - * @param {Function} callback The function to be invoked with the error as first parameter and the host iterator as - * second parameter. - */ -TokenAwarePolicy.prototype.newQueryPlan = function (keyspace, executionOptions, callback) { - let routingKey; - if (executionOptions) { - routingKey = executionOptions.getRoutingKey(); - if (executionOptions.getKeyspace()) { - keyspace = executionOptions.getKeyspace(); - } - } - let replicas; - if (routingKey) { - replicas = this.client.getReplicas(keyspace, routingKey); - } - if (!routingKey || !replicas) { - return this.childPolicy.newQueryPlan(keyspace, executionOptions, callback); - } - const iterator = new TokenAwareIterator(keyspace, executionOptions, replicas, this.childPolicy); - iterator.iterate(callback); -}; - -/** - * An iterator that holds the context for the subsequent next() calls - * @param {String} keyspace - * @param {ExecutionOptions} execOptions - * @param {Array} replicas - * @param childPolicy - * @constructor - * @ignore - */ -function TokenAwareIterator(keyspace, execOptions, replicas, childPolicy) { - this.keyspace = keyspace; - this.childPolicy = childPolicy; - this.options = execOptions; - this.localReplicas = []; - this.replicaIndex = 0; - this.replicaMap = {}; - this.childIterator = null; - // Memoize the local replicas - // The amount of local replicas should be defined before start iterating, in order to select an - // appropriate (pseudo random) startIndex - for (let i = 0; i < replicas.length; i++) { - const host = replicas[i]; - if (this.childPolicy.getDistance(host) !== types.distance.local) { - continue; - } - this.replicaMap[host.address] = true; - this.localReplicas.push(host); - } - // We use a PRNG to set the replica index - // We only care about proportional fair scheduling between replicas of a given token - // Math.random() has an extremely short permutation cycle length but we don't care about collisions - this.startIndex = Math.floor(Math.random() * this.localReplicas.length); -} - -TokenAwareIterator.prototype.iterate = function (callback) { - //Load the child policy hosts - const self = this; - this.childPolicy.newQueryPlan(this.keyspace, this.options, function (err, iterator) { - if (err) { - return callback(err); - } - //get the iterator of the child policy in case is needed - self.childIterator = iterator; - callback(null, { - next: function () { return self.computeNext(); } - }); - }); -}; - -TokenAwareIterator.prototype.computeNext = function () { - let host; - if (this.replicaIndex < this.localReplicas.length) { - host = this.localReplicas[(this.startIndex + (this.replicaIndex++)) % this.localReplicas.length]; - return { value: host, done: false }; - } - // Return hosts from child policy - let item; - while ((item = this.childIterator.next()) && !item.done) { - if (this.replicaMap[item.value.address]) { - // Avoid yielding local replicas from the child load balancing policy query plan - continue; - } - return item; - } - return doneIteratorObject; -}; - -/** - * Gets an associative array containing the policy options. - */ -TokenAwarePolicy.prototype.getOptions = function () { - const map = new Map([ - ['childPolicy', this.childPolicy.constructor !== undefined ? this.childPolicy.constructor.name : null ] - ]); - - if (this.childPolicy instanceof DCAwareRoundRobinPolicy) { - map.set('localDataCenter', this.childPolicy.localDc); - } - - return map; -}; - -/** - * Create a new policy that wraps the provided child policy but only "allow" hosts - * from the provided list. - * @class - * @classdesc - * A load balancing policy wrapper that ensure that only hosts from a provided - * allow list will ever be returned. - *

- * This policy wraps another load balancing policy and will delegate the choice - * of hosts to the wrapped policy with the exception that only hosts contained - * in the allow list provided when constructing this policy will ever be - * returned. Any host not in the while list will be considered ignored - * and thus will not be connected to. - *

- * This policy can be useful to ensure that the driver only connects to a - * predefined set of hosts. Keep in mind however that this policy defeats - * somewhat the host auto-detection of the driver. As such, this policy is only - * useful in a few special cases or for testing, but is not optimal in general. - * If all you want to do is limiting connections to hosts of the local - * data-center then you should use DCAwareRoundRobinPolicy and *not* this policy - * in particular. - * @param {LoadBalancingPolicy} childPolicy the wrapped policy. - * @param {Array.} allowList The hosts address in the format ipAddress:port. - * Only hosts from this list may get connected - * to (whether they will get connected to or not depends on the child policy). - * @extends LoadBalancingPolicy - * @constructor - */ -function AllowListPolicy (childPolicy, allowList) { - if (!childPolicy) { - throw new Error("You must specify a child load balancing policy"); - } - if (!Array.isArray(allowList)) { - throw new Error("You must provide the list of allowed host addresses"); - } - - this.childPolicy = childPolicy; - this.allowList = new Map(allowList.map(address => [ address, true ])); -} - -util.inherits(AllowListPolicy, LoadBalancingPolicy); - -AllowListPolicy.prototype.init = function (client, hosts, callback) { - this.childPolicy.init(client, hosts, callback); -}; - -/** - * Uses the child policy to return the distance to the host if included in the allow list. - * Any host not in the while list will be considered ignored. - * @param host - */ -AllowListPolicy.prototype.getDistance = function (host) { - if (!this._contains(host)) { - return types.distance.ignored; - } - return this.childPolicy.getDistance(host); -}; - -/** - * @param {Host} host - * @returns {boolean} - * @private - */ -AllowListPolicy.prototype._contains = function (host) { - return !!this.allowList.get(host.address); -}; - -/** - * Returns the hosts to use for a new query filtered by the allow list. - */ -AllowListPolicy.prototype.newQueryPlan = function (keyspace, info, callback) { - const self = this; - this.childPolicy.newQueryPlan(keyspace, info, function (err, iterator) { - if (err) { - return callback(err); - } - callback(null, self._filter(iterator)); - }); -}; - -AllowListPolicy.prototype._filter = function (childIterator) { - const self = this; - return { - next: function () { - const item = childIterator.next(); - if (!item.done && !self._contains(item.value)) { - return this.next(); - } - return item; - } - }; -}; - -/** - * Gets an associative array containing the policy options. - */ -AllowListPolicy.prototype.getOptions = function () { - return new Map([ - ['childPolicy', this.childPolicy.constructor !== undefined ? this.childPolicy.constructor.name : null ], - ['allowList', Array.from(this.allowList.keys())] - ]); -}; - -/** - * Creates a new instance of the policy. - * @classdesc - * Exposed for backward-compatibility only, it's recommended that you use {@link AllowListPolicy} instead. - * @param {LoadBalancingPolicy} childPolicy the wrapped policy. - * @param {Array.} allowList The hosts address in the format ipAddress:port. - * Only hosts from this list may get connected to (whether they will get connected to or not depends on the child - * policy). - * @extends AllowListPolicy - * @deprecated Use allow-list instead. It will be removed in future major versions. - * @constructor - */ -function WhiteListPolicy(childPolicy, allowList) { - AllowListPolicy.call(this, childPolicy, allowList); -} - -util.inherits(WhiteListPolicy, AllowListPolicy); - -/** - * A load-balancing policy implementation that attempts to fairly distribute the load based on the amount of in-flight - * request per hosts. The local replicas are initially shuffled and - * between the first two nodes in the - * shuffled list, the one with fewer in-flight requests is selected as coordinator. - * - *

- * Additionally, it detects unresponsive replicas and reorders them at the back of the query plan. - *

- * - *

- * For graph analytics queries, it uses the preferred analytics graph server previously obtained by driver as first - * host in the query plan. - *

- */ -class DefaultLoadBalancingPolicy extends LoadBalancingPolicy { - - /** - * Creates a new instance of DefaultLoadBalancingPolicy. - * @param {String|Object} [options] The local data center name or the optional policy options object. - *

- * Note that when providing the local data center name, it overrides localDataCenter option at - * Client level. - *

- * @param {String} [options.localDc] local data center name. This value overrides the 'localDataCenter' Client option - * and is useful for cases where you have multiple execution profiles that you intend on using for routing - * requests to different data centers. - * @param {Function} [options.filter] A function to apply to determine if hosts are included in the query plan. - * The function takes a Host parameter and returns a Boolean. - */ - constructor(options) { - super(); - - if (typeof options === 'string') { - options = { localDc: options }; - } else if (!options) { - options = utils.emptyObject; - } - - this._client = null; - this._hosts = null; - this._filteredHosts = null; - this._preferredHost = null; - this._index = 0; - this.localDc = options.localDc; - this._filter = options.filter || this._defaultFilter; - - // Allow some checks to be injected - if (options.isHostNewlyUp) { - this._isHostNewlyUp = options.isHostNewlyUp; - } - if (options.healthCheck) { - this._healthCheck = options.healthCheck; - } - if (options.compare) { - this._compare = options.compare; - } - if (options.getReplicas) { - this._getReplicas = options.getReplicas; - } - } - - /** - * Initializes the load balancing policy, called after the driver obtained the information of the cluster. - * @param {Client} client - * @param {HostMap} hosts - * @param {Function} callback - */ - init(client, hosts, callback) { - this._client = client; - this._hosts = hosts; - - // Clean local host cache - this._hosts.on('add', () => this._filteredHosts = null); - this._hosts.on('remove', () => this._filteredHosts = null); - - try { - setLocalDc(this, client, this._hosts); - } catch (err) { - return callback(err); - } - - callback(); - } - - /** - * Returns the distance assigned by this policy to the provided host, relatively to the client instance. - * @param {Host} host - */ - getDistance(host) { - if (this._preferredHost !== null && host === this._preferredHost) { - // Set the last preferred host as local. - // It ensures that the pool for the graph analytics host has the appropriate size - return types.distance.local; - } - - if (!this._filter(host)) { - return types.distance.ignored; - } - - return host.datacenter === this.localDc ? types.distance.local : types.distance.ignored; - } - - /** - * Returns a host iterator to be used for a query execution. - * @override - * @param {String} keyspace - * @param {ExecutionOptions} executionOptions - * @param {Function} callback - */ - newQueryPlan(keyspace, executionOptions, callback) { - let routingKey; - let preferredHost; - - if (executionOptions) { - routingKey = executionOptions.getRoutingKey(); - - if (executionOptions.getKeyspace()) { - keyspace = executionOptions.getKeyspace(); - } - - preferredHost = executionOptions.getPreferredHost(); - } - - let iterable; - - if (!keyspace || !routingKey) { - iterable = this._getLocalHosts(); - } else { - iterable = this._getReplicasAndLocalHosts(keyspace, routingKey); - } - - if (preferredHost) { - // Set it on an instance level field to set the distance - this._preferredHost = preferredHost; - iterable = DefaultLoadBalancingPolicy._getPreferredHostFirst(preferredHost, iterable); - } - - return callback(null, iterable); - } - - /** - * Yields the preferred host first, followed by the host in the provided iterable - * @param preferredHost - * @param iterable - * @private - */ - static *_getPreferredHostFirst(preferredHost, iterable) { - yield preferredHost; - - for (const host of iterable) { - if (host !== preferredHost) { - yield host; - } - } - } - - /** - * Yields the local hosts without the replicas already yielded - * @param {Array} [localReplicas] The local replicas that we should avoid to include again - * @private - */ - *_getLocalHosts(localReplicas) { - // Use a local reference - const hosts = this._getFilteredLocalHosts(); - const initialIndex = this._getIndex(); - - // indexOf() over an Array is a O(n) operation but given that there should be 3 to 7 replicas, - // it shouldn't be an expensive call. Additionally, this will only be executed when the local replicas - // have been exhausted in a lazy manner. - const canBeYield = localReplicas - ? h => localReplicas.indexOf(h) === -1 - : h => true; - - for (let i = 0; i < hosts.length; i++) { - const h = hosts[(i + initialIndex) % hosts.length]; - if (canBeYield(h) && h.isUp()) { - yield h; - } - } - } - - _getReplicasAndLocalHosts(keyspace, routingKey) { - let replicas = this._getReplicas(keyspace, routingKey); - if (replicas === null) { - return this._getLocalHosts(); - } - - const filteredReplicas = []; - let newlyUpReplica = null; - let newlyUpReplicaTimestamp = Number.MIN_SAFE_INTEGER; - let unhealthyReplicas = 0; - - // Filter by DC, predicate and UP replicas - // Use the same iteration to perform other checks: whether if its newly UP or unhealthy - // As this is part of the hot path, we use a simple loop and avoid using Array.prototype.filter() + closure - for (let i = 0; i < replicas.length; i++) { - const h = replicas[i]; - if (!this._filter(h) || h.datacenter !== this.localDc || !h.isUp()) { - continue; - } - const isUpSince = this._isHostNewlyUp(h); - if (isUpSince !== null && isUpSince > newlyUpReplicaTimestamp) { - newlyUpReplica = h; - newlyUpReplicaTimestamp = isUpSince; - } - if (newlyUpReplica === null && !this._healthCheck(h)) { - unhealthyReplicas++; - } - filteredReplicas.push(h); - } - - replicas = filteredReplicas; - - // Shuffle remaining local replicas - utils.shuffleArray(replicas); - - if (replicas.length < 3) { - // Avoid reordering replicas of a set of 2 as we could be doing more harm than good - return this.yieldReplicasFirst(replicas); - } - - let temp; - - if (newlyUpReplica === null) { - if (unhealthyReplicas > 0 && unhealthyReplicas < Math.floor(replicas.length / 2 + 1)) { - // There is one or more unhealthy replicas and there is a majority of healthy replicas - this._sendUnhealthyToTheBack(replicas, unhealthyReplicas); - } - } - else if ((newlyUpReplica === replicas[0] || newlyUpReplica === replicas[1]) && Math.random() * 4 >= 1) { - // There is a newly UP replica and the replica in first or second position is the most recent replica - // marked as UP and dice roll 1d4!=1 -> Send it to the back of the Array - const index = newlyUpReplica === replicas[0] ? 0 : 1; - temp = replicas[replicas.length - 1]; - replicas[replicas.length - 1] = replicas[index]; - replicas[index] = temp; - } - - if (this._compare(replicas[1], replicas[0]) > 0) { - // Power of two random choices - temp = replicas[0]; - replicas[0] = replicas[1]; - replicas[1] = temp; - } - - return this.yieldReplicasFirst(replicas); - } - - /** - * Yields the local replicas followed by the rest of local nodes. - * @param {Array} replicas The local replicas - */ - *yieldReplicasFirst(replicas) { - for (let i = 0; i < replicas.length; i++) { - yield replicas[i]; - } - yield* this._getLocalHosts(replicas); - } - - _isHostNewlyUp(h) { - return (h.isUpSince !== null && Date.now() - h.isUpSince < newlyUpInterval) ? h.isUpSince : null; - } - - /** - * Returns a boolean determining whether the host health is ok or not. - * A Host is considered unhealthy when there are enough items in the queue (10 items in-flight) but the - * Host is not responding to those requests. - * @param {Host} h - * @return {boolean} - * @private - */ - _healthCheck(h) { - return !(h.getInFlight() >= 10 && h.getResponseCount() <= 1); - } - - /** - * Compares to host and returns 1 if it needs to favor the first host otherwise, -1. - * @return {number} - * @private - */ - _compare(h1, h2) { - return h1.getInFlight() < h2.getInFlight() ? 1 : -1; - } - - _getReplicas(keyspace, routingKey) { - return this._client.getReplicas(keyspace, routingKey); - } - - /** - * Returns an Array of hosts filtered by DC and predicate. - * @returns {Array} - * @private - */ - _getFilteredLocalHosts() { - if (this._filteredHosts === null) { - this._filteredHosts = this._hosts.values() - .filter(h => this._filter(h) && h.datacenter === this.localDc); - } - return this._filteredHosts; - } - - _getIndex() { - const result = this._index++; - // Overflow protection - if (this._index === 0x7fffffff) { - this._index = 0; - } - return result; - } - - _sendUnhealthyToTheBack(replicas, unhealthyReplicas) { - let counter = 0; - - // Start from the back, move backwards and stop once all unhealthy replicas are at the back - for (let i = replicas.length - 1; i >= 0 && counter < unhealthyReplicas; i--) { - const host = replicas[i]; - if (this._healthCheck(host)) { - continue; - } - - const targetIndex = replicas.length - 1 - counter; - if (targetIndex !== i) { - const temp = replicas[targetIndex]; - replicas[targetIndex] = host; - replicas[i] = temp; - } - counter++; - } - } - - _defaultFilter() { - return true; - } - - /** - * Gets an associative array containing the policy options. - */ - getOptions() { - return new Map([ - ['localDataCenter', this.localDc ], - ['filterFunction', this._filter !== this._defaultFilter ] - ]); - } -} - -/** - * Validates and sets the local data center to be used. - * @param {LoadBalancingPolicy} lbp - * @param {Client} client - * @param {HostMap} hosts - * @private - */ -function setLocalDc(lbp, client, hosts) { - if (!(lbp instanceof LoadBalancingPolicy)) { - throw new errors.DriverInternalError('LoadBalancingPolicy instance was not provided'); - } - - if (client && client.options) { - if (lbp.localDc && !client.options.localDataCenter) { - client.log('info', `Local data center '${lbp.localDc}' was provided as an argument to the load-balancing` + - ` policy. It is preferable to specify the local data center using 'localDataCenter' in Client` + - ` options instead when your application is targeting a single data center.`); - } - - // If localDc is unset, use value set in client options. - lbp.localDc = lbp.localDc || client.options.localDataCenter; - } - - const dcs = getDataCenters(hosts); - - if (!lbp.localDc) { - throw new errors.ArgumentError( - `'localDataCenter' is not defined in Client options and also was not specified in constructor.` + - ` At least one is required. Available DCs are: [${Array.from(dcs)}]`); - } - - if (!dcs.has(lbp.localDc)) { - throw new errors.ArgumentError(`Datacenter ${lbp.localDc} was not found. Available DCs are: [${Array.from(dcs)}]`); - } -} - -function getDataCenters(hosts) { - return new Set(hosts.values().map(h => h.datacenter)); -} - -module.exports = { - AllowListPolicy, - DCAwareRoundRobinPolicy, - DefaultLoadBalancingPolicy, - LoadBalancingPolicy, - RoundRobinPolicy, - TokenAwarePolicy, - // Deprecated: for backward compatibility only. - WhiteListPolicy -}; \ No newline at end of file diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/policies/reconnection.js b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/policies/reconnection.js deleted file mode 100644 index fa6a899adb..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/policies/reconnection.js +++ /dev/null @@ -1,157 +0,0 @@ -/* - * Copyright DataStax, Inc. - * - * 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 util = require('util'); - -/** @module policies/reconnection */ -/** - * Base class for Reconnection Policies - * @constructor - */ -function ReconnectionPolicy() { - -} - -/** - * A new reconnection schedule. - * @returns {{next: function}} An infinite iterator - */ -ReconnectionPolicy.prototype.newSchedule = function () { - throw new Error('You must implement a new schedule for the Reconnection class'); -}; - -/** - * Gets an associative array containing the policy options. - */ -ReconnectionPolicy.prototype.getOptions = function () { - return new Map(); -}; - -/** - * A reconnection policy that waits a constant time between each reconnection attempt. - * @param {Number} delay Delay in ms - * @constructor - */ -function ConstantReconnectionPolicy(delay) { - this.delay = delay; -} - -util.inherits(ConstantReconnectionPolicy, ReconnectionPolicy); - -/** - * A new reconnection schedule that returns the same next delay value - * @returns {{next: Function}} An infinite iterator - */ -ConstantReconnectionPolicy.prototype.newSchedule = function () { - const self = this; - return { - next: function () { - return {value: self.delay, done: false}; - } - }; -}; - -/** - * Gets an associative array containing the policy options. - */ -ConstantReconnectionPolicy.prototype.getOptions = function () { - return new Map([['delay', this.delay ]]); -}; - -/** - * A reconnection policy that waits exponentially longer between each - * reconnection attempt (but keeps a constant delay once a maximum delay is reached). - *

- * A random amount of jitter (+/- 15%) will be added to the pure exponential delay value to avoid situations - * where many clients are in the reconnection process at exactly the same time. The jitter will never cause the - * delay to be less than the base delay, or more than the max delay. - *

- * @param {Number} baseDelay The base delay in milliseconds to use for the schedules created by this policy. - * @param {Number} maxDelay The maximum delay in milliseconds to wait between two reconnection attempt. - * @param {Boolean} startWithNoDelay Determines if the first attempt should be zero delay - * @constructor - */ -function ExponentialReconnectionPolicy(baseDelay, maxDelay, startWithNoDelay) { - this.baseDelay = baseDelay; - this.maxDelay = maxDelay; - this.startWithNoDelay = startWithNoDelay; -} - -util.inherits(ExponentialReconnectionPolicy, ReconnectionPolicy); - -/** - * A new schedule that uses an exponentially growing delay between reconnection attempts. - * @returns {{next: Function}} An infinite iterator. - */ -ExponentialReconnectionPolicy.prototype.newSchedule = function* () { - let index = this.startWithNoDelay ? -1 : 0; - - while (true) { - let delay = 0; - - if (index >= 64) { - delay = this.maxDelay; - } else if (index !== -1) { - delay = Math.min(Math.pow(2, index) * this.baseDelay, this.maxDelay); - } - - index++; - - yield this._addJitter(delay); - } -}; - -/** - * Adds a random portion of +-15% to the delay provided. - * Initially, its adds a random value of 15% to avoid reconnection before reaching the base delay. - * When the schedule reaches max delay, only subtracts a random portion of 15%. - */ -ExponentialReconnectionPolicy.prototype._addJitter = function (value) { - if (value === 0) { - // Instant reconnection without jitter - return value; - } - - // Use the formula: 85% + rnd() * 30% to calculate the percentage of the original delay - let minPercentage = 0.85; - let range = 0.30; - - if (!this.startWithNoDelay && value === this.baseDelay) { - // Between 100% to 115% of the original value - minPercentage = 1; - range = 0.15; - } else if (value === this.maxDelay) { - // Between 85% to 100% of the original value - range = 0.15; - } - - return Math.floor(value * (Math.random() * range + minPercentage)); -}; - -/** - * Gets an associative array containing the policy options. - */ -ExponentialReconnectionPolicy.prototype.getOptions = function () { - return new Map([ - ['baseDelay', this.baseDelay ], - ['maxDelay', this.maxDelay ], - ['startWithNoDelay', this.startWithNoDelay ] - ]); -}; - -exports.ReconnectionPolicy = ReconnectionPolicy; -exports.ConstantReconnectionPolicy = ConstantReconnectionPolicy; -exports.ExponentialReconnectionPolicy = ExponentialReconnectionPolicy; \ No newline at end of file diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/policies/retry.js b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/policies/retry.js deleted file mode 100644 index 370d6c5d9f..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/policies/retry.js +++ /dev/null @@ -1,276 +0,0 @@ -/* - * Copyright DataStax, Inc. - * - * 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 util = require('util'); - - -/** @module policies/retry */ -/** - * Base and default RetryPolicy. - * Determines what to do when the drivers runs into an specific Cassandra exception - * @constructor - */ -function RetryPolicy() { - -} - -/** - * Determines what to do when the driver gets an UnavailableException response from a Cassandra node. - * @param {OperationInfo} info - * @param {Number} consistency The [consistency]{@link module:types~consistencies} level of the query that triggered - * the exception. - * @param {Number} required The number of replicas whose response is required to achieve the - * required [consistency]{@link module:types~consistencies}. - * @param {Number} alive The number of replicas that were known to be alive when the request had been processed - * (since an unavailable exception has been triggered, there will be alive < required) - * @returns {DecisionInfo} - */ -RetryPolicy.prototype.onUnavailable = function (info, consistency, required, alive) { - if (info.nbRetry > 0) { - return this.rethrowResult(); - } - return this.retryResult(undefined, false); -}; - -/** - * Determines what to do when the driver gets a ReadTimeoutException response from a Cassandra node. - * @param {OperationInfo} info - * @param {Number} consistency The [consistency]{@link module:types~consistencies} level of the query that triggered - * the exception. - * @param {Number} received The number of nodes having answered the request. - * @param {Number} blockFor The number of replicas whose response is required to achieve the - * required [consistency]{@link module:types~consistencies}. - * @param {Boolean} isDataPresent When false, it means the replica that was asked for data has not responded. - * @returns {DecisionInfo} - */ -RetryPolicy.prototype.onReadTimeout = function (info, consistency, received, blockFor, isDataPresent) { - if (info.nbRetry > 0) { - return this.rethrowResult(); - } - return ((received >= blockFor && !isDataPresent) ? - this.retryResult() : - this.rethrowResult()); -}; - -/** - * Determines what to do when the driver gets a WriteTimeoutException response from a Cassandra node. - * @param {OperationInfo} info - * @param {Number} consistency The [consistency]{@link module:types~consistencies} level of the query that triggered - * the exception. - * @param {Number} received The number of nodes having acknowledged the request. - * @param {Number} blockFor The number of replicas whose acknowledgement is required to achieve the required - * [consistency]{@link module:types~consistencies}. - * @param {String} writeType A string that describes the type of the write that timed out ("SIMPLE" - * / "BATCH" / "BATCH_LOG" / "UNLOGGED_BATCH" / "COUNTER"). - * @returns {DecisionInfo} - */ -RetryPolicy.prototype.onWriteTimeout = function (info, consistency, received, blockFor, writeType) { - if (info.nbRetry > 0) { - return this.rethrowResult(); - } - // If the batch log write failed, retry the operation as this might just be we were unlucky at picking candidates - return writeType === "BATCH_LOG" ? this.retryResult() : this.rethrowResult(); -}; - -/** - * Defines whether to retry and at which consistency level on an unexpected error. - *

- * This method might be invoked in the following situations: - *

- *
    - *
  1. On a client timeout, while waiting for the server response - * (see [socketOptions.readTimeout]{@link ClientOptions}), being the error an instance of - * [OperationTimedOutError]{@link module:errors~OperationTimedOutError}.
  2. - *
  3. On a connection error (socket closed, etc.).
  4. - *
  5. When the contacted host replies with an error, such as overloaded, isBootstrapping, - * serverError, etc. In this case, the error is instance of [ResponseError]{@link module:errors~ResponseError}. - *
  6. - *
- *

- * Note that when this method is invoked, the driver cannot guarantee that the mutation has been effectively - * applied server-side; a retry should only be attempted if the request is known to be idempotent. - *

- * @param {OperationInfo} info - * @param {Number|undefined} consistency The [consistency]{@link module:types~consistencies} level of the query that triggered - * the exception. - * @param {Error} err The error that caused this request to fail. - * @returns {DecisionInfo} - */ -RetryPolicy.prototype.onRequestError = function (info, consistency, err) { - // The default implementation triggers a retry on the next host in the query plan with the same consistency level, - // regardless of the statement's idempotence, for historical reasons. - return this.retryResult(undefined, false); -}; - -/** - * Returns a {@link DecisionInfo} to retry the request with the given [consistency]{@link module:types~consistencies}. - * @param {Number|undefined} [consistency] When specified, it retries the request with the given consistency. - * @param {Boolean} [useCurrentHost] When specified, determines if the retry should be made using the same coordinator. - * Default: true. - * @returns {DecisionInfo} - */ -RetryPolicy.prototype.retryResult = function (consistency, useCurrentHost) { - return { - decision: RetryPolicy.retryDecision.retry, - consistency: consistency, - useCurrentHost: useCurrentHost !== false - }; -}; - -/** - * Returns a {@link DecisionInfo} to callback in error when a err is obtained for a given request. - * @returns {DecisionInfo} - */ -RetryPolicy.prototype.rethrowResult = function () { - return { decision: RetryPolicy.retryDecision.rethrow }; -}; - -/** - * Determines the retry decision for the retry policies. - * @type {Object} - * @property {Number} rethrow - * @property {Number} retry - * @property {Number} ignore - * @static - */ -RetryPolicy.retryDecision = { - rethrow: 0, - retry: 1, - ignore: 2 -}; - -/** - * Creates a new instance of IdempotenceAwareRetryPolicy. - * @classdesc - * A retry policy that avoids retrying non-idempotent statements. - *

- * In case of write timeouts or unexpected errors, this policy will always return - * [rethrowResult()]{@link module:policies/retry~RetryPolicy#rethrowResult} if the statement is deemed non-idempotent - * (see [QueryOptions.isIdempotent]{@link QueryOptions}). - *

- * For all other cases, this policy delegates the decision to the child policy. - * @param {RetryPolicy} [childPolicy] The child retry policy to wrap. When not defined, it will use an instance of - * [RetryPolicy]{@link module:policies/retry~RetryPolicy} as child policy. - * @extends module:policies/retry~RetryPolicy - * @constructor - * @deprecated Since version 4.0 non-idempotent operations are never tried for write timeout or request error, use the - * default retry policy instead. - */ -function IdempotenceAwareRetryPolicy(childPolicy) { - this._childPolicy = childPolicy || new RetryPolicy(); -} - -util.inherits(IdempotenceAwareRetryPolicy, RetryPolicy); - -IdempotenceAwareRetryPolicy.prototype.onReadTimeout = function (info, consistency, received, blockFor, isDataPresent) { - return this._childPolicy.onReadTimeout(info, consistency, received, blockFor, isDataPresent); -}; - -/** - * If the query is not idempotent, it returns a rethrow decision. Otherwise, it relies on the child policy to decide. - */ -IdempotenceAwareRetryPolicy.prototype.onRequestError = function (info, consistency, err) { - if (info.executionOptions.isIdempotent()) { - return this._childPolicy.onRequestError(info, consistency, err); - } - return this.rethrowResult(); -}; - -IdempotenceAwareRetryPolicy.prototype.onUnavailable = function (info, consistency, required, alive) { - return this._childPolicy.onUnavailable(info, consistency, required, alive); -}; - -/** - * If the query is not idempotent, it return a rethrow decision. Otherwise, it relies on the child policy to decide. - */ -IdempotenceAwareRetryPolicy.prototype.onWriteTimeout = function (info, consistency, received, blockFor, writeType) { - if (info.executionOptions.isIdempotent()) { - return this._childPolicy.onWriteTimeout(info, consistency, received, blockFor, writeType); - } - return this.rethrowResult(); -}; - -/** - * Creates a new instance of FallthroughRetryPolicy. - * @classdesc - * A retry policy that never retries nor ignores. - *

- * All of the methods of this retry policy unconditionally return - * [rethrow]{@link module:policies/retry~Retry#rethrowResult()}. If this policy is used, retry logic will have to be - * implemented in business code. - *

- * @alias module:policies/retry~FallthroughRetryPolicy - * @extends RetryPolicy - * @constructor - */ -function FallthroughRetryPolicy() { - -} - -util.inherits(FallthroughRetryPolicy, RetryPolicy); - -/** - * Implementation of RetryPolicy method that returns [rethrow]{@link module:policies/retry~Retry#rethrowResult()}. - */ -FallthroughRetryPolicy.prototype.onReadTimeout = function () { - return this.rethrowResult(); -}; - -/** - * Implementation of RetryPolicy method that returns [rethrow]{@link module:policies/retry~Retry#rethrowResult()}. - */ -FallthroughRetryPolicy.prototype.onRequestError = function () { - return this.rethrowResult(); -}; - -/** - * Implementation of RetryPolicy method that returns [rethrow]{@link module:policies/retry~Retry#rethrowResult()}. - */ -FallthroughRetryPolicy.prototype.onUnavailable = function () { - return this.rethrowResult(); -}; - -/** - * Implementation of RetryPolicy method that returns [rethrow]{@link module:policies/retry~Retry#rethrowResult()}. - */ -FallthroughRetryPolicy.prototype.onWriteTimeout = function () { - return this.rethrowResult(); -}; - -/** - * Decision information - * @typedef {Object} DecisionInfo - * @property {Number} decision The decision as specified in - * [retryDecision]{@link module:policies/retry~RetryPolicy.retryDecision}. - * @property {Number} [consistency] The [consistency level]{@link module:types~consistencies}. - * @property {useCurrentHost} [useCurrentHost] Determines if it should use the same host to retry the request. - *

- * In the case that the current host is not available anymore, it will be retried on the next host even when - * useCurrentHost is set to true. - *

- */ - -/** - * Information of the execution to be used to determine whether the operation should be retried. - * @typedef {Object} OperationInfo - * @property {String} query The query that was executed. - * @param {ExecutionOptions} executionOptions The options related to the execution of the request. - * @property {Number} nbRetry The number of retries already performed for this operation. - */ - -exports.IdempotenceAwareRetryPolicy = IdempotenceAwareRetryPolicy; -exports.FallthroughRetryPolicy = FallthroughRetryPolicy; -exports.RetryPolicy = RetryPolicy; \ No newline at end of file diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/policies/speculative-execution.js b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/policies/speculative-execution.js deleted file mode 100644 index 7705802cb6..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/policies/speculative-execution.js +++ /dev/null @@ -1,143 +0,0 @@ -/* - * Copyright DataStax, Inc. - * - * 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 util = require('util'); -const errors = require('../errors'); - -/** @module policies/speculativeExecution */ - -/** - * @classdesc - * The policy that decides if the driver will send speculative queries to the next hosts when the current host takes too - * long to respond. - *

Note that only idempotent statements will be speculatively retried.

- * @constructor - * @abstract - */ -function SpeculativeExecutionPolicy() { - -} - -/** - * Initialization method that gets invoked on Client startup. - * @param {Client} client - * @abstract - */ -SpeculativeExecutionPolicy.prototype.init = function (client) { - -}; - -/** - * Gets invoked at client shutdown, giving the opportunity to the implementor to perform cleanup. - * @abstract - */ -SpeculativeExecutionPolicy.prototype.shutdown = function () { - -}; - -/** - * Gets the plan to use for a new query. - * Returns an object with a nextExecution() method, which returns a positive number representing the - * amount of milliseconds to delay the next execution or a non-negative number to avoid further executions. - * @param {String} keyspace The currently logged keyspace. - * @param {String|Array} queryInfo The query, or queries in the case of batches, for which to build a plan. - * @return {{nextExecution: function}} - * @abstract - */ -SpeculativeExecutionPolicy.prototype.newPlan = function (keyspace, queryInfo) { - throw new Error('You must implement newPlan() method in the SpeculativeExecutionPolicy'); -}; - -/** - * Gets an associative array containing the policy options. - */ -SpeculativeExecutionPolicy.prototype.getOptions = function () { - return new Map(); -}; - -/** - * Creates a new instance of NoSpeculativeExecutionPolicy. - * @classdesc - * A {@link SpeculativeExecutionPolicy} that never schedules speculative executions. - * @constructor - * @extends {SpeculativeExecutionPolicy} - */ -function NoSpeculativeExecutionPolicy() { - this._plan = { - nextExecution: function () { - return -1; - } - }; -} - -util.inherits(NoSpeculativeExecutionPolicy, SpeculativeExecutionPolicy); - -NoSpeculativeExecutionPolicy.prototype.newPlan = function () { - return this._plan; -}; - - -/** - * Creates a new instance of ConstantSpeculativeExecutionPolicy. - * @classdesc - * A {@link SpeculativeExecutionPolicy} that schedules a given number of speculative executions, - * separated by a fixed delay. - * @constructor - * @param {Number} delay The delay between each speculative execution. - * @param {Number} maxSpeculativeExecutions The amount of speculative executions that should be scheduled after the - * initial execution. Must be strictly positive. - * @extends {SpeculativeExecutionPolicy} - */ -function ConstantSpeculativeExecutionPolicy(delay, maxSpeculativeExecutions) { - if (!(delay >= 0)) { - throw new errors.ArgumentError('delay must be a positive number or zero'); - } - if (!(maxSpeculativeExecutions > 0)) { - throw new errors.ArgumentError('maxSpeculativeExecutions must be a positive number'); - } - this._delay = delay; - this._maxSpeculativeExecutions = maxSpeculativeExecutions; -} - -util.inherits(ConstantSpeculativeExecutionPolicy, SpeculativeExecutionPolicy); - -ConstantSpeculativeExecutionPolicy.prototype.newPlan = function () { - let executions = 0; - const self = this; - return { - nextExecution: function () { - if (executions++ < self._maxSpeculativeExecutions) { - return self._delay; - } - return -1; - } - }; -}; - -/** - * Gets an associative array containing the policy options. - */ -ConstantSpeculativeExecutionPolicy.prototype.getOptions = function () { - return new Map([ - ['delay', this._delay ], - ['maxSpeculativeExecutions', this._maxSpeculativeExecutions ] - ]); -}; - -exports.NoSpeculativeExecutionPolicy = NoSpeculativeExecutionPolicy; -exports.SpeculativeExecutionPolicy = SpeculativeExecutionPolicy; -exports.ConstantSpeculativeExecutionPolicy = ConstantSpeculativeExecutionPolicy; \ No newline at end of file diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/policies/timestamp-generation.js b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/policies/timestamp-generation.js deleted file mode 100644 index dbae075e55..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/policies/timestamp-generation.js +++ /dev/null @@ -1,170 +0,0 @@ -/* - * Copyright DataStax, Inc. - * - * 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 util = require('util'); -const { Long } = require('../types'); -const errors = require('../errors'); - -/** @module policies/timestampGeneration */ - -/** - * Defines the maximum date in milliseconds that can be represented in microseconds using Number ((2 ^ 53) / 1000) - * @const - * @private - */ -const _maxSafeNumberDate = 9007199254740; - -/** - * A long representing the value 1000 - * @const - * @private - */ -const _longOneThousand = Long.fromInt(1000); - -/** - * Creates a new instance of {@link TimestampGenerator}. - * @classdesc - * Generates client-side, microsecond-precision query timestamps. - *

- * Given that Cassandra uses those timestamps to resolve conflicts, implementations should generate - * monotonically increasing timestamps for successive invocations of {@link TimestampGenerator.next()}. - *

- * @constructor - */ -function TimestampGenerator() { - -} - -/** - * Returns the next timestamp. - *

- * Implementors should enforce increasing monotonicity of timestamps, that is, - * a timestamp returned should always be strictly greater that any previously returned - * timestamp. - *

- *

- * Implementors should strive to achieve microsecond precision in the best possible way, - * which is usually largely dependent on the underlying operating system's capabilities. - *

- * @param {Client} client The {@link Client} instance to generate timestamps to. - * @returns {Long|Number|null} the next timestamp (in microseconds). If it's equals to null, it won't be - * sent by the driver, letting the server to generate the timestamp. - * @abstract - */ -TimestampGenerator.prototype.next = function (client) { - throw new Error('next() must be implemented'); -}; - -/** - * A timestamp generator that guarantees monotonically increasing timestamps and logs warnings when timestamps - * drift in the future. - *

- * {@link Date} has millisecond precision and client timestamps require microsecond precision. This generator - * keeps track of the last generated timestamp, and if the current time is within the same millisecond as the last, - * it fills the microsecond portion of the new timestamp with the value of an incrementing counter. - *

- * @param {Number} [warningThreshold] Determines how far in the future timestamps are allowed to drift before a - * warning is logged, expressed in milliseconds. Default: 1000. - * @param {Number} [minLogInterval] In case of multiple log events, it determines the time separation between log - * events, expressed in milliseconds. Use 0 to disable. Default: 1000. - * @extends {TimestampGenerator} - * @constructor - */ -function MonotonicTimestampGenerator(warningThreshold, minLogInterval) { - if (warningThreshold < 0) { - throw new errors.ArgumentError('warningThreshold can not be lower than 0'); - } - this._warningThreshold = warningThreshold || 1000; - this._minLogInterval = 1000; - if (typeof minLogInterval === 'number') { - // A value under 1 will disable logging - this._minLogInterval = minLogInterval; - } - this._micros = -1; - this._lastDate = 0; - this._lastLogDate = 0; -} - -util.inherits(MonotonicTimestampGenerator, TimestampGenerator); - -/** - * Returns the current time in milliseconds since UNIX epoch - * @returns {Number} - */ -MonotonicTimestampGenerator.prototype.getDate = function () { - return Date.now(); -}; - -MonotonicTimestampGenerator.prototype.next = function (client) { - let date = this.getDate(); - let drifted = 0; - if (date > this._lastDate) { - this._micros = 0; - this._lastDate = date; - return this._generateMicroseconds(); - } - - if (date < this._lastDate) { - drifted = this._lastDate - date; - date = this._lastDate; - } - if (++this._micros === 1000) { - this._micros = 0; - if (date === this._lastDate) { - // Move date 1 millisecond into the future - date++; - drifted++; - } - } - const lastDate = this._lastDate; - this._lastDate = date; - const result = this._generateMicroseconds(); - if (drifted >= this._warningThreshold) { - // Avoid logging an unbounded amount of times within a clock-skew event or during an interval when more than 1 - // query is being issued by microsecond - const currentLogDate = Date.now(); - if (this._minLogInterval > 0 && this._lastLogDate + this._minLogInterval <= currentLogDate){ - const message = util.format( - 'Timestamp generated using current date was %d milliseconds behind the last generated timestamp (which ' + - 'millisecond portion was %d), the returned value (%s) is being artificially incremented to guarantee ' + - 'monotonicity.', - drifted, lastDate, result); - this._lastLogDate = currentLogDate; - client.log('warning', message); - } - } - return result; -}; - -/** - * @private - * @returns {Number|Long} - */ -MonotonicTimestampGenerator.prototype._generateMicroseconds = function () { - if (this._lastDate < _maxSafeNumberDate) { - // We are safe until Jun 06 2255, its faster to perform this operations on Number than on Long - // We hope to have native int64 by then :) - return this._lastDate * 1000 + this._micros; - } - return Long - .fromNumber(this._lastDate) - .multiply(_longOneThousand) - .add(Long.fromInt(this._micros)); -}; - -exports.TimestampGenerator = TimestampGenerator; -exports.MonotonicTimestampGenerator = MonotonicTimestampGenerator; \ No newline at end of file diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/prepare-handler.js b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/prepare-handler.js deleted file mode 100644 index 0edaa60de0..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/prepare-handler.js +++ /dev/null @@ -1,297 +0,0 @@ -/* - * Copyright DataStax, Inc. - * - * 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 errors = require('./errors'); -const utils = require('./utils'); -const types = require('./types'); -const promiseUtils = require('./promise-utils'); - -/** - * Encapsulates the logic for dealing with the different prepare request and response flows, including failover when - * trying to prepare a query. - */ -class PrepareHandler { - /** - * Creates a new instance of PrepareHandler - * @param {Client} client - * @param {LoadBalancingPolicy} loadBalancing - */ - constructor(client, loadBalancing) { - this._client = client; - this._loadBalancing = loadBalancing; - this.logEmitter = client.options.logEmitter; - this.log = utils.log; - } - - /** - * Gets the query id and metadata for a prepared statement, preparing it on - * single host or on all hosts depending on the options. - * @param {Client} client - * @param {LoadBalancingPolicy} loadBalancing - * @param {String} query - * @param {String} keyspace - * @returns {Promise<{queryId, meta}>} - * @static - */ - static async getPrepared(client, loadBalancing, query, keyspace) { - const info = client.metadata.getPreparedInfo(keyspace, query); - if (info.queryId) { - return info; - } - - if (info.preparing) { - // It's already being prepared - return await promiseUtils.fromEvent(info, 'prepared'); - } - - const instance = new PrepareHandler(client, loadBalancing); - return await instance._prepare(info, query, keyspace); - } - - /** - * @param {Client} client - * @param {LoadBalancingPolicy} loadBalancing - * @param {Array} queries - * @param {String} keyspace - * @static - */ - static async getPreparedMultiple(client, loadBalancing, queries, keyspace) { - const result = []; - - for (const item of queries) { - let query; - - if (item) { - query = typeof item === 'string' ? item : item.query; - } - - if (typeof query !== 'string') { - throw new errors.ArgumentError('Query item should be a string'); - } - - const { queryId, meta } = await PrepareHandler.getPrepared(client, loadBalancing, query, keyspace); - result.push({ query, params: utils.adaptNamedParamsPrepared(item.params, meta.columns), queryId, meta }); - } - - return result; - } - - /** - * Prepares the query on a single host or on all hosts depending on the options. - * Uses the info 'prepared' event to emit the result. - * @param {Object} info - * @param {String} query - * @param {String} keyspace - * @returns {Promise<{queryId, meta}>} - */ - async _prepare(info, query, keyspace) { - info.preparing = true; - let iterator; - - try { - iterator = await promiseUtils.newQueryPlan(this._loadBalancing, keyspace, null); - return await this._prepareWithQueryPlan(info, iterator, query, keyspace); - } catch (err) { - info.preparing = false; - err.query = query; - info.emit('prepared', err); - - throw err; - } - } - - /** - * Uses the query plan to prepare the query on the first host and optionally on the rest of the hosts. - * @param {Object} info - * @param {Iterator} iterator - * @param {String} query - * @param {String} keyspace - * @returns {Promise<{queryId, meta}>} - * @private - */ - async _prepareWithQueryPlan(info, iterator, query, keyspace) { - const triedHosts = {}; - - while (true) { - const host = PrepareHandler.getNextHost(iterator, this._client.profileManager, triedHosts); - - if (host === null) { - throw new errors.NoHostAvailableError(triedHosts); - } - - try { - const connection = await PrepareHandler._borrowWithKeyspace(host, keyspace); - const response = await connection.prepareOnceAsync(query, keyspace); - - if (this._client.options.prepareOnAllHosts) { - await this._prepareOnAllHosts(iterator, query, keyspace); - } - - // Set the prepared metadata - info.preparing = false; - info.queryId = response.id; - info.meta = response.meta; - this._client.metadata.setPreparedById(info); - info.emit('prepared', null, info); - - return info; - - } catch (err) { - triedHosts[host.address] = err; - - if (!err.isSocketError && !(err instanceof errors.OperationTimedOutError)) { - // There's no point in retrying syntax errors and other response errors - throw err; - } - } - } - } - - /** - * Gets the next host from the query plan. - * @param {Iterator} iterator - * @param {ProfileManager} profileManager - * @param {Object} [triedHosts] - * @return {Host|null} - */ - static getNextHost(iterator, profileManager, triedHosts) { - let host; - // Get a host that is UP in a sync loop - while (true) { - const item = iterator.next(); - if (item.done) { - return null; - } - - host = item.value; - - // set the distance relative to the client first - const distance = profileManager.getDistance(host); - if (distance === types.distance.ignored) { - //If its marked as ignore by the load balancing policy, move on. - continue; - } - - if (host.isUp()) { - break; - } - - if (triedHosts) { - triedHosts[host.address] = 'Host considered as DOWN'; - } - } - - return host; - } - - /** - * Prepares all queries on a single host. - * @param {Host} host - * @param {Array} allPrepared - */ - static async prepareAllQueries(host, allPrepared) { - const anyKeyspaceQueries = []; - - const queriesByKeyspace = new Map(); - allPrepared.forEach(info => { - let arr; - if (info.keyspace) { - arr = queriesByKeyspace.get(info.keyspace); - - if (!arr) { - arr = []; - queriesByKeyspace.set(info.keyspace, arr); - } - } else { - arr = anyKeyspaceQueries; - } - - arr.push(info.query); - }); - - for (const [keyspace, queries] of queriesByKeyspace) { - await PrepareHandler._borrowAndPrepare(host, keyspace, queries); - } - - await PrepareHandler._borrowAndPrepare(host, null, anyKeyspaceQueries); - } - - /** - * Borrows a connection from the host and prepares the queries provided. - * @param {Host} host - * @param {String} keyspace - * @param {Array} queries - * @returns {Promise} - * @private - */ - static async _borrowAndPrepare(host, keyspace, queries) { - if (queries.length === 0) { - return; - } - - const connection = await PrepareHandler._borrowWithKeyspace(host, keyspace); - - for (const query of queries) { - await connection.prepareOnceAsync(query, keyspace); - } - } - - /** - * Borrows a connection and changes the active keyspace on the connection, if needed. - * It does not perform any retry or error handling. - * @param {Host!} host - * @param {string} keyspace - * @returns {Promise} - * @throws {errors.BusyConnectionError} When the connection is busy. - * @throws {errors.ResponseError} For invalid keyspaces. - * @throws {Error} For socket errors. - * @private - */ - static async _borrowWithKeyspace(host, keyspace) { - const connection = host.borrowConnection(); - - if (keyspace && connection.keyspace !== keyspace) { - await connection.changeKeyspace(keyspace); - } - - return connection; - } - - /** - * Prepares the provided query on all hosts, except the host provided. - * @param {Iterator} iterator - * @param {String} query - * @param {String} keyspace - * @private - */ - _prepareOnAllHosts(iterator, query, keyspace) { - const queries = [ query ]; - let h; - const hosts = []; - - while ((h = PrepareHandler.getNextHost(iterator, this._client.profileManager)) !== null) { - hosts.push(h); - } - - return Promise.all(hosts.map(h => - PrepareHandler - ._borrowAndPrepare(h, keyspace, queries) - .catch(err => this.log('verbose', `Unexpected error while preparing query (${query}) on ${h.address}`, err)))); - } -} - -module.exports = PrepareHandler; \ No newline at end of file diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/promise-utils.js b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/promise-utils.js deleted file mode 100644 index 1fc5680291..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/promise-utils.js +++ /dev/null @@ -1,177 +0,0 @@ -/* - * Copyright DataStax, Inc. - * - * 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'; - -/** - * Creates a non-clearable timer that resolves the promise once elapses. - * @param {number} ms - * @returns {Promise} - */ -function delay(ms) { - return new Promise(r => setTimeout(r, ms || 0)); -} - -/** - * Creates a Promise that gets resolved or rejected based on an event. - * @param {object} emitter - * @param {string} eventName - * @returns {Promise} - */ -function fromEvent(emitter, eventName) { - return new Promise((resolve, reject) => - emitter.once(eventName, (err, result) => { - if (err) { - reject(err); - } else { - resolve(result); - } - })); -} - -/** - * Creates a Promise from a callback based function. - * @param {Function} fn - * @returns {Promise} - */ -function fromCallback(fn) { - return new Promise((resolve, reject) => - fn((err, result) => { - if (err) { - reject(err); - } else { - resolve(result); - } - })); -} - -/** - * Gets a function that has the signature of a callback that invokes the appropriate promise handler parameters. - * @param {Function} resolve - * @param {Function} reject - * @returns {Function} - */ -function getCallback(resolve, reject) { - return function (err, result) { - if (err) { - reject(err); - } else { - resolve(result); - } - }; -} - -async function invokeSequentially(info, length, fn) { - let index; - while ((index = info.counter++) < length) { - await fn(index); - } -} - -/** - * Invokes the new query plan of the load balancing policy and returns a Promise. - * @param {LoadBalancingPolicy} lbp The load balancing policy. - * @param {String} keyspace Name of currently logged keyspace at Client level. - * @param {ExecutionOptions|null} executionOptions The information related to the execution of the request. - * @returns {Promise} - */ -function newQueryPlan(lbp, keyspace, executionOptions) { - return new Promise((resolve, reject) => { - lbp.newQueryPlan(keyspace, executionOptions, (err, iterator) => { - if (err) { - reject(err); - } else { - resolve(iterator); - } - }); - }); -} - -/** - * Method that handles optional callbacks (dual promise and callback support). - * When callback is undefined it returns the promise. - * When using a callback, it will use it as handlers of the continuation of the promise. - * @param {Promise} promise - * @param {Function?} callback - * @returns {Promise|undefined} - */ -function optionalCallback(promise, callback) { - if (!callback) { - return promise; - } - - toCallback(promise, callback); -} - -/** - * Invokes the provided function multiple times, considering the concurrency level limit. - * @param {Number} count - * @param {Number} limit - * @param {Function} fn - * @returns {Promise} - */ -function times(count, limit, fn) { - if (limit > count) { - limit = count; - } - - const promises = new Array(limit); - - const info = { - counter: 0 - }; - - for (let i = 0; i < limit; i++) { - promises[i] = invokeSequentially(info, count, fn); - } - - return Promise.all(promises); -} - -/** - * Deals with unexpected rejections in order to avoid the unhandled promise rejection warning or failure. - * @param {Promise} promise - * @returns {undefined} - */ -function toBackground(promise) { - promise.catch(() => {}); -} - -/** - * Invokes the callback once outside the promise chain the promise is resolved or rejected. - * @param {Promise} promise - * @param {Function?} callback - * @returns {undefined} - */ -function toCallback(promise, callback) { - promise - .then( - result => process.nextTick(() => callback(null, result)), - // Avoid marking the promise as rejected - err => process.nextTick(() => callback(err))); -} - -module.exports = { - delay, - fromCallback, - fromEvent, - getCallback, - newQueryPlan, - optionalCallback, - times, - toBackground, - toCallback -}; \ No newline at end of file diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/readers.js b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/readers.js deleted file mode 100644 index 57f0e0f732..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/readers.js +++ /dev/null @@ -1,542 +0,0 @@ -/* - * Copyright DataStax, Inc. - * - * 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 util = require('util'); -const utils = require('./utils'); -const types = require('./types'); -const errors = require('./errors'); - -/** - * Information on the formatting of the returned rows - */ -const resultFlag = { - globalTablesSpec: 0x0001, - hasMorePages: 0x0002, - noMetadata: 0x0004, - metadataChanged: 0x0008, - continuousPaging: 0x40000000, - lastContinuousPage: 0x80000000, -}; - -// templates for derived error messages. -const _writeTimeoutQueryMessage = 'Server timeout during write query at consistency %s (%d peer(s) acknowledged the write over %d required)'; -const _writeTimeoutBatchLogMessage = 'Server timeout during batchlog write at consistency %s (%d peer(s) acknowledged the write over %d required)'; -const _writeFailureMessage = 'Server failure during write query at consistency %s (%d responses were required but only %d replicas responded, %d failed)'; -const _unavailableMessage = 'Not enough replicas available for query at consistency %s (%d required but only %d alive)'; -const _readTimeoutMessage = 'Server timeout during read query at consistency %s (%s)'; -const _readFailureMessage = 'Server failure during read query at consistency %s (%d responses were required but only %d replicas responded, %d failed)'; - -/** - * Buffer forward reader of CQL binary frames - * @param {FrameHeader} header - * @param {Buffer} body - * @param {Number} [offset] - */ -class FrameReader { - - /** - * Creates a new instance of the reader - * @param {FrameHeader} header - * @param {Buffer} body - * @param {Number} [offset] - */ - constructor(header, body, offset) { - this.header = header; - this.opcode = header.opcode; - this.offset = offset || 0; - this.buf = body; - } - - remainingLength() { - return this.buf.length - this.offset; - } - - getBuffer() { - return this.buf; - } - - /** - * Slices the underlining buffer - * @param {Number} begin - * @param {Number} [end] - * @returns {Buffer} - */ - slice(begin, end) { - if (typeof end === 'undefined') { - end = this.buf.length; - } - return this.buf.slice(begin, end); - } - - /** - * Modifies the underlying buffer, it concatenates the given buffer with the original (internalBuffer = concat(bytes, internalBuffer) - */ - unshift(bytes) { - if (this.offset > 0) { - throw new Error('Can not modify the underlying buffer if already read'); - } - this.buf = Buffer.concat([bytes, this.buf], bytes.length + this.buf.length); - } - - /** - * Reads any number of bytes and moves the offset. - * if length not provided or it's larger than the remaining bytes, reads to end. - * @param length - * @returns {Buffer} - */ - read(length) { - let end = this.buf.length; - if (typeof length !== 'undefined' && this.offset + length < this.buf.length) { - end = this.offset + length; - } - const bytes = this.slice(this.offset, end); - this.offset = end; - return bytes; - } - - /** - * Moves the reader cursor to the end - */ - toEnd() { - this.offset = this.buf.length; - } - - /** - * Reads a BE Int and moves the offset - * @returns {Number} - */ - readInt() { - const result = this.buf.readInt32BE(this.offset); - this.offset += 4; - return result; - } - - /** @returns {Number} */ - readShort() { - const result = this.buf.readUInt16BE(this.offset); - this.offset += 2; - return result; - } - - readByte() { - const result = this.buf.readUInt8(this.offset); - this.offset += 1; - return result; - } - - readString() { - const length = this.readShort(); - this.checkOffset(length); - const result = this.buf.toString('utf8', this.offset, this.offset + length); - this.offset += length; - return result; - } - - /** - * Checks that the new length to read is within the range of the buffer length. Throws a RangeError if not. - * @param {Number} newLength - */ - checkOffset(newLength) { - if (this.offset + newLength > this.buf.length) { - const err = new RangeError('Trying to access beyond buffer length'); - err.expectedLength = newLength; - throw err; - } - } - - /** - * Reads a protocol string list - * @returns {Array} - */ - readStringList() { - const length = this.readShort(); - const list = new Array(length); - for (let i = 0; i < length; i++) { - list[i] = this.readString(); - } - return list; - } - - /** - * Reads the amount of bytes that the field has and returns them (slicing them). - * @returns {Buffer} - */ - readBytes() { - const length = this.readInt(); - if (length < 0) { - return null; - } - this.checkOffset(length); - return this.read(length); - } - - readShortBytes() { - const length = this.readShort(); - if (length < 0) { - return null; - } - this.checkOffset(length); - return this.read(length); - } - - /** - * Reads an associative array of strings as keys and bytes as values - * @param {Number} length - * @param {Function} keyFn - * @param {Function} valueFn - * @returns {Object} - */ - readMap(length, keyFn, valueFn) { - if (length < 0) { - return null; - } - const map = {}; - for (let i = 0; i < length; i++) { - map[keyFn.call(this)] = valueFn.call(this); - } - return map; - } - - /** - * Reads an associative array of strings as keys and string lists as values - * @returns {Object} - */ - readStringMultiMap() { - //A [short] n, followed by n pair where is a - //[string] and is a [string[]]. - const length = this.readShort(); - if (length < 0) { - return null; - } - const map = {}; - for (let i = 0; i < length; i++) { - map[this.readString()] = this.readStringList(); - } - return map; - } - - /** - * Reads a data type definition - * @returns {{code: Number, info: Object|null}} An array of 2 elements - */ - readType() { - let i; - const type = { - code: this.readShort(), - type: null - }; - switch (type.code) { - case types.dataTypes.custom: - type.info = this.readString(); - break; - case types.dataTypes.list: - case types.dataTypes.set: - type.info = this.readType(); - break; - case types.dataTypes.map: - type.info = [this.readType(), this.readType()]; - break; - case types.dataTypes.udt: - type.info = { - keyspace: this.readString(), - name: this.readString(), - fields: new Array(this.readShort()) - }; - for (i = 0; i < type.info.fields.length; i++) { - type.info.fields[i] = { - name: this.readString(), - type: this.readType() - }; - } - break; - case types.dataTypes.tuple: - type.info = new Array(this.readShort()); - for (i = 0; i < type.info.length; i++) { - type.info[i] = this.readType(); - } - break; - } - return type; - } - - /** - * Reads an Ip address and port - * @returns {{address: exports.InetAddress, port: Number}} - */ - readInet() { - const length = this.readByte(); - const address = this.read(length); - return { address: new types.InetAddress(address), port: this.readInt() }; - } - - /** - * Reads an Ip address - * @returns {InetAddress} - */ - readInetAddress() { - const length = this.readByte(); - return new types.InetAddress(this.read(length)); - } - - /** - * Reads the body bytes corresponding to the flags - * @returns {{traceId: Uuid, warnings: Array, customPayload}} - * @throws {RangeError} - */ - readFlagsInfo() { - if (this.header.flags === 0) { - return utils.emptyObject; - } - const result = {}; - if (this.header.flags & types.frameFlags.tracing) { - this.checkOffset(16); - result.traceId = new types.Uuid(utils.copyBuffer(this.read(16))); - } - if (this.header.flags & types.frameFlags.warning) { - result.warnings = this.readStringList(); - } - if (this.header.flags & types.frameFlags.customPayload) { - // Custom payload is a Map - result.customPayload = this.readMap(this.readShort(), this.readString, this.readBytes); - } - return result; - } - - /** - * Reads the metadata from a row or a prepared result response - * @param {Number} kind - * @returns {Object} - * @throws {RangeError} - */ - readMetadata(kind) { - let i; - //Determines if its a prepared metadata - const isPrepared = (kind === types.resultKind.prepared); - const meta = {}; - if (types.protocolVersion.supportsResultMetadataId(this.header.version) && isPrepared) { - meta.resultId = utils.copyBuffer(this.readShortBytes()); - } - //as used in Rows and Prepared responses - const flags = this.readInt(); - const columnLength = this.readInt(); - if (types.protocolVersion.supportsPreparedPartitionKey(this.header.version) && isPrepared) { - //read the pk columns - meta.partitionKeys = new Array(this.readInt()); - for (i = 0; i < meta.partitionKeys.length; i++) { - meta.partitionKeys[i] = this.readShort(); - } - } - if (flags & resultFlag.hasMorePages) { - meta.pageState = utils.copyBuffer(this.readBytes()); - } - if (flags & resultFlag.metadataChanged) { - meta.newResultId = utils.copyBuffer(this.readShortBytes()); - } - if (flags & resultFlag.continuousPaging) { - meta.continuousPageIndex = this.readInt(); - meta.lastContinuousPage = !!(flags & resultFlag.lastContinuousPage); - } - if (flags & resultFlag.globalTablesSpec) { - meta.global_tables_spec = true; - meta.keyspace = this.readString(); - meta.table = this.readString(); - } - meta.columns = new Array(columnLength); - meta.columnsByName = utils.emptyObject; - if (isPrepared) { - //for prepared metadata, we will need a index of the columns (param) by name - meta.columnsByName = {}; - } - for (i = 0; i < columnLength; i++) { - const col = {}; - if (!meta.global_tables_spec) { - col.ksname = this.readString(); - col.tablename = this.readString(); - } - col.name = this.readString(); - col.type = this.readType(); - meta.columns[i] = col; - if (isPrepared) { - meta.columnsByName[col.name] = i; - } - } - return meta; - } - - /** - * Reads the error from the frame - * @throws {RangeError} - * @returns {ResponseError} - */ - readError() { - const code = this.readInt(); - const message = this.readString(); - const err = new errors.ResponseError(code, message); - //read extra info - switch (code) { - case types.responseErrorCodes.unavailableException: - err.consistencies = this.readShort(); - err.required = this.readInt(); - err.alive = this.readInt(); - err.message = util.format(_unavailableMessage, types.consistencyToString[err.consistencies], err.required, err.alive); - break; - case types.responseErrorCodes.readTimeout: - case types.responseErrorCodes.readFailure: - err.consistencies = this.readShort(); - err.received = this.readInt(); - err.blockFor = this.readInt(); - if (code === types.responseErrorCodes.readFailure) { - if (types.protocolVersion.supportsFailureReasonMap(this.header.version)) { - err.failures = this.readInt(); - err.reasons = this.readMap(err.failures, this.readInetAddress, this.readShort); - } - else { - err.failures = this.readInt(); - } - } - err.isDataPresent = this.readByte(); - if (code === types.responseErrorCodes.readTimeout) { - let details; - if (err.received < err.blockFor) { - details = util.format('%d replica(s) responded over %d required', err.received, err.blockFor); - } - else if (!err.isDataPresent) { - details = 'the replica queried for the data didn\'t respond'; - } - else { - details = 'timeout while waiting for repair of inconsistent replica'; - } - err.message = util.format(_readTimeoutMessage, types.consistencyToString[err.consistencies], details); - } - else { - err.message = util.format(_readFailureMessage, types.consistencyToString[err.consistencies], err.blockFor, err.received, err.failures); - } - break; - case types.responseErrorCodes.writeTimeout: - case types.responseErrorCodes.writeFailure: - err.consistencies = this.readShort(); - err.received = this.readInt(); - err.blockFor = this.readInt(); - if (code === types.responseErrorCodes.writeFailure) { - if (types.protocolVersion.supportsFailureReasonMap(this.header.version)) { - err.failures = this.readInt(); - err.reasons = this.readMap(err.failures, this.readInetAddress, this.readShort); - } - else { - err.failures = this.readInt(); - } - } - err.writeType = this.readString(); - if (code === types.responseErrorCodes.writeTimeout) { - const template = err.writeType === 'BATCH_LOG' ? _writeTimeoutBatchLogMessage : _writeTimeoutQueryMessage; - err.message = util.format(template, types.consistencyToString[err.consistencies], err.received, err.blockFor); - } - else { - err.message = util.format(_writeFailureMessage, types.consistencyToString[err.consistencies], err.blockFor, err.received, err.failures); - } - break; - case types.responseErrorCodes.unprepared: - err.queryId = utils.copyBuffer(this.readShortBytes()); - break; - case types.responseErrorCodes.functionFailure: - err.keyspace = this.readString(); - err.functionName = this.readString(); - err.argTypes = this.readStringList(); - break; - case types.responseErrorCodes.alreadyExists: { - err.keyspace = this.readString(); - const table = this.readString(); - if (table.length > 0) { - err.table = table; - } - break; - } - } - return err; - } - - /** - * Reads an event from Cassandra and returns the detail - * @returns {{eventType: String, inet: {address: Buffer, port: Number}}, *} - */ - readEvent() { - const eventType = this.readString(); - switch (eventType) { - case types.protocolEvents.topologyChange: - return { - added: this.readString() === 'NEW_NODE', - inet: this.readInet(), - eventType: eventType - }; - case types.protocolEvents.statusChange: - return { - up: this.readString() === 'UP', - inet: this.readInet(), - eventType: eventType - }; - case types.protocolEvents.schemaChange: - return this.parseSchemaChange(); - } - //Forward compatibility - return { eventType: eventType }; - } - - parseSchemaChange() { - let result; - if (!types.protocolVersion.supportsSchemaChangeFullMetadata(this.header.version)) { - //v1/v2: 3 strings, the table value can be empty - result = { - eventType: types.protocolEvents.schemaChange, - schemaChangeType: this.readString(), - keyspace: this.readString(), - table: this.readString() - }; - result.isKeyspace = !result.table; - return result; - } - //v3+: 3 or 4 strings: change_type, target, keyspace and (table, type, functionName or aggregate) - result = { - eventType: types.protocolEvents.schemaChange, - schemaChangeType: this.readString(), - target: this.readString(), - keyspace: this.readString(), - table: null, - udt: null, - signature: null - }; - result.isKeyspace = result.target === 'KEYSPACE'; - switch (result.target) { - case 'TABLE': - result.table = this.readString(); - break; - case 'TYPE': - result.udt = this.readString(); - break; - case 'FUNCTION': - result.functionName = this.readString(); - result.signature = this.readStringList(); - break; - case 'AGGREGATE': - result.aggregate = this.readString(); - result.signature = this.readStringList(); - } - return result; - } -} - -module.exports = { FrameReader }; diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/request-execution.js b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/request-execution.js deleted file mode 100644 index 00cd9a5f10..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/request-execution.js +++ /dev/null @@ -1,497 +0,0 @@ -/* - * Copyright DataStax, Inc. - * - * 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 errors = require('./errors'); -const requests = require('./requests'); -const retry = require('./policies/retry'); -const types = require('./types'); -const utils = require('./utils'); -const promiseUtils = require('./promise-utils'); - -const retryOnCurrentHost = Object.freeze({ - decision: retry.RetryPolicy.retryDecision.retry, - useCurrentHost: true, - consistency: undefined -}); - -const rethrowDecision = Object.freeze({ decision: retry.RetryPolicy.retryDecision.rethrow }); - -/** - * An internal representation of an error that occurred during the execution of a request. - */ -const errorCodes = { - none: 0, - // Socket error - socketError: 1, - // Socket error before the request was written to the wire - socketErrorBeforeRequestWritten: 2, - // OperationTimedOutError - clientTimeout: 3, - // Response error "unprepared" - serverErrorUnprepared: 4, - // Response error "overloaded", "is_bootstrapping" and "truncateError": - serverErrorOverloaded: 5, - serverErrorReadTimeout: 6, - serverErrorUnavailable: 7, - serverErrorWriteTimeout: 8, - // Any other server error (different from the ones detailed above) - serverErrorOther: 9 -}; - -const metricsHandlers = new Map([ - [ errorCodes.none, (metrics, err, latency) => metrics.onSuccessfulResponse(latency) ], - [ errorCodes.socketError, (metrics, err) => metrics.onConnectionError(err) ], - [ errorCodes.clientTimeout, (metrics, err) => metrics.onClientTimeoutError(err) ], - [ errorCodes.serverErrorOverloaded, (metrics, err) => metrics.onOtherError(err) ], - [ errorCodes.serverErrorReadTimeout, (metrics, err) => metrics.onReadTimeoutError(err) ], - [ errorCodes.serverErrorUnavailable, (metrics, err) => metrics.onUnavailableError(err) ], - [ errorCodes.serverErrorWriteTimeout, (metrics, err) => metrics.onWriteTimeoutError(err) ], - [ errorCodes.serverErrorOther, (metrics, err) => metrics.onOtherError(err) ] -]); - -const metricsRetryHandlers = new Map([ - [ errorCodes.socketError, (metrics, err) => metrics.onOtherErrorRetry(err) ], - [ errorCodes.clientTimeout, (metrics, err) => metrics.onClientTimeoutRetry(err) ], - [ errorCodes.serverErrorOverloaded, (metrics, err) => metrics.onOtherErrorRetry(err) ], - [ errorCodes.serverErrorReadTimeout, (metrics, err) => metrics.onReadTimeoutRetry(err) ], - [ errorCodes.serverErrorUnavailable, (metrics, err) => metrics.onUnavailableRetry(err) ], - [ errorCodes.serverErrorWriteTimeout, (metrics, err) => metrics.onWriteTimeoutRetry(err) ], - [ errorCodes.serverErrorOther, (metrics, err) => metrics.onOtherErrorRetry(err) ] -]); - -class RequestExecution { - /** - * Encapsulates a single flow of execution against a coordinator, handling individual retries and failover. - * @param {RequestHandler!} parent - * @param {Host!} host - * @param {Connection!} connection - */ - constructor(parent, host, connection) { - this._parent = parent; - /** @type {OperationState} */ - this._operation = null; - this._host = host; - this._connection = connection; - this._cancelled = false; - this._startTime = null; - this._retryCount = 0; - // The streamId information is not included in the request. - // A pointer to the parent request can be used, except when changing the consistency level from the retry policy - this._request = this._parent.request; - - // Mark that it launched a new execution - parent.speculativeExecutions++; - } - - /** - * Sends the request using the active connection. - */ - start() { - this._sendOnConnection(); - } - - /** - * Borrows the next connection available using the query plan and sends the request. - * @returns {Promise} - */ - async restart() { - try { - const { host, connection } = this._parent.getNextConnection(); - - this._connection = connection; - this._host = host; - } catch (err) { - return this._parent.handleNoHostAvailable(err, this); - } - - // It could be a new connection from the pool, we should make sure it's in the correct keyspace. - const keyspace = this._parent.client.keyspace; - if (keyspace && keyspace !== this._connection.keyspace) { - try { - await this._connection.changeKeyspace(keyspace); - } catch (err) { - // When its a socket error, attempt to retry. - // Otherwise, rethrow the error to the user. - return this._handleError(err, RequestExecution._getErrorCode(err)); - } - } - - if (this._cancelled) { - // No need to send the request or invoke any callback - return; - } - - this._sendOnConnection(); - } - - /** - * Sends the request using the active connection. - * @private - */ - _sendOnConnection() { - this._startTime = process.hrtime(); - - this._operation = - this._connection.sendStream(this._request, this._parent.executionOptions, (err, response, length) => { - const errorCode = RequestExecution._getErrorCode(err); - - this._trackResponse(process.hrtime(this._startTime), errorCode, err, length); - - if (this._cancelled) { - // Avoid handling the response / err - return; - } - - if (errorCode !== errorCodes.none) { - return this._handleError(errorCode, err); - } - - if (response.schemaChange) { - return promiseUtils.toBackground( - this._parent.client - .handleSchemaAgreementAndRefresh(this._connection, response.schemaChange) - .then(agreement => { - if (this._cancelled) { - // After the schema agreement method was started, this execution was cancelled - return; - } - - this._parent.setCompleted(null, this._getResultSet(response, agreement)); - }) - ); - } - - if (response.keyspaceSet) { - this._parent.client.keyspace = response.keyspaceSet; - } - - if (response.meta && response.meta.newResultId && this._request.queryId) { - // Update the resultId on the existing prepared statement. - // Eventually would want to update the result metadata as well (NODEJS-433) - const info = this._parent.client.metadata.getPreparedById(this._request.queryId); - info.meta.resultId = response.meta.newResultId; - } - - this._parent.setCompleted(null, this._getResultSet(response)); - }); - } - - _trackResponse(latency, errorCode, err, length) { - // Record metrics - RequestExecution._invokeMetricsHandler(errorCode, this._parent.client.metrics, err, latency); - - // Request tracker - const tracker = this._parent.client.options.requestTracker; - - if (tracker === null) { - return; - } - - // Avoid using instanceof as property check is faster - const query = this._request.query || this._request.queries; - const parameters = this._request.params; - const requestLength = this._request.length; - - if (err) { - tracker.onError(this._host, query, parameters, this._parent.executionOptions, requestLength, err, latency); - } else { - tracker.onSuccess(this._host, query, parameters, this._parent.executionOptions, requestLength, length, latency); - } - } - - _getResultSet(response, agreement) { - const rs = new types.ResultSet(response, this._host.address, this._parent.triedHosts, this._parent.speculativeExecutions, - this._request.consistency, agreement === undefined || agreement); - - if (rs.rawPageState) { - rs.nextPageAsync = this._parent.getNextPageHandler(); - } - - return rs; - } - - /** - * Gets the method of the {ClientMetrics} instance depending on the error code and invokes it. - * @param {Number} errorCode - * @param {ClientMetrics} metrics - * @param {Error} err - * @param {Array} latency - * @private - */ - static _invokeMetricsHandler(errorCode, metrics, err, latency) { - const handler = metricsHandlers.get(errorCode); - if (handler !== undefined) { - handler(metrics, err, latency); - } - - if (!err || err instanceof errors.ResponseError) { - metrics.onResponse(latency); - } - } - - /** - * Gets the method of the {ClientMetrics} instance related to retry depending on the error code and invokes it. - * @param {Number} errorCode - * @param {ClientMetrics} metrics - * @param {Error} err - * @private - */ - static _invokeMetricsHandlerForRetry(errorCode, metrics, err) { - const handler = metricsRetryHandlers.get(errorCode); - - if (handler !== undefined) { - handler(metrics, err); - } - } - - /** - * Allows the handler to cancel the current request. - * When the request has been already written, we can unset the callback and forget about it. - */ - cancel() { - this._cancelled = true; - - if (this._operation === null) { - return; - } - - this._operation.cancel(); - } - - /** - * Determines if the current execution was cancelled. - */ - wasCancelled() { - return this._cancelled; - } - - _handleError(errorCode, err) { - this._parent.triedHosts[this._host.address] = err; - err['coordinator'] = this._host.address; - - if (errorCode === errorCodes.serverErrorUnprepared) { - return this._prepareAndRetry(err.queryId); - } - - if (errorCode === errorCodes.socketError || errorCode === errorCodes.socketErrorBeforeRequestWritten) { - this._host.removeFromPool(this._connection); - } else if (errorCode === errorCodes.clientTimeout) { - this._parent.log('warning', err.message); - this._host.checkHealth(this._connection); - } - - const decisionInfo = this._getDecision(errorCode, err); - - if (!decisionInfo || decisionInfo.decision === retry.RetryPolicy.retryDecision.rethrow) { - if (this._request instanceof requests.QueryRequest || this._request instanceof requests.ExecuteRequest) { - err['query'] = this._request.query; - } - return this._parent.setCompleted(err); - } - - const metrics = this._parent.client.metrics; - - if (decisionInfo.decision === retry.RetryPolicy.retryDecision.ignore) { - metrics.onIgnoreError(err); - - // Return an empty ResultSet - return this._parent.setCompleted(null, this._getResultSet(utils.emptyObject)); - } - - RequestExecution._invokeMetricsHandlerForRetry(errorCode, metrics, err); - - return this._retry(decisionInfo.consistency, decisionInfo.useCurrentHost); - } - - /** - * Gets a decision whether or not to retry based on the error information. - * @param {Number} errorCode - * @param {Error} err - * @returns {{decision, useCurrentHost, consistency}} - */ - _getDecision(errorCode, err) { - const operationInfo = { - query: this._request && this._request.query, - executionOptions: this._parent.executionOptions, - nbRetry: this._retryCount - }; - - const retryPolicy = operationInfo.executionOptions.getRetryPolicy(); - - switch (errorCode) { - case errorCodes.socketErrorBeforeRequestWritten: - // The request was definitely not applied, it's safe to retry. - // Retry on the current host as there might be other connections open, in case it fails to obtain a connection - // on the current host, the driver will immediately retry on the next host. - return retryOnCurrentHost; - case errorCodes.socketError: - case errorCodes.clientTimeout: - case errorCodes.serverErrorOverloaded: - if (operationInfo.executionOptions.isIdempotent()) { - return retryPolicy.onRequestError(operationInfo, this._request.consistency, err); - } - return rethrowDecision; - case errorCodes.serverErrorUnavailable: - return retryPolicy.onUnavailable(operationInfo, err.consistencies, err.required, err.alive); - case errorCodes.serverErrorReadTimeout: - return retryPolicy.onReadTimeout( - operationInfo, err.consistencies, err.received, err.blockFor, err.isDataPresent); - case errorCodes.serverErrorWriteTimeout: - if (operationInfo.executionOptions.isIdempotent()) { - return retryPolicy.onWriteTimeout( - operationInfo, err.consistencies, err.received, err.blockFor, err.writeType); - } - return rethrowDecision; - default: - return rethrowDecision; - } - } - - static _getErrorCode(err) { - if (!err) { - return errorCodes.none; - } - - if (err.isSocketError) { - if (err.requestNotWritten) { - return errorCodes.socketErrorBeforeRequestWritten; - } - return errorCodes.socketError; - } - - if (err instanceof errors.OperationTimedOutError) { - return errorCodes.clientTimeout; - } - - if (err instanceof errors.ResponseError) { - switch (err.code) { - case types.responseErrorCodes.overloaded: - case types.responseErrorCodes.isBootstrapping: - case types.responseErrorCodes.truncateError: - return errorCodes.serverErrorOverloaded; - case types.responseErrorCodes.unavailableException: - return errorCodes.serverErrorUnavailable; - case types.responseErrorCodes.readTimeout: - return errorCodes.serverErrorReadTimeout; - case types.responseErrorCodes.writeTimeout: - return errorCodes.serverErrorWriteTimeout; - case types.responseErrorCodes.unprepared: - return errorCodes.serverErrorUnprepared; - } - } - - return errorCodes.serverErrorOther; - } - - /** - * @param {Number|undefined} consistency - * @param {Boolean} useCurrentHost - * @param {Object} [meta] - * @private - */ - _retry(consistency, useCurrentHost, meta) { - if (this._cancelled) { - // No point in retrying - return; - } - - this._parent.log('info', 'Retrying request'); - this._retryCount++; - - if (meta || (typeof consistency === 'number' && this._request.consistency !== consistency)) { - this._request = this._request.clone(); - if (typeof consistency === 'number') { - this._request.consistency = consistency; - } - // possible that we are retrying because we had to reprepare. In this case it is also possible - // that our known metadata had changed, therefore we update it on the request. - if (meta) { - this._request.meta = meta; - } - } - - if (useCurrentHost !== false) { - // Reusing the existing connection is suitable for the most common scenarios, like server read timeouts that - // will be fixed with a new request. - // To cover all scenarios (e.g., where a different connection to the same host might mean something different), - // we obtain a new connection from the host pool. - // When there was a socket error, the connection provided was already removed from the pool earlier. - try { - this._connection = this._host.borrowConnection(this._connection); - } catch (err) { - // All connections are busy (`BusyConnectionError`) or there isn't a ready connection in the pool (`Error`) - // The retry policy declared the intention to retry on the current host but its not available anymore. - // Use the next host - return promiseUtils.toBackground(this.restart()); - } - - return this._sendOnConnection(); - } - - // Use the next host in the query plan to send the request in the background - promiseUtils.toBackground(this.restart()); - } - - /** - * Issues a PREPARE request on the current connection. - * If there's a socket or timeout issue, it moves to next host and executes the original request. - * @param {Buffer} queryId - * @private - */ - _prepareAndRetry(queryId) { - const connection = this._connection; - - this._parent.log('info', - `Query 0x${queryId.toString('hex')} not prepared on` + - ` host ${connection.endpointFriendlyName}, preparing and retrying`); - - const info = this._parent.client.metadata.getPreparedById(queryId); - - if (!info) { - return this._parent.setCompleted(new errors.DriverInternalError( - `Unprepared response invalid, id: 0x${queryId.toString('hex')}`)); - } - - const version = this._connection.protocolVersion; - - if (!types.protocolVersion.supportsKeyspaceInRequest(version) && info.keyspace && info.keyspace !== connection.keyspace) { - return this._parent.setCompleted( - new Error(`Query was prepared on keyspace ${info.keyspace}, can't execute it on ${connection.keyspace} (${info.query})`)); - } - - const self = this; - this._connection.prepareOnce(info.query, info.keyspace, function (err, result) { - if (err) { - if (!err.isSocketError && err instanceof errors.OperationTimedOutError) { - self._parent.log('warning', - `Unexpected timeout error when re-preparing query on host ${connection.endpointFriendlyName}`); - } - - // There was a failure re-preparing on this connection. - // Execute the original request on the next connection and forget about the PREPARE-UNPREPARE flow. - return self._retry(undefined, false); - } - - // It's possible that when re-preparing we got new metadata (i.e. if schema changed), update cache. - info.meta = result.meta; - // pass the metadata so it can be used in retry. - self._retry(undefined, true, result.meta); - }); - } -} - -module.exports = RequestExecution; \ No newline at end of file diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/request-handler.js b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/request-handler.js deleted file mode 100644 index c1c7b6daf9..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/request-handler.js +++ /dev/null @@ -1,311 +0,0 @@ -/* - * Copyright DataStax, Inc. - * - * 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 util = require('util'); - -const errors = require('./errors'); -const types = require('./types'); -const utils = require('./utils'); -const RequestExecution = require('./request-execution'); -const promiseUtils = require('./promise-utils'); - -/** - * Handles a BATCH, QUERY and EXECUTE request to the server, dealing with host fail-over and retries on error - */ -class RequestHandler { - /** - * Creates a new instance of RequestHandler. - * @param {Request} request - * @param {ExecutionOptions} execOptions - * @param {Client} client Client instance used to retrieve and set the keyspace. - */ - constructor(request, execOptions, client) { - this.client = client; - this._speculativeExecutionPlan = client.options.policies.speculativeExecution.newPlan( - client.keyspace, request.query || request.queries); - this.logEmitter = client.options.logEmitter; - this.log = utils.log; - this.request = request; - this.executionOptions = execOptions; - this.stackContainer = null; - this.triedHosts = {}; - // start at -1 as first request does not count. - this.speculativeExecutions = -1; - this._hostIterator = null; - this._resolveCallback = null; - this._rejectCallback = null; - this._newExecutionTimeout = null; - /** @type {RequestExecution[]} */ - this._executions = []; - } - - /** - * Sends a new BATCH, QUERY or EXECUTE request. - * @param {Request} request - * @param {ExecutionOptions} execOptions - * @param {Client} client Client instance used to retrieve and set the keyspace. - * @returns {Promise} - */ - static send(request, execOptions, client) { - const instance = new RequestHandler(request, execOptions, client); - return instance.send(); - } - - /** - * Gets a connection from the next host according to the query plan or throws a NoHostAvailableError. - * @returns {{host, connection}} - * @throws {NoHostAvailableError} - */ - getNextConnection() { - let host; - let connection; - const iterator = this._hostIterator; - - // Get a host that is UP in a sync loop - while (true) { - const item = iterator.next(); - if (item.done) { - throw new errors.NoHostAvailableError(this.triedHosts); - } - - host = item.value; - - // Set the distance relative to the client first - const distance = this.client.profileManager.getDistance(host); - if (distance === types.distance.ignored) { - //If its marked as ignore by the load balancing policy, move on. - continue; - } - - if (!host.isUp()) { - this.triedHosts[host.address] = 'Host considered as DOWN'; - continue; - } - - try { - connection = host.borrowConnection(); - this.triedHosts[host.address] = null; - break; - } catch (err) { - this.triedHosts[host.address] = err; - } - } - - return { connection, host }; - } - - /** - * Gets an available connection and sends the request - * @returns {Promise} - */ - send() { - if (this.executionOptions.getCaptureStackTrace()) { - Error.captureStackTrace(this.stackContainer = {}); - } - - return new Promise((resolve, reject) => { - this._resolveCallback = resolve; - this._rejectCallback = reject; - - const lbp = this.executionOptions.getLoadBalancingPolicy(); - const fixedHost = this.executionOptions.getFixedHost(); - - if (fixedHost) { - // if host is configured bypass load balancing policy and use - // a single host plan. - this._hostIterator = utils.arrayIterator([fixedHost]); - promiseUtils.toBackground(this._startNewExecution()); - } else { - lbp.newQueryPlan(this.client.keyspace, this.executionOptions, (err, iterator) => { - if (err) { - return reject(err); - } - - this._hostIterator = iterator; - promiseUtils.toBackground(this._startNewExecution()); - }); - } - }); - } - - /** - * Starts a new execution on the next host of the query plan. - * @param {Boolean} [isSpecExec] - * @returns {Promise} - * @private - */ - async _startNewExecution(isSpecExec) { - if (isSpecExec) { - this.client.metrics.onSpeculativeExecution(); - } - - let host; - let connection; - - try { - ({ host, connection } = this.getNextConnection()); - } catch (err) { - return this.handleNoHostAvailable(err, null); - } - - if (isSpecExec && this._executions.length >= 0 && this._executions[0].wasCancelled()) { - // This method was called on the next tick and could not be cleared, the previous execution was cancelled so - // there's no point in launching a new execution. - return; - } - - if (this.client.keyspace && this.client.keyspace !== connection.keyspace) { - try { - await connection.changeKeyspace(this.client.keyspace); - } catch (err) { - this.triedHosts[host.address] = err; - // The error occurred asynchronously - // We can blindly re-try to obtain a different host/connection. - return this._startNewExecution(isSpecExec); - } - } - - const execution = new RequestExecution(this, host, connection); - this._executions.push(execution); - execution.start(); - - if (this.executionOptions.isIdempotent()) { - this._scheduleSpeculativeExecution(host); - } - } - - /** - * Schedules next speculative execution, if any. - * @param {Host!} host - * @private - */ - _scheduleSpeculativeExecution(host) { - const delay = this._speculativeExecutionPlan.nextExecution(host); - if (typeof delay !== 'number' || delay < 0) { - return; - } - - if (delay === 0) { - // Parallel speculative execution - return process.nextTick(() => { - promiseUtils.toBackground(this._startNewExecution(true)); - }); - } - - // Create timer for speculative execution - this._newExecutionTimeout = setTimeout(() => - promiseUtils.toBackground(this._startNewExecution(true)), delay); - } - - /** - * Sets the keyspace in any connection that is already opened. - * @param {Client} client - * @returns {Promise} - */ - static setKeyspace(client) { - let connection; - - for (const host of client.hosts.values()) { - connection = host.getActiveConnection(); - if (connection) { - break; - } - } - - if (!connection) { - throw new errors.DriverInternalError('No active connection found'); - } - - return connection.changeKeyspace(client.keyspace); - } - - /** - * @param {Error} err - * @param {ResultSet} [result] - */ - setCompleted(err, result) { - if (this._newExecutionTimeout !== null) { - clearTimeout(this._newExecutionTimeout); - } - - // Mark all executions as cancelled - for (const execution of this._executions) { - execution.cancel(); - } - - if (err) { - if (this.executionOptions.getCaptureStackTrace()) { - utils.fixStack(this.stackContainer.stack, err); - } - - // Reject the promise - return this._rejectCallback(err); - } - - if (result.info.warnings) { - // Log the warnings from the response - result.info.warnings.forEach(function (message, i, warnings) { - this.log('warning', util.format( - 'Received warning (%d of %d) "%s" for "%s"', - i + 1, - warnings.length, - message, - this.request.query || 'batch')); - }, this); - } - - // We used to invoke the callback on next tick to allow stack unwinding and prevent the optimizing compiler to - // optimize read and write functions together. - // As we are resolving a Promise then() and catch() are always scheduled in the microtask queue - // We can invoke the resolve method directly. - this._resolveCallback(result); - } - - /** - * @param {NoHostAvailableError} err - * @param {RequestExecution|null} execution - */ - handleNoHostAvailable(err, execution) { - if (execution !== null) { - // Remove the execution - const index = this._executions.indexOf(execution); - this._executions.splice(index, 1); - } - - if (this._executions.length === 0) { - // There aren't any other executions, we should report back to the user that there isn't - // a host available for executing the request - this.setCompleted(err); - } - } - - /** - * Gets a long lived closure that can fetch the next page. - * @returns {Function} - */ - getNextPageHandler() { - const request = this.request; - const execOptions = this.executionOptions; - const client = this.client; - - return function nextPageHandler(pageState) { - execOptions.setPageState(pageState); - return new RequestHandler(request, execOptions, client).send(); - }; - } -} - -module.exports = RequestHandler; diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/requests.js b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/requests.js deleted file mode 100644 index 443347ee30..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/requests.js +++ /dev/null @@ -1,542 +0,0 @@ -/* - * Copyright DataStax, Inc. - * - * 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 util = require('util'); - -const { FrameWriter } = require('./writers'); -const types = require('./types'); -const utils = require('./utils'); -const { ExecutionOptions } = require('./execution-options'); -const packageInfo = require('../package.json'); - -/** - * Options for the execution of the query / prepared statement - * @private - */ -const queryFlag = { - values: 0x01, - skipMetadata: 0x02, - pageSize: 0x04, - withPagingState: 0x08, - withSerialConsistency: 0x10, - withDefaultTimestamp: 0x20, - withNameForValues: 0x40, - withKeyspace: 0x80, - withPageSizeBytes: 0x40000000, - withContinuousPaging: 0x80000000 -}; - -/** - * Options for the execution of a batch request from protocol v3 and above - * @private - */ -const batchFlag = { - withSerialConsistency: 0x10, - withDefaultTimestamp: 0x20, - withNameForValues: 0x40, - withKeyspace: 0x80 -}; - -/** - * Options for execution of a prepare request from protocol DSE_V2 and above - * @private - */ -const prepareFlag = { - withKeyspace: 0x01 -}; - -const batchType = { - logged: 0, - unlogged: 1, - counter: 2 -}; - -/** - * Abstract class Request - */ -class Request { - constructor() { - this.length = 0; - } - - /** - * @abstract - * @param {Encoder} encoder - * @param {Number} streamId - * @throws {TypeError} - * @returns {Buffer} - */ - write(encoder, streamId) { - throw new Error('Method must be implemented'); - } - - /** - * Creates a new instance using the same constructor as the current instance, copying the properties. - * @return {Request} - */ - clone() { - const newRequest = new (this.constructor)(); - const keysArray = Object.keys(this); - for (let i = 0; i < keysArray.length; i++) { - const key = keysArray[i]; - newRequest[key] = this[key]; - } - return newRequest; - } -} - -/** - * Writes a execute query (given a prepared queryId) - * @param {String} query - * @param {Buffer} queryId - * @param {Array} params - * @param options - */ -class ExecuteRequest extends Request { - /** - * @param {String} query - * @param queryId - * @param params - * @param {ExecutionOptions} execOptions - * @param meta - */ - constructor(query, queryId, params, execOptions, meta) { - super(); - - this.query = query; - this.queryId = queryId; - this.params = params; - this.meta = meta; - this.options = execOptions || ExecutionOptions.empty(); - this.consistency = this.options.getConsistency() || types.consistencies.one; - // Only QUERY request parameters are encoded as named parameters - // EXECUTE request parameters are always encoded as positional parameters - this.namedParameters = false; - } - - getParamType(index) { - const columnInfo = this.meta.columns[index]; - return columnInfo ? columnInfo.type : null; - } - - write(encoder, streamId) { - //v1: - // .... - //v2: - // [...][][][] - //v3: - // [[name_1]...[name_n]][][][][] - const frameWriter = new FrameWriter(types.opcodes.execute); - let headerFlags = this.options.isQueryTracing() ? types.frameFlags.tracing : 0; - if (this.options.getCustomPayload()) { - //The body may contain the custom payload - headerFlags |= types.frameFlags.customPayload; - frameWriter.writeCustomPayload(this.options.getCustomPayload()); - } - frameWriter.writeShortBytes(this.queryId); - if(types.protocolVersion.supportsResultMetadataId(encoder.protocolVersion)) { - frameWriter.writeShortBytes(this.meta.resultId); - } - this.writeQueryParameters(frameWriter, encoder); - - // Record the length of the body of the request before writing it - this.length = frameWriter.bodyLength; - - return frameWriter.write(encoder.protocolVersion, streamId, headerFlags); - } - - /** - * Writes v1 and v2 execute query parameters - * @param {FrameWriter} frameWriter - * @param {Encoder} encoder - * @param {Boolean} [isQuery] True if query, otherwise assumed to be execute request. - */ - writeQueryParameters(frameWriter, encoder, isQuery) { - //v1: .... - //v2: [...][][][] - //v3: [[name_1]...[name_n]][][][][] - //dse_v1: [[name_1]...[name_n]][][] - // [][][continuous_paging_options] - //dse_v2: [[name_1]...[name_n]][][] - // [][][keyspace][continuous_paging_options] - let flags = 0; - - const timestamp = this.options.getOrGenerateTimestamp(); - - if (types.protocolVersion.supportsPaging(encoder.protocolVersion)) { - flags |= (this.params && this.params.length) ? queryFlag.values : 0; - flags |= (this.options.getFetchSize() > 0) ? queryFlag.pageSize : 0; - flags |= this.options.getPageState() ? queryFlag.withPagingState : 0; - flags |= this.options.getSerialConsistency() ? queryFlag.withSerialConsistency : 0; - flags |= timestamp !== null && timestamp !== undefined ? queryFlag.withDefaultTimestamp : 0; - flags |= this.namedParameters ? queryFlag.withNameForValues : 0; - - // Don't inject keyspace for EXECUTE requests as inherited from prepared statement. - const supportsKeyspace = isQuery && types.protocolVersion.supportsKeyspaceInRequest(encoder.protocolVersion); - flags |= supportsKeyspace && this.options.getKeyspace() ? queryFlag.withKeyspace : 0; - - frameWriter.writeShort(this.consistency); - if (types.protocolVersion.uses4BytesQueryFlags(encoder.protocolVersion)) { - frameWriter.writeInt(flags); - } - else { - frameWriter.writeByte(flags); - } - } - - if (this.params && this.params.length) { - frameWriter.writeShort(this.params.length); - for (let i = 0; i < this.params.length; i++) { - let paramValue = this.params[i]; - if (flags & queryFlag.withNameForValues) { - //parameter is composed by name / value - frameWriter.writeString(paramValue.name); - paramValue = paramValue.value; - } - frameWriter.writeBytes(encoder.encode(paramValue, this.getParamType(i))); - } - } - - if (!types.protocolVersion.supportsPaging(encoder.protocolVersion)) { - if (!this.params || !this.params.length) { - //zero parameters - frameWriter.writeShort(0); - } - frameWriter.writeShort(this.consistency); - return; - } - if (flags & queryFlag.pageSize) { - frameWriter.writeInt(this.options.getFetchSize()); - } - if (flags & queryFlag.withPagingState) { - frameWriter.writeBytes(this.options.getPageState()); - } - if (flags & queryFlag.withSerialConsistency) { - frameWriter.writeShort(this.options.getSerialConsistency()); - } - if (flags & queryFlag.withDefaultTimestamp) { - frameWriter.writeLong(timestamp); - } - if (flags & queryFlag.withKeyspace) { - frameWriter.writeString(this.options.getKeyspace()); - } - } -} - -class QueryRequest extends ExecuteRequest { - /** - * @param {String} query - * @param params - * @param {ExecutionOptions} [execOptions] - * @param {Boolean} [namedParameters] - */ - constructor(query, params, execOptions, namedParameters) { - super(query, null, params, execOptions, null); - this.hints = this.options.getHints() || utils.emptyArray; - this.namedParameters = namedParameters; - } - - getParamType(index) { - return this.hints[index]; - } - - write(encoder, streamId) { - //v1: - //v2: - // [...][][][] - //v3: - // [[name_1]...[name_n]][][][][] - const frameWriter = new FrameWriter(types.opcodes.query); - let headerFlags = this.options.isQueryTracing() ? types.frameFlags.tracing : 0; - if (this.options.getCustomPayload()) { - //The body may contain the custom payload - headerFlags |= types.frameFlags.customPayload; - frameWriter.writeCustomPayload(this.options.getCustomPayload()); - } - - frameWriter.writeLString(this.query); - - if (!types.protocolVersion.supportsPaging(encoder.protocolVersion)) { - frameWriter.writeShort(this.consistency); - } else { - //Use the same fields as the execute writer - this.writeQueryParameters(frameWriter, encoder, true); - } - - // Record the length of the body of the request before writing it - this.length = frameWriter.bodyLength; - - return frameWriter.write(encoder.protocolVersion, streamId, headerFlags); - } -} - -class PrepareRequest extends Request { - constructor(query, keyspace) { - super(); - this.query = query; - this.keyspace = keyspace; - } - - write(encoder, streamId) { - const frameWriter = new FrameWriter(types.opcodes.prepare); - frameWriter.writeLString(this.query); - if (types.protocolVersion.supportsPrepareFlags(encoder.protocolVersion)) { - const flags = this.keyspace && types.protocolVersion.supportsKeyspaceInRequest(encoder.protocolVersion) ? prepareFlag.withKeyspace : 0; - frameWriter.writeInt(flags); - if (flags & prepareFlag.withKeyspace) { - frameWriter.writeString(this.keyspace); - } - } - return frameWriter.write(encoder.protocolVersion, streamId); - } -} - -class StartupRequest extends Request { - - /** - * Creates a new instance of {@link StartupRequest}. - * @param {Object} [options] - * @param [options.cqlVersion] - * @param [options.noCompact] - * @param [options.clientId] - * @param [options.applicationName] - * @param [options.applicationVersion] - */ - constructor(options) { - super(); - this.options = options || {}; - } - - write(encoder, streamId) { - const frameWriter = new FrameWriter(types.opcodes.startup); - - const startupOptions = { - CQL_VERSION: this.options.cqlVersion || '3.0.0', - DRIVER_NAME: packageInfo.description, - DRIVER_VERSION: packageInfo.version - }; - - if(this.options.noCompact) { - startupOptions['NO_COMPACT'] = 'true'; - } - - if (this.options.clientId) { - startupOptions['CLIENT_ID'] = this.options.clientId.toString(); - } - - if (this.options.applicationName) { - startupOptions['APPLICATION_NAME'] = this.options.applicationName; - } - - if (this.options.applicationVersion) { - startupOptions['APPLICATION_VERSION'] = this.options.applicationVersion; - } - - frameWriter.writeStringMap(startupOptions); - return frameWriter.write(encoder.protocolVersion, streamId); - } -} - -class RegisterRequest extends Request { - constructor(events) { - super(); - this.events = events; - } - - write(encoder, streamId) { - const frameWriter = new FrameWriter(types.opcodes.register); - frameWriter.writeStringList(this.events); - return frameWriter.write(encoder.protocolVersion, streamId); - } -} - -/** - * Represents an AUTH_RESPONSE request - * @param {Buffer} token - */ -class AuthResponseRequest extends Request { - constructor(token) { - super(); - this.token = token; - } - - write(encoder, streamId) { - const frameWriter = new FrameWriter(types.opcodes.authResponse); - frameWriter.writeBytes(this.token); - return frameWriter.write(encoder.protocolVersion, streamId); - } -} - -/** - * Represents a protocol v1 CREDENTIALS request message - */ -class CredentialsRequest extends Request { - constructor(username, password) { - super(); - this.username = username; - this.password = password; - } - - write(encoder, streamId) { - const frameWriter = new FrameWriter(types.opcodes.credentials); - frameWriter.writeStringMap({ username:this.username, password:this.password }); - return frameWriter.write(encoder.protocolVersion, streamId); - } -} - -class BatchRequest extends Request { - /** - * Creates a new instance of BatchRequest. - * @param {Array.<{query, params, [info]}>} queries Array of objects with the properties query and params - * @param {ExecutionOptions} execOptions - */ - constructor(queries, execOptions) { - super(); - this.queries = queries; - this.options = execOptions; - this.hints = execOptions.getHints() || utils.emptyArray; - this.type = batchType.logged; - - if (execOptions.isBatchCounter()) { - this.type = batchType.counter; - } else if (!execOptions.isBatchLogged()) { - this.type = batchType.unlogged; - } - } - - /** - * Writes a batch request - */ - write(encoder, streamId) { - //v2: ... - //v3: ...[][] - //dseV1+: similar to v3/v4, flags is an int instead of a byte - if (!this.queries || !(this.queries.length > 0)) { - throw new TypeError(util.format('Invalid queries provided %s', this.queries)); - } - const frameWriter = new FrameWriter(types.opcodes.batch); - let headerFlags = this.options.isQueryTracing() ? types.frameFlags.tracing : 0; - if (this.options.getCustomPayload()) { - //The body may contain the custom payload - headerFlags |= types.frameFlags.customPayload; - frameWriter.writeCustomPayload(this.options.getCustomPayload()); - } - frameWriter.writeByte(this.type); - frameWriter.writeShort(this.queries.length); - const self = this; - this.queries.forEach(function eachQuery(item, i) { - const hints = self.hints[i]; - const params = item.params || utils.emptyArray; - let getParamType; - if (item.queryId) { - // Contains prepared queries - frameWriter.writeByte(1); - frameWriter.writeShortBytes(item.queryId); - getParamType = i => item.meta.columns[i].type; - } - else { - // Contains string queries - frameWriter.writeByte(0); - frameWriter.writeLString(item.query); - getParamType = hints ? (i => hints[i]) : (() => null); - } - - frameWriter.writeShort(params.length); - params.forEach((param, index) => frameWriter.writeBytes(encoder.encode(param, getParamType(index)))); - }, this); - - frameWriter.writeShort(this.options.getConsistency()); - - if (types.protocolVersion.supportsTimestamp(encoder.protocolVersion)) { - // Batch flags - let flags = this.options.getSerialConsistency() ? batchFlag.withSerialConsistency : 0; - const timestamp = this.options.getOrGenerateTimestamp(); - flags |= timestamp !== null && timestamp !== undefined ? batchFlag.withDefaultTimestamp : 0; - - flags |= this.options.getKeyspace() && types.protocolVersion.supportsKeyspaceInRequest(encoder.protocolVersion) - ? batchFlag.withKeyspace : 0; - - if (types.protocolVersion.uses4BytesQueryFlags(encoder.protocolVersion)) { - frameWriter.writeInt(flags); - } - else { - frameWriter.writeByte(flags); - } - - if (flags & batchFlag.withSerialConsistency) { - frameWriter.writeShort(this.options.getSerialConsistency()); - } - - if (flags & batchFlag.withDefaultTimestamp) { - frameWriter.writeLong(timestamp); - } - - if (flags & batchFlag.withKeyspace) { - frameWriter.writeString(this.options.getKeyspace()); - } - } - - // Set the length of the body of the request before writing it - this.length = frameWriter.bodyLength; - - return frameWriter.write(encoder.protocolVersion, streamId, headerFlags); - } - - clone() { - return new BatchRequest(this.queries, this.options); - } -} - -function CancelRequest(operationId) { - this.streamId = null; - this.operationId = operationId; -} - -util.inherits(CancelRequest, Request); - -CancelRequest.prototype.write = function (encoder, streamId) { - const frameWriter = new FrameWriter(types.opcodes.cancel); - frameWriter.writeInt(1); - frameWriter.writeInt(this.operationId); - return frameWriter.write(encoder.protocolVersion, streamId); -}; - -class OptionsRequest extends Request { - - write(encoder, streamId) { - const frameWriter = new FrameWriter(types.opcodes.options); - return frameWriter.write(encoder.protocolVersion, streamId, 0); - } - - clone() { - // since options has no unique state, simply return self. - return this; - } -} - -const options = new OptionsRequest(); - -exports.AuthResponseRequest = AuthResponseRequest; -exports.BatchRequest = BatchRequest; -exports.CancelRequest = CancelRequest; -exports.CredentialsRequest = CredentialsRequest; -exports.ExecuteRequest = ExecuteRequest; -exports.PrepareRequest = PrepareRequest; -exports.QueryRequest = QueryRequest; -exports.Request = Request; -exports.RegisterRequest = RegisterRequest; -exports.StartupRequest = StartupRequest; -exports.options = options; diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/stream-id-stack.js b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/stream-id-stack.js deleted file mode 100644 index 7947af79d1..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/stream-id-stack.js +++ /dev/null @@ -1,200 +0,0 @@ -/* - * Copyright DataStax, Inc. - * - * 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 types = require('./types'); - -/** - * Group size - * @type {number} - */ -const groupSize = 128; - -/** - * Number used to right shift ids to allocate them into groups - * @const - * @type {number} - */ -const shiftToGroup = 7; - -/** - * Amount of groups that can be released per time - * If it grows larger than 4 groups (128 * 4), groups can be released - * @const - * @type {number} - */ -const releasableSize = 4; - -/** - * 32K possible stream ids depending for protocol v3 and above - * @const - * @type {number} - */ -const maxGroupsFor2Bytes = 256; - -/** - * Delay used to check if groups can be released - * @const - * @type {number} - */ -const defaultReleaseDelay = 5000; - -/** - * Represents a queue of ids from 0 to maximum stream id supported by the protocol version. - * Clients can dequeue a stream id using {@link StreamIdStack#shift()} and enqueue (release) using - * {@link StreamIdStack#push()} - */ -class StreamIdStack { - /** - * Creates a new instance of StreamIdStack. - * @param {number} version Protocol version - * @constructor - */ - constructor(version) { - //Ecmascript Number is 64-bit double, it can be optimized by the engine into a 32-bit int, but nothing below that. - //We try to allocate as few as possible in arrays of 128 - this.currentGroup = generateGroup(0); - this.groupIndex = 0; - this.groups = [this.currentGroup]; - this.releaseTimeout = null; - this.setVersion(version); - /** - * Returns the amount of ids currently in use - * @member {number} - */ - this.inUse = 0; - this.releaseDelay = defaultReleaseDelay; - } - - /** - * Sets the protocol version - * @param {Number} version - */ - setVersion(version) { - //128 or 32K stream ids depending on the protocol version - this.maxGroups = types.protocolVersion.uses2BytesStreamIds(version) ? maxGroupsFor2Bytes : 1; - } - - /** - * Dequeues an id. - * Similar to {@link Array#pop()}. - * @returns {Number} Returns an id or null - */ - pop() { - let id = this.currentGroup.pop(); - if (typeof id !== 'undefined') { - this.inUse++; - return id; - } - //try to use the following groups - while (this.groupIndex < this.groups.length - 1) { - //move to the following group - this.currentGroup = this.groups[++this.groupIndex]; - //try dequeue - id = this.currentGroup.pop(); - if (typeof id !== 'undefined') { - this.inUse++; - return id; - } - } - return this._tryCreateGroup(); - } - - /** - * Enqueue an id for future use. - * Similar to {@link Array#push()}. - * @param {Number} id - */ - push(id) { - this.inUse--; - const groupIndex = id >> shiftToGroup; - const group = this.groups[groupIndex]; - group.push(id); - if (groupIndex < this.groupIndex) { - //Set the lower group to be used to dequeue from - this.groupIndex = groupIndex; - this.currentGroup = group; - } - this._tryIssueRelease(); - } - - /** - * Clears all timers - */ - clear() { - if (this.releaseTimeout) { - clearTimeout(this.releaseTimeout); - this.releaseTimeout = null; - } - } - - /** - * Tries to create an additional group and returns a new id - * @returns {Number} Returns a new id or null if it's not possible to create a new group - * @private - */ - _tryCreateGroup() { - if (this.groups.length === this.maxGroups) { - //we can have an additional group - return null; - } - //Add a new group at the last position - this.groupIndex = this.groups.length; - //Using 128 * groupIndex as initial value - this.currentGroup = generateGroup(this.groupIndex << shiftToGroup); - this.groups.push(this.currentGroup); - this.inUse++; - return this.currentGroup.pop(); - } - - _tryIssueRelease() { - if (this.releaseTimeout || this.groups.length <= releasableSize) { - //Nothing to release or a release delay has been issued - return; - } - - this.releaseTimeout = setTimeout(() => this._releaseGroups(), this.releaseDelay); - } - - _releaseGroups() { - let counter = 0; - let index = this.groups.length - 1; - //only release up to n groups (n = releasable size) - //shrink back up to n groups not all the way up to 1 - while (counter++ < releasableSize && this.groups.length > releasableSize && index > this.groupIndex) { - if (this.groups[index].length !== groupSize) { - //the group is being used - break; - } - this.groups.pop(); - index--; - } - this.releaseTimeout = null; - //Issue next release if applies - this._tryIssueRelease(); - } -} - -function generateGroup(initialValue) { - const arr = new Array(groupSize); - const upperBound = initialValue + groupSize - 1; - for (let i = 0; i < groupSize; i++) { - arr[i] = upperBound - i; - } - return arr; -} - -module.exports = StreamIdStack; \ No newline at end of file diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/streams.js b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/streams.js deleted file mode 100644 index 158cc8b727..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/streams.js +++ /dev/null @@ -1,582 +0,0 @@ -/* - * Copyright DataStax, Inc. - * - * 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 util = require('util'); -const { Transform, Writable } = require('stream'); - -const types = require('./types'); -const utils = require('./utils'); -const errors = require('./errors'); -const { FrameHeader } = types; -const { FrameReader } = require('./readers'); - -/** - * Transforms chunks, emits data objects {header, chunk} - * @param options Stream options - * @extends Transform - */ -function Protocol (options) { - Transform.call(this, options); - this.header = null; - this.bodyLength = 0; - this.clearHeaderChunks(); - this.version = 0; - this.headerSize = 0; -} - -util.inherits(Protocol, Transform); - -Protocol.prototype._transform = function (chunk, encoding, callback) { - let error = null; - try { - this.readItems(chunk); - } - catch (err) { - error = err; - } - callback(error); -}; - -/** - * Parses the chunk into frames (header and body). - * Emits (push) complete frames or frames with incomplete bodies. Following chunks containing the rest of the body will - * be emitted using the same frame. - * It buffers incomplete headers. - * @param {Buffer} chunk - */ -Protocol.prototype.readItems = function (chunk) { - if (!chunk || chunk.length === 0) { - return; - } - if (this.version === 0) { - //The server replies the first message with the max protocol version supported - this.version = FrameHeader.getProtocolVersion(chunk); - this.headerSize = FrameHeader.size(this.version); - } - let offset = 0; - let currentHeader = this.header; - this.header = null; - if (this.headerChunks.byteLength !== 0) { - //incomplete header was buffered try to read the header from the buffered chunks - this.headerChunks.parts.push(chunk); - if (this.headerChunks.byteLength + chunk.length < this.headerSize) { - this.headerChunks.byteLength += chunk.length; - return; - } - currentHeader = FrameHeader.fromBuffer(Buffer.concat(this.headerChunks.parts, this.headerSize)); - offset = this.headerSize - this.headerChunks.byteLength; - this.clearHeaderChunks(); - } - const items = []; - while (true) { - if (!currentHeader) { - if (this.headerSize > chunk.length - offset) { - if (chunk.length - offset <= 0) { - break; - } - //the header is incomplete, buffer it until the next chunk - const headerPart = chunk.slice(offset, chunk.length); - this.headerChunks.parts.push(headerPart); - this.headerChunks.byteLength = headerPart.length; - break; - } - //read header - currentHeader = FrameHeader.fromBuffer(chunk, offset); - offset += this.headerSize; - } - //parse body - const remaining = chunk.length - offset; - if (currentHeader.bodyLength <= remaining + this.bodyLength) { - items.push({ header: currentHeader, chunk: chunk, offset: offset, frameEnded: true }); - offset += currentHeader.bodyLength - this.bodyLength; - //reset the body length - this.bodyLength = 0; - } - else if (remaining >= 0) { - //the body is not fully contained in this chunk - //will continue later - this.header = currentHeader; - this.bodyLength += remaining; - if (remaining > 0) { - //emit if there is at least a byte to emit - items.push({ header: currentHeader, chunk: chunk, offset: offset, frameEnded: false }); - } - break; - } - currentHeader = null; - } - for (let i = 0; i < items.length; i++) { - this.push(items[i]); - } -}; - -Protocol.prototype.clearHeaderChunks = function () { - this.headerChunks = { byteLength: 0, parts: [] }; -}; - -/** - * A stream that gets reads header + body chunks and transforms them into header + (row | error) - * @param {Object} streamOptions Node.js Stream options - * @param {Encoder} encoder Encoder instance for the parser to use - * @extends Transform - */ -function Parser (streamOptions, encoder) { - Transform.call(this, streamOptions); - //frames that are streaming, indexed by id - this.frames = {}; - this.encoder = encoder; -} - -util.inherits(Parser, Transform); - -Parser.prototype._transform = function (item, encoding, callback) { - const frameInfo = this.frameState(item); - - let error = null; - try { - this.parseBody(frameInfo, item); - } - catch (err) { - error = err; - } - callback(error); - - if (item.frameEnded) { - if (frameInfo.cellBuffer) { - //Frame was being streamed but an error force it to buffer the result - this.push({ - header: frameInfo.header, - error: new errors.DriverInternalError('There was an problem while parsing streaming frame, opcode ' + - frameInfo.header.opcode) - }); - } - //all the parsing finished and it was streamed down - //emit an item that signals it - this.push({ header: frameInfo.header, frameEnded: true}); - } -}; - -/** - * @param frameInfo - * @param {{header: FrameHeader, chunk: Buffer, offset: Number}} item - */ -Parser.prototype.parseBody = function (frameInfo, item) { - frameInfo.isStreaming = frameInfo.byRow && item.header.opcode === types.opcodes.result; - if (!this.handleFrameBuffers(frameInfo, item)) { - // Frame isn't complete and we are not streaming the frame - return; - } - const reader = new FrameReader(item.header, item.chunk, item.offset); - // Check that flags have not been parsed yet for this frame - if (frameInfo.flagsInfo === undefined) { - const originalOffset = reader.offset; - try { - frameInfo.flagsInfo = reader.readFlagsInfo(); - } - catch (e) { - return this.handleParsingError(e, frameInfo, reader, originalOffset); - } - } - - //All the body for most operations is already buffered at this stage - //Except for RESULT - switch (item.header.opcode) { - case types.opcodes.result: - return this.parseResult(frameInfo, reader); - case types.opcodes.ready: - case types.opcodes.authSuccess: - return this.push({ header: frameInfo.header, ready: true }); - case types.opcodes.authChallenge: - return this.push({ header: frameInfo.header, authChallenge: true, token: reader.readBytes()}); - case types.opcodes.authenticate: - return this.push({ header: frameInfo.header, mustAuthenticate: true, authenticatorName: reader.readString()}); - case types.opcodes.error: - return this.push({ header: frameInfo.header, error: reader.readError()}); - case types.opcodes.supported: - return this.push({ header: frameInfo.header, supported: reader.readStringMultiMap()}); - case types.opcodes.event: - return this.push({ header: frameInfo.header, event: reader.readEvent()}); - default: - return this.push({ header: frameInfo.header, error: new Error('Received invalid opcode: ' + item.header.opcode) }); - } -}; - -/** - * Buffers if needed and returns true if it has all the necessary data to continue parsing the frame. - * @param frameInfo - * @param {{header: FrameHeader, chunk: Buffer, offset: Number}} item - * @returns {Boolean} - */ -Parser.prototype.handleFrameBuffers = function (frameInfo, item) { - if (!frameInfo.isStreaming) { - // Handle buffering for complete frame bodies - const currentLength = (frameInfo.bufferLength || 0) + item.chunk.length - item.offset; - if (currentLength < item.header.bodyLength) { - //buffer until the frame is completed - this.addFrameBuffer(frameInfo, item); - return false; - } - //We have received the full frame body - if (frameInfo.buffers) { - item.chunk = this.getFrameBuffer(frameInfo, item); - item.offset = 0; - } - return true; - } - if (frameInfo.cellBuffer) { - // Handle buffering for frame cells (row cells or metadata cells) - if (item.offset !== 0) { - throw new errors.DriverInternalError('Following chunks can not have an offset greater than zero'); - } - frameInfo.cellBuffer.parts.push(item.chunk); - if (!frameInfo.cellBuffer.expectedLength) { - //Its a buffer outside a row cell (metadata or other) - if (frameInfo.cellBuffer.parts.length !== 2) { - throw new errors.DriverInternalError('Buffer for streaming frame can not contain more than 1 item'); - } - item.chunk = Buffer.concat(frameInfo.cellBuffer.parts, frameInfo.cellBuffer.byteLength + item.chunk.length); - frameInfo.cellBuffer = null; - return true; - } - if (frameInfo.cellBuffer.expectedLength > frameInfo.cellBuffer.byteLength + item.chunk.length) { - //We still haven't got the cell data - frameInfo.cellBuffer.byteLength += item.chunk.length; - return false; - } - item.chunk = Buffer.concat(frameInfo.cellBuffer.parts, frameInfo.cellBuffer.byteLength + item.chunk.length); - frameInfo.cellBuffer = null; - } - return true; -}; - -/** - * Adds this chunk to the frame buffers. - * @param frameInfo - * @param {{header: FrameHeader, chunk: Buffer, offset: Number}} item - */ -Parser.prototype.addFrameBuffer = function (frameInfo, item) { - if (!frameInfo.buffers) { - frameInfo.buffers = [ item.chunk.slice(item.offset) ]; - frameInfo.bufferLength = item.chunk.length - item.offset; - return; - } - if (item.offset > 0) { - throw new errors.DriverInternalError('Following chunks can not have an offset greater than zero'); - } - frameInfo.buffers.push(item.chunk); - frameInfo.bufferLength += item.chunk.length; -}; - -/** - * Adds the last chunk and concatenates the frame buffers - * @param frameInfo - * @param {{header: FrameHeader, chunk: Buffer, offset: Number}} item - */ -Parser.prototype.getFrameBuffer = function (frameInfo, item) { - frameInfo.buffers.push(item.chunk); - const result = Buffer.concat(frameInfo.buffers, frameInfo.bodyLength); - frameInfo.buffers = null; - return result; -}; - -/** - * Tries to read the result in the body of a message - * @param frameInfo Frame information, header / metadata - * @param {FrameReader} reader - */ -Parser.prototype.parseResult = function (frameInfo, reader) { - let result; - // As we might be streaming and the frame buffer might not be complete, - // read the metadata and different types of result values in a try-catch. - // Store the reader position - const originalOffset = reader.offset; - try { - if (!frameInfo.meta) { - frameInfo.kind = reader.readInt(); - // Spec 4.2.5 - switch (frameInfo.kind) { - case types.resultKind.voidResult: - result = { header: frameInfo.header, flags: frameInfo.flagsInfo }; - break; - case types.resultKind.rows: - // Parse the rows metadata, the rest of the response is going to be parsed afterwards - frameInfo.meta = reader.readMetadata(frameInfo.kind); - break; - case types.resultKind.setKeyspace: - result = { header: frameInfo.header, keyspaceSet: reader.readString(), flags: frameInfo.flagsInfo }; - break; - case types.resultKind.prepared: - { - const preparedId = utils.copyBuffer(reader.readShortBytes()); - frameInfo.meta = reader.readMetadata(frameInfo.kind); - result = { header: frameInfo.header, id: preparedId, meta: frameInfo.meta, flags: frameInfo.flagsInfo }; - break; - } - case types.resultKind.schemaChange: - result = { header: frameInfo.header, schemaChange: reader.parseSchemaChange(), flags: frameInfo.flagsInfo }; - break; - default: - throw errors.DriverInternalError('Unexpected result kind: ' + frameInfo.kind); - } - } - } - catch (e) { - return this.handleParsingError(e, frameInfo, reader, originalOffset); - } - if (result) { - if (frameInfo.emitted) { - // It may contain additional metadata and info that it's not being parsed - return; - } - frameInfo.emitted = true; - return this.push(result); - } - if (reader.remainingLength() > 0) { - this.parseRows(frameInfo, reader); - } -}; - -/** - * @param frameInfo - * @param {FrameReader} reader - */ -Parser.prototype.parseRows = function (frameInfo, reader) { - if (frameInfo.parsingError) { - //No more processing on this frame - return; - } - if (frameInfo.rowLength === undefined) { - try { - frameInfo.rowLength = reader.readInt(); - } - catch (e) { - return this.handleParsingError(e, frameInfo, reader); - } - } - if (frameInfo.rowLength === 0) { - return this.push({ - header: frameInfo.header, - result: { rows: utils.emptyArray, meta: frameInfo.meta, flags: frameInfo.flagsInfo } - }); - } - const meta = frameInfo.meta; - frameInfo.rowIndex = frameInfo.rowIndex || 0; - for (let i = frameInfo.rowIndex; i < frameInfo.rowLength; i++) { - const rowOffset = reader.offset; - const row = new types.Row(meta.columns); - let cellBuffer; - for (let j = 0; j < meta.columns.length; j++ ) { - const c = meta.columns[j]; - try { - cellBuffer = reader.readBytes(); - } - catch (e) { - return this.handleParsingError(e, frameInfo, reader, rowOffset, i); - } - try { - row[c.name] = this.encoder.decode(cellBuffer, c.type); - } - catch (e) { - //Something went wrong while decoding, we are not going to be able to recover - return this.handleParsingError(e, frameInfo, null); - } - } - this.push({ - header: frameInfo.header, - row: row, - meta: frameInfo.meta, - byRow: frameInfo.byRow, - length: frameInfo.rowLength, - flags: frameInfo.flagsInfo - }); - } - if (frameInfo.byRow) { - // Use an event item to identify that all the streaming rows have finished processing - this.push({ - header: frameInfo.header, - byRowCompleted: true, - meta: frameInfo.meta, - length: frameInfo.rowLength, - flags: frameInfo.flagsInfo - }); - } -}; - -/** - * Sets parser options (ie: how to yield the results as they are parsed) - * @param {Number} id Id of the stream - * @param options - */ -Parser.prototype.setOptions = function (id, options) { - if (this.frames[id.toString()]) { - throw new types.DriverError('There was already state for this frame'); - } - this.frames[id.toString()] = options; -}; - -/** - * Manually clears the frame options. - * This class already clears the provided options when the frame ends, so it's usually not required to invoke this - * method. - * When manually setting the options for continuous paging, it's possible that the frame options are set while - * it's being cancelled. - * @param {Number} id The streamId - */ -Parser.prototype.clearOptions = function (id) { - delete this.frames[id.toString()]; -}; - -/** - * Gets the frame info from the internal state. - * In case it is not there, it creates it. - * In case the frame ended - */ -Parser.prototype.frameState = function (item) { - let frameInfo = this.frames[item.header.streamId]; - if (!frameInfo) { - frameInfo = {}; - if (!item.frameEnded) { - //store it in the frames - this.frames[item.header.streamId] = frameInfo; - } - } - else if (item.frameEnded) { - //if it was already stored, remove it - delete this.frames[item.header.streamId]; - } - frameInfo.header = item.header; - return frameInfo; -}; - -/** - * Handles parsing error: pushing an error if its unexpected or buffer the cell if its streaming - * @param {Error} e - * @param frameInfo - * @param {FrameReader} reader - * @param {Number} [originalOffset] - * @param {Number} [rowIndex] - */ -Parser.prototype.handleParsingError = function (e, frameInfo, reader, originalOffset, rowIndex) { - if (reader && frameInfo.isStreaming && (e instanceof RangeError)) { - //A controlled error, buffer from offset and move on - return this.bufferResultCell(frameInfo, reader, originalOffset, rowIndex, e.expectedLength); - } - frameInfo.parsingError = true; - frameInfo.cellBuffer = null; - this.push({ header: frameInfo.header, error: e }); -}; - -/** - * When streaming, it buffers data since originalOffset. - * @param frameInfo - * @param {FrameReader} reader - * @param {Number} [originalOffset] - * @param {Number} [rowIndex] - * @param {Number} [expectedLength] - */ -Parser.prototype.bufferResultCell = function (frameInfo, reader, originalOffset, rowIndex, expectedLength) { - if (!originalOffset && originalOffset !== 0) { - originalOffset = reader.offset; - } - frameInfo.rowIndex = rowIndex; - const buffer = reader.slice(originalOffset); - frameInfo.cellBuffer = { - parts: [ buffer ], - byteLength: buffer.length, - expectedLength: expectedLength - }; -}; - -/** - * Represents a writable streams that emits results - */ -function ResultEmitter(options) { - Writable.call(this, options); - /** - * Stores the rows for frames that needs to be yielded as one result with many rows - */ - this.rowBuffer = {}; -} - -util.inherits(ResultEmitter, Writable); - -ResultEmitter.prototype._write = function (item, encoding, callback) { - let error = null; - try { - this.each(item); - } - catch (err) { - error = err; - } - callback(error); -}; - - -/** - * Analyzes the item and emit the corresponding event - */ -ResultEmitter.prototype.each = function (item) { - if (item.error || item.result) { - //Its either an error or an empty array rows - //no transformation needs to be made - return this.emit('result', item.header, item.error, item.result); - } - if (item.frameEnded) { - return this.emit('frameEnded', item.header); - } - if (item.lastContinuousPage) { - return this.emit('lastContinuousPage', item.header); - } - if (item.byRowCompleted) { - return this.emit('byRowCompleted', item.header, item.row, item.meta, item.flags); - } - if (item.byRow) { - //it should be yielded by row - return this.emit('row', item.header, item.row, item.meta, item.length, item.flags); - } - if (item.row) { - //it should be yielded as a result - //it needs to be buffered to an array of rows - return this.bufferAndEmit(item); - } - if (item.event) { - //its an event from Cassandra - return this.emit('nodeEvent', item.header, item.event); - } - //its a raw response (object with flags) - return this.emit('result', item.header, null, item); -}; - -/** - * Buffers the rows until the result set is completed and emits the result event. - */ -ResultEmitter.prototype.bufferAndEmit = function (item) { - let rows = this.rowBuffer[item.header.streamId]; - if (!rows) { - rows = this.rowBuffer[item.header.streamId] = []; - } - rows.push(item.row); - if (rows.length === item.length) { - this.emit('result', item.header, null, { rows: rows, meta: item.meta, flags: item.flags}); - delete this.rowBuffer[item.header.streamId]; - } -}; - -exports.Protocol = Protocol; -exports.Parser = Parser; -exports.ResultEmitter = ResultEmitter; diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/token.js b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/token.js deleted file mode 100644 index dabed71f11..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/token.js +++ /dev/null @@ -1,286 +0,0 @@ -/* - * Copyright DataStax, Inc. - * - * 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 types = require('./types'); -const util = require('util'); - -const _Murmur3TokenType = types.dataTypes.getByName('bigint'); -const _RandomTokenType = types.dataTypes.getByName('varint'); -const _OrderedTokenType = types.dataTypes.getByName('blob'); - -/** - * Represents a token on the Cassandra ring. - */ -class Token { - constructor(value) { - this._value = value; - } - - /** - * @returns {{code: number, info: *|Object}} The type info for the - * type of the value of the token. - */ - getType() { - throw new Error('You must implement a getType function for this Token instance'); - } - - /** - * @returns {*} The raw value of the token. - */ - getValue() { - return this._value; - } - - toString() { - return this._value.toString(); - } - - /** - * Returns 0 if the values are equal, 1 if greater than other, -1 - * otherwise. - * - * @param {Token} other - * @returns {Number} - */ - compare(other) { - return this._value.compare(other._value); - } - - equals(other) { - return this.compare(other) === 0; - } - - inspect() { - return this.constructor.name + ' { ' + this.toString() + ' }'; - } -} - -/** - * Represents a token from a Cassandra ring where the partitioner - * is Murmur3Partitioner. - * - * The raw token type is a varint (represented by MutableLong). - */ -class Murmur3Token extends Token { - constructor(value) { - super(value); - } - - getType() { - return _Murmur3TokenType; - } -} - -/** - * Represents a token from a Cassandra ring where the partitioner - * is RandomPartitioner. - * - * The raw token type is a bigint (represented by Number). - */ -class RandomToken extends Token { - constructor(value) { - super(value); - } - - getType() { - return _RandomTokenType; - } -} - -/** - * Represents a token from a Cassandra ring where the partitioner - * is ByteOrderedPartitioner. - * - * The raw token type is a blob (represented by Buffer or Array). - */ -class ByteOrderedToken extends Token { - constructor(value) { - super(value); - } - - getType() { - return _OrderedTokenType; - } - - toString() { - return this._value.toString('hex').toUpperCase(); - } -} - -/** - * Represents a range of tokens on a Cassandra ring. - * - * A range is start-exclusive and end-inclusive. It is empty when - * start and end are the same token, except if that is the minimum - * token, in which case the range covers the whole ring (this is - * consistent with the behavior of CQL range queries). - * - * Note that CQL does not handle wrapping. To query all partitions - * in a range, see {@link unwrap}. - */ -class TokenRange { - constructor(start, end, tokenizer) { - this.start = start; - this.end = end; - Object.defineProperty(this, '_tokenizer', { value: tokenizer, enumerable: false}); - } - - /** - * Splits this range into a number of smaller ranges of equal "size" - * (referring to the number of tokens, not the actual amount of data). - * - * Splitting an empty range is not permitted. But not that, in edge - * cases, splitting a range might produce one or more empty ranges. - * - * @param {Number} numberOfSplits Number of splits to make. - * @returns {TokenRange[]} Split ranges. - * @throws {Error} If splitting an empty range. - */ - splitEvenly(numberOfSplits) { - if (numberOfSplits < 1) { - throw new Error(util.format("numberOfSplits (%d) must be greater than 0.", numberOfSplits)); - } - if (this.isEmpty()) { - throw new Error("Can't split empty range " + this.toString()); - } - - const tokenRanges = []; - const splitPoints = this._tokenizer.split(this.start, this.end, numberOfSplits); - let splitStart = this.start; - let splitEnd; - for (let splitIndex = 0; splitIndex < splitPoints.length; splitIndex++) { - splitEnd = splitPoints[splitIndex]; - tokenRanges.push(new TokenRange(splitStart, splitEnd, this._tokenizer)); - splitStart = splitEnd; - } - tokenRanges.push(new TokenRange(splitStart, this.end, this._tokenizer)); - return tokenRanges; - } - - /** - * A range is empty when start and end are the same token, except if - * that is the minimum token, in which case the range covers the - * whole ring. This is consistent with the behavior of CQL range - * queries. - * - * @returns {boolean} Whether this range is empty. - */ - isEmpty() { - return this.start.equals(this.end) && !this.start.equals(this._tokenizer.minToken()); - } - - /** - * A range wraps around the end of the ring when the start token - * is greater than the end token and the end token is not the - * minimum token. - * - * @returns {boolean} Whether this range wraps around. - */ - isWrappedAround() { - return this.start.compare(this.end) > 0 && !this.end.equals(this._tokenizer.minToken()); - } - - /** - * Splits this range into a list of two non-wrapping ranges. - * - * This will return the range itself if it is non-wrapped, or two - * ranges otherwise. - * - * This is useful for CQL range queries, which do not handle - * wrapping. - * - * @returns {TokenRange[]} The list of non-wrapping ranges. - */ - unwrap() { - if (this.isWrappedAround()) { - return [ - new TokenRange(this.start, this._tokenizer.minToken(), this._tokenizer), - new TokenRange(this._tokenizer.minToken(), this.end, this._tokenizer) - ]; - } - return [this]; - } - - /** - * Whether this range contains a given Token. - * - * @param {*} token Token to check for. - * @returns {boolean} Whether or not the Token is in this range. - */ - contains(token) { - if (this.isEmpty()) { - return false; - } - const minToken = this._tokenizer.minToken(); - if (this.end.equals(minToken)) { - if (this.start.equals(minToken)) { - return true; // ]minToken, minToken] === full ring - } else if (token.equals(minToken)) { - return true; - } - return token.compare(this.start) > 0; - } - - const isAfterStart = token.compare(this.start) > 0; - const isBeforeEnd = token.compare(this.end) <= 0; - // if wrapped around ring, token is in ring if its after start or before end. - // otherwise, token is in ring if its after start and before end. - return this.isWrappedAround() - ? isAfterStart || isBeforeEnd - : isAfterStart && isBeforeEnd; - } - - /** - * Determines if the input range is equivalent to this one. - * - * @param {TokenRange} other Range to compare with. - * @returns {boolean} Whether or not the ranges are equal. - */ - equals(other) { - if (other === this) { - return true; - } else if (other instanceof TokenRange) { - return this.compare(other) === 0; - } - return false; - } - - /** - * Returns 0 if the values are equal, otherwise compares against - * start, if start is equal, compares against end. - * - * @param {TokenRange} other Range to compare with. - * @returns {Number} - */ - compare(other) { - const compareStart = this.start.compare(other.start); - return compareStart !== 0 ? compareStart : this.end.compare(other.end); - } - - toString() { - return util.format(']%s, %s]', - this.start.toString(), - this.end.toString() - ); - } -} - -exports.Token = Token; -exports.TokenRange = TokenRange; -exports.ByteOrderedToken = ByteOrderedToken; -exports.Murmur3Token = Murmur3Token; -exports.RandomToken = RandomToken; \ No newline at end of file diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/tokenizer.js b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/tokenizer.js deleted file mode 100644 index 57340e651b..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/tokenizer.js +++ /dev/null @@ -1,584 +0,0 @@ -/* - * Copyright DataStax, Inc. - * - * 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 types = require('./types'); -const token = require('./token'); -const utils = require('./utils'); -const MutableLong = require('./types/mutable-long'); -const { Integer } = types; - -// Murmur3 constants -//-0x783C846EEEBDAC2B -const mconst1 = new MutableLong(0x53d5, 0x1142, 0x7b91, 0x87c3); -//0x4cf5ad432745937f -const mconst2 = new MutableLong(0x937f, 0x2745, 0xad43, 0x4cf5); -const mlongFive = MutableLong.fromNumber(5); -//0xff51afd7ed558ccd -const mconst3 = new MutableLong(0x8ccd, 0xed55, 0xafd7, 0xff51); -//0xc4ceb9fe1a85ec53 -const mconst4 = new MutableLong(0xec53, 0x1a85, 0xb9fe, 0xc4ce); -const mconst5 = MutableLong.fromNumber(0x52dce729); -const mconst6 = MutableLong.fromNumber(0x38495ab5); - -/** - * Represents a set of methods that are able to generate and parse tokens for the C* partitioner. - * @abstract - */ -class Tokenizer { - constructor() { - - } - - /** - * Creates a token based on the Buffer value provided - * @abstract - * @param {Buffer|Array} value - * @returns {Token} Computed token - */ - hash(value) { - throw new Error('You must implement a hash function for the tokenizer'); - } - - /** - * Parses a token string and returns a representation of the token - * @abstract - * @param {String} value - */ - parse(value) { - throw new Error('You must implement a parse function for the tokenizer'); - } - - minToken() { - throw new Error('You must implement a minToken function for the tokenizer'); - } - - /** - * Splits the range specified by start and end into numberOfSplits equal parts. - * @param {Token} start Starting token - * @param {Token} end End token - * @param {Number} numberOfSplits Number of splits to make. - */ - split(start, end, numberOfSplits) { - throw new Error('You must implement a split function for the tokenizer'); - } - - /** - * Common implementation for splitting token ranges when start is in - * a shared Integer format. - * - * @param {Integer} start Starting token - * @param {Integer} range How large the range of the split is - * @param {Integer} ringEnd The end point of the ring so we know where to wrap - * @param {Integer} ringLength The total size of the ring - * @param {Number} numberOfSplits The number of splits to make - * @returns {Array} The evenly-split points on the range - */ - splitBase(start, range, ringEnd, ringLength, numberOfSplits) { - const numberOfSplitsInt = Integer.fromInt(numberOfSplits); - const divider = range.divide(numberOfSplitsInt); - let remainder = range.modulo(numberOfSplitsInt); - - const results = []; - let current = start; - const dividerPlusOne = divider.add(Integer.ONE); - - for(let i = 1; i < numberOfSplits; i++) { - if (remainder.greaterThan(Integer.ZERO)) { - current = current.add(dividerPlusOne); - } else { - current = current.add(divider); - } - if (ringLength && current.greaterThan(ringEnd)) { - current = current.subtract(ringLength); - } - results.push(current); - remainder = remainder.subtract(Integer.ONE); - } - return results; - } - - /** - * Return internal string based representation of a Token. - * @param {Token} token - */ - stringify(token) { - return token.getValue().toString(); - } -} - -/** - * Uniformly distributes data across the cluster based on Cassandra flavored Murmur3 hashed values. - */ -class Murmur3Tokenizer extends Tokenizer { - - constructor() { - super(); - } - - /** - * @param {Buffer} value - * @return {Murmur3Token} - */ - hash(value) { - // This is an adapted version of the MurmurHash.hash3_x64_128 from Cassandra used - // for M3P. Compared to that methods, there's a few inlining of arguments and we - // only return the first 64-bits of the result since that's all M3 partitioner uses. - - const data = value; - let offset = 0; - const length = data.length; - - const nblocks = length >> 4; // Process as 128-bit blocks. - - const h1 = new MutableLong(); - const h2 = new MutableLong(); - let k1 = new MutableLong(); - let k2 = new MutableLong(); - - for (let i = 0; i < nblocks; i++) { - k1 = this.getBlock(data, offset, i * 2); - k2 = this.getBlock(data, offset, i * 2 + 1); - - k1.multiply(mconst1); - this.rotl64(k1, 31); - k1.multiply(mconst2); - - h1.xor(k1); - this.rotl64(h1, 27); - h1.add(h2); - h1.multiply(mlongFive).add(mconst5); - - k2.multiply(mconst2); - this.rotl64(k2, 33); - k2.multiply(mconst1); - h2.xor(k2); - this.rotl64(h2, 31); - h2.add(h1); - h2.multiply(mlongFive).add(mconst6); - } - //---------- - // tail - - // Advance offset to the unprocessed tail of the data. - offset += nblocks * 16; - - k1 = new MutableLong(); - k2 = new MutableLong(); - - /* eslint-disable no-fallthrough */ - switch(length & 15) { - case 15: - k2.xor(fromSignedByte(data[offset+14]).shiftLeft(48)); - case 14: - k2.xor(fromSignedByte(data[offset+13]).shiftLeft(40)); - case 13: - k2.xor(fromSignedByte(data[offset+12]).shiftLeft(32)); - case 12: - k2.xor(fromSignedByte(data[offset+11]).shiftLeft(24)); - case 11: - k2.xor(fromSignedByte(data[offset+10]).shiftLeft(16)); - case 10: - k2.xor(fromSignedByte(data[offset+9]).shiftLeft(8)); - case 9: - k2.xor(fromSignedByte(data[offset+8])); - k2.multiply(mconst2); - this.rotl64(k2, 33); - k2.multiply(mconst1); - h2.xor(k2); - case 8: - k1.xor(fromSignedByte(data[offset+7]).shiftLeft(56)); - case 7: - k1.xor(fromSignedByte(data[offset+6]).shiftLeft(48)); - case 6: - k1.xor(fromSignedByte(data[offset+5]).shiftLeft(40)); - case 5: - k1.xor(fromSignedByte(data[offset+4]).shiftLeft(32)); - case 4: - k1.xor(fromSignedByte(data[offset+3]).shiftLeft(24)); - case 3: - k1.xor(fromSignedByte(data[offset+2]).shiftLeft(16)); - case 2: - k1.xor(fromSignedByte(data[offset+1]).shiftLeft(8)); - case 1: - k1.xor(fromSignedByte(data[offset])); - k1.multiply(mconst1); - this.rotl64(k1,31); - k1.multiply(mconst2); - h1.xor(k1); - } - /* eslint-enable no-fallthrough */ - - h1.xor(MutableLong.fromNumber(length)); - h2.xor(MutableLong.fromNumber(length)); - - h1.add(h2); - h2.add(h1); - - - this.fmix(h1); - this.fmix(h2); - - h1.add(h2); - - return new token.Murmur3Token(h1); - } - - /** - * - * @param {Array} key - * @param {Number} offset - * @param {Number} index - * @return {MutableLong} - */ - getBlock(key, offset, index) { - const i8 = index << 3; - const blockOffset = offset + i8; - return new MutableLong( - (key[blockOffset]) | (key[blockOffset + 1] << 8), - (key[blockOffset + 2]) | (key[blockOffset + 3] << 8), - (key[blockOffset + 4]) | (key[blockOffset + 5] << 8), - (key[blockOffset + 6]) | (key[blockOffset + 7] << 8) - ); - } - - /** - * @param {MutableLong} v - * @param {Number} n - */ - rotl64(v, n) { - const left = v.clone().shiftLeft(n); - v.shiftRightUnsigned(64 - n).or(left); - } - - /** @param {MutableLong} k */ - fmix(k) { - k.xor(new MutableLong(k.getUint16(2) >>> 1 | ((k.getUint16(3) << 15) & 0xffff), k.getUint16(3) >>> 1, 0, 0)); - k.multiply(mconst3); - const other = new MutableLong( - (k.getUint16(2) >>> 1) | ((k.getUint16(3) << 15) & 0xffff), - k.getUint16(3) >>> 1, - 0, - 0 - ); - k.xor(other); - k.multiply(mconst4); - k.xor(new MutableLong(k.getUint16(2) >>> 1 | (k.getUint16(3) << 15 & 0xffff), k.getUint16(3) >>> 1, 0, 0)); - } - - /** - * Parses a int64 decimal string representation into a MutableLong. - * @param {String} value - * @returns {Murmur3Token} - */ - parse(value) { - return new token.Murmur3Token(MutableLong.fromString(value)); - } - - minToken() { - if (!this._minToken) { - // minimum long value. - this._minToken = this.parse('-9223372036854775808'); - } - return this._minToken; - } - - maxToken() { - if (!this._maxToken) { - this._maxToken = this.parse('9223372036854775807'); - } - return this._maxToken; - } - - maxValue() { - if (!this._maxValue) { - this._maxValue = Integer.fromString('9223372036854775807'); - } - return this._maxValue; - } - - minValue() { - if (!this._minValue) { - this._minValue = Integer.fromString('-9223372036854775808'); - } - return this._minValue; - } - - ringLength() { - if (!this._ringLength) { - this._ringLength = this.maxValue().subtract(this.minValue()); - } - return this._ringLength; - } - - split(start, end, numberOfSplits) { - // ]min, min] means the whole ring. - if (start.equals(end) && start.equals(this.minToken())) { - end = this.maxToken(); - } - - const startVal = Integer.fromString(start.getValue().toString()); - const endVal = Integer.fromString(end.getValue().toString()); - - let range = endVal.subtract(startVal); - if (range.isNegative()) { - range = range.add(this.ringLength()); - } - - const values = this.splitBase(startVal, range, this.maxValue(), this.ringLength(), numberOfSplits); - return values.map(v => this.parse(v.toString())); - } - - stringify(token) { - // Get the underlying MutableLong - const value = token.getValue(); - // We need a way to uniquely represent a token, it doesn't have to be the decimal string representation - // Using the uint16 avoids divisions and other expensive operations on the longs - return value.getUint16(0) + ',' + value.getUint16(1) + ',' + value.getUint16(2) + ',' + value.getUint16(3); - } -} - -/** - * Uniformly distributes data across the cluster based on MD5 hash values. - */ -class RandomTokenizer extends Tokenizer { - constructor() { - super(); - // eslint-disable-next-line - this._crypto = require('crypto'); - } - - /** - * @param {Buffer|Array} value - * @returns {RandomToken} - */ - hash(value) { - if (Array.isArray(value)) { - value = utils.allocBufferFromArray(value); - } - const hashedValue = this._crypto.createHash('md5').update(value).digest(); - return new token.RandomToken(Integer.fromBuffer(hashedValue).abs()); - } - - /** - * @returns {Token} - */ - parse(value) { - return new token.RandomToken(Integer.fromString(value)); - } - - minToken() { - if (!this._minToken) { - this._minToken = this.parse('-1'); - } - return this._minToken; - } - - maxValue() { - if (!this._maxValue) { - this._maxValue = Integer.fromNumber(Math.pow(2, 127)); - } - return this._maxValue; - } - - maxToken() { - if (!this._maxToken) { - this._maxToken = new token.RandomToken(this.maxValue()); - } - return this._maxToken; - } - - ringLength() { - if (!this._ringLength) { - this._ringLength = this.maxValue().add(Integer.ONE); - } - return this._ringLength; - } - - split(start, end, numberOfSplits) { - // ]min, min] means the whole ring. - if (start.equals(end) && start.equals(this.minToken())) { - end = this.maxToken(); - } - - const startVal = start.getValue(); - const endVal = end.getValue(); - - let range = endVal.subtract(startVal); - if (range.lessThan(Integer.ZERO)) { - range = range.add(this.ringLength()); - } - - const values = this.splitBase(startVal, range, this.maxValue(), this.ringLength(), numberOfSplits); - return values.map(v => new token.RandomToken(v)); - } -} - -class ByteOrderedTokenizer extends Tokenizer { - constructor() { - super(); - } - - /** - * @param {Buffer} value - * @returns {ByteOrderedToken} - */ - hash(value) { - // strip any trailing zeros as tokens with trailing zeros are equivalent - // to those who don't have them. - if (Array.isArray(value)) { - value = utils.allocBufferFromArray(value); - } - let zeroIndex = value.length; - for(let i = value.length - 1; i > 0; i--) { - if(value[i] === 0) { - zeroIndex = i; - } else { - break; - } - } - return new token.ByteOrderedToken(value.slice(0, zeroIndex)); - } - - stringify(token) { - return token.getValue().toString('hex'); - } - - parse(value) { - return this.hash(utils.allocBufferFromString(value, 'hex')); - } - - minToken() { - if (!this._minToken) { - this._minToken = this.hash([]); - } - return this._minToken; - } - - _toNumber(buffer, significantBytes) { - // Convert a token's byte array to a number in order to perform computations. - // This depends on the number of significant bytes that is used to normalize all tokens - // to the same size. For example if the token is 0x01 but significant bytes is 2, the - // result is 0x0100. - let target = buffer; - if(buffer.length !== significantBytes) { - target = Buffer.alloc(significantBytes); - buffer.copy(target); - } - - // similar to Integer.fromBuffer except we force the sign to 0. - const bits = new Array(Math.ceil(target.length / 4)); - for (let i = 0; i < bits.length; i++) { - let offset = target.length - ((i + 1) * 4); - let value; - if (offset < 0) { - //The buffer length is not multiple of 4 - offset = offset + 4; - value = 0; - for (let j = 0; j < offset; j++) { - const byte = target[j]; - value = value | (byte << (offset - j - 1) * 8); - } - } - else { - value = target.readInt32BE(offset); - } - bits[i] = value; - } - return new Integer(bits, 0); - } - - _toBuffer(number, significantBytes) { - // Convert numeric representation back to a buffer. - const buffer = Integer.toBuffer(number); - if (buffer.length === significantBytes) { - return buffer; - } - - // if first byte is a sign byte, skip it. - let start, length; - if (buffer[0] === 0) { - start = 1; - length = buffer.length - 1; - } else { - start = 0; - length = buffer.length; - } - - const target = Buffer.alloc(significantBytes); - buffer.copy(target, significantBytes - length, start, length + start); - return target; - } - - split(start, end, numberOfSplits) { - const tokenOrder = start.compare(end); - - if (tokenOrder === 0 && start.equals(this.minToken())) { - throw new Error("Cannot split whole ring with ordered partitioner"); - } - - let startVal, endVal, range, ringLength, ringEnd; - const intNumberOfSplits = Integer.fromNumber(numberOfSplits); - // Since tokens are compared lexicographically, convert to numbers using the - // largest length (i.e. given 0x0A and 0x0BCD, switch to 0x0A00 and 0x0BCD) - let significantBytes = Math.max(start.getValue().length, end.getValue().length); - if (tokenOrder < 0) { - let addedBytes = 0; - while (true) { - startVal = this._toNumber(start.getValue(), significantBytes); - endVal = this._toNumber(end.getValue(), significantBytes); - range = endVal.subtract(startVal); - if (addedBytes === 4 || range.compare(intNumberOfSplits) >= 0) { - break; - } - significantBytes += 1; - addedBytes += 1; - } - } else { - let addedBytes = 0; - while (true) { - startVal = this._toNumber(start.getValue(), significantBytes); - endVal = this._toNumber(end.getValue(), significantBytes); - ringLength = Integer.fromNumber(Math.pow(2, significantBytes * 8)); - ringEnd = ringLength.subtract(Integer.ONE); - range = endVal.subtract(startVal).add(ringLength); - if (addedBytes === 4 || range.compare(intNumberOfSplits) >= 0) { - break; - } - significantBytes += 1; - addedBytes += 1; - } - } - - const values = this.splitBase(startVal, range, ringEnd, ringLength, numberOfSplits); - return values.map(v => new token.ByteOrderedToken(this._toBuffer(v, significantBytes))); - } -} - -/** - * @param {Number} value - * @return {MutableLong} - */ -function fromSignedByte(value) { - if (value < 128) { - return new MutableLong(value, 0, 0, 0); - } - return new MutableLong((value - 256) & 0xffff, 0xffff, 0xffff, 0xffff); -} - -exports.Murmur3Tokenizer = Murmur3Tokenizer; -exports.RandomTokenizer = RandomTokenizer; -exports.ByteOrderedTokenizer = ByteOrderedTokenizer; diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/tracker/index.d.ts b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/tracker/index.d.ts deleted file mode 100644 index e39e8bae3a..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/tracker/index.d.ts +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Copyright DataStax, Inc. - * - * 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. - */ - -import { ExecutionOptions, Host } from '../../'; - -export namespace tracker { - interface RequestTracker { - onError( - host: Host, - query: string | Array<{ query: string, params?: any }>, - parameters: any[] | { [key: string]: any } | null, - executionOptions: ExecutionOptions, - requestLength: number, - err: Error, - latency: number[]): void; - - onSuccess( - host: Host, - query: string | Array<{ query: string, params?: any }>, - parameters: any[] | { [key: string]: any } | null, - executionOptions: ExecutionOptions, - requestLength: number, - responseLength: number, - latency: number[]): void; - - shutdown(): void; - } - - class RequestLogger implements RequestTracker { - constructor(options: { - slowThreshold?: number; - logNormalRequests?: boolean; - logErroredRequests?: boolean; - messageMaxQueryLength?: number; - messageMaxParameterValueLength?: number; - messageMaxErrorStackTraceLength?: number; - }); - - onError(host: Host, query: string | Array<{ query: string; params?: any }>, parameters: any[] | { [p: string]: any } | null, executionOptions: ExecutionOptions, requestLength: number, err: Error, latency: number[]): void; - - onSuccess(host: Host, query: string | Array<{ query: string; params?: any }>, parameters: any[] | { [p: string]: any } | null, executionOptions: ExecutionOptions, requestLength: number, responseLength: number, latency: number[]): void; - - shutdown(): void; - } -} \ No newline at end of file diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/tracker/index.js b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/tracker/index.js deleted file mode 100644 index 848d5bb3b8..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/tracker/index.js +++ /dev/null @@ -1,25 +0,0 @@ -/* - * Copyright DataStax, Inc. - * - * 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'; - -/** - * Tracker module. - * @module tracker - */ - -exports.RequestLogger = require('./request-logger'); -exports.RequestTracker = require('./request-tracker'); \ No newline at end of file diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/tracker/request-logger.js b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/tracker/request-logger.js deleted file mode 100644 index da3d2085a1..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/tracker/request-logger.js +++ /dev/null @@ -1,294 +0,0 @@ -/* - * Copyright DataStax, Inc. - * - * 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 events = require('events'); -const RequestTracker = require('./request-tracker'); -const errors = require('../errors'); -const { format } = require('util'); - -const nanosToMillis = 1000000; -const defaultMessageMaxQueryLength = 500; -const defaultMaxParameterValueLength = 50; -const defaultMaxErrorStackTraceLength = 200; - -/** - * A request tracker that logs the requests executed through the session, according to a set of - * configurable options. - * @implements {module:tracker~RequestTracker} - * @alias module:tracker~RequestLogger - * @example Logging slow queries - * const requestLogger = new RequestLogger({ slowThreshold: 1000 }); - * requestLogger.emitter.on('show', message => console.log(message)); - * // Add the requestLogger to the client options - * const client = new Client({ contactPoints, requestTracker: requestLogger }); - */ -class RequestLogger extends RequestTracker { - - /** - * Creates a new instance of {@link RequestLogger}. - * @param {Object} options - * @param {Number} [options.slowThreshold] The threshold in milliseconds beyond which queries are considered 'slow' - * and logged as such by the driver. - * @param {Number} [options.requestSizeThreshold] The threshold in bytes beyond which requests are considered 'large' - * and logged as such by the driver. - * @param {Boolean} [options.logNormalRequests] Determines whether it should emit 'normal' events for every - * EXECUTE, QUERY and BATCH request executed successfully, useful only for debugging. This option can be modified - * after the client is connected using the property {@link RequestLogger#logNormalRequests}. - * @param {Boolean} [options.logErroredRequests] Determines whether it should emit 'failure' events for every - * EXECUTE, QUERY and BATCH request execution that resulted in an error. This option can be modified - * after the client is connected using the property {@link RequestLogger#logErroredRequests}. - * @param {Number} [options.messageMaxQueryLength] The maximum amount of characters that are logged from the query - * portion of the message. Defaults to 500. - * @param {Number} [options.messageMaxParameterValueLength] The maximum amount of characters of each query parameter - * value that will be included in the message. Defaults to 50. - * @param {Number} [options.messageMaxErrorStackTraceLength] The maximum amount of characters of the stack trace - * that will be included in the message. Defaults to 200. - */ - constructor(options) { - super(); - if (!options) { - throw new errors.ArgumentError('RequestLogger options parameter is required'); - } - - this._options = options; - - /** - * Determines whether it should emit 'normal' events for every EXECUTE, QUERY and BATCH request executed - * successfully, useful only for debugging - * @type {Boolean} - */ - this.logNormalRequests = this._options.logNormalRequests; - - /** - * Determines whether it should emit 'failure' events for every EXECUTE, QUERY and BATCH request execution that - * resulted in an error - * @type {Boolean} - */ - this.logErroredRequests = this._options.logErroredRequests; - - /** - * The object instance that emits 'slow', 'large', 'normal' and - * 'failure' events. - * @type {EventEmitter} - */ - this.emitter = new events.EventEmitter(); - } - - /** - * Logs message if request execution was deemed too slow, large or if normal requests are logged. - * @override - */ - onSuccess(host, query, parameters, execOptions, requestLength, responseLength, latency) { - if (this._options.slowThreshold > 0 && toMillis(latency) > this._options.slowThreshold) { - this._logSlow(host, query, parameters, execOptions, requestLength, responseLength, latency); - } - else if (this._options.requestSizeThreshold > 0 && requestLength > this._options.requestSizeThreshold) { - this._logLargeRequest(host, query, parameters, execOptions, requestLength, responseLength, latency); - } - else if (this.logNormalRequests) { - this._logNormalRequest(host, query, parameters, execOptions, requestLength, responseLength, latency); - } - } - - /** - * Logs message if request execution was too large and/or encountered an error. - * @override - */ - onError(host, query, parameters, execOptions, requestLength, err, latency) { - if (this._options.requestSizeThreshold > 0 && requestLength > this._options.requestSizeThreshold) { - this._logLargeErrorRequest(host, query, parameters, execOptions, requestLength, err, latency); - } - else if (this.logErroredRequests) { - this._logErrorRequest(host, query, parameters, execOptions, requestLength, err, latency); - } - } - - _logSlow(host, query, parameters, execOptions, requestLength, responseLength, latency) { - const message = format('[%s] Slow request, took %d ms (%s): %s', host.address, Math.floor(toMillis(latency)), - getPayloadSizes(requestLength, responseLength), getStatementInfo(query, parameters, execOptions, this._options)); - this.emitter.emit('slow', message); - } - - _logLargeRequest(host, query, parameters, execOptions, requestLength, responseLength, latency) { - const message = format('[%s] Request exceeded length, %s (took %d ms): %s', host.address, - getPayloadSizes(requestLength, responseLength), ~~toMillis(latency), - getStatementInfo(query, parameters, execOptions, this._options)); - this.emitter.emit('large', message); - } - - _logNormalRequest(host, query, parameters, execOptions, requestLength, responseLength, latency) { - const message = format('[%s] Request completed normally, took %d ms (%s): %s', host.address, ~~toMillis(latency), - getPayloadSizes(requestLength, responseLength), getStatementInfo(query, parameters, execOptions, this._options)); - this.emitter.emit('normal', message); - } - - _logLargeErrorRequest(host, query, parameters, execOptions, requestLength, err, latency) { - const maxStackTraceLength = this._options.messageMaxErrorStackTraceLength || defaultMaxErrorStackTraceLength; - const message = format('[%s] Request exceeded length and execution failed, %s (took %d ms): %s; error: %s', - host.address, getPayloadSizes(requestLength), ~~toMillis(latency), - getStatementInfo(query, parameters, execOptions, this._options), err.stack.substr(0, maxStackTraceLength)); - - // Use 'large' event and not 'failure' as this log is caused by exceeded length - this.emitter.emit('large', message); - } - - _logErrorRequest(host, query, parameters, execOptions, requestLength, err, latency) { - const maxStackTraceLength = this._options.messageMaxErrorStackTraceLength || defaultMaxErrorStackTraceLength; - const message = format('[%s] Request execution failed, took %d ms (%s): %s; error: %s', host.address, - ~~toMillis(latency), getPayloadSizes(requestLength), - getStatementInfo(query, parameters, execOptions, this._options), err.stack.substr(0, maxStackTraceLength)); - - // Avoid using 'error' as its a special event - this.emitter.emit('failure', message); - } -} - -function toMillis(latency) { - return latency[0] * 1000 + latency[1] / nanosToMillis; -} - -function getStatementInfo(query, parameters, execOptions, options) { - const maxQueryLength = options.messageMaxQueryLength || defaultMessageMaxQueryLength; - const maxParameterLength = options.messageMaxParameterValueLength || defaultMaxParameterValueLength; - - if (Array.isArray(query)) { - return getBatchStatementInfo(query, execOptions, maxQueryLength, maxParameterLength); - } - - // String concatenation is usually faster than Array#join() in V8 - let message = query.substr(0, maxQueryLength); - const remaining = maxQueryLength - message.length - 1; - message += getParametersInfo(parameters, remaining, maxParameterLength); - - if (!execOptions.isPrepared()) { - // This part of the message is not accounted for in "maxQueryLength" - message += ' (not prepared)'; - } - - return message; -} - -function getBatchStatementInfo(queries, execOptions, maxQueryLength, maxParameterLength) { - // This part of the message is not accounted for in "maxQueryLength" - let message = (execOptions.isBatchLogged() ? 'LOGGED ' : '') + 'BATCH w/ ' + queries.length + - (!execOptions.isPrepared() ? ' not prepared' : '') + ' queries ('; - let remaining = maxQueryLength; - let i; - - for (i = 0; i < queries.length && remaining > 0; i++) { - let q = queries[i]; - const params = q.params; - if (typeof q !== 'string') { - q = q.query; - } - - if (i > 0) { - message += ','; - remaining--; - } - - const queryLength = Math.min(remaining, q.length); - message += q.substr(0, queryLength); - remaining -= queryLength; - - if (remaining <= 0) { - break; - } - - const parameters = getParametersInfo(params, remaining, maxParameterLength); - remaining -= parameters.length; - message += parameters; - } - - message += i < queries.length ? ',...)' : ')'; - return message; -} - -function getParametersInfo(params, remaining, maxParameterLength) { - if (remaining <= 3) { - // We need at least 3 chars to describe the parameters - // its OK to add more chars in an effort to be descriptive - return ' [...]'; - } - - if (!params) { - return ' []'; - } - - let paramStringifier = (index, length) => formatParam(params[index], length); - if (!Array.isArray(params)) { - const obj = params; - params = Object.keys(params); - paramStringifier = (index, length) => { - const key = params[index]; - let result = key.substr(0, length); - const rem = length - result.length - 1; - if (rem <= 0) { - return result; - } - result += ":" + formatParam(obj[key], rem); - return result; - }; - } - - let message = ' ['; - let i; - for (i = 0; remaining > 0 && i < params.length; i++) { - if (i > 0) { - message += ','; - remaining--; - } - - const paramString = paramStringifier(i, Math.min(maxParameterLength, remaining)); - remaining -= paramString.length; - message += paramString; - } - - if (i < params.length) { - message += '...'; - } - - message += ']'; - return message; -} - -function formatParam(value, maxLength) { - if (value === undefined) { - return 'undefined'; - } - - if (value === null) { - return 'null'; - } - - return value.toString().substr(0, maxLength); -} - -function getPayloadSizes(requestLength, responseLength) { - let message = 'request size ' + formatSize(requestLength); - if (responseLength !== undefined) { - message += ' / response size ' + formatSize(responseLength); - } - return message; -} - -function formatSize(length) { - return length > 1000 ? Math.round(length / 1024) + ' KB' : length + ' bytes'; -} - -module.exports = RequestLogger; \ No newline at end of file diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/tracker/request-tracker.js b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/tracker/request-tracker.js deleted file mode 100644 index 3a00732e17..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/tracker/request-tracker.js +++ /dev/null @@ -1,74 +0,0 @@ -/* - * Copyright DataStax, Inc. - * - * 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'; - -/** - * Tracks request execution for a {@link Client}. - *

- * A {@link RequestTracker} can be configured in the client options. The Client will execute - * {@link RequestTracker#onSuccess} or {@link RequestTracker#onError} for every query or batch - * executed (QUERY, EXECUTE and BATCH requests). - *

- * @interface - * @alias module:tracker~RequestTracker - */ -class RequestTracker { - - /** - * Invoked each time a query or batch request succeeds. - * @param {Host} host The node that acted as coordinator of the request. - * @param {String|Array} query In the case of prepared or unprepared query executions, the provided - * query string. For batch requests, an Array containing the queries and parameters provided. - * @param {Array|Object|null} parameters In the case of prepared or unprepared query executions, the provided - * parameters. - * @param {ExecutionOptions} executionOptions The information related to the execution of the request. - * @param {Number} requestLength Length of the body of the request. - * @param {Number} responseLength Length of the body of the response. - * @param {Array} latency An array containing [seconds, nanoseconds] tuple, where nanoseconds is the - * remaining part of the real time that can't be represented in second precision (see process.hrtime()). - */ - onSuccess(host, query, parameters, executionOptions, requestLength, responseLength, latency) { - - } - - /** - * Invoked each time a query or batch request fails. - * @param {Host} host The node that acted as coordinator of the request. - * @param {String|Array} query In the case of prepared or unprepared query executions, the provided - * query string. For batch requests, an Array containing the queries and parameters provided. - * @param {Array|Object|null} parameters In the case of prepared or unprepared query executions, the provided - * parameters. - * @param {ExecutionOptions} executionOptions The information related to the execution of the request. - * @param {Number} requestLength Length of the body of the request. When the failure occurred before the request was - * written to the wire, the length will be 0. - * @param {Error} err The error that caused that caused the request to fail. - * @param {Array} latency An array containing [seconds, nanoseconds] tuple, where nanoseconds is the - * remaining part of the real time that can't be represented in second precision (see process.hrtime()). - */ - onError(host, query, parameters, executionOptions, requestLength, err, latency) { - - } - - /** - * Invoked when the Client is being shutdown. - */ - shutdown() { - - } -} - -module.exports = RequestTracker; \ No newline at end of file diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/types/big-decimal.js b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/types/big-decimal.js deleted file mode 100644 index 39ec9f7bce..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/types/big-decimal.js +++ /dev/null @@ -1,271 +0,0 @@ -/* - * Copyright DataStax, Inc. - * - * 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 Integer = require('./integer'); -const utils = require('../utils'); - -/** @module types */ -/** - * Constructs an immutable arbitrary-precision signed decimal number. - * A BigDecimal consists of an [arbitrary precision integer]{@link module:types~Integer} - * unscaled value and a 32-bit integer scale. If zero - * or positive, the scale is the number of digits to the right of the - * decimal point. If negative, the unscaled value of the number is - * multiplied by ten to the power of the negation of the scale. The - * value of the number represented by the BigDecimal is - * therefore (unscaledValue × 10-scale). - * @class - * @classdesc The BigDecimal class provides operations for - * arithmetic, scale manipulation, rounding, comparison and - * format conversion. The {@link #toString} method provides a - * canonical representation of a BigDecimal. - * @param {Integer|Number} unscaledValue The integer part of the decimal. - * @param {Number} scale The scale of the decimal. - * @constructor - */ -function BigDecimal(unscaledValue, scale) { - if (typeof unscaledValue === 'number') { - unscaledValue = Integer.fromNumber(unscaledValue); - } - /** - * @type {Integer} - * @private - */ - this._intVal = unscaledValue; - /** - * @type {Number} - * @private - */ - this._scale = scale; -} - -/** - * Returns the BigDecimal representation of a buffer composed of the scale (int32BE) and the unsigned value (varint BE) - * @param {Buffer} buf - * @returns {BigDecimal} - */ -BigDecimal.fromBuffer = function (buf) { - const scale = buf.readInt32BE(0); - const unscaledValue = Integer.fromBuffer(buf.slice(4)); - return new BigDecimal(unscaledValue, scale); -}; - -/** - * Returns a buffer representation composed of the scale as a BE int 32 and the unsigned value as a BE varint - * @param {BigDecimal} value - * @returns {Buffer} - */ -BigDecimal.toBuffer = function (value) { - const unscaledValueBuffer = Integer.toBuffer(value._intVal); - const scaleBuffer = utils.allocBufferUnsafe(4); - scaleBuffer.writeInt32BE(value._scale, 0); - return Buffer.concat([scaleBuffer, unscaledValueBuffer], scaleBuffer.length + unscaledValueBuffer.length); -}; - -/** - * Returns a BigDecimal representation of the string - * @param {String} value - * @returns {BigDecimal} - */ -BigDecimal.fromString = function (value) { - if (!value) { - throw new TypeError('Invalid null or undefined value'); - } - value = value.trim(); - const scaleIndex = value.indexOf('.'); - let scale = 0; - if (scaleIndex >= 0) { - scale = value.length - 1 - scaleIndex; - value = value.substr(0, scaleIndex) + value.substr(scaleIndex + 1); - } - return new BigDecimal(Integer.fromString(value), scale); -}; - -/** - * Returns a BigDecimal representation of the Number - * @param {Number} value - * @returns {BigDecimal} - */ -BigDecimal.fromNumber = function (value) { - if (isNaN(value)) { - return new BigDecimal(Integer.ZERO, 0); - } - let textValue = value.toString(); - if (textValue.indexOf('e') >= 0) { - //get until scale 20 - textValue = value.toFixed(20); - } - return BigDecimal.fromString(textValue); -}; - -/** - * Returns true if the value of the BigDecimal instance and other are the same - * @param {BigDecimal} other - * @returns {Boolean} - */ -BigDecimal.prototype.equals = function (other) { - return ((other instanceof BigDecimal) && this.compare(other) === 0); -}; - -BigDecimal.prototype.inspect = function () { - return this.constructor.name + ': ' + this.toString(); -}; - -/** - * @param {BigDecimal} other - * @returns {boolean} - */ -BigDecimal.prototype.notEquals = function (other) { - return !this.equals(other); -}; - -/** - * Compares this BigDecimal with the given one. - * @param {BigDecimal} other Integer to compare against. - * @return {number} 0 if they are the same, 1 if the this is greater, and -1 - * if the given one is greater. - */ -BigDecimal.prototype.compare = function (other) { - const diff = this.subtract(other); - if (diff.isNegative()) { - return -1; - } - if (diff.isZero()) { - return 0; - } - return +1; -}; - -/** - * Returns the difference of this and the given BigDecimal. - * @param {BigDecimal} other The BigDecimal to subtract from this. - * @return {!BigDecimal} The BigDecimal result. - */ -BigDecimal.prototype.subtract = function (other) { - const first = this; - if (first._scale === other._scale) { - return new BigDecimal(first._intVal.subtract(other._intVal), first._scale); - } - let diffScale; - let unscaledValue; - if (first._scale < other._scale) { - //The scale of this is lower - diffScale = other._scale - first._scale; - //multiple this unScaledValue to compare in the same scale - unscaledValue = first._intVal - .multiply(Integer.fromNumber(Math.pow(10, diffScale))) - .subtract(other._intVal); - return new BigDecimal(unscaledValue, other._scale); - } - //The scale of this is higher - diffScale = first._scale - other._scale; - //multiple this unScaledValue to compare in the same scale - unscaledValue = first._intVal - .subtract( - other._intVal.multiply(Integer.fromNumber(Math.pow(10, diffScale)))); - return new BigDecimal(unscaledValue, first._scale); -}; - -/** - * Returns the sum of this and the given BigDecimal. - * @param {BigDecimal} other The BigDecimal to sum to this. - * @return {!BigDecimal} The BigDecimal result. - */ -BigDecimal.prototype.add = function (other) { - const first = this; - if (first._scale === other._scale) { - return new BigDecimal(first._intVal.add(other._intVal), first._scale); - } - let diffScale; - let unscaledValue; - if (first._scale < other._scale) { - //The scale of this is lower - diffScale = other._scale - first._scale; - //multiple this unScaledValue to compare in the same scale - unscaledValue = first._intVal - .multiply(Integer.fromNumber(Math.pow(10, diffScale))) - .add(other._intVal); - return new BigDecimal(unscaledValue, other._scale); - } - //The scale of this is higher - diffScale = first._scale - other._scale; - //multiple this unScaledValue to compare in the same scale - unscaledValue = first._intVal - .add( - other._intVal.multiply(Integer.fromNumber(Math.pow(10, diffScale)))); - return new BigDecimal(unscaledValue, first._scale); -}; - -/** - * Returns true if the current instance is greater than the other - * @param {BigDecimal} other - * @returns {boolean} - */ -BigDecimal.prototype.greaterThan = function (other) { - return this.compare(other) === 1; -}; - -/** @return {boolean} Whether this value is negative. */ -BigDecimal.prototype.isNegative = function () { - return this._intVal.isNegative(); -}; - -/** @return {boolean} Whether this value is zero. */ -BigDecimal.prototype.isZero = function () { - return this._intVal.isZero(); -}; - -/** - * Returns the string representation of this BigDecimal - * @returns {string} - */ -BigDecimal.prototype.toString = function () { - let intString = this._intVal.toString(); - if (this._scale === 0) { - return intString; - } - let signSymbol = ''; - if (intString.charAt(0) === '-') { - signSymbol = '-'; - intString = intString.substr(1); - } - let separatorIndex = intString.length - this._scale; - if (separatorIndex <= 0) { - //add zeros at the beginning, plus an additional zero - intString = utils.stringRepeat('0', (-separatorIndex) + 1) + intString; - separatorIndex = intString.length - this._scale; - } - return signSymbol + intString.substr(0, separatorIndex) + '.' + intString.substr(separatorIndex); -}; - -/** - * Returns a Number representation of this BigDecimal. - * @returns {Number} - */ -BigDecimal.prototype.toNumber = function () { - return parseFloat(this.toString()); -}; - -/** - * Returns the string representation. - * Method used by the native JSON.stringify() to serialize this instance. - */ -BigDecimal.prototype.toJSON = function () { - return this.toString(); -}; - - -module.exports = BigDecimal; \ No newline at end of file diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/types/duration.js b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/types/duration.js deleted file mode 100644 index aa1b41975a..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/types/duration.js +++ /dev/null @@ -1,714 +0,0 @@ -/* - * Copyright DataStax, Inc. - * - * 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 Long = require('long'); -const util = require('util'); -const utils = require('../utils'); - -/** @module types */ - -// Reuse the same buffers that should perform slightly better than built-in buffer pool -const reusableBuffers = { - months: utils.allocBuffer(9), - days: utils.allocBuffer(9), - nanoseconds: utils.allocBuffer(9) -}; - -const maxInt32 = 0x7FFFFFFF; -const longOneThousand = Long.fromInt(1000); -const nanosPerMicro = longOneThousand; -const nanosPerMilli = longOneThousand.multiply(nanosPerMicro); -const nanosPerSecond = longOneThousand.multiply(nanosPerMilli); -const nanosPerMinute = Long.fromInt(60).multiply(nanosPerSecond); -const nanosPerHour = Long.fromInt(60).multiply(nanosPerMinute); -const daysPerWeek = 7; -const monthsPerYear = 12; -const standardRegex = /(\d+)(y|mo|w|d|h|s|ms|us|µs|ns|m)/gi; -const iso8601Regex = /P((\d+)Y)?((\d+)M)?((\d+)D)?(T((\d+)H)?((\d+)M)?((\d+)S)?)?/; -const iso8601WeekRegex = /P(\d+)W/; -const iso8601AlternateRegex = /P(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})/; - -/** - * Creates a new instance of {@link Duration}. - * @classdesc - * Represents a duration. A duration stores separately months, days, and seconds due to the fact that the number of - * days in a month varies, and a day can have 23 or 25 hours if a daylight saving is involved. - * @param {Number} months The number of months. - * @param {Number} days The number of days. - * @param {Number|Long} nanoseconds The number of nanoseconds. - * @constructor - */ -function Duration(months, days, nanoseconds) { - /** - * Gets the number of months. - * @type {Number} - */ - this.months = months; - /** - * Gets the number of days. - * @type {Number} - */ - this.days = days; - /** - * Gets the number of nanoseconds represented as a int64. - * @type {Long} - */ - this.nanoseconds = typeof nanoseconds === 'number' ? Long.fromNumber(nanoseconds) : nanoseconds; -} - -Duration.prototype.equals = function (other) { - if (!(other instanceof Duration)) { - return false; - } - return this.months === other.months && - this.days === other.days && - this.nanoseconds.equals(other.nanoseconds); -}; - -/** - * Serializes the duration and returns the representation of the value in bytes. - * @returns {Buffer} - */ -Duration.prototype.toBuffer = function () { - const lengthMonths = VIntCoding.writeVInt(Long.fromNumber(this.months), reusableBuffers.months); - const lengthDays = VIntCoding.writeVInt(Long.fromNumber(this.days), reusableBuffers.days); - const lengthNanoseconds = VIntCoding.writeVInt(this.nanoseconds, reusableBuffers.nanoseconds); - const buffer = utils.allocBufferUnsafe(lengthMonths + lengthDays + lengthNanoseconds); - reusableBuffers.months.copy(buffer, 0, 0, lengthMonths); - let offset = lengthMonths; - reusableBuffers.days.copy(buffer, offset, 0, lengthDays); - offset += lengthDays; - reusableBuffers.nanoseconds.copy(buffer, offset, 0, lengthNanoseconds); - return buffer; -}; - -/** - * Returns the string representation of the value. - * @return {string} - */ -Duration.prototype.toString = function () { - let value = ''; - function append(dividend, divisor, unit) { - if (dividend === 0 || dividend < divisor) { - return dividend; - } - // string concatenation is supposed to be fasted than join() - value += (dividend / divisor).toFixed(0) + unit; - return dividend % divisor; - } - function append64(dividend, divisor, unit) { - if (dividend.equals(Long.ZERO) || dividend.lessThan(divisor)) { - return dividend; - } - // string concatenation is supposed to be fasted than join() - value += dividend.divide(divisor).toString() + unit; - return dividend.modulo(divisor); - } - if (this.months < 0 || this.days < 0 || this.nanoseconds.isNegative()) { - value = '-'; - } - let remainder = append(Math.abs(this.months), monthsPerYear, "y"); - append(remainder, 1, "mo"); - append(Math.abs(this.days), 1, "d"); - - if (!this.nanoseconds.equals(Long.ZERO)) { - const nanos = this.nanoseconds.isNegative() ? this.nanoseconds.negate() : this.nanoseconds; - remainder = append64(nanos, nanosPerHour, "h"); - remainder = append64(remainder, nanosPerMinute, "m"); - remainder = append64(remainder, nanosPerSecond, "s"); - remainder = append64(remainder, nanosPerMilli, "ms"); - remainder = append64(remainder, nanosPerMicro, "us"); - append64(remainder, Long.ONE, "ns"); - } - return value; -}; - -/** - * Creates a new {@link Duration} instance from the binary representation of the value. - * @param {Buffer} buffer - * @returns {Duration} - */ -Duration.fromBuffer = function (buffer) { - const offset = { value: 0 }; - const months = VIntCoding.readVInt(buffer, offset).toNumber(); - const days = VIntCoding.readVInt(buffer, offset).toNumber(); - const nanoseconds = VIntCoding.readVInt(buffer, offset); - return new Duration(months, days, nanoseconds); -}; - -/** - * Creates a new {@link Duration} instance from the string representation of the value. - *

- * Accepted formats: - *

- *
    - *
  • multiple digits followed by a time unit like: 12h30m where the time unit can be: - *
      - *
    • {@code y}: years
    • - *
    • {@code m}: months
    • - *
    • {@code w}: weeks
    • - *
    • {@code d}: days
    • - *
    • {@code h}: hours
    • - *
    • {@code m}: minutes
    • - *
    • {@code s}: seconds
    • - *
    • {@code ms}: milliseconds
    • - *
    • {@code us} or {@code µs}: microseconds
    • - *
    • {@code ns}: nanoseconds
    • - *
    - *
  • - *
  • ISO 8601 format: P[n]Y[n]M[n]DT[n]H[n]M[n]S or P[n]W
  • - *
  • ISO 8601 alternative format: P[YYYY]-[MM]-[DD]T[hh]:[mm]:[ss]
  • - *
- * @param {String} input - * @returns {Duration} - */ -Duration.fromString = function (input) { - const isNegative = input.charAt(0) === '-'; - const source = isNegative ? input.substr(1) : input; - if (source.charAt(0) === 'P') { - if (source.charAt(source.length - 1) === 'W') { - return parseIso8601WeekFormat(isNegative, source); - } - if (source.indexOf('-') > 0) { - return parseIso8601AlternativeFormat(isNegative, source); - } - return parseIso8601Format(isNegative, source); - } - return parseStandardFormat(isNegative, source); -}; - -/** - * @param {Boolean} isNegative - * @param {String} source - * @returns {Duration} - * @private - */ -function parseStandardFormat(isNegative, source) { - const builder = new Builder(isNegative); - standardRegex.lastIndex = 0; - let matches; - while ((matches = standardRegex.exec(source)) && matches.length <= 3) { - builder.add(matches[1], matches[2]); - } - return builder.build(); -} - -/** - * @param {Boolean} isNegative - * @param {String} source - * @returns {Duration} - * @private - */ -function parseIso8601Format(isNegative, source) { - const matches = iso8601Regex.exec(source); - if (!matches || matches[0] !== source) { - throw new TypeError(util.format("Unable to convert '%s' to a duration", source)); - } - const builder = new Builder(isNegative); - if (matches[1]) { - builder.addYears(matches[2]); - } - if (matches[3]) { - builder.addMonths(matches[4]); - } - if (matches[5]) { - builder.addDays(matches[6]); - } - if (matches[7]) { - if (matches[8]) { - builder.addHours(matches[9]); - } - if (matches[10]) { - builder.addMinutes(matches[11]); - } - if (matches[12]) { - builder.addSeconds(matches[13]); - } - } - return builder.build(); -} - -/** - * @param {Boolean} isNegative - * @param {String} source - * @returns {Duration} - * @private - */ -function parseIso8601WeekFormat(isNegative, source) { - const matches = iso8601WeekRegex.exec(source); - if (!matches || matches[0] !== source) { - throw new TypeError(util.format("Unable to convert '%s' to a duration", source)); - } - return new Builder(isNegative) - .addWeeks(matches[1]) - .build(); -} - -/** - * @param {Boolean} isNegative - * @param {String} source - * @returns {Duration} - * @private - */ -function parseIso8601AlternativeFormat(isNegative, source) { - const matches = iso8601AlternateRegex.exec(source); - if (!matches || matches[0] !== source) { - throw new TypeError(util.format("Unable to convert '%s' to a duration", source)); - } - return new Builder(isNegative).addYears(matches[1]) - .addMonths(matches[2]) - .addDays(matches[3]) - .addHours(matches[4]) - .addMinutes(matches[5]) - .addSeconds(matches[6]) - .build(); -} - -/** - * @param {Boolean} isNegative - * @private - * @constructor - */ -function Builder(isNegative) { - this._isNegative = isNegative; - this._unitIndex = 0; - this._months = 0; - this._days = 0; - this._nanoseconds = Long.ZERO; - this._addMethods = { - 'y': this.addYears, - 'mo': this.addMonths, - 'w': this.addWeeks, - 'd': this.addDays, - 'h': this.addHours, - 'm': this.addMinutes, - 's': this.addSeconds, - 'ms': this.addMillis, - // µs - '\u00B5s': this.addMicros, - 'us': this.addMicros, - 'ns': this.addNanos - }; - this._unitByIndex = [ - null, 'years', 'months', 'weeks', 'days', 'hours', 'minutes', 'seconds', 'milliseconds', 'microseconds', - 'nanoseconds' - ]; -} - -Builder.prototype._validateOrder = function (unitIndex) { - if (unitIndex === this._unitIndex) { - throw new TypeError(util.format("Invalid duration. The %s are specified multiple times", this._getUnitName(unitIndex))); - } - - if (unitIndex <= this._unitIndex) { - throw new TypeError(util.format("Invalid duration. The %s should be after %s", - this._getUnitName(this._unitIndex), - this._getUnitName(unitIndex))); - } - this._unitIndex = unitIndex; -}; - -/** - * @param {Number} units - * @param {Number} monthsPerUnit - */ -Builder.prototype._validateMonths = function(units, monthsPerUnit) { - this._validate32(units, (maxInt32 - this._months) / monthsPerUnit, "months"); -}; - -/** - * @param {Number} units - * @param {Number} daysPerUnit - */ -Builder.prototype._validateDays = function(units, daysPerUnit) { - this._validate32(units, (maxInt32 - this._days) / daysPerUnit, "days"); -}; - -/** - * @param {Long} units - * @param {Long} nanosPerUnit - */ -Builder.prototype._validateNanos = function(units, nanosPerUnit) { - this._validate64(units, Long.MAX_VALUE.subtract(this._nanoseconds).divide(nanosPerUnit), "nanoseconds"); -}; - -/** - * @param {Number} units - * @param {Number} limit - * @param {String} unitName - */ -Builder.prototype._validate32 = function(units, limit, unitName) { - if (units > limit) { - throw new TypeError(util.format('Invalid duration. The total number of %s must be less or equal to %s', - unitName, - maxInt32)); - } -}; - -/** - * @param {Long} units - * @param {Long} limit - * @param {String} unitName - */ -Builder.prototype._validate64 = function(units, limit, unitName) { - if (units.greaterThan(limit)) { - throw new TypeError(util.format('Invalid duration. The total number of %s must be less or equal to %s', - unitName, - Long.MAX_VALUE.toString())); - } -}; - -Builder.prototype._getUnitName = function(unitIndex) { - const name = this._unitByIndex[+unitIndex]; - if (!name) { - throw new Error('unknown unit index: ' + unitIndex); - } - return name; -}; - -Builder.prototype.add = function (textValue, symbol) { - const addMethod = this._addMethods[symbol.toLowerCase()]; - if (!addMethod) { - throw new TypeError(util.format("Unknown duration symbol '%s'", symbol)); - } - return addMethod.call(this, textValue); -}; - -/** - * @param {String|Number} years - * @return {Builder} - */ -Builder.prototype.addYears = function (years) { - const value = +years; - this._validateOrder(1); - this._validateMonths(value, monthsPerYear); - this._months += value * monthsPerYear; - return this; -}; - -/** - * @param {String|Number} months - * @return {Builder} - */ -Builder.prototype.addMonths = function(months) { - const value = +months; - this._validateOrder(2); - this._validateMonths(value, 1); - this._months += value; - return this; -}; - -/** - * @param {String|Number} weeks - * @return {Builder} - */ -Builder.prototype.addWeeks = function(weeks) { - const value = +weeks; - this._validateOrder(3); - this._validateDays(value, daysPerWeek); - this._days += value * daysPerWeek; - return this; -}; - -/** - * @param {String|Number} days - * @return {Builder} - */ -Builder.prototype.addDays = function(days) { - const value = +days; - this._validateOrder(4); - this._validateDays(value, 1); - this._days += value; - return this; -}; - -/** - * @param {String|Long} hours - * @return {Builder} - */ -Builder.prototype.addHours = function(hours) { - const value = typeof hours === 'string' ? Long.fromString(hours) : hours; - this._validateOrder(5); - this._validateNanos(value, nanosPerHour); - this._nanoseconds = this._nanoseconds.add(value.multiply(nanosPerHour)); - return this; -}; - -/** - * @param {String|Long} minutes - * @return {Builder} - */ -Builder.prototype.addMinutes = function(minutes) { - const value = typeof minutes === 'string' ? Long.fromString(minutes) : minutes; - this._validateOrder(6); - this._validateNanos(value, nanosPerMinute); - this._nanoseconds = this._nanoseconds.add(value.multiply(nanosPerMinute)); - return this; -}; - -/** - * @param {String|Long} seconds - * @return {Builder} - */ -Builder.prototype.addSeconds = function(seconds) { - const value = typeof seconds === 'string' ? Long.fromString(seconds) : seconds; - this._validateOrder(7); - this._validateNanos(value, nanosPerSecond); - this._nanoseconds = this._nanoseconds.add(value.multiply(nanosPerSecond)); - return this; -}; - -/** - * @param {String|Long} millis - * @return {Builder} - */ -Builder.prototype.addMillis = function(millis) { - const value = typeof millis === 'string' ? Long.fromString(millis) : millis; - this._validateOrder(8); - this._validateNanos(value, nanosPerMilli); - this._nanoseconds = this._nanoseconds.add(value.multiply(nanosPerMilli)); - return this; -}; - -/** - * @param {String|Long} micros - * @return {Builder} - */ -Builder.prototype.addMicros = function(micros) { - const value = typeof micros === 'string' ? Long.fromString(micros) : micros; - this._validateOrder(9); - this._validateNanos(value, nanosPerMicro); - this._nanoseconds = this._nanoseconds.add(value.multiply(nanosPerMicro)); - return this; -}; - -/** - * @param {String|Long} nanos - * @return {Builder} - */ -Builder.prototype.addNanos = function(nanos) { - const value = typeof nanos === 'string' ? Long.fromString(nanos) : nanos; - this._validateOrder(10); - this._validateNanos(value, Long.ONE); - this._nanoseconds = this._nanoseconds.add(value); - return this; -}; - -/** @return {Duration} */ -Builder.prototype.build = function () { - return (this._isNegative ? - new Duration(-this._months, -this._days, this._nanoseconds.negate()) : - new Duration(this._months, this._days, this._nanoseconds)); -}; - -/** - * Contains the methods for reading and writing vints into binary format. - * Exposes only 2 internal methods, the rest are hidden. - * @private - */ -const VIntCoding = (function () { - /** @param {Long} n */ - function encodeZigZag64(n) { - // (n << 1) ^ (n >> 63); - return n.toUnsigned().shiftLeft(1).xor(n.shiftRight(63)); - } - - /** @param {Long} n */ - function decodeZigZag64(n) { - // (n >>> 1) ^ -(n & 1); - return n.shiftRightUnsigned(1).xor(n.and(Long.ONE).negate()); - } - - /** - * @param {Long} value - * @param {Buffer} buffer - * @returns {Number} - */ - function writeVInt(value, buffer) { - return writeUnsignedVInt(encodeZigZag64(value), buffer); - } - - /** - * @param {Long} value - * @param {Buffer} buffer - * @returns {number} - */ - function writeUnsignedVInt(value, buffer) { - const size = computeUnsignedVIntSize(value); - if (size === 1) { - buffer[0] = value.getLowBits(); - return 1; - } - encodeVInt(value, size, buffer); - return size; - } - - /** - * @param {Long} value - * @returns {number} - */ - function computeUnsignedVIntSize(value) { - const magnitude = numberOfLeadingZeros(value.or(Long.ONE)); - return (639 - magnitude * 9) >> 6; - } - - /** - * @param {Long} value - * @param {Number} size - * @param {Buffer} buffer - */ - function encodeVInt(value, size, buffer) { - const extraBytes = size - 1; - let intValue = value.getLowBits(); - let i; - let intBytes = 4; - for (i = extraBytes; i >= 0 && (intBytes--) > 0; i--) { - buffer[i] = 0xFF & intValue; - intValue >>= 8; - } - intValue = value.getHighBits(); - for (; i >= 0; i--) { - buffer[i] = 0xFF & intValue; - intValue >>= 8; - } - buffer[0] |= encodeExtraBytesToRead(extraBytes); - } - /** - * Returns the number of zero bits preceding the highest-order one-bit in the binary representation of the value. - * @param {Long} value - * @returns {Number} - */ - function numberOfLeadingZeros(value) { - if (value.equals(Long.ZERO)) { - return 64; - } - let n = 1; - let x = value.getHighBits(); - if (x === 0) { - n += 32; - x = value.getLowBits(); - } - if (x >>> 16 === 0) { - n += 16; - x <<= 16; - } - if (x >>> 24 === 0) { - n += 8; - x <<= 8; - } - if (x >>> 28 === 0) { - n += 4; - x <<= 4; - } - if (x >>> 30 === 0) { - n += 2; - x <<= 2; - } - n -= x >>> 31; - return n; - } - - - function encodeExtraBytesToRead(extraBytesToRead) { - return ~(0xff >> extraBytesToRead); - } - - /** - * @param {Buffer} buffer - * @param {{value: number}} offset - * @returns {Long} - */ - function readVInt(buffer, offset) { - return decodeZigZag64(readUnsignedVInt(buffer, offset)); - } - - /** - * @param {Buffer} input - * @param {{ value: number}} offset - * @returns {Long} - */ - function readUnsignedVInt(input, offset) { - const firstByte = input[offset.value++]; - if ((firstByte & 0x80) === 0) { - return Long.fromInt(firstByte); - } - const sByteInt = fromSignedByteToInt(firstByte); - const size = numberOfExtraBytesToRead(sByteInt); - let result = Long.fromInt(sByteInt & firstByteValueMask(size)); - for (let ii = 0; ii < size; ii++) { - const b = Long.fromInt(input[offset.value++]); - // (result << 8) | b - result = result.shiftLeft(8).or(b); - } - return result; - } - - function fromSignedByteToInt(value) { - if (value > 0x7f) { - return value - 0x0100; - } - return value; - } - - function numberOfLeadingZerosInt32(i) { - if (i === 0) { - return 32; - } - let n = 1; - if (i >>> 16 === 0) { - n += 16; - i <<= 16; - } - if (i >>> 24 === 0) { - n += 8; - i <<= 8; - } - if (i >>> 28 === 0) { - n += 4; - i <<= 4; - } - if (i >>> 30 === 0) { - n += 2; - i <<= 2; - } - n -= i >>> 31; - return n; - } - - /** - * @param {Number} firstByte - * @returns {Number} - */ - function numberOfExtraBytesToRead(firstByte) { - // Instead of counting 1s of the byte, we negate and count 0 of the byte - return numberOfLeadingZerosInt32(~firstByte) - 24; - } - - /** - * @param {Number} extraBytesToRead - * @returns {Number} - */ - function firstByteValueMask(extraBytesToRead) { - return 0xff >> extraBytesToRead; - } - - return { - readVInt: readVInt, - writeVInt: writeVInt - }; -})(); - -module.exports = Duration; diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/types/index.d.ts b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/types/index.d.ts deleted file mode 100644 index 038f3bcb56..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/types/index.d.ts +++ /dev/null @@ -1,426 +0,0 @@ -/* - * Copyright DataStax, Inc. - * - * 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. - */ - -import _Long = require('long'); -import * as stream from 'stream'; -import { ValueCallback } from '../../'; - -export namespace types { - class Long extends _Long { - - } - - enum consistencies { - any = 0x00, - one = 0x01, - two = 0x02, - three = 0x03, - quorum = 0x04, - all = 0x05, - localQuorum = 0x06, - eachQuorum = 0x07, - serial = 0x08, - localSerial = 0x09, - localOne = 0x0a - } - - enum dataTypes { - custom = 0x0000, - ascii = 0x0001, - bigint = 0x0002, - blob = 0x0003, - boolean = 0x0004, - counter = 0x0005, - decimal = 0x0006, - double = 0x0007, - float = 0x0008, - int = 0x0009, - text = 0x000a, - timestamp = 0x000b, - uuid = 0x000c, - varchar = 0x000d, - varint = 0x000e, - timeuuid = 0x000f, - inet = 0x0010, - date = 0x0011, - time = 0x0012, - smallint = 0x0013, - tinyint = 0x0014, - duration = 0x0015, - list = 0x0020, - map = 0x0021, - set = 0x0022, - udt = 0x0030, - tuple = 0x0031, - } - - enum distance { - local = 0, - remote, - ignored - } - - enum responseErrorCodes { - serverError = 0x0000, - protocolError = 0x000A, - badCredentials = 0x0100, - unavailableException = 0x1000, - overloaded = 0x1001, - isBootstrapping = 0x1002, - truncateError = 0x1003, - writeTimeout = 0x1100, - readTimeout = 0x1200, - readFailure = 0x1300, - functionFailure = 0x1400, - writeFailure = 0x1500, - syntaxError = 0x2000, - unauthorized = 0x2100, - invalid = 0x2200, - configError = 0x2300, - alreadyExists = 0x2400, - unprepared = 0x2500, - clientWriteFailure = 0x8000 - } - - enum protocolVersion { - v1 = 0x01, - v2 = 0x02, - v3 = 0x03, - v4 = 0x04, - v5 = 0x05, - dseV1 = 0x41, - dseV2 = 0x42, - maxSupported = dseV2, - minSupported = v1 - } - - namespace protocolVersion { - function isSupported(version: protocolVersion): boolean; - } - - const unset: object; - - class BigDecimal { - constructor(unscaledValue: number, scale: number); - - static fromBuffer(buf: Buffer): BigDecimal; - - static fromString(value: string): BigDecimal; - - static toBuffer(value: BigDecimal): Buffer; - - static fromNumber(value: number): BigDecimal; - - add(other: BigDecimal): BigDecimal; - - compare(other: BigDecimal): number; - - equals(other: BigDecimal): boolean; - - greaterThan(other: BigDecimal): boolean; - - isNegative(): boolean; - - isZero(): boolean; - - notEquals(other: BigDecimal): boolean; - - subtract(other: BigDecimal): BigDecimal; - - toNumber(): number; - - toString(): string; - - toJSON(): string; - } - - class Duration { - constructor(month: number, days: number, nanoseconds: number | Long); - - static fromBuffer(buffer: Buffer): Duration; - - static fromString(input: string): Duration; - - equals(other: Duration): boolean; - - toBuffer(): Buffer; - - toString(): string; - } - - class InetAddress { - length: number; - - version: number; - - constructor(buffer: Buffer); - - static fromString(value: string): InetAddress; - - equals(other: InetAddress): boolean; - - getBuffer(): Buffer; - - toString(): string; - - toJSON(): string; - } - - class Integer { - static ONE: Integer; - static ZERO: Integer; - - constructor(bits: Array, sign: number); - - static fromBits(bits: Array): Integer; - - static fromBuffer(bits: Buffer): Integer; - - static fromInt(value: number): Integer; - - static fromNumber(value: number): Integer; - - static fromString(str: string, opt_radix?: number): Integer; - - static toBuffer(value: Integer): Buffer; - - abs(): Integer; - - add(other: Integer): Integer; - - compare(other: Integer): number; - - divide(other: Integer): Integer; - - equals(other: Integer): boolean; - - getBits(index: number): number; - - getBitsUnsigned(index: number): number; - - getSign(): number; - - greaterThan(other: Integer): boolean; - - greaterThanOrEqual(other: Integer): boolean; - - isNegative(): boolean; - - isOdd(): boolean; - - isZero(): boolean; - - lessThan(other: Integer): boolean; - - lessThanOrEqual(other: Integer): boolean; - - modulo(other: Integer): Integer; - - multiply(other: Integer): Integer; - - negate(): Integer; - - not(): Integer; - - notEquals(other: Integer): boolean; - - or(other: Integer): Integer; - - shiftLeft(numBits: number): Integer; - - shiftRight(numBits: number): Integer; - - shorten(numBits: number): Integer; - - subtract(other: Integer): Integer; - - toInt(): number; - - toJSON(): string; - - toNumber(): number; - - toString(opt_radix?: number): string; - - xor(other: Integer): Integer; - } - - class LocalDate { - year: number; - month: number; - day: number; - - constructor(year: number, month: number, day: number); - - static fromDate(date: Date): LocalDate; - - static fromString(value: string): LocalDate; - - static fromBuffer(buffer: Buffer): LocalDate; - - static now(): LocalDate; - - static utcNow(): LocalDate; - - equals(other: LocalDate): boolean; - - inspect(): string; - - toBuffer(): Buffer; - - toJSON(): string; - - toString(): string; - } - - class LocalTime { - hour: number; - minute: number; - nanosecond: number; - second: number; - - constructor(totalNanoseconds: Long); - - static fromBuffer(value: Buffer): LocalTime; - - static fromDate(date: Date, nanoseconds: number): LocalTime; - - static fromMilliseconds(milliseconds: number, nanoseconds?: number): LocalTime; - - static fromString(value: string): LocalTime; - - static now(nanoseconds?: number): LocalTime; - - compare(other: LocalTime): boolean; - - equals(other: LocalTime): boolean; - - getTotalNanoseconds(): Long; - - inspect(): string; - - toBuffer(): Buffer; - - toJSON(): string; - - toString(): string; - } - - interface ResultSet extends Iterable, AsyncIterable { - info: { - queriedHost: string, - triedHosts: { [key: string]: any; }, - speculativeExecutions: number, - achievedConsistency: consistencies, - traceId: Uuid, - warnings: string[], - customPayload: any - }; - - columns: Array<{ name: string, type: { code: dataTypes, info: any } }>; - nextPage: (() => void) | null; - pageState: string; - rowLength: number; - rows: Row[]; - - first(): Row; - - wasApplied(): boolean; - } - - interface ResultStream extends stream.Readable { - buffer: Buffer; - paused: boolean; - - add(chunk: Buffer): void; - } - - interface Row { - get(columnName: string | number): any; - - keys(): string[]; - - forEach(callback: (row: Row) => void): void; - - values(): any[]; - - [key: string]: any; - } - - class TimeUuid extends Uuid { - static now(): TimeUuid; - - static now(nodeId: string | Buffer, clockId?: string | Buffer): TimeUuid; - - static now(nodeId: string | Buffer, clockId: string | Buffer, callback: ValueCallback): void; - - static now(callback: ValueCallback): void; - - static fromDate(date: Date, ticks?: number, nodeId?: string | Buffer, clockId?: string | Buffer): TimeUuid; - - static fromDate( - date: Date, - ticks: number, - nodeId: string | Buffer, - clockId: string | Buffer, - callback: ValueCallback): void; - - static fromString(value: string): TimeUuid; - - static max(date: Date, ticks: number): TimeUuid; - - static min(date: Date, ticks: number): TimeUuid; - - getDatePrecision(): { date: Date, ticks: number }; - - getDate(): Date; - } - - class Tuple { - elements: any[]; - length: number; - - constructor(...args: any[]); - - static fromArray(elements: any[]): Tuple; - - get(index: number): any; - - toString(): string; - - toJSON(): string; - - values(): any[]; - } - - class Uuid { - constructor(buffer: Buffer); - - static fromString(value: string): Uuid; - - static random(callback: ValueCallback): void; - - static random(): Uuid; - - equals(other: Uuid): boolean; - - getBuffer(): Buffer; - - toString(): string; - - toJSON(): string; - } -} \ No newline at end of file diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/types/index.js b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/types/index.js deleted file mode 100644 index dae3089d6a..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/types/index.js +++ /dev/null @@ -1,630 +0,0 @@ -/* - * Copyright DataStax, Inc. - * - * 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 util = require('util'); - -const errors = require('../errors'); -const TimeUuid = require('./time-uuid'); -const Uuid = require('./uuid'); -const protocolVersion = require('./protocol-version'); -const utils = require('../utils'); - -/** @module types */ -/** - * Long constructor, wrapper of the internal library used: {@link https://github.com/dcodeIO/long.js Long.js}. - * @constructor - */ -const Long = require('long'); - - -/** - * Consistency levels - * @type {Object} - * @property {Number} any Writing: A write must be written to at least one node. If all replica nodes for the given row key are down, the write can still succeed after a hinted handoff has been written. If all replica nodes are down at write time, an ANY write is not readable until the replica nodes for that row have recovered. - * @property {Number} one Returns a response from the closest replica, as determined by the snitch. - * @property {Number} two Returns the most recent data from two of the closest replicas. - * @property {Number} three Returns the most recent data from three of the closest replicas. - * @property {Number} quorum Reading: Returns the record with the most recent timestamp after a quorum of replicas has responded regardless of data center. Writing: A write must be written to the commit log and memory table on a quorum of replica nodes. - * @property {Number} all Reading: Returns the record with the most recent timestamp after all replicas have responded. The read operation will fail if a replica does not respond. Writing: A write must be written to the commit log and memory table on all replica nodes in the cluster for that row. - * @property {Number} localQuorum Reading: Returns the record with the most recent timestamp once a quorum of replicas in the current data center as the coordinator node has reported. Writing: A write must be written to the commit log and memory table on a quorum of replica nodes in the same data center as the coordinator node. Avoids latency of inter-data center communication. - * @property {Number} eachQuorum Reading: Returns the record once a quorum of replicas in each data center of the cluster has responded. Writing: Strong consistency. A write must be written to the commit log and memtable on a quorum of replica nodes in all data centers. - * @property {Number} serial Achieves linearizable consistency for lightweight transactions by preventing unconditional updates. - * @property {Number} localSerial Same as serial but confined to the data center. A write must be written conditionally to the commit log and memtable on a quorum of replica nodes in the same data center. - * @property {Number} localOne Similar to One but only within the DC the coordinator is in. - */ -const consistencies = { - any: 0x00, - one: 0x01, - two: 0x02, - three: 0x03, - quorum: 0x04, - all: 0x05, - localQuorum: 0x06, - eachQuorum: 0x07, - serial: 0x08, - localSerial: 0x09, - localOne: 0x0a -}; - -/** - * Mapping of consistency level codes to their string representation. - * @type {Object} - */ -const consistencyToString = {}; -consistencyToString[consistencies.any] = 'ANY'; -consistencyToString[consistencies.one] = 'ONE'; -consistencyToString[consistencies.two] = 'TWO'; -consistencyToString[consistencies.three] = 'THREE'; -consistencyToString[consistencies.quorum] = 'QUORUM'; -consistencyToString[consistencies.all] = 'ALL'; -consistencyToString[consistencies.localQuorum] = 'LOCAL_QUORUM'; -consistencyToString[consistencies.eachQuorum] = 'EACH_QUORUM'; -consistencyToString[consistencies.serial] = 'SERIAL'; -consistencyToString[consistencies.localSerial] = 'LOCAL_SERIAL'; -consistencyToString[consistencies.localOne] = 'LOCAL_ONE'; - -/** - * CQL data types - * @type {Object} - * @property {Number} custom A custom type. - * @property {Number} ascii ASCII character string. - * @property {Number} bigint 64-bit signed long. - * @property {Number} blob Arbitrary bytes (no validation). - * @property {Number} boolean true or false. - * @property {Number} counter Counter column (64-bit signed value). - * @property {Number} decimal Variable-precision decimal. - * @property {Number} double 64-bit IEEE-754 floating point. - * @property {Number} float 32-bit IEEE-754 floating point. - * @property {Number} int 32-bit signed integer. - * @property {Number} text UTF8 encoded string. - * @property {Number} timestamp A timestamp. - * @property {Number} uuid Type 1 or type 4 UUID. - * @property {Number} varchar UTF8 encoded string. - * @property {Number} varint Arbitrary-precision integer. - * @property {Number} timeuuid Type 1 UUID. - * @property {Number} inet An IP address. It can be either 4 bytes long (IPv4) or 16 bytes long (IPv6). - * @property {Number} date A date without a time-zone in the ISO-8601 calendar system. - * @property {Number} time A value representing the time portion of the day. - * @property {Number} smallint 16-bit two's complement integer. - * @property {Number} tinyint 8-bit two's complement integer. - * @property {Number} list A collection of elements. - * @property {Number} map Key/value pairs. - * @property {Number} set A collection that contains no duplicate elements. - * @property {Number} udt User-defined type. - * @property {Number} tuple A sequence of values. - */ -const dataTypes = { - custom: 0x0000, - ascii: 0x0001, - bigint: 0x0002, - blob: 0x0003, - boolean: 0x0004, - counter: 0x0005, - decimal: 0x0006, - double: 0x0007, - float: 0x0008, - int: 0x0009, - text: 0x000a, - timestamp: 0x000b, - uuid: 0x000c, - varchar: 0x000d, - varint: 0x000e, - timeuuid: 0x000f, - inet: 0x0010, - date: 0x0011, - time: 0x0012, - smallint: 0x0013, - tinyint: 0x0014, - duration: 0x0015, - list: 0x0020, - map: 0x0021, - set: 0x0022, - udt: 0x0030, - tuple: 0x0031, - /** - * Returns the typeInfo of a given type name - * @param name - * @returns {{code: number, info: *|Object}} - */ - getByName: function(name) { - name = name.toLowerCase(); - if (name.indexOf('<') > 0) { - const listMatches = /^(list|set)<(.+)>$/.exec(name); - if (listMatches) { - return { code: this[listMatches[1]], info: this.getByName(listMatches[2])}; - } - const mapMatches = /^(map)< *(.+) *, *(.+)>$/.exec(name); - if (mapMatches) { - return { code: this[mapMatches[1]], info: [this.getByName(mapMatches[2]), this.getByName(mapMatches[3])]}; - } - const udtMatches = /^(udt)<(.+)>$/.exec(name); - if (udtMatches) { - //udt name as raw string - return { code: this[udtMatches[1]], info: udtMatches[2]}; - } - const tupleMatches = /^(tuple)<(.+)>$/.exec(name); - if (tupleMatches) { - //tuple info as an array of types - return { code: this[tupleMatches[1]], info: tupleMatches[2].split(',').map(function (x) { - return this.getByName(x.trim()); - }, this)}; - } - } - const typeInfo = { code: this[name], info: null}; - if (typeof typeInfo.code !== 'number') { - throw new TypeError('Data type with name ' + name + ' not valid'); - } - return typeInfo; - } -}; - -/** - * Map of Data types by code - * @internal - * @private - */ -const _dataTypesByCode = (function () { - const result = {}; - for (const key in dataTypes) { - if (!dataTypes.hasOwnProperty(key)) { - continue; - } - const val = dataTypes[key]; - if (typeof val !== 'number') { - continue; - } - result[val] = key; - } - return result; -})(); - -/** - * Represents the distance of Cassandra node as assigned by a LoadBalancingPolicy relatively to the driver instance. - * @type {Object} - * @property {Number} local A local node. - * @property {Number} remote A remote node. - * @property {Number} ignored A node that is meant to be ignored. - */ -const distance = { - local: 0, - remote: 1, - ignored: 2 -}; - -/** - * An integer byte that distinguish the actual message from and to Cassandra - * @internal - * @ignore - */ -const opcodes = { - error: 0x00, - startup: 0x01, - ready: 0x02, - authenticate: 0x03, - credentials: 0x04, - options: 0x05, - supported: 0x06, - query: 0x07, - result: 0x08, - prepare: 0x09, - execute: 0x0a, - register: 0x0b, - event: 0x0c, - batch: 0x0d, - authChallenge: 0x0e, - authResponse: 0x0f, - authSuccess: 0x10, - cancel: 0xff, - - /** - * Determines if the code is a valid opcode - */ - isInRange: function (code) { - return code > this.error && code > this.event; - } -}; - -/** - * Event types from Cassandra - * @type {{topologyChange: string, statusChange: string, schemaChange: string}} - * @internal - * @ignore - */ -const protocolEvents = { - topologyChange: 'TOPOLOGY_CHANGE', - statusChange: 'STATUS_CHANGE', - schemaChange: 'SCHEMA_CHANGE' -}; - -/** - * Server error codes returned by Cassandra - * @type {Object} - * @property {Number} serverError Something unexpected happened. - * @property {Number} protocolError Some client message triggered a protocol violation. - * @property {Number} badCredentials Authentication was required and failed. - * @property {Number} unavailableException Raised when coordinator knows there is not enough replicas alive to perform a query with the requested consistency level. - * @property {Number} overloaded The request cannot be processed because the coordinator is overloaded. - * @property {Number} isBootstrapping The request was a read request but the coordinator node is bootstrapping. - * @property {Number} truncateError Error encountered during a truncate request. - * @property {Number} writeTimeout Timeout encountered on write query on coordinator waiting for response(s) from replicas. - * @property {Number} readTimeout Timeout encountered on read query on coordinator waitign for response(s) from replicas. - * @property {Number} readFailure A non-timeout error encountered during a read request. - * @property {Number} functionFailure A (user defined) function encountered during execution. - * @property {Number} writeFailure A non-timeout error encountered during a write request. - * @property {Number} syntaxError The submitted query has a syntax error. - * @property {Number} unauthorized The logged user doesn't have the right to perform the query. - * @property {Number} invalid The query is syntactically correct but invalid. - * @property {Number} configError The query is invalid because of some configuration issue. - * @property {Number} alreadyExists The query attempted to create a schema element (i.e. keyspace, table) that already exists. - * @property {Number} unprepared Can be thrown while a prepared statement tries to be executed if the provided statement is not known by the coordinator. - */ -const responseErrorCodes = { - serverError: 0x0000, - protocolError: 0x000A, - badCredentials: 0x0100, - unavailableException: 0x1000, - overloaded: 0x1001, - isBootstrapping: 0x1002, - truncateError: 0x1003, - writeTimeout: 0x1100, - readTimeout: 0x1200, - readFailure: 0x1300, - functionFailure: 0x1400, - writeFailure: 0x1500, - syntaxError: 0x2000, - unauthorized: 0x2100, - invalid: 0x2200, - configError: 0x2300, - alreadyExists: 0x2400, - unprepared: 0x2500, - clientWriteFailure: 0x8000, -}; - -/** - * Type of result included in a response - * @internal - * @ignore - */ -const resultKind = { - voidResult: 0x0001, - rows: 0x0002, - setKeyspace: 0x0003, - prepared: 0x0004, - schemaChange: 0x0005 -}; - -/** - * Message frame flags - * @internal - * @ignore - */ -const frameFlags = { - compression: 0x01, - tracing: 0x02, - customPayload: 0x04, - warning: 0x08 -}; - -/** - * Unset representation. - *

- * Use this field if you want to set a parameter to unset. Valid for Cassandra 2.2 and above. - *

- */ -const unset = Object.freeze({'unset': true}); - -/** - * A long representing the value 1000 - * @const - * @private - */ -const _longOneThousand = Long.fromInt(1000); - -/** - * Counter used to generate up to 1000 different timestamp values with the same Date - * @private - */ -let _timestampTicks = 0; - -/** - *

Backward compatibility only, use [TimeUuid]{@link module:types~TimeUuid} instead.

- * Generates and returns a RFC4122 v1 (timestamp based) UUID in a string representation. - * @param {{msecs, node, clockseq, nsecs}} [options] - * @param {Buffer} [buffer] - * @param {Number} [offset] - * @deprecated Use [TimeUuid]{@link module:types~TimeUuid} instead - */ -function timeuuid(options, buffer, offset) { - let date; - let ticks; - let nodeId; - let clockId; - if (options) { - if (typeof options.msecs === 'number') { - date = new Date(options.msecs); - } - if (options.msecs instanceof Date) { - date = options.msecs; - } - if (Array.isArray(options.node)) { - nodeId = utils.allocBufferFromArray(options.node); - } - if (typeof options.clockseq === 'number') { - clockId = utils.allocBufferUnsafe(2); - clockId.writeUInt16BE(options.clockseq, 0); - } - if (typeof options.nsecs === 'number') { - ticks = options.nsecs; - } - } - const uuid = new TimeUuid(date, ticks, nodeId, clockId); - if (buffer instanceof Buffer) { - //copy the values into the buffer - uuid.getBuffer().copy(buffer, offset || 0); - return buffer; - } - return uuid.toString(); -} - -/** - *

Backward compatibility only, use [Uuid]{@link module:types~Uuid} class instead.

- * Generate and return a RFC4122 v4 UUID in a string representation. - * @deprecated Use [Uuid]{@link module:types~Uuid} class instead - */ -function uuid(options, buffer, offset) { - let uuid; - if (options) { - if (Array.isArray(options.random)) { - uuid = new Uuid(utils.allocBufferFromArray(options.random)); - } - } - if (!uuid) { - uuid = Uuid.random(); - } - if (buffer instanceof Buffer) { - //copy the values into the buffer - uuid.getBuffer().copy(buffer, offset || 0); - return buffer; - } - return uuid.toString(); -} - -/** - * Gets the data type name for a given type definition - * @internal - * @ignore - * @throws {ArgumentError} - */ -function getDataTypeNameByCode(item) { - if (!item || typeof item.code !== 'number') { - throw new errors.ArgumentError('Invalid signature type definition'); - } - const typeName = _dataTypesByCode[item.code]; - if (!typeName) { - throw new errors.ArgumentError(util.format('Type with code %d not found', item.code)); - } - if (!item.info) { - return typeName; - } - if (Array.isArray(item.info)) { - return (typeName + - '<' + - item.info.map(function (t) { - return getDataTypeNameByCode(t); - }).join(', ') + - '>'); - } - if (typeof item.info.code === 'number') { - return typeName + '<' + getDataTypeNameByCode(item.info) + '>'; - } - return typeName; -} - -//classes - -/** - * Represents a frame header that could be used to read from a Buffer or to write to a Buffer - * @ignore - * @param {Number} version Protocol version - * @param {Number} flags - * @param {Number} streamId - * @param {Number} opcode - * @param {Number} bodyLength - * @constructor - */ -function FrameHeader(version, flags, streamId, opcode, bodyLength) { - this.version = version; - this.flags = flags; - this.streamId = streamId; - this.opcode = opcode; - this.bodyLength = bodyLength; -} - -/** - * The length of the header of the frame based on the protocol version - * @returns {Number} - */ -FrameHeader.size = function (version) { - if (protocolVersion.uses2BytesStreamIds(version)) { - return 9; - } - return 8; -}; - -/** - * Gets the protocol version based on the first byte of the header - * @param {Buffer} buffer - * @returns {Number} - */ -FrameHeader.getProtocolVersion = function (buffer) { - return buffer[0] & 0x7F; -}; - -/** - * @param {Buffer} buf - * @param {Number} [offset] - * @returns {FrameHeader} - */ -FrameHeader.fromBuffer = function (buf, offset) { - let streamId = 0; - if (!offset) { - offset = 0; - } - const version = buf[offset++] & 0x7F; - const flags = buf.readUInt8(offset++); - if (!protocolVersion.uses2BytesStreamIds(version)) { - streamId = buf.readInt8(offset++); - } - else { - streamId = buf.readInt16BE(offset); - offset += 2; - } - return new FrameHeader(version, flags, streamId, buf.readUInt8(offset++), buf.readUInt32BE(offset)); -}; - -/** @returns {Buffer} */ -FrameHeader.prototype.toBuffer = function () { - const buf = utils.allocBufferUnsafe(FrameHeader.size(this.version)); - buf.writeUInt8(this.version, 0); - buf.writeUInt8(this.flags, 1); - let offset = 3; - if (!protocolVersion.uses2BytesStreamIds(this.version)) { - buf.writeInt8(this.streamId, 2); - } - else { - buf.writeInt16BE(this.streamId, 2); - offset = 4; - } - buf.writeUInt8(this.opcode, offset++); - buf.writeUInt32BE(this.bodyLength, offset); - return buf; -}; -/** - * Returns a long representation. - * Used internally for deserialization - */ -Long.fromBuffer = function (value) { - if (!(value instanceof Buffer)) { - throw new TypeError('Expected Buffer, obtained ' + util.inspect(value)); - } - return new Long(value.readInt32BE(4), value.readInt32BE(0)); -}; - -/** - * Returns a big-endian buffer representation of the Long instance - * @param {Long} value - */ -Long.toBuffer = function (value) { - if (!(value instanceof Long)) { - throw new TypeError('Expected Long, obtained ' + util.inspect(value)); - } - const buffer = utils.allocBufferUnsafe(8); - buffer.writeUInt32BE(value.getHighBitsUnsigned(), 0); - buffer.writeUInt32BE(value.getLowBitsUnsigned(), 4); - return buffer; -}; - -/** - * Provide the name of the constructor and the string representation - * @returns {string} - */ -Long.prototype.inspect = function () { - return 'Long: ' + this.toString(); -}; - -/** - * Returns the string representation. - * Method used by the native JSON.stringify() to serialize this instance - */ -Long.prototype.toJSON = function () { - return this.toString(); -}; - -/** - * Generates a value representing the timestamp for the query in microseconds based on the date and the microseconds provided - * @param {Date} [date] The date to generate the value, if not provided it will use the current date. - * @param {Number} [microseconds] A number from 0 to 999 used to build the microseconds part of the date. - * @returns {Long} - */ -function generateTimestamp(date, microseconds) { - if (!date) { - date = new Date(); - } - let longMicro = Long.ZERO; - if (typeof microseconds === 'number' && microseconds >= 0 && microseconds < 1000) { - longMicro = Long.fromInt(microseconds); - } - else { - if (_timestampTicks > 999) { - _timestampTicks = 0; - } - longMicro = Long.fromInt(_timestampTicks); - _timestampTicks++; - } - return Long - .fromNumber(date.getTime()) - .multiply(_longOneThousand) - .add(longMicro); -} - -//error classes - -/** @private */ -function QueryParserError(e) { - QueryParserError.super_.call(this, e.message, this.constructor); - this.internalError = e; -} -util.inherits(QueryParserError, errors.DriverError); - -/** @private */ -function TimeoutError (message) { - TimeoutError.super_.call(this, message, this.constructor); - this.info = 'Represents an error that happens when the maximum amount of time for an operation passed.'; -} -util.inherits(TimeoutError, errors.DriverError); - -exports.opcodes = opcodes; -exports.consistencies = consistencies; -exports.consistencyToString = consistencyToString; -exports.dataTypes = dataTypes; -exports.getDataTypeNameByCode = getDataTypeNameByCode; -exports.distance = distance; -exports.frameFlags = frameFlags; -exports.protocolEvents = protocolEvents; -exports.protocolVersion = protocolVersion; -exports.responseErrorCodes = responseErrorCodes; -exports.resultKind = resultKind; -exports.timeuuid = timeuuid; -exports.uuid = uuid; -exports.BigDecimal = require('./big-decimal'); -exports.Duration = require('./duration'); -exports.FrameHeader = FrameHeader; -exports.InetAddress = require('./inet-address'); -exports.Integer = require('./integer'); -exports.LocalDate = require('./local-date'); -exports.LocalTime = require('./local-time'); -exports.Long = Long; -exports.ResultSet = require('./result-set'); -exports.ResultStream = require('./result-stream'); -exports.Row = require('./row'); -//export DriverError for backward-compatibility -exports.DriverError = errors.DriverError; -exports.TimeoutError = TimeoutError; -exports.TimeUuid = TimeUuid; -exports.Tuple = require('./tuple'); -exports.Uuid = Uuid; -exports.unset = unset; -exports.generateTimestamp = generateTimestamp; diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/types/inet-address.js b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/types/inet-address.js deleted file mode 100644 index 1647deaf6b..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/types/inet-address.js +++ /dev/null @@ -1,248 +0,0 @@ -/* - * Copyright DataStax, Inc. - * - * 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 utils = require('../utils'); - -/** @module types */ -/** - * Creates a new instance of InetAddress - * @class - * @classdesc Represents an v4 or v6 Internet Protocol (IP) address. - * @param {Buffer} buffer - * @constructor - */ -function InetAddress(buffer) { - if (!(buffer instanceof Buffer) || (buffer.length !== 4 && buffer.length !== 16)) { - throw new TypeError('The ip address must contain 4 or 16 bytes'); - } - - /** - * Immutable buffer that represents the IP address - * @type Array - */ - this.buffer = buffer; - - /** - * Returns the length of the underlying buffer - * @type Number - */ - this.length = buffer.length; - - /** - * Returns the Ip version (4 or 6) - * @type Number - */ - this.version = buffer.length === 4 ? 4 : 6; -} - -/** - * Parses the string representation and returns an Ip address - * @param {String} value - */ -InetAddress.fromString = function (value) { - if (!value) { - return new InetAddress(utils.allocBufferFromArray([0, 0, 0, 0])); - } - const ipv4Pattern = /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/; - const ipv6Pattern = /^[\da-f:.]+$/i; - let parts; - if (ipv4Pattern.test(value)) { - parts = value.split('.'); - return new InetAddress(utils.allocBufferFromArray(parts)); - } - if (!ipv6Pattern.test(value)) { - throw new TypeError('Value could not be parsed as InetAddress: ' + value); - } - parts = value.split(':'); - if (parts.length < 3) { - throw new TypeError('Value could not be parsed as InetAddress: ' + value); - } - const buffer = utils.allocBufferUnsafe(16); - let filling = 8 - parts.length + 1; - let applied = false; - let offset = 0; - const embeddedIp4 = ipv4Pattern.test(parts[parts.length - 1]); - if (embeddedIp4) { - // Its IPv6 address with an embedded IPv4 address: - // subtract 1 from the potential empty filling as ip4 contains 4 bytes instead of 2 of a ipv6 section - filling -= 1; - } - function writeItem(uIntValue) { - buffer.writeUInt8(+uIntValue, offset++); - } - for (let i = 0; i < parts.length; i++) { - const item = parts[i]; - if (item) { - if (embeddedIp4 && i === parts.length - 1) { - item.split('.').forEach(writeItem); - break; - } - buffer.writeUInt16BE(parseInt(item, 16), offset); - offset = offset + 2; - continue; - } - //its an empty string - if (applied) { - //there could be 2 occurrences of empty string - filling = 1; - } - applied = true; - for (let j = 0; j < filling; j++) { - buffer[offset++] = 0; - buffer[offset++] = 0; - } - } - if (embeddedIp4 && !isValidIPv4Mapped(buffer)) { - throw new TypeError('Only IPv4-Mapped IPv6 addresses are allowed as IPv6 address with embedded IPv4 address'); - } - return new InetAddress(buffer); -}; - -/** - * Compares 2 addresses and returns true if the underlying bytes are the same - * @param {InetAddress} other - * @returns {Boolean} - */ -InetAddress.prototype.equals = function (other) { - if (!(other instanceof InetAddress)) { - return false; - } - return (this.buffer.length === other.buffer.length && - this.buffer.toString('hex') === other.buffer.toString('hex')); -}; - -/** - * Returns the underlying buffer - * @returns {Buffer} - */ -InetAddress.prototype.getBuffer = function () { - return this.buffer; -}; - -/** - * Provide the name of the constructor and the string representation - * @returns {string} - */ -InetAddress.prototype.inspect = function () { - return this.constructor.name + ': ' + this.toString(); -}; - -/** - * Returns the string representation of the IP address. - *

For v4 IP addresses, a string in the form of d.d.d.d is returned.

- *

- * For v6 IP addresses, a string in the form of x:x:x:x:x:x:x:x is returned, where the 'x's are the hexadecimal - * values of the eight 16-bit pieces of the address, according to rfc5952. - * In cases where there is more than one field of only zeros, it can be shortened. For example, 2001:0db8:0:0:0:1:0:1 - * will be expressed as 2001:0db8::1:0:1. - *

- * @param {String} [encoding] - * @returns {String} - */ -InetAddress.prototype.toString = function (encoding) { - if (encoding === 'hex') { - //backward compatibility: behave in the same way as the buffer - return this.buffer.toString('hex'); - } - if (this.buffer.length === 4) { - return ( - this.buffer[0] + '.' + - this.buffer[1] + '.' + - this.buffer[2] + '.' + - this.buffer[3] - ); - } - let start = -1; - const longest = { length: 0, start: -1}; - function checkLongest (i) { - if (start >= 0) { - //close the group - const length = i - start; - if (length > longest.length) { - longest.length = length; - longest.start = start; - start = -1; - } - } - } - //get the longest 16-bit group of zeros - for (let i = 0; i < this.buffer.length; i = i + 2) { - if (this.buffer[i] === 0 && this.buffer[i + 1] === 0) { - //its a group of zeros - if (start < 0) { - start = i; - } - - // at the end of the buffer, make a final call to checkLongest. - if(i === this.buffer.length - 2) { - checkLongest(i+2); - } - continue; - } - //its a group of non-zeros - checkLongest(i); - } - - let address = ''; - for (let h = 0; h < this.buffer.length; h = h + 2) { - if (h === longest.start) { - address += ':'; - continue; - } - if (h < (longest.start + longest.length) && h > longest.start) { - //its a group of zeros - continue; - } - if (address.length > 0) { - address += ':'; - } - address += ((this.buffer[h] << 8) | this.buffer[h+1]).toString(16); - } - if (address.charAt(address.length-1) === ':') { - address += ':'; - } - return address; -}; - -/** - * Returns the string representation. - * Method used by the native JSON.stringify() to serialize this instance. - */ -InetAddress.prototype.toJSON = function () { - return this.toString(); -}; - -/** - * Validates for a IPv4-Mapped IPv6 according to https://tools.ietf.org/html/rfc4291#section-2.5.5 - * @private - * @param {Buffer} buffer - */ -function isValidIPv4Mapped(buffer) { - // check the form - // | 80 bits | 16 | 32 bits - // +----------------+----+------------- - // |0000........0000|FFFF| IPv4 address - - for (let i = 0; i < buffer.length - 6; i++) { - if (buffer[i] !== 0) { - return false; - } - } - return !(buffer[10] !== 255 || buffer[11] !== 255); -} - -module.exports = InetAddress; \ No newline at end of file diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/types/integer.js b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/types/integer.js deleted file mode 100644 index d70d789a18..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/types/integer.js +++ /dev/null @@ -1,855 +0,0 @@ -// Copyright 2009 The Closure Library 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. - -/** @module types */ - -var utils = require('../utils'); - -/** - * Constructs a two's-complement integer an array containing bits of the - * integer in 32-bit (signed) pieces, given in little-endian order (i.e., - * lowest-order bits in the first piece), and the sign of -1 or 0. - * - * See the from* functions below for other convenient ways of constructing - * Integers. - * - * The internal representation of an integer is an array of 32-bit signed - * pieces, along with a sign (0 or -1) that indicates the contents of all the - * other 32-bit pieces out to infinity. We use 32-bit pieces because these are - * the size of integers on which Javascript performs bit-operations. For - * operations like addition and multiplication, we split each number into 16-bit - * pieces, which can easily be multiplied within Javascript's floating-point - * representation without overflow or change in sign. - * - * @constructor - * @param {Array.} bits Array containing the bits of the number. - * @param {number} sign The sign of the number: -1 for negative and 0 positive. - * @final - */ -function Integer (bits, sign) { - /** - * @type {!Array.} - * @private - */ - this.bits_ = []; - - /** - * @type {number} - * @private - */ - this.sign_ = sign; - - // Copy the 32-bit signed integer values passed in. We prune out those at the - // top that equal the sign since they are redundant. - var top = true; - for (var i = bits.length - 1; i >= 0; i--) { - var val = bits[i] | 0; - if (!top || val != sign) { - this.bits_[i] = val; - top = false; - } - } -} - - -// NOTE: Common constant values ZERO, ONE, NEG_ONE, etc. are defined below the -// from* methods on which they depend. - - -/** - * A cache of the Integer representations of small integer values. - * @type {!Object} - * @private - */ -Integer.IntCache_ = {}; - - -/** - * Returns an Integer representing the given (32-bit) integer value. - * @param {number} value A 32-bit integer value. - * @return {!Integer} The corresponding Integer value. - */ -Integer.fromInt = function(value) { - if (-128 <= value && value < 128) { - var cachedObj = Integer.IntCache_[value]; - if (cachedObj) { - return cachedObj; - } - } - - var obj = new Integer([value | 0], value < 0 ? -1 : 0); - if (-128 <= value && value < 128) { - Integer.IntCache_[value] = obj; - } - return obj; -}; - - -/** - * Returns an Integer representing the given value, provided that it is a finite - * number. Otherwise, zero is returned. - * @param {number} value The value in question. - * @return {!Integer} The corresponding Integer value. - */ -Integer.fromNumber = function(value) { - if (isNaN(value) || !isFinite(value)) { - return Integer.ZERO; - } else if (value < 0) { - return Integer.fromNumber(-value).negate(); - } else { - var bits = []; - var pow = 1; - for (var i = 0; value >= pow; i++) { - bits[i] = (value / pow) | 0; - pow *= Integer.TWO_PWR_32_DBL_; - } - return new Integer(bits, 0); - } -}; - - -/** - * Returns a Integer representing the value that comes by concatenating the - * given entries, each is assumed to be 32 signed bits, given in little-endian - * order (lowest order bits in the lowest index), and sign-extending the highest - * order 32-bit value. - * @param {Array.} bits The bits of the number, in 32-bit signed pieces, - * in little-endian order. - * @return {!Integer} The corresponding Integer value. - */ -Integer.fromBits = function(bits) { - var high = bits[bits.length - 1]; - //noinspection JSBitwiseOperatorUsage - return new Integer(bits, high & (1 << 31) ? -1 : 0); -}; - - -/** - * Returns an Integer representation of the given string, written using the - * given radix. - * @param {string} str The textual representation of the Integer. - * @param {number=} opt_radix The radix in which the text is written. - * @return {!Integer} The corresponding Integer value. - */ -Integer.fromString = function(str, opt_radix) { - if (str.length == 0) { - throw TypeError('number format error: empty string'); - } - - var radix = opt_radix || 10; - if (radix < 2 || 36 < radix) { - throw Error('radix out of range: ' + radix); - } - - if (str.charAt(0) == '-') { - return Integer.fromString(str.substring(1), radix).negate(); - } else if (str.indexOf('-') >= 0) { - throw TypeError('number format error: interior "-" character'); - } - - // Do several (8) digits each time through the loop, so as to - // minimize the calls to the very expensive emulated div. - var radixToPower = Integer.fromNumber(Math.pow(radix, 8)); - - var result = Integer.ZERO; - for (var i = 0; i < str.length; i += 8) { - var size = Math.min(8, str.length - i); - var value = parseInt(str.substring(i, i + size), radix); - if (size < 8) { - var power = Integer.fromNumber(Math.pow(radix, size)); - result = result.multiply(power).add(Integer.fromNumber(value)); - } else { - result = result.multiply(radixToPower); - result = result.add(Integer.fromNumber(value)); - } - } - return result; -}; - -/** - * Returns an Integer representation of a given big endian Buffer. - * The internal representation of bits contains bytes in groups of 4 - * @param {Buffer} buf - * @returns {Integer} - */ -Integer.fromBuffer = function (buf) { - var bits = new Array(Math.ceil(buf.length / 4)); - //noinspection JSBitwiseOperatorUsage - var sign = buf[0] & (1 << 7) ? -1 : 0; - for (var i = 0; i < bits.length; i++) { - var offset = buf.length - ((i + 1) * 4); - var value; - if (offset < 0) { - //The buffer length is not multiple of 4 - offset = offset + 4; - value = 0; - for (var j = 0; j < offset; j++) { - var byte = buf[j]; - if (sign === -1) { - //invert the bits - byte = ~byte & 0xff; - } - value = value | (byte << (offset - j - 1) * 8); - } - if (sign === -1) { - //invert all the bits - value = ~value; - } - } - else { - value = buf.readInt32BE(offset); - } - bits[i] = value; - } - return new Integer(bits, sign); -}; - -/** - * Returns a big endian buffer representation of an Integer. - * Internally the bits are represented using 4 bytes groups (numbers), - * in the Buffer representation there might be the case where we need less than the 4 bytes. - * For example: 0x00000001 -> '01', 0xFFFFFFFF -> 'FF', 0xFFFFFF01 -> 'FF01' - * @param {Integer} value - * @returns {Buffer} -*/ -Integer.toBuffer = function (value) { - var sign = value.sign_; - var bits = value.bits_; - if (bits.length === 0) { - //[0] or [0xffffffff] - return utils.allocBufferFromArray([value.sign_]); - } - //the high bits might need to be represented in less than 4 bytes - var highBits = bits[bits.length-1]; - if (sign === -1) { - highBits = ~highBits; - } - var high = []; - if (highBits >>> 24 > 0) { - high.push((highBits >> 24) & 0xff); - } - if (highBits >>> 16 > 0) { - high.push((highBits >> 16) & 0xff); - } - if (highBits >>> 8 > 0) { - high.push((highBits >> 8) & 0xff); - } - high.push(highBits & 0xff); - if (sign === -1) { - //The byte containing the sign bit got removed - if (high[0] >> 7 !== 0) { - //it is going to be negated - high.unshift(0); - } - } - else if (high[0] >> 7 !== 0) { - //its positive but it lost the byte containing the sign bit - high.unshift(0); - } - var buf = utils.allocBufferUnsafe(high.length + ((bits.length-1) * 4)); - for (var j = 0; j < high.length; j++) { - var b = high[j]; - if (sign === -1) { - buf[j] = ~b; - } - else { - buf[j] = b; - } - } - for (var i = 0; i < bits.length - 1; i++) { - var group = bits[bits.length - 2 - i]; - var offset = high.length + i * 4; - buf.writeInt32BE(group, offset); - } - return buf; -}; - - -/** - * A number used repeatedly in calculations. This must appear before the first - * call to the from* functions below. - * @type {number} - * @private - */ -Integer.TWO_PWR_32_DBL_ = (1 << 16) * (1 << 16); - - -/** @type {!Integer} */ -Integer.ZERO = Integer.fromInt(0); - - -/** @type {!Integer} */ -Integer.ONE = Integer.fromInt(1); - - -/** - * @type {!Integer} - * @private - */ -Integer.TWO_PWR_24_ = Integer.fromInt(1 << 24); - - -/** - * Returns the value, assuming it is a 32-bit integer. - * @return {number} The corresponding int value. - */ -Integer.prototype.toInt = function() { - return this.bits_.length > 0 ? this.bits_[0] : this.sign_; -}; - - -/** @return {number} The closest floating-point representation to this value. */ -Integer.prototype.toNumber = function() { - if (this.isNegative()) { - return -this.negate().toNumber(); - } else { - var val = 0; - var pow = 1; - for (var i = 0; i < this.bits_.length; i++) { - val += this.getBitsUnsigned(i) * pow; - pow *= Integer.TWO_PWR_32_DBL_; - } - return val; - } -}; - - -/** - * @param {number=} opt_radix The radix in which the text should be written. - * @return {string} The textual representation of this value. - * @override - */ -Integer.prototype.toString = function(opt_radix) { - var radix = opt_radix || 10; - if (radix < 2 || 36 < radix) { - throw Error('radix out of range: ' + radix); - } - - if (this.isZero()) { - return '0'; - } else if (this.isNegative()) { - return '-' + this.negate().toString(radix); - } - - // Do several (6) digits each time through the loop, so as to - // minimize the calls to the very expensive emulated div. - var radixToPower = Integer.fromNumber(Math.pow(radix, 6)); - - var rem = this; - var result = ''; - while (true) { - var remDiv = rem.divide(radixToPower); - var intval = rem.subtract(remDiv.multiply(radixToPower)).toInt(); - var digits = intval.toString(radix); - - rem = remDiv; - if (rem.isZero()) { - return digits + result; - } else { - while (digits.length < 6) { - digits = '0' + digits; - } - result = '' + digits + result; - } - } -}; - - -/** - * Returns the index-th 32-bit (signed) piece of the Integer according to - * little-endian order (i.e., index 0 contains the smallest bits). - * @param {number} index The index in question. - * @return {number} The requested 32-bits as a signed number. - */ -Integer.prototype.getBits = function(index) { - if (index < 0) { - return 0; // Allowing this simplifies bit shifting operations below... - } else if (index < this.bits_.length) { - return this.bits_[index]; - } else { - return this.sign_; - } -}; - - -/** - * Returns the index-th 32-bit piece as an unsigned number. - * @param {number} index The index in question. - * @return {number} The requested 32-bits as an unsigned number. - */ -Integer.prototype.getBitsUnsigned = function(index) { - var val = this.getBits(index); - return val >= 0 ? val : Integer.TWO_PWR_32_DBL_ + val; -}; - - -/** @return {number} The sign bit of this number, -1 or 0. */ -Integer.prototype.getSign = function() { - return this.sign_; -}; - - -/** @return {boolean} Whether this value is zero. */ -Integer.prototype.isZero = function() { - if (this.sign_ != 0) { - return false; - } - for (var i = 0; i < this.bits_.length; i++) { - if (this.bits_[i] != 0) { - return false; - } - } - return true; -}; - - -/** @return {boolean} Whether this value is negative. */ -Integer.prototype.isNegative = function() { - return this.sign_ == -1; -}; - - -/** @return {boolean} Whether this value is odd. */ -Integer.prototype.isOdd = function() { - return (this.bits_.length == 0) && (this.sign_ == -1) || - (this.bits_.length > 0) && ((this.bits_[0] & 1) != 0); -}; - - -/** - * @param {Integer} other Integer to compare against. - * @return {boolean} Whether this Integer equals the other. - */ -Integer.prototype.equals = function(other) { - if (this.sign_ != other.sign_) { - return false; - } - var len = Math.max(this.bits_.length, other.bits_.length); - for (var i = 0; i < len; i++) { - if (this.getBits(i) != other.getBits(i)) { - return false; - } - } - return true; -}; - - -/** - * @param {Integer} other Integer to compare against. - * @return {boolean} Whether this Integer does not equal the other. - */ -Integer.prototype.notEquals = function(other) { - return !this.equals(other); -}; - - -/** - * @param {Integer} other Integer to compare against. - * @return {boolean} Whether this Integer is greater than the other. - */ -Integer.prototype.greaterThan = function(other) { - return this.compare(other) > 0; -}; - - -/** - * @param {Integer} other Integer to compare against. - * @return {boolean} Whether this Integer is greater than or equal to the other. - */ -Integer.prototype.greaterThanOrEqual = function(other) { - return this.compare(other) >= 0; -}; - - -/** - * @param {Integer} other Integer to compare against. - * @return {boolean} Whether this Integer is less than the other. - */ -Integer.prototype.lessThan = function(other) { - return this.compare(other) < 0; -}; - - -/** - * @param {Integer} other Integer to compare against. - * @return {boolean} Whether this Integer is less than or equal to the other. - */ -Integer.prototype.lessThanOrEqual = function(other) { - return this.compare(other) <= 0; -}; - - -/** - * Compares this Integer with the given one. - * @param {Integer} other Integer to compare against. - * @return {number} 0 if they are the same, 1 if the this is greater, and -1 - * if the given one is greater. - */ -Integer.prototype.compare = function(other) { - var diff = this.subtract(other); - if (diff.isNegative()) { - return -1; - } else if (diff.isZero()) { - return 0; - } else { - return +1; - } -}; - - -/** - * Returns an integer with only the first numBits bits of this value, sign - * extended from the final bit. - * @param {number} numBits The number of bits by which to shift. - * @return {!Integer} The shorted integer value. - */ -Integer.prototype.shorten = function(numBits) { - var arr_index = (numBits - 1) >> 5; - var bit_index = (numBits - 1) % 32; - var bits = []; - for (var i = 0; i < arr_index; i++) { - bits[i] = this.getBits(i); - } - var sigBits = bit_index == 31 ? 0xFFFFFFFF : (1 << (bit_index + 1)) - 1; - var val = this.getBits(arr_index) & sigBits; - //noinspection JSBitwiseOperatorUsage - if (val & (1 << bit_index)) { - val |= 0xFFFFFFFF - sigBits; - bits[arr_index] = val; - return new Integer(bits, -1); - } else { - bits[arr_index] = val; - return new Integer(bits, 0); - } -}; - - -/** @return {!Integer} The negation of this value. */ -Integer.prototype.negate = function() { - return this.not().add(Integer.ONE); -}; - - -/** - * Returns the sum of this and the given Integer. - * @param {Integer} other The Integer to add to this. - * @return {!Integer} The Integer result. - */ -Integer.prototype.add = function(other) { - var len = Math.max(this.bits_.length, other.bits_.length); - var arr = []; - var carry = 0; - - for (var i = 0; i <= len; i++) { - var a1 = this.getBits(i) >>> 16; - var a0 = this.getBits(i) & 0xFFFF; - - var b1 = other.getBits(i) >>> 16; - var b0 = other.getBits(i) & 0xFFFF; - - var c0 = carry + a0 + b0; - var c1 = (c0 >>> 16) + a1 + b1; - carry = c1 >>> 16; - c0 &= 0xFFFF; - c1 &= 0xFFFF; - arr[i] = (c1 << 16) | c0; - } - return Integer.fromBits(arr); -}; - - -/** - * Returns the difference of this and the given Integer. - * @param {Integer} other The Integer to subtract from this. - * @return {!Integer} The Integer result. - */ -Integer.prototype.subtract = function(other) { - return this.add(other.negate()); -}; - - -/** - * Returns the product of this and the given Integer. - * @param {Integer} other The Integer to multiply against this. - * @return {!Integer} The product of this and the other. - */ -Integer.prototype.multiply = function(other) { - if (this.isZero()) { - return Integer.ZERO; - } else if (other.isZero()) { - return Integer.ZERO; - } - - if (this.isNegative()) { - if (other.isNegative()) { - return this.negate().multiply(other.negate()); - } else { - return this.negate().multiply(other).negate(); - } - } else if (other.isNegative()) { - return this.multiply(other.negate()).negate(); - } - - // If both numbers are small, use float multiplication - if (this.lessThan(Integer.TWO_PWR_24_) && - other.lessThan(Integer.TWO_PWR_24_)) { - return Integer.fromNumber(this.toNumber() * other.toNumber()); - } - - // Fill in an array of 16-bit products. - var len = this.bits_.length + other.bits_.length; - var arr = []; - for (var i = 0; i < 2 * len; i++) { - arr[i] = 0; - } - for (var i = 0; i < this.bits_.length; i++) { - for (var j = 0; j < other.bits_.length; j++) { - var a1 = this.getBits(i) >>> 16; - var a0 = this.getBits(i) & 0xFFFF; - - var b1 = other.getBits(j) >>> 16; - var b0 = other.getBits(j) & 0xFFFF; - - arr[2 * i + 2 * j] += a0 * b0; - Integer.carry16_(arr, 2 * i + 2 * j); - arr[2 * i + 2 * j + 1] += a1 * b0; - Integer.carry16_(arr, 2 * i + 2 * j + 1); - arr[2 * i + 2 * j + 1] += a0 * b1; - Integer.carry16_(arr, 2 * i + 2 * j + 1); - arr[2 * i + 2 * j + 2] += a1 * b1; - Integer.carry16_(arr, 2 * i + 2 * j + 2); - } - } - - // Combine the 16-bit values into 32-bit values. - for (var i = 0; i < len; i++) { - arr[i] = (arr[2 * i + 1] << 16) | arr[2 * i]; - } - for (var i = len; i < 2 * len; i++) { - arr[i] = 0; - } - return new Integer(arr, 0); -}; - - -/** - * Carries any overflow from the given index into later entries. - * @param {Array.} bits Array of 16-bit values in little-endian order. - * @param {number} index The index in question. - * @private - */ -Integer.carry16_ = function(bits, index) { - while ((bits[index] & 0xFFFF) != bits[index]) { - bits[index + 1] += bits[index] >>> 16; - bits[index] &= 0xFFFF; - } -}; - - -/** - * Returns this Integer divided by the given one. - * @param {Integer} other Th Integer to divide this by. - * @return {!Integer} This value divided by the given one. - */ -Integer.prototype.divide = function(other) { - if (other.isZero()) { - throw Error('division by zero'); - } else if (this.isZero()) { - return Integer.ZERO; - } - - if (this.isNegative()) { - if (other.isNegative()) { - return this.negate().divide(other.negate()); - } else { - return this.negate().divide(other).negate(); - } - } else if (other.isNegative()) { - return this.divide(other.negate()).negate(); - } - - // Repeat the following until the remainder is less than other: find a - // floating-point that approximates remainder / other *from below*, add this - // into the result, and subtract it from the remainder. It is critical that - // the approximate value is less than or equal to the real value so that the - // remainder never becomes negative. - var res = Integer.ZERO; - var rem = this; - while (rem.greaterThanOrEqual(other)) { - // Approximate the result of division. This may be a little greater or - // smaller than the actual value. - var approx = Math.max(1, Math.floor(rem.toNumber() / other.toNumber())); - - // We will tweak the approximate result by changing it in the 48-th digit or - // the smallest non-fractional digit, whichever is larger. - var log2 = Math.ceil(Math.log(approx) / Math.LN2); - var delta = (log2 <= 48) ? 1 : Math.pow(2, log2 - 48); - - // Decrease the approximation until it is smaller than the remainder. Note - // that if it is too large, the product overflows and is negative. - var approxRes = Integer.fromNumber(approx); - var approxRem = approxRes.multiply(other); - while (approxRem.isNegative() || approxRem.greaterThan(rem)) { - approx -= delta; - approxRes = Integer.fromNumber(approx); - approxRem = approxRes.multiply(other); - } - - // We know the answer can't be zero... and actually, zero would cause - // infinite recursion since we would make no progress. - if (approxRes.isZero()) { - approxRes = Integer.ONE; - } - - res = res.add(approxRes); - rem = rem.subtract(approxRem); - } - return res; -}; - - -/** - * Returns this Integer modulo the given one. - * @param {Integer} other The Integer by which to mod. - * @return {!Integer} This value modulo the given one. - */ -Integer.prototype.modulo = function(other) { - return this.subtract(this.divide(other).multiply(other)); -}; - - -/** @return {!Integer} The bitwise-NOT of this value. */ -Integer.prototype.not = function() { - var len = this.bits_.length; - var arr = []; - for (var i = 0; i < len; i++) { - arr[i] = ~this.bits_[i]; - } - return new Integer(arr, ~this.sign_); -}; - - -/** - * Returns the bitwise-AND of this Integer and the given one. - * @param {Integer} other The Integer to AND with this. - * @return {!Integer} The bitwise-AND of this and the other. - */ -Integer.prototype.and = function(other) { - var len = Math.max(this.bits_.length, other.bits_.length); - var arr = []; - for (var i = 0; i < len; i++) { - arr[i] = this.getBits(i) & other.getBits(i); - } - return new Integer(arr, this.sign_ & other.sign_); -}; - - -/** - * Returns the bitwise-OR of this Integer and the given one. - * @param {Integer} other The Integer to OR with this. - * @return {!Integer} The bitwise-OR of this and the other. - */ -Integer.prototype.or = function(other) { - var len = Math.max(this.bits_.length, other.bits_.length); - var arr = []; - for (var i = 0; i < len; i++) { - arr[i] = this.getBits(i) | other.getBits(i); - } - return new Integer(arr, this.sign_ | other.sign_); -}; - - -/** - * Returns the bitwise-XOR of this Integer and the given one. - * @param {Integer} other The Integer to XOR with this. - * @return {!Integer} The bitwise-XOR of this and the other. - */ -Integer.prototype.xor = function(other) { - var len = Math.max(this.bits_.length, other.bits_.length); - var arr = []; - for (var i = 0; i < len; i++) { - arr[i] = this.getBits(i) ^ other.getBits(i); - } - return new Integer(arr, this.sign_ ^ other.sign_); -}; - - -/** - * Returns this value with bits shifted to the left by the given amount. - * @param {number} numBits The number of bits by which to shift. - * @return {!Integer} This shifted to the left by the given amount. - */ -Integer.prototype.shiftLeft = function(numBits) { - var arr_delta = numBits >> 5; - var bit_delta = numBits % 32; - var len = this.bits_.length + arr_delta + (bit_delta > 0 ? 1 : 0); - var arr = []; - for (var i = 0; i < len; i++) { - if (bit_delta > 0) { - arr[i] = (this.getBits(i - arr_delta) << bit_delta) | - (this.getBits(i - arr_delta - 1) >>> (32 - bit_delta)); - } else { - arr[i] = this.getBits(i - arr_delta); - } - } - return new Integer(arr, this.sign_); -}; - - -/** - * Returns this value with bits shifted to the right by the given amount. - * @param {number} numBits The number of bits by which to shift. - * @return {!Integer} This shifted to the right by the given amount. - */ -Integer.prototype.shiftRight = function(numBits) { - var arr_delta = numBits >> 5; - var bit_delta = numBits % 32; - var len = this.bits_.length - arr_delta; - var arr = []; - for (var i = 0; i < len; i++) { - if (bit_delta > 0) { - arr[i] = (this.getBits(i + arr_delta) >>> bit_delta) | - (this.getBits(i + arr_delta + 1) << (32 - bit_delta)); - } else { - arr[i] = this.getBits(i + arr_delta); - } - } - return new Integer(arr, this.sign_); -}; - -/** - * Provide the name of the constructor and the string representation - * @returns {string} - */ -Integer.prototype.inspect = function () { - return this.constructor.name + ': ' + this.toString(); -}; - -/** - * Returns a Integer whose value is the absolute value of this - * @returns {Integer} - */ -Integer.prototype.abs = function () { - return this.sign_ === 0 ? this : this.negate(); -}; - -/** - * Returns the string representation. - * Method used by the native JSON.stringify() to serialize this instance. - */ -Integer.prototype.toJSON = function () { - return this.toString(); -}; - -module.exports = Integer; diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/types/local-date.js b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/types/local-date.js deleted file mode 100644 index 9651d7355e..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/types/local-date.js +++ /dev/null @@ -1,252 +0,0 @@ -/* - * Copyright DataStax, Inc. - * - * 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 util = require('util'); - -const utils = require('../utils'); -/** @module types */ - -/** - * @private - * @const - */ -const millisecondsPerDay = 86400000; -/** - * @private - */ -const dateCenter = Math.pow(2,31); -/** - * - * Creates a new instance of LocalDate. - * @class - * @classdesc A date without a time-zone in the ISO-8601 calendar system, such as 2010-08-05. - *

- * LocalDate is an immutable object that represents a date, often viewed as year-month-day. For example, the value "1st October 2014" can be stored in a LocalDate. - *

- *

- * This class does not store or represent a time or time-zone. Instead, it is a description of the date, as used for birthdays. It cannot represent an instant on the time-line without additional information such as an offset or time-zone. - *

- *

- * Note that this type can represent dates in the range [-5877641-06-23; 5881580-07-17] while the ES5 date type can only represent values in the range of [-271821-04-20; 275760-09-13]. - * In the event that year, month, day parameters do not fall within the ES5 date range an Error will be thrown. If you wish to represent a date outside of this range, pass a single - * parameter indicating the days since epoch. For example, -1 represents 1969-12-31. - *

- * @param {Number} year The year or days since epoch. If days since epoch, month and day should not be provided. - * @param {Number} month Between 1 and 12 inclusive. - * @param {Number} day Between 1 and the number of days in the given month of the given year. - * - * @property {Date} date The date representation if falls within a range of an ES5 data type, otherwise an invalid date. - * - * @constructor - */ -function LocalDate(year, month, day) { - //implementation detail: internally uses a UTC based date - if (typeof year === 'number' && typeof month === 'number' && typeof day === 'number') { - // Use setUTCFullYear as if there is a 2 digit year, Date.UTC() assumes - // that is the 20th century. - this.date = new Date(); - this.date.setUTCHours(0, 0, 0, 0); - this.date.setUTCFullYear(year, month-1, day); - if(isNaN(this.date.getTime())) { - throw new Error(util.format('%d-%d-%d does not form a valid ES5 date!', - year, month, day)); - } - } - else if (typeof month === 'undefined' && typeof day === 'undefined') { - if (typeof year === 'number') { - //in days since epoch. - if(year < -2147483648 || year > 2147483647) { - throw new Error('You must provide a valid value for days since epoch (-2147483648 <= value <= 2147483647).'); - } - this.date = new Date(year * millisecondsPerDay); - } - } - - if (typeof this.date === 'undefined') { - throw new Error('You must provide a valid year, month and day'); - } - - /** - * If date cannot be represented yet given a valid days since epoch, track - * it internally. - */ - this._value = isNaN(this.date.getTime()) ? year : null; - - /** - * A number representing the year. May return NaN if cannot be represented as - * a Date. - * @type Number - */ - this.year = this.date.getUTCFullYear(); - /** - * A number between 1 and 12 inclusive representing the month. May return - * NaN if cannot be represented as a Date. - * @type Number - */ - this.month = this.date.getUTCMonth() + 1; - /** - * A number between 1 and the number of days in the given month of the given year (28, 29, 30, 31). - * May return NaN if cannot be represented as a Date. - * @type Number - */ - this.day = this.date.getUTCDate(); -} - -/** - * Creates a new instance of LocalDate using the current year, month and day from the system clock in the default time-zone. - */ -LocalDate.now = function () { - return LocalDate.fromDate(new Date()); -}; - -/** - * Creates a new instance of LocalDate using the current date from the system clock at UTC. - */ -LocalDate.utcNow = function () { - return new LocalDate(Date.now()); -}; - - -/** - * Creates a new instance of LocalDate using the year, month and day from the provided local date time. - * @param {Date} date - */ -LocalDate.fromDate = function (date) { - if (isNaN(date.getTime())) { - throw new TypeError('Invalid date: ' + date); - } - return new LocalDate(date.getFullYear(), date.getMonth() + 1, date.getDate()); -}; - -/** - * Creates a new instance of LocalDate using the year, month and day provided in the form: yyyy-mm-dd or - * days since epoch (i.e. -1 for Dec 31, 1969). - * @param {String} value - */ -LocalDate.fromString = function (value) { - const dashCount = (value.match(/-/g) || []).length; - if(dashCount >= 2) { - let multiplier = 1; - if (value[0] === '-') { - value = value.substring(1); - multiplier = -1; - } - const parts = value.split('-'); - return new LocalDate(multiplier * parseInt(parts[0], 10), parseInt(parts[1], 10), parseInt(parts[2], 10)); - } - if(value.match(/^-?\d+$/)) { - // Parse as days since epoch. - return new LocalDate(parseInt(value, 10)); - } - throw new Error("Invalid input '" + value + "'."); -}; - -/** - * Creates a new instance of LocalDate using the bytes representation. - * @param {Buffer} buffer - */ -LocalDate.fromBuffer = function (buffer) { - //move to unix epoch: 0. - return new LocalDate((buffer.readUInt32BE(0) - dateCenter)); -}; - -/** - * Compares this LocalDate with the given one. - * @param {LocalDate} other date to compare against. - * @return {number} 0 if they are the same, 1 if the this is greater, and -1 - * if the given one is greater. - */ -LocalDate.prototype.compare = function (other) { - const thisValue = isNaN(this.date.getTime()) ? this._value * millisecondsPerDay : this.date.getTime(); - const otherValue = isNaN(other.date.getTime()) ? other._value * millisecondsPerDay : other.date.getTime(); - const diff = thisValue - otherValue; - if (diff < 0) { - return -1; - } - if (diff > 0) { - return 1; - } - return 0; -}; - -/** - * Returns true if the value of the LocalDate instance and other are the same - * @param {LocalDate} other - * @returns {Boolean} - */ -LocalDate.prototype.equals = function (other) { - return ((other instanceof LocalDate)) && this.compare(other) === 0; -}; - -LocalDate.prototype.inspect = function () { - return this.constructor.name + ': ' + this.toString(); -}; - -/** - * Gets the bytes representation of the instance. - * @returns {Buffer} - */ -LocalDate.prototype.toBuffer = function () { - //days since unix epoch - const daysSinceEpoch = isNaN(this.date.getTime()) ? this._value : Math.floor(this.date.getTime() / millisecondsPerDay); - const value = daysSinceEpoch + dateCenter; - const buf = utils.allocBufferUnsafe(4); - buf.writeUInt32BE(value, 0); - return buf; -}; - -/** - * Gets the string representation of the instance in the form: yyyy-mm-dd if - * the value can be parsed as a Date, otherwise days since epoch. - * @returns {String} - */ -LocalDate.prototype.toString = function () { - let result; - //if cannot be parsed as date, return days since epoch representation. - if (isNaN(this.date.getTime())) { - return this._value.toString(); - } - if (this.year < 0) { - result = '-' + fillZeros((this.year * -1).toString(), 4); - } - else { - result = fillZeros(this.year.toString(), 4); - } - result += '-' + fillZeros(this.month.toString(), 2) + '-' + fillZeros(this.day.toString(), 2); - return result; -}; - -/** - * Gets the string representation of the instance in the form: yyyy-mm-dd, valid for JSON. - * @returns {String} - */ -LocalDate.prototype.toJSON = function () { - return this.toString(); -}; - -/** - * @param {String} value - * @param {Number} amount - * @private - */ -function fillZeros(value, amount) { - if (value.length >= amount) { - return value; - } - return utils.stringRepeat('0', amount - value.length) + value; -} - -module.exports = LocalDate; \ No newline at end of file diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/types/local-time.js b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/types/local-time.js deleted file mode 100644 index 2b726cf236..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/types/local-time.js +++ /dev/null @@ -1,295 +0,0 @@ -/* - * Copyright DataStax, Inc. - * - * 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 Long = require('long'); -const util = require('util'); -const utils = require('../utils'); -/** @module types */ - -/** - * @const - * @private - * */ -const maxNanos = Long.fromString('86399999999999'); -/** - * Nanoseconds in a second - * @const - * @private - * */ -const nanoSecInSec = Long.fromNumber(1000000000); -/** - * Nanoseconds in a millisecond - * @const - * @private - * */ -const nanoSecInMillis = Long.fromNumber(1000000); -/** - * Milliseconds in day - * @const - * @private - * */ -const millisInDay = 86400000; -/** - * - * Creates a new instance of LocalTime. - * @class - * @classdesc A time without a time-zone in the ISO-8601 calendar system, such as 10:30:05. - *

- * LocalTime is an immutable date-time object that represents a time, often viewed as hour-minute-second. Time is represented to nanosecond precision. For example, the value "13:45.30.123456789" can be stored in a LocalTime. - *

- * @param {Long} totalNanoseconds Total nanoseconds since midnight. - * @constructor - */ -function LocalTime(totalNanoseconds) { - if (!(totalNanoseconds instanceof Long)) { - throw new Error('You must specify a Long value as totalNanoseconds'); - } - if (totalNanoseconds.lessThan(Long.ZERO) || totalNanoseconds.greaterThan(maxNanos)) { - throw new Error('Total nanoseconds out of range'); - } - this.value = totalNanoseconds; - - /** - * Gets the hour component of the time represented by the current instance, a number from 0 to 23. - * @type Number - */ - this.hour = this._getParts()[0]; - /** - * Gets the minute component of the time represented by the current instance, a number from 0 to 59. - * @type Number - */ - this.minute = this._getParts()[1]; - /** - * Gets the second component of the time represented by the current instance, a number from 0 to 59. - * @type Number - */ - this.second = this._getParts()[2]; - /** - * Gets the nanoseconds component of the time represented by the current instance, a number from 0 to 999999999. - * @type Number - */ - this.nanosecond = this._getParts()[3]; -} - -/** - * Parses an string representation and returns a new LocalDate. - * @param {String} value - * @returns {LocalTime} - */ -LocalTime.fromString = function (value) { - if (typeof value !== 'string') { - throw new Error('Argument type invalid: ' + util.inspect(value)); - } - const parts = value.split(':'); - let millis = parseInt(parts[0], 10) * 3600000 + parseInt(parts[1], 10) * 60000; - let nanos; - if (parts.length === 3) { - const secParts = parts[2].split('.'); - millis += parseInt(secParts[0], 10) * 1000; - if (secParts.length === 2) { - nanos = secParts[1]; - //add zeros at the end - nanos = nanos + utils.stringRepeat('0', 9 - nanos.length); - } - } - return LocalTime.fromMilliseconds(millis, parseInt(nanos, 10) || 0); -}; - -/** - * Uses the current local time (in milliseconds) and the nanoseconds to create a new instance of LocalTime - * @param {Number} [nanoseconds] A Number from 0 to 999,999, representing the time nanosecond portion. - * @returns {LocalTime} - */ -LocalTime.now = function (nanoseconds) { - return LocalTime.fromDate(new Date(), nanoseconds); -}; - -/** - * Uses the provided local time (in milliseconds) and the nanoseconds to create a new instance of LocalTime - * @param {Date} date Local date portion to extract the time passed since midnight. - * @param {Number} [nanoseconds] A Number from 0 to 999,999, representing the nanosecond time portion. - * @returns {LocalTime} - */ -LocalTime.fromDate = function (date, nanoseconds) { - if (!util.isDate(date)) { - throw new Error('Not a valid date'); - } - //Use the local representation, only the milliseconds portion - const millis = (date.getTime() + date.getTimezoneOffset() * -60000) % millisInDay; - return LocalTime.fromMilliseconds(millis, nanoseconds); -}; - -/** - * Uses the provided local time (in milliseconds) and the nanoseconds to create a new instance of LocalTime - * @param {Number} milliseconds A Number from 0 to 86,399,999. - * @param {Number} [nanoseconds] A Number from 0 to 999,999, representing the time nanosecond portion. - * @returns {LocalTime} - */ -LocalTime.fromMilliseconds = function (milliseconds, nanoseconds) { - if (typeof nanoseconds !== 'number') { - nanoseconds = 0; - } - return new LocalTime(Long - .fromNumber(milliseconds) - .multiply(nanoSecInMillis) - .add(Long.fromNumber(nanoseconds))); -}; - -/** - * Creates a new instance of LocalTime from the bytes representation. - * @param {Buffer} value - * @returns {LocalTime} - */ -LocalTime.fromBuffer = function (value) { - if (!(value instanceof Buffer)) { - throw new TypeError('Expected Buffer, obtained ' + util.inspect(value)); - } - return new LocalTime(new Long(value.readInt32BE(4), value.readInt32BE(0))); -}; - -/** - * Compares this LocalTime with the given one. - * @param {LocalTime} other time to compare against. - * @return {number} 0 if they are the same, 1 if the this is greater, and -1 - * if the given one is greater. - */ -LocalTime.prototype.compare = function (other) { - return this.value.compare(other.value); -}; - -/** - * Returns true if the value of the LocalTime instance and other are the same - * @param {LocalTime} other - * @returns {Boolean} - */ -LocalTime.prototype.equals = function (other) { - return ((other instanceof LocalTime)) && this.compare(other) === 0; -}; - -/** - * Gets the total amount of nanoseconds since midnight for this instance. - * @returns {Long} - */ -LocalTime.prototype.getTotalNanoseconds = function () { - return this.value; -}; - -LocalTime.prototype.inspect = function () { - return this.constructor.name + ': ' + this.toString(); -}; - -/** - * Returns a big-endian bytes representation of the instance - * @returns {Buffer} - */ -LocalTime.prototype.toBuffer = function () { - const buffer = utils.allocBufferUnsafe(8); - buffer.writeUInt32BE(this.value.getHighBitsUnsigned(), 0); - buffer.writeUInt32BE(this.value.getLowBitsUnsigned(), 4); - return buffer; -}; - -/** - * Returns the string representation of the instance in the form of hh:MM:ss.ns - * @returns {String} - */ -LocalTime.prototype.toString = function () { - return formatTime(this._getParts()); -}; - -/** - * Gets the string representation of the instance in the form: hh:MM:ss.ns - * @returns {String} - */ -LocalTime.prototype.toJSON = function () { - return this.toString(); -}; - -/** - * @returns {Array.} - * @ignore - */ -LocalTime.prototype._getParts = function () { - if (!this._partsCache) { - //hours, minutes, seconds and nanos - const parts = [0, 0, 0, 0]; - const secs = this.value.div(nanoSecInSec); - //faster modulo - //total nanos - parts[3] = this.value.subtract(secs.multiply(nanoSecInSec)).toNumber(); - //seconds - parts[2] = secs.toNumber(); - if (parts[2] >= 60) { - //minutes - parts[1] = Math.floor(parts[2] / 60); - parts[2] = parts[2] % 60; - } - if (parts[1] >= 60) { - //hours - parts[0] = Math.floor(parts[1] / 60); - parts[1] = parts[1] % 60; - } - this._partsCache = parts; - } - return this._partsCache; -}; - -/** - * @param {Array.} values - * @private - */ -function formatTime(values) { - let result; - if (values[0] < 10) { - result = '0' + values[0] + ':'; - } - else { - result = values[0] + ':'; - } - if (values[1] < 10) { - result += '0' + values[1] + ':'; - } - else { - result += values[1] + ':'; - } - if (values[2] < 10) { - result += '0' + values[2]; - } - else { - result += values[2]; - } - if (values[3] > 0) { - let nanos = values[3].toString(); - //nine digits - if (nanos.length < 9) { - nanos = utils.stringRepeat('0', 9 - nanos.length) + nanos; - } - let lastPosition; - for (let i = nanos.length - 1; i > 0; i--) { - if (nanos[i] !== '0') { - break; - } - lastPosition = i; - } - if (lastPosition) { - nanos = nanos.substring(0, lastPosition); - } - result += '.' + nanos; - } - return result; -} - -module.exports = LocalTime; \ No newline at end of file diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/types/mutable-long.js b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/types/mutable-long.js deleted file mode 100644 index 43992d50b0..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/types/mutable-long.js +++ /dev/null @@ -1,329 +0,0 @@ -/* - * Copyright DataStax, Inc. - * - * 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 Long = require('long'); - -const TWO_PWR_16_DBL = 1 << 16; -const TWO_PWR_32_DBL = TWO_PWR_16_DBL * TWO_PWR_16_DBL; - -/** - * Constructs a signed int64 representation. - * @ignore - */ -class MutableLong { - constructor(b00, b16, b32, b48) { - // Use an array of uint16 - this._arr = [b00 & 0xffff, b16 & 0xffff, b32 & 0xffff, b48 & 0xffff]; - } - - toString() { - return this.toImmutable().toString(); - } - - /** - * Compares this value with the provided value. - * @param {MutableLong} other - * @return {number} - */ - compare(other) { - const thisNeg = this.isNegative(); - const otherNeg = other.isNegative(); - if (thisNeg && !otherNeg) { - return -1; - } - if (!thisNeg && otherNeg) { - return 1; - } - // At this point the sign bits are the same - return this._compareBits(other); - } - - _compareBits(other) { - for (let i = 3; i >= 0; i--) { - if (this._arr[i] > other._arr[i]) { - return 1; - } - if (this._arr[i] < other._arr[i]) { - return -1; - } - } - return 0; - } - - getUint16(index) { - return this._arr[index]; - } - - getLowBitsUnsigned() { - return (this._arr[0] | ((this._arr[1] & 0xffff) << 16)) >>> 0; - } - - getHighBitsUnsigned() { - return (this._arr[2] | (this._arr[3] << 16)) >>> 0; - } - - toNumber() { - return (this._arr[3] << 16 | this._arr[2]) * TWO_PWR_32_DBL + ((this._arr[1] << 16 | this._arr[0]) >>> 0); - } - - /** - * Performs the bitwise NOT of this value. - * @return {MutableLong} - */ - not() { - this._arr[0] = ~this._arr[0] & 0xffff; - this._arr[1] = ~this._arr[1] & 0xffff; - this._arr[2] = ~this._arr[2] & 0xffff; - this._arr[3] = ~this._arr[3] & 0xffff; - return this; - } - - add(addend) { - let c48 = 0, c32 = 0, c16 = 0, c00 = 0; - c00 += this._arr[0] + addend._arr[0]; - this._arr[0] = c00 & 0xffff; - c16 += c00 >>> 16; - c16 += this._arr[1] + addend._arr[1]; - this._arr[1] = c16 & 0xffff; - c32 += c16 >>> 16; - c32 += this._arr[2] + addend._arr[2]; - this._arr[2] = c32 & 0xffff; - c48 += c32 >>> 16; - c48 += this._arr[3] + addend._arr[3]; - this._arr[3] = c48 & 0xffff; - return this; - } - - shiftLeft(numBits) { - if (numBits === 0) { - return this; - } - if (numBits >= 64) { - return this.toZero(); - } - const remainingBits = numBits % 16; - const pos = Math.floor(numBits / 16); - if (pos > 0) { - this._arr[3] = this._arr[3 - pos]; - this._arr[2] = pos > 2 ? 0 : this._arr[2 - pos]; - this._arr[1] = pos > 1 ? 0 : this._arr[0]; - this._arr[0] = 0; - } - if (remainingBits > 0) { - // shift left within the int16 and the next one - this._arr[3] = ((this._arr[3] << remainingBits) | (this._arr[2] >>> (16 - remainingBits))) & 0xffff; - this._arr[2] = ((this._arr[2] << remainingBits) | (this._arr[1] >>> (16 - remainingBits))) & 0xffff; - this._arr[1] = ((this._arr[1] << remainingBits) | (this._arr[0] >>> (16 - remainingBits))) & 0xffff; - this._arr[0] = (this._arr[0] << remainingBits) & 0xffff; - } - return this; - } - - shiftRightUnsigned(numBits) { - if (numBits === 0) { - return this; - } - if (numBits >= 64) { - return this.toZero(); - } - const remainingBits = numBits % 16; - const pos = Math.floor(numBits / 16); - if (pos > 0) { - this._arr[0] = this._arr[pos]; - this._arr[1] = pos > 2 ? 0 : this._arr[1 + pos]; - this._arr[2] = pos > 1 ? 0 : this._arr[3]; - this._arr[3] = 0; - } - if (remainingBits > 0) { - this._arr[0] = (this._arr[0] >>> remainingBits) | ((this._arr[1] << (16 - remainingBits)) & 0xffff); - this._arr[1] = (this._arr[1] >>> remainingBits) | ((this._arr[2] << (16 - remainingBits)) & 0xffff); - this._arr[2] = (this._arr[2] >>> remainingBits) | ((this._arr[3] << (16 - remainingBits)) & 0xffff); - this._arr[3] = this._arr[3] >>> remainingBits; - } - return this; - } - - or(other) { - this._arr[0] |= other._arr[0]; - this._arr[1] |= other._arr[1]; - this._arr[2] |= other._arr[2]; - this._arr[3] |= other._arr[3]; - return this; - } - - /** - * Returns the bitwise XOR of this Long and the given one. - * @param {MutableLong} other - * @returns {MutableLong} this instance. - */ - xor(other) { - this._arr[0] ^= other._arr[0]; - this._arr[1] ^= other._arr[1]; - this._arr[2] ^= other._arr[2]; - this._arr[3] ^= other._arr[3]; - return this; - } - - clone() { - return new MutableLong(this._arr[0], this._arr[1], this._arr[2], this._arr[3]); - } - - /** - * Performs the product of this and the specified Long. - * @param {MutableLong} multiplier - * @returns {MutableLong} this instance. - */ - multiply(multiplier) { - let negate = false; - if (this.isZero() || multiplier.isZero()) { - return this.toZero(); - } - if (this.isNegative()) { - this.negate(); - negate = !negate; - } - if (multiplier.isNegative()) { - multiplier = multiplier.clone().negate(); - negate = !negate; - } - // We can skip products that would overflow. - let c48 = 0, c32 = 0, c16 = 0, c00 = 0; - c00 += this._arr[0] * multiplier._arr[0]; - c16 += c00 >>> 16; - c16 += this._arr[1] * multiplier._arr[0]; - c32 += c16 >>> 16; - c16 &= 0xFFFF; - c16 += this._arr[0] * multiplier._arr[1]; - c32 += c16 >>> 16; - c32 += this._arr[2] * multiplier._arr[0]; - c48 += c32 >>> 16; - c32 &= 0xFFFF; - c32 += this._arr[1] * multiplier._arr[1]; - c48 += c32 >>> 16; - c32 &= 0xFFFF; - c32 += this._arr[0] * multiplier._arr[2]; - c48 += c32 >>> 16; - c48 += this._arr[3] * multiplier._arr[0] + this._arr[2] * multiplier._arr[1] + - this._arr[1] * multiplier._arr[2] + this._arr[0] * multiplier._arr[3]; - this._arr[0] = c00 & 0xffff; - this._arr[1] = c16 & 0xffff; - this._arr[2] = c32 & 0xffff; - this._arr[3] = c48 & 0xffff; - if (negate) { - this.negate(); - } - return this; - } - - toZero() { - this._arr[3] = this._arr[2] = this._arr[1] = this._arr[0] = 0; - return this; - } - - isZero() { - return (this._arr[3] === 0 && this._arr[2] === 0 && this._arr[1] === 0 && this._arr[0] === 0); - } - - isNegative() { - // most significant bit turned on - return (this._arr[3] & 0x8000) > 0; - } - - /** - * Negates this value. - * @return {MutableLong} - */ - negate() { - return this.not().add(MutableLong.one); - } - - equals(other) { - if (!(other instanceof MutableLong)) { - return false; - } - return (this._arr[0] === other._arr[0] && this._arr[1] === other._arr[1] && - this._arr[2] === other._arr[2] && this._arr[3] === other._arr[3]); - } - - toImmutable() { - return Long.fromBits(this.getLowBitsUnsigned(), this.getHighBitsUnsigned(), false); - } - - static fromNumber(value) { - if (isNaN(value) || !isFinite(value)) { - return new MutableLong(); - } - if (value < 0) { - return MutableLong.fromNumber(-value).negate(); - } - const low32Bits = value % TWO_PWR_32_DBL; - const high32Bits = value / TWO_PWR_32_DBL; - return MutableLong.fromBits(low32Bits, high32Bits); - } - - static fromBits(low32Bits, high32Bits) { - return new MutableLong(low32Bits, low32Bits >>> 16, high32Bits, high32Bits >>> 16); - } - - /** - * Returns a Long representation of the given string, written using the specified radix. - * @param {String} str - * @param {Number} [radix] - * @return {MutableLong} - */ - static fromString(str, radix) { - if (typeof str !== 'string') { - throw new Error('String format is not valid: ' + str); - } - if (str.length === 0) { - throw Error('number format error: empty string'); - } - if (str === "NaN" || str === "Infinity" || str === "+Infinity" || str === "-Infinity") { - return new MutableLong(); - } - radix = radix || 10; - if (radix < 2 || radix > 36) { - throw Error('radix out of range: ' + radix); - } - let p; - if ((p = str.indexOf('-')) > 0) { - throw Error('number format error: interior "-" character: ' + str); - } - if (p === 0) { - return MutableLong.fromString(str.substring(1), radix).negate(); - } - // Do several (8) digits each time through the loop - const radixToPower = MutableLong.fromNumber(Math.pow(radix, 8)); - const result = new MutableLong(); - for (let i = 0; i < str.length; i += 8) { - const size = Math.min(8, str.length - i); - const value = parseInt(str.substring(i, i + size), radix); - if (size < 8) { - const power = MutableLong.fromNumber(Math.pow(radix, size)); - result.multiply(power).add(MutableLong.fromNumber(value)); - break; - } - result.multiply(radixToPower); - result.add(MutableLong.fromNumber(value)); - } - return result; - } -} - -MutableLong.one = new MutableLong(1, 0, 0, 0); - -module.exports = MutableLong; \ No newline at end of file diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/types/protocol-version.js b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/types/protocol-version.js deleted file mode 100644 index fc558e4da1..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/types/protocol-version.js +++ /dev/null @@ -1,337 +0,0 @@ -/* - * Copyright DataStax, Inc. - * - * 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 utils = require('../utils'); -const VersionNumber = require('./version-number'); -const v200 = VersionNumber.parse('2.0.0'); -const v210 = VersionNumber.parse('2.1.0'); -const v220 = VersionNumber.parse('2.2.0'); -const v300 = VersionNumber.parse('3.0.0'); -const v510 = VersionNumber.parse('5.1.0'); -const v600 = VersionNumber.parse('6.0.0'); - -/** - * Contains information for the different protocol versions supported by the driver. - * @type {Object} - * @property {Number} v1 Cassandra protocol v1, supported in Apache Cassandra 1.2-->2.2. - * @property {Number} v2 Cassandra protocol v2, supported in Apache Cassandra 2.0-->2.2. - * @property {Number} v3 Cassandra protocol v3, supported in Apache Cassandra 2.1-->3.x. - * @property {Number} v4 Cassandra protocol v4, supported in Apache Cassandra 2.2-->3.x. - * @property {Number} v5 Cassandra protocol v5, in beta from Apache Cassandra 3.x+. Currently not supported by the - * driver. - * @property {Number} dseV1 DataStax Enterprise protocol v1, DSE 5.1+ - * @property {Number} dseV2 DataStax Enterprise protocol v2, DSE 6.0+ - * @property {Number} maxSupported Returns the higher protocol version that is supported by this driver. - * @property {Number} minSupported Returns the lower protocol version that is supported by this driver. - * @property {Function} isSupported A function that returns a boolean determining whether a given protocol version - * is supported. - * @alias module:types~protocolVersion - */ -const protocolVersion = { - // Strict equality operators to compare versions are allowed, other comparison operators are discouraged. Instead, - // use a function that checks if a functionality is present on a certain version, for maintainability purposes. - v1: 0x01, - v2: 0x02, - v3: 0x03, - v4: 0x04, - v5: 0x05, - dseV1: 0x41, - dseV2: 0x42, - maxSupported: 0x42, - minSupported: 0x01, - - /** - * Determines whether the protocol version is a DSE-specific protocol version. - * @param {Number} version - * @returns {Boolean} - * @ignore - */ - isDse: function(version) { - return ((version >= this.dseV1 && version <= this.dseV2)); - }, - /** - * Determines whether the protocol protocol version is supported by this driver. - * @param {Number} version - * @returns {Boolean} - * @ignore - */ - isSupported: function (version) { - return (this.isDse(version) || (version <= 0x04 && version >= 0x01)); - }, - /** - * Determines whether the protocol includes flags for PREPARE messages. - * @param {Number} version - * @returns {Boolean} - * @ignore - */ - supportsPrepareFlags: function (version) { - return (version === this.dseV2); - }, - /** - * Determines whether the protocol supports sending the keyspace as part of PREPARE, QUERY, EXECUTE, and BATCH. - * @param {Number} version - * @returns {Boolean} - * @ignore - */ - supportsKeyspaceInRequest: function (version) { - return (version === this.dseV2); - }, - /** - * Determines whether the protocol supports result_metadata_id on `prepared` response and - * and `execute` request. - * @param {Number} version - * @returns {Boolean} - * @ignore - */ - supportsResultMetadataId: function (version) { - return (version === this.dseV2); - }, - /** - * Determines whether the protocol supports partition key indexes in the `prepared` RESULT responses. - * @param {Number} version - * @returns {Boolean} - * @ignore - */ - supportsPreparedPartitionKey: function (version) { - return (version >= this.v4); - }, - /** - * Determines whether the protocol supports up to 4 strings (ie: change_type, target, keyspace and table) in the - * schema change responses. - * @param version - * @return {boolean} - * @ignore - */ - supportsSchemaChangeFullMetadata: function (version) { - return (version >= this.v3); - }, - /** - * Determines whether the protocol supports continuous paging. - * @param version - * @return {boolean} - * @ignore - */ - supportsContinuousPaging: function (version) { - return (this.isDse(version)); - }, - /** - * Determines whether the protocol supports paging state and serial consistency parameters in QUERY and EXECUTE - * requests. - * @param version - * @return {boolean} - * @ignore - */ - supportsPaging: function (version) { - return (version >= this.v2); - }, - /** - * Determines whether the protocol supports timestamps parameters in BATCH, QUERY and EXECUTE requests. - * @param {Number} version - * @return {boolean} - * @ignore - */ - supportsTimestamp: function (version) { - return (version >= this.v3); - }, - /** - * Determines whether the protocol supports named parameters in QUERY and EXECUTE requests. - * @param {Number} version - * @return {boolean} - * @ignore - */ - supportsNamedParameters: function (version) { - return (version >= this.v3); - }, - /** - * Determines whether the protocol supports unset parameters. - * @param {Number} version - * @return {boolean} - * @ignore - */ - supportsUnset: function (version) { - return (version >= this.v4); - }, - /** - * Determines whether the protocol provides a reason map for read and write failure errors. - * @param version - * @return {boolean} - * @ignore - */ - supportsFailureReasonMap: function (version) { - return (version >= this.v5); - }, - /** - * Determines whether the protocol supports timestamp and serial consistency parameters in BATCH requests. - * @param {Number} version - * @return {boolean} - * @ignore - */ - uses2BytesStreamIds: function (version) { - return (version >= this.v3); - }, - /** - * Determines whether the collection length is encoded using 32 bits. - * @param {Number} version - * @return {boolean} - * @ignore - */ - uses4BytesCollectionLength: function (version) { - return (version >= this.v3); - }, - /** - * Determines whether the QUERY, EXECUTE and BATCH flags are encoded using 32 bits. - * @param {Number} version - * @return {boolean} - * @ignore - */ - uses4BytesQueryFlags: function (version) { - return (this.isDse(version)); - }, - /** - * Startup responses using protocol v4+ can be a SERVER_ERROR wrapping a ProtocolException, this method returns true - * when is possible to receive such error. - * @param {Number} version - * @return {boolean} - * @ignore - */ - canStartupResponseErrorBeWrapped: function (version) { - return (version >= this.v4); - }, - /** - * Gets the first version number that is supported, lower than the one provided. - * Returns zero when there isn't a lower supported version. - * @param {Number} version - * @return {Number} - * @ignore - */ - getLowerSupported: function (version) { - if (version >= this.v5) { - return this.v4; - } - if (version <= this.v1) { - return 0; - } - return version - 1; - }, - - /** - * Computes the highest supported protocol version collectively by the given hosts. - * - * Considers the cassandra_version of the input hosts to determine what protocol versions - * are supported and uses the highest common protocol version among them. - * - * If hosts >= C* 3.0 are detected, any hosts older than C* 2.1 will not be considered - * as those cannot be connected to. In general this will not be a problem as C* does - * not support clusters with nodes that have versions that are more than one major - * version away from each other. - * @param {Connection} connection Connection hosts were discovered from. - * @param {Array.} hosts The hosts to determine highest protocol version from. - * @return {Number} Highest supported protocol version among hosts. - */ - getHighestCommon: function(connection, hosts) { - const log = connection.log ? connection.log.bind(connection) : utils.noop; - let maxVersion = connection.protocolVersion; - // whether or not protocol v3 is required (nodes detected that don't support < 3). - let v3Requirement = false; - // track the common protocol version >= v3 in case we encounter older versions. - let maxVersionWith3OrMore = maxVersion; - hosts.forEach(h => { - let dseVersion = null; - if (h.dseVersion) { - // As of DSE 5.1, DSE has it's own specific protocol versions. If we detect 5.1+ - // consider those protocol versions. - dseVersion = VersionNumber.parse(h.dseVersion); - log('verbose', `Encountered host ${h.address} with dse version ${dseVersion}`); - if (dseVersion.compare(v510) >= 0) { - v3Requirement = true; - if (dseVersion.compare(v600) >= 0) { - maxVersion = Math.min(this.dseV2, maxVersion); - } else { - maxVersion = Math.min(this.dseV1, maxVersion); - } - maxVersionWith3OrMore = maxVersion; - return; - } - // If DSE < 5.1, we fall back on the cassandra protocol logic. - } - - if (!h.cassandraVersion || h.cassandraVersion.length === 0) { - log('warning', 'Encountered host ' + h.address + ' with no cassandra version,' + - ' skipping as part of protocol version evaluation'); - return; - } - - try { - const cassandraVersion = VersionNumber.parse(h.cassandraVersion); - if (!dseVersion) { - log('verbose', 'Encountered host ' + h.address + ' with cassandra version ' + cassandraVersion); - } - if (cassandraVersion.compare(v300) >= 0) { - // Anything 3.0.0+ has a max protocol version of V4 and requires at least V3. - v3Requirement = true; - maxVersion = Math.min(this.v4, maxVersion); - maxVersionWith3OrMore = maxVersion; - } else if (cassandraVersion.compare(v220) >= 0) { - // Cassandra 2.2.x has a max protocol version of V4. - maxVersion = Math.min(this.v4, maxVersion); - maxVersionWith3OrMore = maxVersion; - } else if (cassandraVersion.compare(v210) >= 0) { - // Cassandra 2.1.x has a max protocol version of V3. - maxVersion = Math.min(this.v3, maxVersion); - maxVersionWith3OrMore = maxVersion; - } else if (cassandraVersion.compare(v200) >= 0) { - // Cassandra 2.0.x has a max protocol version of V2. - maxVersion = Math.min(this.v2, maxVersion); - } else { - // Anything else is < 2.x and requires protocol version V1. - maxVersion = this.v1; - } - } catch (e) { - log('warning', 'Encountered host ' + h.address + ' with unparseable cassandra version ' + h.cassandraVersion - + ' skipping as part of protocol version evaluation'); - } - }); - - if (v3Requirement && maxVersion < this.v3) { - const addendum = '. This should not be possible as nodes within a cluster can\'t be separated by more than one major version'; - if (maxVersionWith3OrMore < this.v3) { - log('error', 'Detected hosts that require at least protocol version 0x3, but currently connected to ' - + connection.address + ':' + connection.port + ' using protocol version 0x' + maxVersionWith3OrMore - + '. Will not be able to connect to these hosts' + addendum); - } else { - log('error', 'Detected hosts with maximum protocol version of 0x' + maxVersion.toString(16) - + ' but there are some hosts that require at least version 0x3. Will not be able to connect to these older hosts' - + addendum); - } - maxVersion = maxVersionWith3OrMore; - } - - log('verbose', 'Resolved protocol version 0x' + maxVersion.toString(16) + ' as the highest common protocol version among hosts'); - return maxVersion; - }, - - /** - * Determines if the protocol is a BETA version of the protocol. - * @param {Number} version - * @return {Number} - */ - isBeta: function (version) { - return version === this.v5; - } -}; - -module.exports = protocolVersion; \ No newline at end of file diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/types/result-set.js b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/types/result-set.js deleted file mode 100644 index 4137ddb03c..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/types/result-set.js +++ /dev/null @@ -1,275 +0,0 @@ -/* - * Copyright DataStax, Inc. - * - * 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 utils = require('../utils'); -const errors = require('../errors'); - -const asyncIteratorSymbol = Symbol.asyncIterator || '@@asyncIterator'; - -/** @module types */ - -/** - * Creates a new instance of ResultSet. - * @class - * @classdesc Represents the result of a query. - * @param {Object} response - * @param {String} host - * @param {Object} triedHosts - * @param {Number} speculativeExecutions - * @param {Number} consistency - * @param {Boolean} isSchemaInAgreement - * @constructor - */ -function ResultSet(response, host, triedHosts, speculativeExecutions, consistency, isSchemaInAgreement) { - // if no execution was made at all, set to 0. - if (speculativeExecutions === -1) { - speculativeExecutions = 0; - } - /** - * Information on the execution of a successful query: - * @member {Object} - * @property {Number} achievedConsistency The consistency level that has been actually achieved by the query. - * @property {String} queriedHost The Cassandra host that coordinated this query. - * @property {Object} triedHosts Gets the associative array of host that were queried before getting a valid response, - * being the last host the one that replied correctly. - * @property {Object} speculativeExecutions The number of speculative executions (not including the first) executed before - * getting a valid response. - * @property {Uuid} traceId Identifier of the trace session. - * @property {Array.} warnings Warning messages generated by the server when executing the query. - * @property {Boolean} isSchemaInAgreement Whether the cluster had reached schema agreement after the execution of - * this query. - *

- * After a successful schema-altering query (ex: creating a table), the driver will check if - * the cluster's nodes agree on the new schema version. If not, it will keep retrying for a given - * delay (see protocolOptions.maxSchemaAgreementWaitSeconds). - *

- *

- * Note that the schema agreement check is only performed for schema-altering queries For other - * query types, this method will always return true. If this method returns false, - * clients can call [Metadata.checkSchemaAgreement()]{@link module:metadata~Metadata#checkSchemaAgreement} later to - * perform the check manually. - *

- */ - this.info = { - queriedHost: host, - triedHosts: triedHosts, - speculativeExecutions: speculativeExecutions, - achievedConsistency: consistency, - traceId: null, - warnings: null, - customPayload: null, - isSchemaInAgreement - }; - - if (response.flags) { - this.info.traceId = response.flags.traceId; - this.info.warnings = response.flags.warnings; - this.info.customPayload = response.flags.customPayload; - } - - /** - * Gets an array rows returned by the query. - * When the result set represents a response from a write query, this property will be undefined. - * When the read query result contains more rows than the fetch size (5000), this property will only contain the - * first rows up to fetch size. To obtain all the rows, you can use the built-in async iterator that will retrieve the - * following pages of results. - * @type {Array|undefined} - */ - this.rows = response.rows; - - /** - * Gets the row length of the result, regardless if the result has been buffered or not - * @type {Number|undefined} - */ - this.rowLength = this.rows ? this.rows.length : response.rowLength; - - /** - * Gets the columns returned in this ResultSet. - * @type {Array.<{name, type}>} - * @default null - */ - this.columns = null; - - /** - * A string token representing the current page state of query. It can be used in the following executions to - * continue paging and retrieve the remained of the result for the query. - * @type {String|null} - * @default null - */ - this.pageState = null; - - /** - * Method used to manually fetch the next page of results. - * This method is only exposed when using the {@link Client#eachRow} method and there are more rows available in - * following pages. - * @type Function - */ - this.nextPage = undefined; - - /** - * Method used internally to fetch the next page of results using promises. - * @internal - * @ignore - * @type {Function} - */ - this.nextPageAsync = undefined; - - const meta = response.meta; - - if (meta) { - this.columns = meta.columns; - - if (meta.pageState) { - this.pageState = meta.pageState.toString('hex'); - - // Expose rawPageState internally - Object.defineProperty(this, 'rawPageState', { value: meta.pageState, enumerable: false }); - } - } -} - -/** - * Returns the first row or null if the result rows are empty. - */ -ResultSet.prototype.first = function () { - if (this.rows && this.rows.length) { - return this.rows[0]; - } - return null; -}; - -ResultSet.prototype.getPageState = function () { - // backward-compatibility - return this.pageState; -}; - -ResultSet.prototype.getColumns = function () { - // backward-compatibility - return this.columns; -}; - -/** - * When this instance is the result of a conditional update query, it returns whether it was successful. - * Otherwise, it returns true. - *

- * For consistency, this method always returns true for non-conditional queries (although there is - * no reason to call the method in that case). This is also the case for conditional DDL statements - * (CREATE KEYSPACE... IF NOT EXISTS, CREATE TABLE... IF NOT EXISTS), for which the server doesn't return - * information whether it was applied or not. - *

- */ -ResultSet.prototype.wasApplied = function () { - if (!this.rows || this.rows.length === 0) { - return true; - } - const firstRow = this.rows[0]; - const applied = firstRow['[applied]']; - return typeof applied === 'boolean' ? applied : true; -}; - -/** - * Gets the iterator function. - *

- * Retrieves the iterator of the underlying fetched rows, without causing the driver to fetch the following - * result pages. For more information on result paging, - * [visit the documentation]{@link http://docs.datastax.com/en/developer/nodejs-driver/latest/features/paging/}. - *

- * @alias module:types~ResultSet#@@iterator - * @see {@link module:types~ResultSet#@@asyncIterator} - * @example Using for...of statement - * const query = 'SELECT user_id, post_id, content FROM timeline WHERE user_id = ?'; - * const result = await client.execute(query, [ id ], { prepare: true }); - * for (const row of result) { - * console.log(row['email']); - * } - * @returns {Iterator.} - */ -ResultSet.prototype[Symbol.iterator] = function getIterator() { - if (!this.rows) { - return utils.emptyArray[Symbol.iterator](); - } - return this.rows[Symbol.iterator](); -}; - -/** - * Gets the async iterator function. - *

- * Retrieves the async iterator representing the entire query result, the driver will fetch the following result - * pages. - *

- *

Use the async iterator when the query result might contain more rows than the fetchSize.

- *

- * Note that using the async iterator will not affect the internal state of the ResultSet instance. - * You should avoid using both rows property that contains the row instances of the first page of - * results, and the async iterator, that will yield all the rows in the result regardless on the number of pages. - *

- *

Multiple concurrent async iterations are not supported.

- * @alias module:types~ResultSet#@@asyncIterator - * @example Using for await...of statement - * const query = 'SELECT user_id, post_id, content FROM timeline WHERE user_id = ?'; - * const result = await client.execute(query, [ id ], { prepare: true }); - * for await (const row of result) { - * console.log(row['email']); - * } - * @returns {AsyncIterator} - */ -ResultSet.prototype[asyncIteratorSymbol] = function getAsyncGenerator() { - let index = 0; - let pageState = this.rawPageState; - let rows = this.rows; - - if (!rows || rows.length === 0) { - return { next: () => Promise.resolve({ done: true }) }; - } - - const self = this; - - // Async generators are not present in Node.js 8, implement it manually - return { - async next() { - if (index >= rows.length && pageState) { - if (!self.nextPageAsync) { - throw new errors.DriverInternalError('Property nextPageAsync should be set when pageState is defined'); - } - - const rs = await self.nextPageAsync(pageState); - rows = rs.rows; - index = 0; - pageState = rs.rawPageState; - } - - if (index < rows.length) { - return { done: false, value: rows[index++] }; - } - - return { done: true }; - } - }; -}; - -/** - * Determines whether there are more pages of results. - * If so, the driver will initially retrieve and contain only the first page of results. - * To obtain all the rows, use the [AsyncIterator]{@linkcode module:types~ResultSet#@@asyncIterator}. - * @returns {boolean} - */ -ResultSet.prototype.isPaged = function() { - return !!this.rawPageState; -}; - -module.exports = ResultSet; \ No newline at end of file diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/types/result-stream.js b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/types/result-stream.js deleted file mode 100644 index 90cb64c746..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/types/result-stream.js +++ /dev/null @@ -1,148 +0,0 @@ -/* - * Copyright DataStax, Inc. - * - * 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 { Readable } = require('stream'); -const utils = require('../utils'); -const errors = require('../errors'); -const clientOptions = require('../client-options'); - -/** @module types */ -/** - * Readable stream using to yield data from a result or a field - */ -class ResultStream extends Readable { - constructor(opt) { - super(opt); - this.buffer = []; - this.paused = true; - this._cancelAllowed = false; - this._handlersObject = null; - this._highWaterMarkRows = 0; - } - - _read() { - this.paused = false; - if (this.buffer.length === 0) { - this._readableState.reading = false; - } - while (!this.paused && this.buffer.length > 0) { - this.paused = !this.push(this.buffer.shift()); - } - this._checkBelowHighWaterMark(); - if (!this.paused && !this.buffer.length && this._readNext) { - this._readNext(); - this._readNext = null; - } - } - - /** - * Allows for throttling, helping nodejs keep the internal buffers reasonably sized. - * @param {function} readNext function that triggers reading the next result chunk - * @ignore - */ - _valve(readNext) { - this._readNext = null; - if (!readNext) { - return; - } - if (this.paused || this.buffer.length) { - this._readNext = readNext; - } - else { - readNext(); - } - } - - add(chunk) { - const length = this.buffer.push(chunk); - this.read(0); - this._checkAboveHighWaterMark(); - return length; - } - - _checkAboveHighWaterMark() { - if (!this._handlersObject || !this._handlersObject.resumeReadingHandler) { - return; - } - if (this._highWaterMarkRows === 0 || this.buffer.length !== this._highWaterMarkRows) { - return; - } - this._handlersObject.resumeReadingHandler(false); - } - - _checkBelowHighWaterMark() { - if (!this._handlersObject || !this._handlersObject.resumeReadingHandler) { - return; - } - if (this._highWaterMarkRows === 0 || this.buffer.length >= this._highWaterMarkRows) { - return; - } - // The consumer has dequeued below the watermark - this._handlersObject.resumeReadingHandler(true); - } - - /** - * When continuous paging is enabled, allows the client to notify to the server to stop pushing further pages. - *

Note: This is not part of the public API yet.

- * @param {Function} [callback] The cancel method accepts an optional callback. - * @example Cancelling a continuous paging execution - * const stream = client.stream(query, params, { prepare: true, continuousPaging: true }); - * // ... - * // Ask the server to stop pushing rows. - * stream.cancel(); - * @ignore - */ - cancel(callback) { - if (!this._cancelAllowed) { - const err = new Error('You can only cancel streaming executions when continuous paging is enabled'); - if (!callback) { - throw err; - } - return callback(err); - } - if (!this._handlersObject) { - throw new errors.DriverInternalError('ResultStream cancel is allowed but the cancel options were not set'); - } - callback = callback || utils.noop; - if (!this._handlersObject.cancelHandler) { - // The handler is not yet set - // Set the callback as a flag to identify that the cancel handler must be invoked when set - this._handlersObject.cancelHandler = callback; - return; - } - this._handlersObject.cancelHandler(callback); - } - - /** - * Sets the pointer to the handler to be used to cancel the continuous page execution. - * @param options - * @internal - * @ignore - */ - setHandlers(options) { - if (!options.continuousPaging) { - return; - } - this._cancelAllowed = true; - this._handlersObject = options; - this._highWaterMarkRows = - options.continuousPaging.highWaterMarkRows || clientOptions.continuousPageDefaultHighWaterMark; - } -} - -module.exports = ResultStream; \ No newline at end of file diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/types/row.js b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/types/row.js deleted file mode 100644 index fca7132114..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/types/row.js +++ /dev/null @@ -1,80 +0,0 @@ -/* - * Copyright DataStax, Inc. - * - * 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'; -/** @module types */ -/** - * Represents a result row - * @param {Array} columns - * @constructor - */ -function Row(columns) { - if (!columns) { - throw new Error('Columns not defined'); - } - //Private non-enumerable properties, with double underscore to avoid interfering with column names - Object.defineProperty(this, '__columns', { value: columns, enumerable: false, writable: false}); -} - -/** - * Returns the cell value. - * @param {String|Number} columnName Name or index of the column - */ -Row.prototype.get = function (columnName) { - if (typeof columnName === 'number') { - //its an index - return this[this.__columns[columnName].name]; - } - return this[columnName]; -}; - -/** - * Returns an array of the values of the row - * @returns {Array} - */ -Row.prototype.values = function () { - const valuesArray = []; - this.forEach(function (val) { - valuesArray.push(val); - }); - return valuesArray; -}; - -/** - * Returns an array of the column names of the row - * @returns {Array} - */ -Row.prototype.keys = function () { - const keysArray = []; - this.forEach(function (val, key) { - keysArray.push(key); - }); - return keysArray; -}; - -/** - * Executes the callback for each field in the row, containing the value as first parameter followed by the columnName - * @param {Function} callback - */ -Row.prototype.forEach = function (callback) { - for (const columnName in this) { - if (!this.hasOwnProperty(columnName)) { - continue; - } - callback(this[columnName], columnName); - } -}; - -module.exports = Row; \ No newline at end of file diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/types/time-uuid.js b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/types/time-uuid.js deleted file mode 100644 index d4caae67a4..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/types/time-uuid.js +++ /dev/null @@ -1,410 +0,0 @@ -/* - * Copyright DataStax, Inc. - * - * 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 util = require('util'); -const crypto = require('crypto'); -const Long = require('long'); - -const Uuid = require('./uuid'); -const utils = require('../utils'); - -/** @module types */ -/** - * Oct 15, 1582 in milliseconds since unix epoch - * @const - * @private - */ -const _unixToGregorian = 12219292800000; -/** - * 10,000 ticks in a millisecond - * @const - * @private - */ -const _ticksInMs = 10000; - -const minNodeId = utils.allocBufferFromString('808080808080', 'hex'); -const minClockId = utils.allocBufferFromString('8080', 'hex'); -const maxNodeId = utils.allocBufferFromString('7f7f7f7f7f7f', 'hex'); -const maxClockId = utils.allocBufferFromString('7f7f', 'hex'); - -/** - * Counter used to generate up to 10000 different timeuuid values with the same Date - * @private - * @type {number} - */ -let _ticks = 0; -/** - * Counter used to generate ticks for the current time - * @private - * @type {number} - */ -let _ticksForCurrentTime = 0; -/** - * Remember the last time when a ticks for the current time so that it can be reset - * @private - * @type {number} - */ -let _lastTimestamp = 0; - -/** - * Creates a new instance of Uuid based on the parameters provided according to rfc4122. - * If any of the arguments is not provided, it will be randomly generated, except for the date that will use the current - * date. - *

- * Note that when nodeId and/or clockId portions are not provided, the constructor will generate them using - * crypto.randomBytes(). As it's possible that crypto.randomBytes() might block, it's - * recommended that you use the callback-based version of the static methods fromDate() or - * now() in that case. - *

- * @class - * @classdesc Represents an immutable version 1 universally unique identifier (UUID). A UUID represents a 128-bit value. - *

Usage: TimeUuid.now()

- * @extends module:types~Uuid - * @param {Date} [value] The datetime for the instance, if not provided, it will use the current Date. - * @param {Number} [ticks] A number from 0 to 10000 representing the 100-nanoseconds units for this instance to fill in the information not available in the Date, - * as Ecmascript Dates have only milliseconds precision. - * @param {String|Buffer} [nodeId] A 6-length Buffer or string of 6 ascii characters representing the node identifier, ie: 'host01'. - * @param {String|Buffer} [clockId] A 2-length Buffer or string of 6 ascii characters representing the clock identifier. - * @constructor - */ -function TimeUuid(value, ticks, nodeId, clockId) { - let buffer; - if (value instanceof Buffer) { - if (value.length !== 16) { - throw new Error('Buffer for v1 uuid not valid'); - } - buffer = value; - } - else { - buffer = generateBuffer(value, ticks, nodeId, clockId); - } - Uuid.call(this, buffer); -} - -util.inherits(TimeUuid, Uuid); - -/** - * Generates a TimeUuid instance based on the Date provided using random node and clock values. - * @param {Date} date Date to generate the v1 uuid. - * @param {Number} [ticks] A number from 0 to 10000 representing the 100-nanoseconds units for this instance to fill in the information not available in the Date, - * as Ecmascript Dates have only milliseconds precision. - * @param {String|Buffer} [nodeId] A 6-length Buffer or string of 6 ascii characters representing the node identifier, ie: 'host01'. - * If not provided, a random nodeId will be generated. - * @param {String|Buffer} [clockId] A 2-length Buffer or string of 6 ascii characters representing the clock identifier. - * If not provided a random clockId will be generated. - * @param {Function} [callback] An optional callback to be invoked with the error as first parameter and the created - * TimeUuid as second parameter. When a callback is provided, the random portions of the - * TimeUuid instance are created asynchronously. - *

- * When nodeId and/or clockId portions are not provided, this method will generate them using - * crypto.randomBytes(). As it's possible that crypto.randomBytes() might block, it's - * recommended that you use the callback-based version of this method in that case. - *

- * @example Generate a TimeUuid from a ECMAScript Date - * const timeuuid = TimeUuid.fromDate(new Date()); - * @example Generate a TimeUuid from a Date with ticks portion - * const timeuuid = TimeUuid.fromDate(new Date(), 1203); - * @example Generate a TimeUuid from a Date without any random portion - * const timeuuid = TimeUuid.fromDate(new Date(), 1203, 'host01', '02'); - * @example Generate a TimeUuid from a Date with random node and clock identifiers - * TimeUuid.fromDate(new Date(), 1203, function (err, timeuuid) { - * // do something with the generated timeuuid - * }); - */ -TimeUuid.fromDate = function (date, ticks, nodeId, clockId, callback) { - if (typeof ticks === 'function') { - callback = ticks; - ticks = nodeId = clockId = null; - } else if (typeof nodeId === 'function') { - callback = nodeId; - nodeId = clockId = null; - } else if (typeof clockId === 'function') { - callback = clockId; - clockId = null; - } - - if (!callback) { - return new TimeUuid(date, ticks, nodeId, clockId); - } - - utils.parallel([ - next => getOrGenerateRandom(nodeId, 6, (err, buffer) => next(err, nodeId = buffer)), - next => getOrGenerateRandom(clockId, 2, (err, buffer) => next(err, clockId = buffer)), - ], (err) => { - if (err) { - return callback(err); - } - - let timeUuid; - try { - timeUuid = new TimeUuid(date, ticks, nodeId, clockId); - } - catch (e) { - return callback(e); - } - - callback(null, timeUuid); - }); -}; - -/** - * Parses a string representation of a TimeUuid - * @param {String} value - * @returns {TimeUuid} - */ -TimeUuid.fromString = function (value) { - return new TimeUuid(Uuid.fromString(value).getBuffer()); -}; - -/** - * Returns the smaller possible type 1 uuid with the provided Date. - */ -TimeUuid.min = function (date, ticks) { - return new TimeUuid(date, ticks, minNodeId, minClockId); -}; - -/** - * Returns the biggest possible type 1 uuid with the provided Date. - */ -TimeUuid.max = function (date, ticks) { - return new TimeUuid(date, ticks, maxNodeId, maxClockId); -}; - -/** - * Generates a TimeUuid instance based on the current date using random node and clock values. - * @param {String|Buffer} [nodeId] A 6-length Buffer or string of 6 ascii characters representing the node identifier, ie: 'host01'. - * If not provided, a random nodeId will be generated. - * @param {String|Buffer} [clockId] A 2-length Buffer or string of 6 ascii characters representing the clock identifier. - * If not provided a random clockId will be generated. - * @param {Function} [callback] An optional callback to be invoked with the error as first parameter and the created - * TimeUuid as second parameter. When a callback is provided, the random portions of the - * TimeUuid instance are created asynchronously. - *

- * When nodeId and/or clockId portions are not provided, this method will generate them using - * crypto.randomBytes(). As it's possible that crypto.randomBytes() might block, it's - * recommended that you use the callback-based version of this method in that case. - *

- * @example Generate a TimeUuid from a Date without any random portion - * const timeuuid = TimeUuid.now('host01', '02'); - * @example Generate a TimeUuid with random node and clock identifiers - * TimeUuid.now(function (err, timeuuid) { - * // do something with the generated timeuuid - * }); - * @example Generate a TimeUuid based on the current date (might block) - * const timeuuid = TimeUuid.now(); - */ -TimeUuid.now = function (nodeId, clockId, callback) { - return TimeUuid.fromDate(null, null, nodeId, clockId, callback); -}; - - -/** - * Gets the Date and 100-nanoseconds units representation of this instance. - * @returns {{date: Date, ticks: Number}} - */ -TimeUuid.prototype.getDatePrecision = function () { - const timeLow = this.buffer.readUInt32BE(0); - - let timeHigh = 0; - timeHigh |= ( this.buffer[4] & 0xff ) << 8; - timeHigh |= this.buffer[5] & 0xff; - timeHigh |= ( this.buffer[6] & 0x0f ) << 24; - timeHigh |= ( this.buffer[7] & 0xff ) << 16; - - const val = Long.fromBits(timeLow, timeHigh); - const ticksInMsLong = Long.fromNumber(_ticksInMs); - const ticks = val.modulo(ticksInMsLong); - const time = val - .div(ticksInMsLong) - .subtract(Long.fromNumber(_unixToGregorian)); - return { date: new Date(time.toNumber()), ticks: ticks.toNumber()}; -}; - -/** - * Gets the Date representation of this instance. - * @returns {Date} - */ -TimeUuid.prototype.getDate = function () { - return this.getDatePrecision().date; -}; - -/** - * Returns the node id this instance - * @returns {Buffer} - */ -TimeUuid.prototype.getNodeId = function () { - return this.buffer.slice(10); -}; - -/** - * Returns the clock id this instance, with the variant applied (first 2 msb being 1 and 0). - * @returns {Buffer} - */ -TimeUuid.prototype.getClockId = function () { - return this.buffer.slice(8, 10); -}; - -/** - * Returns the node id this instance as an ascii string - * @returns {String} - */ -TimeUuid.prototype.getNodeIdString = function () { - return this.buffer.slice(10).toString('ascii'); -}; - -function writeTime(buffer, time, ticks) { - //value time expressed in ticks precision - const val = Long - .fromNumber(time + _unixToGregorian) - .multiply(Long.fromNumber(10000)) - .add(Long.fromNumber(ticks)); - const timeHigh = val.getHighBitsUnsigned(); - buffer.writeUInt32BE(val.getLowBitsUnsigned(), 0); - buffer.writeUInt16BE(timeHigh & 0xffff, 4); - buffer.writeUInt16BE(timeHigh >>> 16 & 0xffff, 6); -} - -/** - * Returns a buffer of length 2 representing the clock identifier - * @param {String|Buffer} clockId - * @returns {Buffer} - * @private - */ -function getClockId(clockId) { - let buffer = clockId; - if (typeof clockId === 'string') { - buffer = utils.allocBufferFromString(clockId, 'ascii'); - } - if (!(buffer instanceof Buffer)) { - //Generate - buffer = getRandomBytes(2); - } - else if (buffer.length !== 2) { - throw new Error('Clock identifier must have 2 bytes'); - } - return buffer; -} - -/** - * Returns a buffer of length 6 representing the clock identifier - * @param {String|Buffer} nodeId - * @returns {Buffer} - * @private - */ -function getNodeId(nodeId) { - let buffer = nodeId; - if (typeof nodeId === 'string') { - buffer = utils.allocBufferFromString(nodeId, 'ascii'); - } - if (!(buffer instanceof Buffer)) { - //Generate - buffer = getRandomBytes(6); - } - else if (buffer.length !== 6) { - throw new Error('Node identifier must have 6 bytes'); - } - return buffer; -} - -/** - * Returns the ticks portion of a timestamp. If the ticks are not provided an internal counter is used that gets reset at 10000. - * @private - * @param {Number} [ticks] - * @returns {Number} - */ -function getTicks(ticks) { - if (typeof ticks !== 'number'|| ticks >= _ticksInMs) { - _ticks++; - if (_ticks >= _ticksInMs) { - _ticks = 0; - } - ticks = _ticks; - } - return ticks; -} - -/** - * Returns an object with the time representation of the date expressed in milliseconds since unix epoch - * and a ticks property for the 100-nanoseconds precision. - * @private - * @returns {{time: Number, ticks: Number}} - */ -function getTimeWithTicks(date, ticks) { - if (!(date instanceof Date) || isNaN(date.getTime())) { - // time with ticks for the current time - date = new Date(); - const time = date.getTime(); - _ticksForCurrentTime++; - if(_ticksForCurrentTime > _ticksInMs || time > _lastTimestamp) { - _ticksForCurrentTime = 0; - _lastTimestamp = time; - } - ticks = _ticksForCurrentTime; - } - return { - time: date.getTime(), - ticks: getTicks(ticks) - }; -} - -function getRandomBytes(length) { - return crypto.randomBytes(length); -} - -function getOrGenerateRandom(id, length, callback) { - if (id) { - return callback(null, id); - } - crypto.randomBytes(length, callback); -} - -/** - * Generates a 16-length Buffer instance - * @private - * @param {Date} date - * @param {Number} ticks - * @param {String|Buffer} nodeId - * @param {String|Buffer} clockId - * @returns {Buffer} - */ -function generateBuffer(date, ticks, nodeId, clockId) { - const timeWithTicks = getTimeWithTicks(date, ticks); - nodeId = getNodeId(nodeId); - clockId = getClockId(clockId); - const buffer = utils.allocBufferUnsafe(16); - //Positions 0-7 Timestamp - writeTime(buffer, timeWithTicks.time, timeWithTicks.ticks); - //Position 8-9 Clock - clockId.copy(buffer, 8, 0); - //Positions 10-15 Node - nodeId.copy(buffer, 10, 0); - //Version Byte: Time based - //0001xxxx - //turn off first 4 bits - buffer[6] = buffer[6] & 0x0f; - //turn on fifth bit - buffer[6] = buffer[6] | 0x10; - - //IETF Variant Byte: 1.0.x - //10xxxxxx - //turn off first 2 bits - buffer[8] = buffer[8] & 0x3f; - //turn on first bit - buffer[8] = buffer[8] | 0x80; - return buffer; -} - -module.exports = TimeUuid; \ No newline at end of file diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/types/tuple.js b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/types/tuple.js deleted file mode 100644 index f8989ccb7a..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/types/tuple.js +++ /dev/null @@ -1,102 +0,0 @@ -/* - * Copyright DataStax, Inc. - * - * 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"; - -/** @module types */ - -/** - * Creates a new sequence of immutable objects with the parameters provided. - * @class - * @classdesc A tuple is a sequence of immutable objects. - * Tuples are sequences, just like [Arrays]{@link Array}. The only difference is that tuples can't be changed. - *

- * As tuples can be used as a Map keys, the {@link Tuple#toString toString()} method calls toString of each element, - * to try to get a unique string key. - *

- * @param args The sequence elements as arguments. - * @constructor - */ -function Tuple(...args) { - - /** - * Immutable elements of Tuple object. - * @type Array - */ - this.elements = args; - - if (this.elements.length === 0) { - throw new TypeError('Tuple must contain at least one value'); - } - - /** - * Returns the number of the elements. - * @type Number - */ - this.length = this.elements.length; -} - -/** - * Creates a new instance of a tuple based on the Array - * @param {Array} elements - * @returns {Tuple} - */ -Tuple.fromArray = function (elements) { - // Apply the elements Array as parameters - return new Tuple(...elements); -}; - -/** - * Returns the value located at the index. - * @param {Number} index Element index - */ -Tuple.prototype.get = function (index) { - return this.elements[index || 0]; -}; - -/** - * Returns the string representation of the sequence surrounded by parenthesis, ie: (1, 2). - *

- * The returned value attempts to be a unique string representation of its values. - *

- * @returns {string} - */ -Tuple.prototype.toString = function () { - return ('(' + - this.elements.reduce(function (prev, x, i) { - return prev + (i > 0 ? ',' : '') + x.toString(); - }, '') + - ')'); -}; - -/** - * Returns the Array representation of the sequence. - * @returns {Array} - */ -Tuple.prototype.toJSON = function () { - return this.elements; -}; - -/** - * Gets the elements as an array - * @returns {Array} - */ -Tuple.prototype.values = function () { - // Clone the elements - return this.elements.slice(0); -}; - -module.exports = Tuple; \ No newline at end of file diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/types/uuid.js b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/types/uuid.js deleted file mode 100644 index 56281d58fa..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/types/uuid.js +++ /dev/null @@ -1,153 +0,0 @@ -/* - * Copyright DataStax, Inc. - * - * 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 crypto = require('crypto'); -const utils = require('../utils'); - -/** @module types */ - -/** - * Creates a new instance of Uuid based on a Buffer - * @class - * @classdesc Represents an immutable universally unique identifier (UUID). A UUID represents a 128-bit value. - * @param {Buffer} buffer The 16-length buffer. - * @constructor - */ -function Uuid(buffer) { - if (!buffer || buffer.length !== 16) { - throw new Error('You must provide a buffer containing 16 bytes'); - } - this.buffer = buffer; -} - -/** - * Parses a string representation of a Uuid - * @param {String} value - * @returns {Uuid} - */ -Uuid.fromString = function (value) { - //36 chars: 32 + 4 hyphens - if (typeof value !== 'string' || value.length !== 36) { - throw new Error('Invalid string representation of Uuid, it should be in the 00000000-0000-0000-0000-000000000000'); - } - return new Uuid(utils.allocBufferFromString(value.replace(/-/g, ''), 'hex')); -}; - -/** - * Creates a new random (version 4) Uuid. - * @param {function} [callback] Optional callback to be invoked with the error as first parameter and the created Uuid as - * second parameter. - * @returns {Uuid} - */ -Uuid.random = function (callback) { - if (callback) { - getRandomBytes(function(err, buffer) { - if (err) { - return callback(err); - } - return callback(null, createUuidFromBuffer(buffer)); - }); - } else { - const buffer = getRandomBytes(); - return createUuidFromBuffer(buffer); - } -}; - -/** - * Gets the bytes representation of a Uuid - * @returns {Buffer} - */ -Uuid.prototype.getBuffer = function () { - return this.buffer; -}; -/** - * Compares this object to the specified object. - * The result is true if and only if the argument is not null, is a UUID object, and contains the same value, bit for bit, as this UUID. - * @param {Uuid} other The other value to test for equality. - */ -Uuid.prototype.equals = function (other) { - return other instanceof Uuid && this.buffer.equals(other.buffer); -}; - -/** - * Returns a string representation of the value of this Uuid instance. - * 32 hex separated by hyphens, in the form of 00000000-0000-0000-0000-000000000000. - * @returns {String} - */ -Uuid.prototype.toString = function () { - //32 hex representation of the Buffer - const hexValue = getHex(this); - return ( - hexValue.substr(0, 8) + '-' + - hexValue.substr(8, 4) + '-' + - hexValue.substr(12, 4) + '-' + - hexValue.substr(16, 4) + '-' + - hexValue.substr(20, 12)); -}; - -/** - * Provide the name of the constructor and the string representation - * @returns {string} - */ -Uuid.prototype.inspect = function () { - return this.constructor.name + ': ' + this.toString(); -}; - -/** - * Returns the string representation. - * Method used by the native JSON.stringify() to serialize this instance. - */ -Uuid.prototype.toJSON = function () { - return this.toString(); -}; - - -/** - * Returns new Uuid - * @private - * @returns {Uuid} - */ -function createUuidFromBuffer (buffer) { - //clear the version - buffer[6] &= 0x0f; - //set the version 4 - buffer[6] |= 0x40; - //clear the variant - buffer[8] &= 0x3f; - //set the IETF variant - buffer[8] |= 0x80; - return new Uuid(buffer); -} - -/** - * @private - * @returns {String} 32 hex representation of the instance, without separators - */ -function getHex (uuid) { - return uuid.buffer.toString('hex'); -} - -/** - * Gets a crypto generated 16 bytes - * @private - * @returns {Buffer} - */ -function getRandomBytes (cb) { - return crypto.randomBytes(16, cb); -} - -module.exports = Uuid; diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/types/version-number.js b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/types/version-number.js deleted file mode 100644 index 7f5b743001..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/types/version-number.js +++ /dev/null @@ -1,144 +0,0 @@ -/* - * Copyright DataStax, Inc. - * - * 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 _versionPattern = /(\d+)\.(\d+)(?:\.(\d+))?(?:\.(\d+)?)?(?:[-~]([\w+]*(?:-\w[.\w]*)*))?(?:\+([.\w]+))?/; - -/** - * Represents a version number in the form of X.Y.Z with optional pre-release and build metadata. - * - * Version numbers compare the usual way, the major version number (X) is compared first, then - * the minor one (Y) and then the patch level one (Z). If pre-release or other build metadata - * is present for a version, that version is considered less than an otherwise equivalent version - * that doesn't have these labels, otherwise they are considered equal. - * - * As of initial implementation versions are only compared against those with at most patch versions - * more refined comparisons are not needed. - * - * @property {Number} major The major version, X of X.Y.Z. - * @property {Number} minor The minor version, Y of X.Y.Z. - * @property {Number} patch The patch version, Z of X.Y.Z. - * @property {Number} dsePatch The dsePatch version, A of X.Y.Z.A or undefined if not present. - * @property {String[]} preReleases Prerelease indicators if present, i.e. SNAPSHOT of X.Y.Z-SNAPSHOT. - * @property {String} build Build string if present, i.e. build1 of X.Y.Z+build1. - * - * @ignore - */ -class VersionNumber { - constructor(major, minor, patch, dsePatch, preReleases, build) { - this.major = major; - this.minor = minor; - this.patch = patch; - this.dsePatch = dsePatch; - this.preReleases = preReleases; - this.build = build; - } - - /** - * @return {String} String representation of this version. - */ - toString() { - let str = this.major + '.' + this.minor; - if (this.patch !== undefined) { - str += '.' + this.patch; - } - if (this.dsePatch !== undefined) { - str += '.' + this.dsePatch; - } - if (this.preReleases !== undefined) { - this.preReleases.forEach((preRelease) => { - str += '-' + preRelease; - }); - } - if (this.build) { - str += '+' + this.build; - } - return str; - } - - /** - * Compares this version with the provided version. - * @param {VersionNumber} other - * @return {Number} -1 if less than other, 0 if equal, 1 if greater than. - */ - compare(other) { - if (this.major < other.major) { - return -1; - } else if (this.major > other.major) { - return 1; - } else if (this.minor < other.minor) { - return -1; - } else if (this.minor > other.minor) { - return 1; - } - - // sanitize patch by setting to 0 if undefined. - const thisPatch = this.patch || 0; - const otherPatch = other.patch || 0; - if (thisPatch < otherPatch) { - return -1; - } else if (thisPatch > otherPatch) { - return 1; - } - - // if dsePatch is set in one case, but not other, consider the one where it is set as greater. - if (this.dsePatch === undefined) { - if (other.dsePatch !== undefined) { - return -1; - } - } else if (other.dsePatch === undefined) { - return 1; - } else { - if (this.dsePatch < other.dsePatch) { - return -1; - } else if (this.dsePatch > other.dsePatch) { - return 1; - } - } - - // If prereleases are present, consider less than those that don't have any. - if (this.preReleases === undefined) { - if (other.preReleases !== undefined) { - return 1; - } - } else if (other.preReleases === undefined) { - return -1; - } - - // Don't consider build. - return 0; - } - - static parse(version) { - if (!version) { - return null; - } - - const match = version.match(_versionPattern); - if (match) { - const major = parseInt(match[1], 10); - const minor = parseInt(match[2], 10); - const patch = match[3] ? parseInt(match[3], 10) : undefined; - const dsePatch = match[4] ? parseInt(match[4], 10) : undefined; - const preReleases = match[5] ? match[5].split('-') : undefined; - const build = match[6]; - return new VersionNumber(major, minor, patch, dsePatch, preReleases, build); - } - throw new TypeError('Could not extract version from \'' + version + '\''); - } -} - -module.exports = VersionNumber; \ No newline at end of file diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/utils.js b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/utils.js deleted file mode 100644 index 349c47e310..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/utils.js +++ /dev/null @@ -1,1086 +0,0 @@ -/* - * Copyright DataStax, Inc. - * - * 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 util = require('util'); -const net = require('net'); -const { EventEmitter } = require('events'); - -const errors = require('./errors'); -const promiseUtils = require('./promise-utils'); - -/** - * Max int that can be accurately represented with 64-bit Number (2^53) - * @type {number} - * @const - */ -const maxInt = 9007199254740992; - -const maxInt32 = 0x7fffffff; - -const emptyObject = Object.freeze({}); - -const emptyArray = Object.freeze([]); - -function noop() {} - -/** - * Forward-compatible allocation of buffer, filled with zeros. - * @type {Function} - */ -const allocBuffer = Buffer.alloc || allocBufferFillDeprecated; - -/** - * Forward-compatible unsafe allocation of buffer. - * @type {Function} - */ -const allocBufferUnsafe = Buffer.allocUnsafe || allocBufferDeprecated; - -/** - * Forward-compatible allocation of buffer to contain a string. - * @type {Function} - */ -const allocBufferFromString = (Int8Array.from !== Buffer.from && Buffer.from) || allocBufferFromStringDeprecated; - -/** - * Forward-compatible allocation of buffer from an array of bytes - * @type {Function} - */ -const allocBufferFromArray = (Int8Array.from !== Buffer.from && Buffer.from) || allocBufferFromArrayDeprecated; - -function allocBufferDeprecated(size) { - // eslint-disable-next-line - return new Buffer(size); -} - -function allocBufferFillDeprecated(size) { - const b = allocBufferDeprecated(size); - b.fill(0); - return b; -} - -function allocBufferFromStringDeprecated(text, encoding) { - if (typeof text !== 'string') { - throw new TypeError('Expected string, obtained ' + util.inspect(text)); - } - // eslint-disable-next-line - return new Buffer(text, encoding); -} - -function allocBufferFromArrayDeprecated(arr) { - if (!Array.isArray(arr)) { - throw new TypeError('Expected Array, obtained ' + util.inspect(arr)); - } - // eslint-disable-next-line - return new Buffer(arr); -} - -/** - * @returns {Function} Returns a wrapper function that invokes the underlying callback only once. - * @param {Function} callback - */ -function callbackOnce(callback) { - let cb = callback; - - return (function wrapperCallback(err, result) { - cb(err, result); - cb = noop; - }); -} - -/** - * Creates a copy of a buffer - */ -function copyBuffer(buf) { - const targetBuffer = allocBufferUnsafe(buf.length); - buf.copy(targetBuffer); - return targetBuffer; -} - -/** - * Appends the original stack trace to the error after a tick of the event loop - */ -function fixStack(stackTrace, error) { - if (stackTrace) { - error.stack += '\n (event loop)\n' + stackTrace.substr(stackTrace.indexOf("\n") + 1); - } - return error; -} - -/** - * Uses the logEmitter to emit log events - * @param {String} type - * @param {String} info - * @param [furtherInfo] - */ -function log(type, info, furtherInfo) { - if (!this.logEmitter) { - if (!this.options || !this.options.logEmitter) { - throw new Error('Log emitter not defined'); - } - this.logEmitter = this.options.logEmitter; - } - this.logEmitter('log', type, this.constructor.name, info, furtherInfo || ''); -} - -/** - * Gets the sum of the length of the items of an array - */ -function totalLength (arr) { - if (arr.length === 1) { - return arr[0].length; - } - let total = 0; - arr.forEach(function (item) { - let length = item.length; - length = length ? length : 0; - total += length; - }); - return total; -} - -/** - * Merge the contents of two or more objects together into the first object. Similar to jQuery.extend / Object.assign. - * The main difference between this method is that declared properties with an undefined value are not set - * to the target. - */ -function extend(target) { - const sources = Array.prototype.slice.call(arguments, 1); - sources.forEach(function (source) { - if (!source) { - return; - } - const keys = Object.keys(source); - for (let i = 0; i < keys.length; i++) { - const key = keys[i]; - const value = source[key]; - if (value === undefined) { - continue; - } - target[key] = value; - } - }); - return target; -} - -/** - * Returns a new object with the property names set to lowercase. - */ -function toLowerCaseProperties(obj) { - const keys = Object.keys(obj); - const result = {}; - for (let i = 0; i < keys.length; i++) { - const k = keys[i]; - result[k.toLowerCase()] = obj[k]; - } - return result; -} - -/** - * Extends the target by the most inner props of sources - * @param {Object} target - * @returns {Object} - */ -function deepExtend(target) { - const sources = Array.prototype.slice.call(arguments, 1); - sources.forEach(function (source) { - for (const prop in source) { - // eslint-disable-next-line no-prototype-builtins - if (!source.hasOwnProperty(prop)) { - continue; - } - const targetProp = target[prop]; - const targetType = (typeof targetProp); - //target prop is - // a native single type - // or not existent - // or is not an anonymous object (not class instance) - if (!targetProp || - targetType === 'number' || - targetType === 'string' || - Array.isArray(targetProp) || - util.isDate(targetProp) || - targetProp.constructor.name !== 'Object') { - target[prop] = source[prop]; - } - else { - //inner extend - target[prop] = deepExtend({}, targetProp, source[prop]); - } - } - }); - return target; -} - -function propCompare(propName) { - return function (a, b) { - if (a[propName] > b[propName]) { - return 1; - } - if (a[propName] < b[propName]) { - return -1; - } - return 0; - }; -} - -function funcCompare(name, argArray) { - return (function (a, b) { - if (typeof a[name] === 'undefined') { - return 0; - } - const valA = a[name].apply(a, argArray); - const valB = b[name].apply(b, argArray); - if (valA > valB) { - return 1; - } - if (valA < valB) { - return -1; - } - return 0; - }); -} -/** - * Uses the iterator protocol to go through the items of the Array - * @param {Array} arr - * @returns {Iterator} - */ -function arrayIterator (arr) { - return arr[Symbol.iterator](); -} - -/** - * Convert the iterator values into an array - * @param iterator - * @returns {Array} - */ -function iteratorToArray(iterator) { - const values = []; - let item = iterator.next(); - while (!item.done) { - values.push(item.value); - item = iterator.next(); - } - return values; -} - -/** - * Searches the specified Array for the provided key using the binary - * search algorithm. The Array must be sorted. - * @param {Array} arr - * @param key - * @param {function} compareFunc - * @returns {number} The position of the key in the Array, if it is found. - * If it is not found, it returns a negative number which is the bitwise complement of the index of the first element that is larger than key. - */ -function binarySearch(arr, key, compareFunc) { - let low = 0; - let high = arr.length-1; - - while (low <= high) { - const mid = (low + high) >>> 1; - const midVal = arr[mid]; - const cmp = compareFunc(midVal, key); - if (cmp < 0) { - low = mid + 1; - } - else if (cmp > 0) { - high = mid - 1; - } - else - { - //The key was found in the Array - return mid; - } - } - // key not found - return ~low; -} - -/** - * Inserts the value in the position determined by its natural order determined by the compare func - * @param {Array} arr - * @param item - * @param {function} compareFunc - */ -function insertSorted(arr, item, compareFunc) { - if (arr.length === 0) { - return arr.push(item); - } - let position = binarySearch(arr, item, compareFunc); - if (position < 0) { - position = ~position; - } - arr.splice(position, 0, item); -} - -/** - * Validates the provided parameter is of type function. - * @param {Function} fn The instance to validate. - * @param {String} [name] Name of the function to use in the error message. Defaults to 'callback'. - * @returns {Function} - */ -function validateFn(fn, name) { - if (typeof fn !== 'function') { - throw new errors.ArgumentError(util.format('%s is not a function', name || 'callback')); - } - return fn; -} - -/** - * Adapts the parameters based on the prepared metadata. - * If the params are passed as an associative array (Object), - * it adapts the object into an array with the same order as columns - * @param {Array|Object} params - * @param {Array} columns - * @returns {Array} Returns an array of parameters. - * @throws {Error} In case a parameter with a specific name is not defined - */ -function adaptNamedParamsPrepared(params, columns) { - if (!params || Array.isArray(params) || !columns || columns.length === 0) { - // params is an array or there aren't parameters - return params; - } - const paramsArray = new Array(columns.length); - params = toLowerCaseProperties(params); - const keys = {}; - for (let i = 0; i < columns.length; i++) { - const name = columns[i].name; - // eslint-disable-next-line no-prototype-builtins - if (!params.hasOwnProperty(name)) { - throw new errors.ArgumentError(util.format('Parameter "%s" not defined', name)); - } - paramsArray[i] = params[name]; - keys[name] = i; - } - return paramsArray; -} - -/** - * Adapts the associative-array of parameters and hints for simple statements - * into Arrays based on the (arbitrary) position of the keys. - * @param {Array|Object} params - * @param {ExecutionOptions} execOptions - * @returns {{ params: Array<{name, value}>, namedParameters: boolean, keyIndexes: object }} Returns an array of - * parameters and the keys as an associative array. - */ -function adaptNamedParamsWithHints(params, execOptions) { - if (!params || Array.isArray(params)) { - //The parameters is an Array or there isn't parameter - return { params: params, namedParameters: false, keyIndexes: null }; - } - - const keys = Object.keys(params); - const paramsArray = new Array(keys.length); - const hints = new Array(keys.length); - const userHints = execOptions.getHints() || emptyObject; - const keyIndexes = {}; - - for (let i = 0; i < keys.length; i++) { - const key = keys[i]; - // As lower cased identifiers - paramsArray[i] = { name: key.toLowerCase(), value: params[key]}; - hints[i] = userHints[key]; - keyIndexes[key] = i; - } - - execOptions.setHints(hints); - - return { params: paramsArray, namedParameters: true, keyIndexes }; -} - -/** - * Returns a string with a value repeated n times - * @param {String} val - * @param {Number} times - * @returns {String} - */ -function stringRepeat(val, times) { - if (!times || times < 0) { - return null; - } - if (times === 1) { - return val; - } - return new Array(times + 1).join(val); -} - -/** - * Returns an array containing the values of the Object, similar to Object.values(). - * If obj is null or undefined, it will return an empty array. - * @param {Object} obj - * @returns {Array} - */ -function objectValues(obj) { - if (!obj) { - return emptyArray; - } - const keys = Object.keys(obj); - const values = new Array(keys.length); - for (let i = 0; i < keys.length; i++) { - values[i] = obj[keys[i]]; - } - return values; -} - -/** - * Wraps the callback-based method. When no originalCallback is not defined, it returns a Promise. - * @param {ClientOptions} options - * @param {Function} originalCallback - * @param {Function} handler - * @returns {Promise|undefined} - */ -function promiseWrapper(options, originalCallback, handler) { - if (typeof originalCallback === 'function') { - // Callback-based invocation - handler.call(this, originalCallback); - return undefined; - } - const factory = options.promiseFactory || defaultPromiseFactory; - const self = this; - return factory(function handlerWrapper(callback) { - handler.call(self, callback); - }); -} - -/** - * @param {Function} handler - * @returns {Promise} - */ -function defaultPromiseFactory(handler) { - return new Promise(function executor(resolve, reject) { - handler(function handlerCallback(err, result) { - if (err) { - return reject(err); - } - resolve(result); - }); - }); -} - -/** - * Returns the first not undefined param - */ -function ifUndefined(v1, v2) { - return v1 !== undefined ? v1 : v2; -} - -/** - * Returns the first not undefined param - */ -function ifUndefined3(v1, v2, v3) { - if (v1 !== undefined) { - return v1; - } - return v2 !== undefined ? v2 : v3; -} - -/** - * Shuffles an Array in-place. - * @param {Array} arr - * @returns {Array} - * @private - */ -function shuffleArray(arr) { - // Fisher–Yates algorithm - for (let i = arr.length - 1; i > 0; i--) { - // Math.random() has an extremely short permutation cycle length but we don't care about collisions - const j = Math.floor(Math.random() * (i + 1)); - const temp = arr[i]; - arr[i] = arr[j]; - arr[j] = temp; - } - - return arr; -} - -// Classes - -/** - * Represents a unique set of values. - * @constructor - */ -function HashSet() { - this.length = 0; - this.items = {}; -} - -/** - * Adds a new item to the set. - * @param {Object} key - * @returns {boolean} Returns true if it was added to the set; false if the key is already present. - */ -HashSet.prototype.add = function (key) { - if (this.contains(key)) { - return false; - } - this.items[key] = true; - this.length++; - return true; -}; - -/** - * @returns {boolean} Returns true if the key is present in the set. - */ -HashSet.prototype.contains = function (key) { - return this.length > 0 && this.items[key] === true; -}; - -/** - * Removes the item from set. - * @param key - * @return {boolean} Returns true if the key existed and was removed, otherwise it returns false. - */ -HashSet.prototype.remove = function (key) { - if (!this.contains(key)) { - return false; - } - delete this.items[key]; - this.length--; -}; - -/** - * Returns an array containing the set items. - * @returns {Array} - */ -HashSet.prototype.toArray = function () { - return Object.keys(this.items); -}; - -/** - * Utility class that resolves host names into addresses. - */ -class AddressResolver { - - /** - * Creates a new instance of the resolver. - * @param {Object} options - * @param {String} options.nameOrIp - * @param {Object} [options.dns] - */ - constructor(options) { - if (!options || !options.nameOrIp || !options.dns) { - throw new Error('nameOrIp and dns lib must be provided as part of the options'); - } - - this._resolve4 = util.promisify(options.dns.resolve4); - this._nameOrIp = options.nameOrIp; - this._isIp = net.isIP(options.nameOrIp); - this._index = 0; - this._addresses = null; - this._refreshing = null; - } - - /** - * Resolves the addresses for the host name. - */ - async init() { - if (this._isIp) { - return; - } - - await this._resolve(); - } - - /** - * Tries to resolve the addresses for the host name. - */ - async refresh() { - if (this._isIp) { - return; - } - - if (this._refreshing) { - return await promiseUtils.fromEvent(this._refreshing, 'finished'); - } - - this._refreshing = new EventEmitter().setMaxListeners(0); - - try { - await this._resolve(); - } catch (err) { - // Ignore the possible resolution error - } - - this._refreshing.emit('finished'); - this._refreshing = null; - } - - async _resolve() { - const arr = await this._resolve4(this._nameOrIp); - - if (!arr || arr.length === 0) { - throw new Error(`${this._nameOrIp} could not be resolved`); - } - - this._addresses = arr; - } - - /** - * Returns resolved ips in a round-robin fashion. - */ - getIp() { - if (this._isIp) { - return this._nameOrIp; - } - - const item = this._addresses[this._index % this._addresses.length]; - this._index = (this._index !== maxInt32) ? (this._index + 1) : 0; - - return item; - } -} - -/** - * @param {Array} arr - * @param {Function} fn - * @param {Function} [callback] - */ -function each(arr, fn, callback) { - if (!Array.isArray(arr)) { - throw new TypeError('First parameter is not an Array'); - } - callback = callback || noop; - const length = arr.length; - if (length === 0) { - return callback(); - } - let completed = 0; - for (let i = 0; i < length; i++) { - fn(arr[i], next); - } - function next(err) { - if (err) { - const cb = callback; - callback = noop; - cb(err); - return; - } - if (++completed !== length) { - return; - } - callback(); - } -} - -/** - * @param {Array} arr - * @param {Function} fn - * @param {Function} [callback] - */ -function eachSeries(arr, fn, callback) { - if (!Array.isArray(arr)) { - throw new TypeError('First parameter is not an Array'); - } - callback = callback || noop; - const length = arr.length; - if (length === 0) { - return callback(); - } - let sync; - let index = 1; - fn(arr[0], next); - if (sync === undefined) { - sync = false; - } - - function next(err) { - if (err) { - return callback(err); - } - if (index >= length) { - return callback(); - } - if (sync === undefined) { - sync = true; - } - if (sync) { - return process.nextTick(function () { - fn(arr[index++], next); - }); - } - fn(arr[index++], next); - } -} - -/** - * @param {Array} arr - * @param {Function} fn - * @param {Function} [callback] - */ -function forEachOf(arr, fn, callback) { - return mapEach(arr, fn, true, callback); -} - -/** - * @param {Array} arr - * @param {Function} fn - * @param {Function} [callback] - */ -function map(arr, fn, callback) { - return mapEach(arr, fn, false, callback); -} - -function mapEach(arr, fn, useIndex, callback) { - if (!Array.isArray(arr)) { - throw new TypeError('First parameter must be an Array'); - } - callback = callback || noop; - const length = arr.length; - if (length === 0) { - return callback(null, []); - } - const result = new Array(length); - let completed = 0; - const invoke = useIndex ? invokeWithIndex : invokeWithoutIndex; - for (let i = 0; i < length; i++) { - invoke(i); - } - - function invokeWithoutIndex(i) { - fn(arr[i], function mapItemCallback(err, transformed) { - result[i] = transformed; - next(err); - }); - } - - function invokeWithIndex(i) { - fn(arr[i], i, function mapItemCallback(err, transformed) { - result[i] = transformed; - next(err); - }); - } - - function next(err) { - if (err) { - const cb = callback; - callback = noop; - cb(err); - return; - } - if (++completed !== length) { - return; - } - callback(null, result); - } -} - -/** - * @param {Array} arr - * @param {Function} fn - * @param {Function} [callback] - */ -function mapSeries(arr, fn, callback) { - if (!Array.isArray(arr)) { - throw new TypeError('First parameter must be an Array'); - } - callback = callback || noop; - const length = arr.length; - if (length === 0) { - return callback(null, []); - } - const result = new Array(length); - let index = 0; - let sync; - invoke(0); - if (sync === undefined) { - sync = false; - } - - function invoke(i) { - fn(arr[i], function mapItemCallback(err, transformed) { - result[i] = transformed; - next(err); - }); - } - - function next(err) { - if (err) { - return callback(err); - } - if (++index === length) { - return callback(null, result); - } - if (sync === undefined) { - sync = true; - } - const i = index; - if (sync) { - return process.nextTick(function () { - invoke(i); - }); - } - invoke(index); - } -} - -/** - * @param {Array.} arr - * @param {Function} [callback] - */ -function parallel(arr, callback) { - if (!Array.isArray(arr)) { - throw new TypeError('First parameter must be an Array'); - } - callback = callback || noop; - const length = arr.length; - let completed = 0; - for (let i = 0; i < length; i++) { - arr[i](next); - } - function next(err) { - if (err) { - const cb = callback; - callback = noop; - return cb(err); - } - if (++completed !== length) { - return; - } - callback(); - } -} - -/** - * Similar to async.series(), but instead accumulating the result in an Array, it callbacks with the result of the last - * function in the array. - * @param {Array.} arr - * @param {Function} [callback] - */ -function series(arr, callback) { - if (!Array.isArray(arr)) { - throw new TypeError('First parameter must be an Array'); - } - callback = callback || noop; - let index = 0; - let sync; - next(); - function next(err, result) { - if (err) { - return callback(err); - } - if (index === arr.length) { - return callback(null, result); - } - if (sync) { - return process.nextTick(function () { - sync = true; - arr[index++](next); - sync = false; - }); - } - sync = true; - arr[index++](next); - sync = false; - } -} - -/** - * @param {Number} count - * @param {Function} iteratorFunc - * @param {Function} [callback] - */ -function times(count, iteratorFunc, callback) { - callback = callback || noop; - count = +count; - if (isNaN(count) || count === 0) { - return callback(); - } - let completed = 0; - for (let i = 0; i < count; i++) { - iteratorFunc(i, next); - } - function next(err) { - if (err) { - const cb = callback; - callback = noop; - return cb(err); - } - if (++completed !== count) { - return; - } - callback(); - } -} - -/** - * @param {Number} count - * @param {Number} limit - * @param {Function} iteratorFunc - * @param {Function} [callback] - */ -function timesLimit(count, limit, iteratorFunc, callback) { - let sync = undefined; - callback = callback || noop; - limit = Math.min(limit, count); - let index = limit - 1; - let i; - let completed = 0; - for (i = 0; i < limit; i++) { - iteratorFunc(i, next); - } - i = -1; - function next(err) { - if (err) { - const cb = callback; - callback = noop; - cb(err); - return; - } - if (++completed === count) { - return callback(); - } - index++; - if (index >= count) { - return; - } - if (sync === undefined) { - sync = (i >= 0); - } - if (sync) { - const captureIndex = index; - return process.nextTick(function () { - iteratorFunc(captureIndex, next); - }); - } - iteratorFunc(index, next); - } -} - -/** - * @param {Number} count - * @param {Function} iteratorFunction - * @param {Function} callback - */ -function timesSeries(count, iteratorFunction, callback) { - count = +count; - if (isNaN(count) || count < 1) { - return callback(); - } - let index = 1; - let sync; - iteratorFunction(0, next); - if (sync === undefined) { - sync = false; - } - function next(err) { - if (err) { - return callback(err); - } - if (index === count) { - return callback(); - } - if (sync === undefined) { - sync = true; - } - const i = index++; - if (sync) { - //Prevent "Maximum call stack size exceeded" - return process.nextTick(function () { - iteratorFunction(i, next); - }); - } - //do a sync call as the callback is going to call on a future tick - iteratorFunction(i, next); - } -} - -/** - * @param {Function} condition - * @param {Function} fn - * @param {Function} callback - */ -function whilst(condition, fn, callback) { - let sync = 0; - next(); - function next(err) { - if (err) { - return callback(err); - } - if (!condition()) { - return callback(); - } - if (sync === 0) { - sync = 1; - fn(function (err) { - if (sync === 1) { - //sync function - sync = 4; - } - next(err); - }); - if (sync === 1) { - //async function - sync = 2; - } - return; - } - if (sync === 4) { - //Prevent "Maximum call stack size exceeded" - return process.nextTick(function () { - fn(next); - }); - } - //do a sync call as the callback is going to call on a future tick - fn(next); - } -} - -exports.adaptNamedParamsPrepared = adaptNamedParamsPrepared; -exports.adaptNamedParamsWithHints = adaptNamedParamsWithHints; -exports.AddressResolver = AddressResolver; -exports.allocBuffer = allocBuffer; -exports.allocBufferUnsafe = allocBufferUnsafe; -exports.allocBufferFromArray = allocBufferFromArray; -exports.allocBufferFromString = allocBufferFromString; -exports.arrayIterator = arrayIterator; -exports.binarySearch = binarySearch; -exports.callbackOnce = callbackOnce; -exports.copyBuffer = copyBuffer; -exports.deepExtend = deepExtend; -exports.each = each; -exports.eachSeries = eachSeries; -/** @const */ -exports.emptyArray = Object.freeze([]); -/** @const */ -exports.emptyObject = emptyObject; -exports.extend = extend; -exports.fixStack = fixStack; -exports.forEachOf = forEachOf; -exports.funcCompare = funcCompare; -exports.ifUndefined = ifUndefined; -exports.ifUndefined3 = ifUndefined3; -exports.insertSorted = insertSorted; -exports.iteratorToArray = iteratorToArray; -exports.log = log; -exports.map = map; -exports.mapSeries = mapSeries; -exports.maxInt = maxInt; -exports.noop = noop; -exports.objectValues = objectValues; -exports.parallel = parallel; -exports.promiseWrapper = promiseWrapper; -exports.propCompare = propCompare; -exports.series = series; -exports.shuffleArray = shuffleArray; -exports.stringRepeat = stringRepeat; -exports.times = times; -exports.timesLimit = timesLimit; -exports.timesSeries = timesSeries; -exports.totalLength = totalLength; -exports.validateFn = validateFn; -exports.whilst = whilst; -exports.HashSet = HashSet; \ No newline at end of file diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/writers.js b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/writers.js deleted file mode 100644 index a3d4f28163..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/lib/writers.js +++ /dev/null @@ -1,310 +0,0 @@ -/* - * Copyright DataStax, Inc. - * - * 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 events = require('events'); - -const types = require('./types'); -const utils = require('./utils.js'); -const FrameHeader = types.FrameHeader; - -/** - * Contains the logic to write all the different types to the frame. - */ -class FrameWriter { - /** - * Creates a new instance of FrameWriter. - * @param {Number} opcode - */ - constructor(opcode) { - if (!opcode) { - throw new Error('Opcode not provided'); - } - this.buffers = []; - this.opcode = opcode; - this.bodyLength = 0; - } - - add(buf) { - this.buffers.push(buf); - this.bodyLength += buf.length; - } - - writeShort(num) { - const buf = utils.allocBufferUnsafe(2); - buf.writeUInt16BE(num, 0); - this.add(buf); - } - - writeInt(num) { - const buf = utils.allocBufferUnsafe(4); - buf.writeInt32BE(num, 0); - this.add(buf); - } - - /** @param {Long} num */ - writeLong(num) { - this.add(types.Long.toBuffer(num)); - } - - /** - * Writes bytes according to Cassandra - * @param {Buffer|null|types.unset} bytes - */ - writeBytes(bytes) { - if (bytes === null) { - //Only the length buffer containing -1 - this.writeInt(-1); - return; - } - if (bytes === types.unset) { - this.writeInt(-2); - return; - } - //Add the length buffer - this.writeInt(bytes.length); - //Add the actual buffer - this.add(bytes); - } - - /** - * Writes a buffer according to Cassandra protocol: bytes.length (2) + bytes - * @param {Buffer} bytes - */ - writeShortBytes(bytes) { - if(bytes === null) { - //Only the length buffer containing -1 - this.writeShort(-1); - return; - } - //Add the length buffer - this.writeShort(bytes.length); - //Add the actual buffer - this.add(bytes); - } - - /** - * Writes a single byte - * @param {Number} num Value of the byte, a number between 0 and 255. - */ - writeByte(num) { - this.add(utils.allocBufferFromArray([num])); - } - - writeString(str) { - if (typeof str === "undefined") { - throw new Error("can not write undefined"); - } - const len = Buffer.byteLength(str, 'utf8'); - const buf = utils.allocBufferUnsafe(2 + len); - buf.writeUInt16BE(len, 0); - buf.write(str, 2, buf.length-2, 'utf8'); - this.add(buf); - } - - writeLString(str) { - const len = Buffer.byteLength(str, 'utf8'); - const buf = utils.allocBufferUnsafe(4 + len); - buf.writeInt32BE(len, 0); - buf.write(str, 4, buf.length-4, 'utf8'); - this.add(buf); - } - - writeStringList(values) { - this.writeShort(values.length); - values.forEach(this.writeString, this); - } - - writeCustomPayload(payload) { - const keys = Object.keys(payload); - this.writeShort(keys.length); - keys.forEach(k => { - this.writeString(k); - this.writeBytes(payload[k]); - }); - } - - writeStringMap(map) { - const keys = []; - for (const k in map) { - if (map.hasOwnProperty(k)) { - keys.push(k); - } - } - - this.writeShort(keys.length); - - for(let i = 0; i < keys.length; i++) { - const key = keys[i]; - this.writeString(key); - this.writeString(map[key]); - } - } - - /** - * @param {Number} version - * @param {Number} streamId - * @param {Number} [flags] Header flags - * @returns {Buffer} - * @throws {TypeError} - */ - write(version, streamId, flags) { - const header = new FrameHeader(version, flags || 0, streamId, this.opcode, this.bodyLength); - const headerBuffer = header.toBuffer(); - this.buffers.unshift(headerBuffer); - return Buffer.concat(this.buffers, headerBuffer.length + this.bodyLength); - } -} - -/** - * Represents a queue that process one write at a time (FIFO). - * @extends {EventEmitter} - */ -class WriteQueue extends events.EventEmitter { - /** - * Creates a new WriteQueue instance. - * @param {Socket} netClient - * @param {Encoder} encoder - * @param {ClientOptions} options - */ - constructor(netClient, encoder, options) { - super(); - this.netClient = netClient; - this.encoder = encoder; - this.isRunning = false; - /** @type {Array<{operation: OperationState, callback: Function}>} */ - this.queue = []; - this.coalescingThreshold = options.socketOptions.coalescingThreshold; - this.error = null; - this.canWrite = true; - - // Listen to drain event that is going to be fired once - // the underlying buffer is empty - netClient.on('drain', () => { - this.canWrite = true; - this.run(); - }); - } - - /** - * Enqueues a new request - * @param {OperationState} operation - * @param {Function} callback The write callback. - */ - push(operation, callback) { - const self = this; - - if (this.error) { - // There was a write error, there is no point in further trying to write to the socket. - return process.nextTick(function writePushError() { - callback(self.error); - }); - } - - this.queue.push({ operation: operation, callback: callback}); - this.run(); - } - - run() { - if (!this.isRunning && this.canWrite) { - this.isRunning = true; - // Use nextTick to allow the queue to build up on the current phase - process.nextTick(() => this.process()); - } - } - - process() { - if (this.error) { - return; - } - - const buffers = []; - const callbacks = []; - let totalLength = 0; - - while (this.queue.length > 0 && totalLength < this.coalescingThreshold) { - const writeItem = this.queue.shift(); - if (!writeItem.operation.canBeWritten()) { - // Invoke the write callback with an error that is not going to be yielded to user - // as the operation has timed out or was cancelled. - writeItem.callback(new Error('The operation was already cancelled or timeout elapsed')); - continue; - } - let data; - try { - data = writeItem.operation.request.write(this.encoder, writeItem.operation.streamId); - } - catch (err) { - writeItem.callback(err); - continue; - } - totalLength += data.length; - buffers.push(data); - callbacks.push(writeItem.callback); - } - - if (totalLength === 0) { - this.isRunning = false; - return; - } - - // We have to invoke the callbacks to avoid race conditions. - // There is a performance benefit from executing all of them in a loop - for (let i = 0; i < callbacks.length; i++) { - callbacks[i](); - } - - // Concatenate buffers and write it to the socket - // Further writes will be throttled until flushed - this.canWrite = this.netClient.write(Buffer.concat(buffers, totalLength), err => { - if (err) { - this.setWriteError(err); - return; - } - - if (this.queue.length === 0 || !this.canWrite) { - // It will start running once we get the next message or has drained - this.isRunning = false; - return; - } - - // Allow IO between writes - setImmediate(() => this.process()); - }); - } - - /** - * Emits the 'error' event and callbacks items that haven't been written and clears them from the queue. - * @param err - */ - setWriteError(err) { - err.isSocketError = true; - this.error = new types.DriverError('Socket was closed'); - this.error.isSocketError = true; - // Use an special flag for items that haven't been written - this.error.requestNotWritten = true; - this.error.innerError = err; - const q = this.queue; - // Not more items can be added to the queue. - this.queue = utils.emptyArray; - for (let i = 0; i < q.length; i++) { - const item = q[i]; - // Use the error marking that it was not written - item.callback(this.error); - } - } -} - -module.exports = { FrameWriter, WriteQueue }; diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/package.json b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/package.json deleted file mode 100644 index ff12d0c16a..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/cassandra-driver/package.json +++ /dev/null @@ -1,82 +0,0 @@ -{ - "_from": "cassandra-driver@^4.6.0", - "_id": "cassandra-driver@4.6.0", - "_inBundle": false, - "_integrity": "sha512-OCYJ3Zuy2La0qf+7dfeYlG3X4C0ns1cbPu0hhpC3xyUWqTy1Ai9a4mlQjSBqbcHi51gdFB5UbS0fWJzZIY6NXw==", - "_location": "/cassandra-driver", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "cassandra-driver@^4.6.0", - "name": "cassandra-driver", - "escapedName": "cassandra-driver", - "rawSpec": "^4.6.0", - "saveSpec": null, - "fetchSpec": "^4.6.0" - }, - "_requiredBy": [ - "#USER", - "/" - ], - "_resolved": "https://registry.npmjs.org/cassandra-driver/-/cassandra-driver-4.6.0.tgz", - "_shasum": "fd10fecb7069cb2e499b58efffbd05166020a314", - "_spec": "cassandra-driver@^4.6.0", - "_where": "/home/jan/Documents/skweb", - "author": { - "name": "DataStax" - }, - "bugs": { - "url": "https://groups.google.com/a/lists.datastax.com/forum/#!forum/nodejs-driver-user" - }, - "bundleDependencies": false, - "dependencies": { - "@types/long": "^4.0.0", - "@types/node": ">=8", - "adm-zip": "^0.4.13", - "long": "^2.2.0" - }, - "deprecated": false, - "description": "DataStax Node.js Driver for Apache Cassandra", - "devDependencies": { - "chai": "4.2.0", - "mocha": "~7.1.1", - "proxyquire": "~2.1.3", - "sinon": "~7.5.0", - "temp": ">= 0.8.3" - }, - "engines": { - "node": ">=8" - }, - "homepage": "https://github.com/datastax/nodejs-driver#readme", - "keywords": [ - "cassandra", - "cql", - "cql3", - "connection", - "gremlin", - "datastax", - "nosql", - "driver", - "database", - "dse", - "graph", - "graphdb" - ], - "license": "Apache-2.0", - "name": "cassandra-driver", - "repository": { - "type": "git", - "url": "git+https://github.com/datastax/nodejs-driver.git" - }, - "scripts": { - "ci_appveyor": "mocha test/unit test/integration/short --recursive -R mocha-appveyor-reporter --exit", - "ci_jenkins": "mocha test/unit test/integration/short --recursive -R mocha-jenkins-reporter --exit", - "ci_unit_appveyor": "mocha test/unit --recursive -R mocha-appveyor-reporter --exit", - "eslint": "eslint lib test", - "server_api": "mocha test/integration/short -g '@SERVER_API' --recursive --exit", - "test": "mocha test/unit -R spec -t 5000 --recursive" - }, - "types": "./index.d.ts", - "version": "4.6.0" -} diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/chalk/index.js b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/chalk/index.js deleted file mode 100644 index 2d85a91747..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/chalk/index.js +++ /dev/null @@ -1,116 +0,0 @@ -'use strict'; -var escapeStringRegexp = require('escape-string-regexp'); -var ansiStyles = require('ansi-styles'); -var stripAnsi = require('strip-ansi'); -var hasAnsi = require('has-ansi'); -var supportsColor = require('supports-color'); -var defineProps = Object.defineProperties; -var isSimpleWindowsTerm = process.platform === 'win32' && !/^xterm/i.test(process.env.TERM); - -function Chalk(options) { - // detect mode if not set manually - this.enabled = !options || options.enabled === undefined ? supportsColor : options.enabled; -} - -// use bright blue on Windows as the normal blue color is illegible -if (isSimpleWindowsTerm) { - ansiStyles.blue.open = '\u001b[94m'; -} - -var styles = (function () { - var ret = {}; - - Object.keys(ansiStyles).forEach(function (key) { - ansiStyles[key].closeRe = new RegExp(escapeStringRegexp(ansiStyles[key].close), 'g'); - - ret[key] = { - get: function () { - return build.call(this, this._styles.concat(key)); - } - }; - }); - - return ret; -})(); - -var proto = defineProps(function chalk() {}, styles); - -function build(_styles) { - var builder = function () { - return applyStyle.apply(builder, arguments); - }; - - builder._styles = _styles; - builder.enabled = this.enabled; - // __proto__ is used because we must return a function, but there is - // no way to create a function with a different prototype. - /* eslint-disable no-proto */ - builder.__proto__ = proto; - - return builder; -} - -function applyStyle() { - // support varags, but simply cast to string in case there's only one arg - var args = arguments; - var argsLen = args.length; - var str = argsLen !== 0 && String(arguments[0]); - - if (argsLen > 1) { - // don't slice `arguments`, it prevents v8 optimizations - for (var a = 1; a < argsLen; a++) { - str += ' ' + args[a]; - } - } - - if (!this.enabled || !str) { - return str; - } - - var nestedStyles = this._styles; - var i = nestedStyles.length; - - // Turns out that on Windows dimmed gray text becomes invisible in cmd.exe, - // see https://github.com/chalk/chalk/issues/58 - // If we're on Windows and we're dealing with a gray color, temporarily make 'dim' a noop. - var originalDim = ansiStyles.dim.open; - if (isSimpleWindowsTerm && (nestedStyles.indexOf('gray') !== -1 || nestedStyles.indexOf('grey') !== -1)) { - ansiStyles.dim.open = ''; - } - - while (i--) { - var code = ansiStyles[nestedStyles[i]]; - - // Replace any instances already present with a re-opening code - // otherwise only the part of the string until said closing code - // will be colored, and the rest will simply be 'plain'. - str = code.open + str.replace(code.closeRe, code.open) + code.close; - } - - // Reset the original 'dim' if we changed it to work around the Windows dimmed gray issue. - ansiStyles.dim.open = originalDim; - - return str; -} - -function init() { - var ret = {}; - - Object.keys(styles).forEach(function (name) { - ret[name] = { - get: function () { - return build.call(this, [name]); - } - }; - }); - - return ret; -} - -defineProps(Chalk.prototype, init()); - -module.exports = new Chalk(); -module.exports.styles = ansiStyles; -module.exports.hasColor = hasAnsi; -module.exports.stripColor = stripAnsi; -module.exports.supportsColor = supportsColor; diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/chalk/license b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/chalk/license deleted file mode 100644 index 654d0bfe94..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/chalk/license +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) Sindre Sorhus (sindresorhus.com) - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/chalk/package.json b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/chalk/package.json deleted file mode 100644 index 82bffb167e..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/chalk/package.json +++ /dev/null @@ -1,114 +0,0 @@ -{ - "_from": "chalk@^1.0.0", - "_id": "chalk@1.1.3", - "_inBundle": false, - "_integrity": "sha1-qBFcVeSnAv5NFQq9OHKCKn4J/Jg=", - "_location": "/chalk", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "chalk@^1.0.0", - "name": "chalk", - "escapedName": "chalk", - "rawSpec": "^1.0.0", - "saveSpec": null, - "fetchSpec": "^1.0.0" - }, - "_requiredBy": [ - "/elasticsearch" - ], - "_resolved": "https://registry.npmjs.org/chalk/-/chalk-1.1.3.tgz", - "_shasum": "a8115c55e4a702fe4d150abd3872822a7e09fc98", - "_spec": "chalk@^1.0.0", - "_where": "/home/jan/Documents/skweb/node_modules/elasticsearch", - "bugs": { - "url": "https://github.com/chalk/chalk/issues" - }, - "bundleDependencies": false, - "dependencies": { - "ansi-styles": "^2.2.1", - "escape-string-regexp": "^1.0.2", - "has-ansi": "^2.0.0", - "strip-ansi": "^3.0.0", - "supports-color": "^2.0.0" - }, - "deprecated": false, - "description": "Terminal string styling done right. Much color.", - "devDependencies": { - "coveralls": "^2.11.2", - "matcha": "^0.6.0", - "mocha": "*", - "nyc": "^3.0.0", - "require-uncached": "^1.0.2", - "resolve-from": "^1.0.0", - "semver": "^4.3.3", - "xo": "*" - }, - "engines": { - "node": ">=0.10.0" - }, - "files": [ - "index.js" - ], - "homepage": "https://github.com/chalk/chalk#readme", - "keywords": [ - "color", - "colour", - "colors", - "terminal", - "console", - "cli", - "string", - "str", - "ansi", - "style", - "styles", - "tty", - "formatting", - "rgb", - "256", - "shell", - "xterm", - "log", - "logging", - "command-line", - "text" - ], - "license": "MIT", - "maintainers": [ - { - "name": "Sindre Sorhus", - "email": "sindresorhus@gmail.com", - "url": "sindresorhus.com" - }, - { - "name": "Joshua Appelman", - "email": "jappelman@xebia.com", - "url": "jbnicolai.com" - }, - { - "name": "JD Ballard", - "email": "i.am.qix@gmail.com", - "url": "github.com/qix-" - } - ], - "name": "chalk", - "repository": { - "type": "git", - "url": "git+https://github.com/chalk/chalk.git" - }, - "scripts": { - "bench": "matcha benchmark.js", - "coverage": "nyc npm test && nyc report", - "coveralls": "nyc npm test && nyc report --reporter=text-lcov | coveralls", - "test": "xo && mocha" - }, - "version": "1.1.3", - "xo": { - "envs": [ - "node", - "mocha" - ] - } -} diff --git a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/chalk/readme.md b/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/chalk/readme.md deleted file mode 100644 index 5cf111e353..0000000000 --- a/pages/students/2016/jan_holp/dp2021/dp2021 zdrojove subory/node_modules/chalk/readme.md +++ /dev/null @@ -1,213 +0,0 @@ -

-
-
- chalk -
-
-
-

- -> Terminal string styling done right - -[![Build Status](https://travis-ci.org/chalk/chalk.svg?branch=master)](https://travis-ci.org/chalk/chalk) -[![Coverage Status](https://coveralls.io/repos/chalk/chalk/badge.svg?branch=master)](https://coveralls.io/r/chalk/chalk?branch=master) -[![](http://img.shields.io/badge/unicorn-approved-ff69b4.svg)](https://www.youtube.com/watch?v=9auOCbH5Ns4) - - -[colors.js](https://github.com/Marak/colors.js) used to be the most popular string styling module, but it has serious deficiencies like extending `String.prototype` which causes all kinds of [problems](https://github.com/yeoman/yo/issues/68). Although there are other ones, they either do too much or not enough. - -**Chalk is a clean and focused alternative.** - -![](https://github.com/chalk/ansi-styles/raw/master/screenshot.png) - - -## Why - -- Highly performant -- Doesn't extend `String.prototype` -- Expressive API -- Ability to nest styles -- Clean and focused -- Auto-detects color support -- Actively maintained -- [Used by ~4500 modules](https://www.npmjs.com/browse/depended/chalk) as of July 15, 2015 - - -## Install - -``` -$ npm install --save chalk -``` - - -## Usage - -Chalk comes with an easy to use composable API where you just chain and nest the styles you want. - -```js -var chalk = require('chalk'); - -// style a string -chalk.blue('Hello world!'); - -// combine styled and normal strings -chalk.blue('Hello') + 'World' + chalk.red('!'); - -// compose multiple styles using the chainable API -chalk.blue.bgRed.bold('Hello world!'); - -// pass in multiple arguments -chalk.blue('Hello', 'World!', 'Foo', 'bar', 'biz', 'baz'); - -// nest styles -chalk.red('Hello', chalk.underline.bgBlue('world') + '!'); - -// nest styles of the same type even (color, underline, background) -chalk.green( - 'I am a green line ' + - chalk.blue.underline.bold('with a blue substring') + - ' that becomes green again!' -); -``` - -Easily define your own themes. - -```js -var chalk = require('chalk'); -var error = chalk.bold.red; -console.log(error('Error!')); -``` - -Take advantage of console.log [string substitution](http://nodejs.org/docs/latest/api/console.html#console_console_log_data). - -```js -var name = 'Sindre'; -console.log(chalk.green('Hello %s'), name); -//=> Hello Sindre -``` - - -## API - -### chalk.`