├── .babelrc ├── .circleci └── config.yml ├── .eslintignore ├── .eslintrc.json ├── .github └── dependabot.yml ├── .gitignore ├── .prettierignore ├── .prettierrc.js ├── .tool-versions ├── LICENSE ├── README.md ├── build └── src │ ├── api.d.ts │ ├── api.js │ ├── api.js.map │ ├── api.test.d.ts │ ├── api.test.js │ ├── api.test.js.map │ ├── common.d.ts │ ├── common.js │ ├── common.js.map │ ├── events.d.ts │ ├── events.js │ ├── events.js.map │ ├── events.test.d.ts │ ├── events.test.js │ ├── events.test.js.map │ ├── index.d.ts │ ├── index.js │ ├── index.js.map │ ├── retries.test.d.ts │ ├── retries.test.js │ └── retries.test.js.map ├── dist ├── pdjs-legacy.js ├── pdjs-legacy.js.map ├── pdjs.js └── pdjs.js.map ├── examples ├── browser.html └── node.js ├── jest.config.js ├── package-lock.json ├── package.json ├── src ├── api.test.ts ├── api.ts ├── common.ts ├── decs.d.ts ├── events.test.ts ├── events.ts ├── index.ts └── retries.test.ts ├── tsconfig.json ├── tslint.json └── webpack.config.js /.babelrc: -------------------------------------------------------------------------------- 1 | { 2 | "presets": ["@babel/env", "@babel/typescript"], 3 | "plugins": [ 4 | "@babel/proposal-class-properties", 5 | "@babel/proposal-object-rest-spread" 6 | ] 7 | } 8 | -------------------------------------------------------------------------------- /.circleci/config.yml: -------------------------------------------------------------------------------- 1 | version: 2.1 2 | 3 | executors: 4 | base: 5 | docker: 6 | - image: cimg/node:16.13.2 7 | working_directory: /home/circleci/pdjs 8 | 9 | jobs: 10 | build: 11 | executor: base 12 | steps: 13 | - checkout 14 | - restore_cache: 15 | key: dependency-cache-{{ checksum "package-lock.json" }} 16 | - run: 17 | name: Install NPM 18 | command: npm ci --prefer-offline 19 | - save_cache: 20 | key: dependency-cache-{{ checksum "package-lock.json" }} 21 | paths: 22 | - ./node_modules 23 | - run: 24 | name: Build packages 25 | command: npm run build 26 | - store_artifacts: 27 | path: dist 28 | lint: 29 | executor: base 30 | steps: 31 | - checkout 32 | - restore_cache: 33 | key: dependency-cache-{{ checksum "package-lock.json" }} 34 | - run: 35 | name: Install NPM 36 | command: npm ci --prefer-offline 37 | - save_cache: 38 | key: dependency-cache-{{ checksum "package-lock.json" }} 39 | paths: 40 | - ./node_modules 41 | - run: 42 | name: Lint 43 | command: npm run lint 44 | test: 45 | executor: base 46 | steps: 47 | - checkout 48 | - restore_cache: 49 | key: dependency-cache-{{ checksum "package-lock.json" }} 50 | - run: 51 | name: Install NPM 52 | command: npm ci --prefer-offline 53 | - save_cache: 54 | key: dependency-cache-{{ checksum "package-lock.json" }} 55 | paths: 56 | - ./node_modules 57 | - run: 58 | name: Test 59 | command: npm run test 60 | 61 | 62 | workflows: 63 | build-and-test: 64 | jobs: 65 | - build 66 | - lint 67 | - test 68 | -------------------------------------------------------------------------------- /.eslintignore: -------------------------------------------------------------------------------- 1 | dist/* 2 | build/* 3 | -------------------------------------------------------------------------------- /.eslintrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "./node_modules/gts/" 3 | } 4 | -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | 3 | updates: 4 | - package-ecosystem: npm 5 | directory: "/" 6 | schedule: 7 | interval: weekly 8 | open-pull-requests-limit: 10 9 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | -------------------------------------------------------------------------------- /.prettierignore: -------------------------------------------------------------------------------- 1 | build 2 | dist -------------------------------------------------------------------------------- /.prettierrc.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | ...require('gts/.prettierrc.json'), 3 | }; 4 | -------------------------------------------------------------------------------- /.tool-versions: -------------------------------------------------------------------------------- 1 | nodejs 16.13.2 2 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # README 2 | 3 | A simple JavaScript wrapper for the PagerDuty APIs. 4 | 5 | - Supports Node and Browser environments 6 | - Supports REST and Events v2 APIs. 7 | - Supports both offset and cursor based pagination 8 | 9 | For full [API Reference see this page.](https://developer.pagerduty.com/api-reference) 10 | 11 | ## Installation 12 | 13 | ```bash 14 | npm install --save @pagerduty/pdjs 15 | ``` 16 | 17 | ## Usage 18 | 19 | ### REST API 20 | 21 | REST API calls can be done using the convenience methods or by passing in a `url` or `endpoint`. 22 | 23 | #### Convenience Methods 24 | 25 | There are some simple convience methods. `get()`, `post()`, `put()`, and `delete()`. 26 | 27 | ```javascript 28 | import {api} from '@pagerduty/pdjs'; 29 | 30 | const pd = api({token: 'someToken1234567890'}); 31 | 32 | pd.get('/incidents') 33 | .then({data, resource, next} => console.log(data, resource, next)) 34 | .catch(console.error); 35 | 36 | // Similarly, for `post`, `put`, `patch` and `delete`. 37 | pd.post('/incidents', { data: { ... } }).then(...); 38 | 39 | // If you need to supply headers: 40 | pd.post('/incidents/id/status_updates', { 41 | headers: { 42 | From: 'user@example.com', 43 | }, 44 | data: { ... }, 45 | }).then(); 46 | ``` 47 | 48 | #### `tokenType` 49 | 50 | Allows you to set either `token` or `bearer` tokens. Defaults to `token` but provides ability to use `bearer` as well. 51 | 52 | - [Tokens](https://developer.pagerduty.com/docs/rest-api-v2/authentication/) are generated in your PagerDuty account. 53 | - **Bearer** tokens are generated through an [OAuth 2.0](https://developer.pagerduty.com/docs/app-integration-development/oauth-2-functionality/) authorization flow. For example, to use a Bearer token when initializing `api` you'll pass int the `tokenType` parameter, like so: 54 | 55 | ```javascript 56 | const pd = api({token: 'someBearerToken1234567890', tokenType: 'bearer'}); 57 | ``` 58 | 59 | #### `url` or `endpoint` 60 | 61 | ```javascript 62 | // Calling the returned function with a `endpoint` or `url` will also send it. 63 | pd({ 64 | method: 'post', 65 | endpoint: '/incidents', 66 | data: { 67 | ... 68 | } 69 | }).then(...) 70 | ``` 71 | 72 | #### The Response Object 73 | 74 | The PD object always returns an APIResponse object which contains some raw data as well as a convenient shortcut to directly access the returns Resource. 75 | 76 | ```javascript 77 | 78 | pd.get('/incidents') 79 | .then({resource, data, response, next} => { 80 | console.log(resource); // Contains the data of resource request. In this example the 'incidents' data. 81 | console.log(data); // The raw data returned from the API, also contains pagination information. 82 | console.log(response); // The response object returned from the cross-fetch 83 | console.log(next); // A convenience function to help with pagination 84 | }) 85 | .catch(console.error); 86 | 87 | ``` 88 | 89 | #### Pagination 90 | 91 | There's an convience method `all` that attempts to fetch all pages for a given endpoint and set of parameters. For convenience this function supports both offset and cursor based pagination. 92 | 93 | Note that the PagerDuty API has a limit for most endpoints and recommends using parameters to refine searches where more results are necessary. More information can be found in the [Developer Documentation.](https://developer.pagerduty.com/docs/rest-api-v2/pagination/) 94 | 95 | The response object of an API call also contains a `nextFunc` which can be used to define your own Pagination function if you feel included. 96 | 97 | ```javascript 98 | import {api} from '@pagerduty/pdjs'; 99 | 100 | const pd = api({token: 'someToken1234567890'}); 101 | 102 | pd.all('/incidents') 103 | .then({data, resource} => console.log(data, resource)) 104 | .catch(console.error); 105 | ``` 106 | 107 | #### Options 108 | 109 | The API interface allows for some extra parameters to be included. 110 | 111 | ##### `server` 112 | 113 | To use this library with a different service region use this parameter to change the root url of requests. Default: `api.pagerduty.com`. 114 | 115 | ```javascript 116 | pd({ 117 | method: 'post', 118 | endpoint: '/incidents', 119 | server: 'api.eu.pagerduty.com', 120 | data: { 121 | ... 122 | } 123 | }).then(...) 124 | ``` 125 | 126 | ##### `headers` 127 | 128 | Some endpoints require the setting of extra `headers` such as a `From` header. 129 | 130 | ```javascript 131 | pd({ 132 | method: 'post', 133 | endpoint: '/incidents', 134 | headers: { 135 | 'From': "me@example.com" 136 | }, 137 | data: { 138 | ... 139 | } 140 | }).then(...) 141 | ``` 142 | 143 | ### Retries 144 | 145 | There is some very simple retry logic baked into each request in the case that the PagerDuty API rate limits your requests (only when it responds HTTP Code 429). Requests will retry 3 times waiting 20 seconds between each request. If the request is still being rate limited after 3 attempts the client will simply return the 429 response. 146 | 147 | ### Events API 148 | 149 | Events V2 is supported along with Change Events. 150 | 151 | ```javascript 152 | import {event} from '@pagerduty/pdjs'; 153 | event({ 154 | data: { 155 | routing_key: 'YOUR_ROUTING_KEY', 156 | event_action: 'trigger', 157 | dedup_key: 'test_incident_2_88f520', 158 | payload: { 159 | summary: 'Test Event V2', 160 | source: 'test-source', 161 | severity: 'error', 162 | }, 163 | }, 164 | }) 165 | .then(console.log) 166 | .catch(console.error); 167 | ``` 168 | 169 | #### Convenience Methods 170 | 171 | ```javascript 172 | import {change, trigger, acknowledge, resolve} from '@pagerduty/pdjs'; 173 | 174 | change({ 175 | "routing_key": "YOUR_ROUTING_KEY", 176 | "payload": { 177 | "summary": "Build Success:!", 178 | "timestamp": "2015-07-17T08:42:58.315+0000", 179 | "source": "prod-build-agent", 180 | "custom_details": { 181 | "build_state": "passed", 182 | "build_number": "220", 183 | "run_time": "1337s" 184 | } 185 | }, 186 | "links": [{ 187 | "href": "https://buildpipeline.com", 188 | "text": "View in Build Pipeline" 189 | }] 190 | }) 191 | .then(console.log) 192 | .catch(console.error); 193 | 194 | trigger({...}) 195 | .then(console.log) 196 | .catch(console.error); 197 | acknowledge({...}) 198 | .then(console.log) 199 | .catch(console.error); 200 | resolve({...}) 201 | .then(console.log) 202 | .catch(console.error); 203 | ``` 204 | 205 | ### Browser 206 | 207 | Two browser-ready scripts are provided: 208 | 209 | - [dist/pdjs.js](https://raw.githubusercontent.com/PagerDuty/pdjs/main/dist/pdjs.js): For browsers supporting `fetch`. 210 | - [dist/pdjs-legacy.js](https://raw.githubusercontent.com/PagerDuty/pdjs/main/dist/pdjs-legacy.js): For older browsers requiring a `fetch` polyfill -- mostly IE 11. 211 | 212 | Either of these files can be used by copying them into your project and including them directly, with all functions namespaced `PagerDuty`: 213 | 214 | ```html 215 | 216 | 221 | ``` 222 | -------------------------------------------------------------------------------- /build/src/api.d.ts: -------------------------------------------------------------------------------- 1 | import { RequestOptions } from './common'; 2 | export interface ShorthandCall { 3 | (res: string, apiParameters?: Partial): APIPromise; 4 | } 5 | export interface PartialCall { 6 | (apiParameters: APIParameters): APIPromise; 7 | (apiParameters: Partial): PartialCall; 8 | get: ShorthandCall; 9 | post: ShorthandCall; 10 | put: ShorthandCall; 11 | patch: ShorthandCall; 12 | delete: ShorthandCall; 13 | all: ShorthandCall; 14 | } 15 | export declare type APIParameters = RequestOptions & { 16 | endpoint?: string; 17 | url?: string; 18 | data?: object; 19 | token?: string; 20 | tokenType?: string; 21 | server?: string; 22 | version?: number; 23 | } & ({ 24 | endpoint: string; 25 | } | { 26 | url: string; 27 | }); 28 | export declare type APIPromise = Promise; 29 | export interface APIResponse extends Response { 30 | data: any; 31 | resource: any; 32 | response: Response; 33 | next?: () => APIPromise; 34 | } 35 | export declare function api(apiParameters: APIParameters): APIPromise; 36 | export declare function api(apiParameters: Partial): PartialCall; 37 | -------------------------------------------------------------------------------- /build/src/api.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | Object.defineProperty(exports, "__esModule", { value: true }); 3 | exports.api = void 0; 4 | const common_1 = require("./common"); 5 | function api(apiParameters) { 6 | var _a; 7 | // If the apiParameters don't include `endpoint` treat it as a partial 8 | // application. 9 | if (!apiParameters.endpoint && !apiParameters.url) { 10 | return partialCall(apiParameters); 11 | } 12 | const types = { 13 | bearer: 'Bearer ', 14 | token: 'Token token=', 15 | }; 16 | const { endpoint, server = 'api.pagerduty.com', token, tokenType = apiParameters.tokenType || 'token', url, version = 2, data, ...rest } = apiParameters; 17 | const config = { 18 | method: 'GET', 19 | ...rest, 20 | headers: { 21 | Accept: `application/vnd.pagerduty+json;version=${version}`, 22 | Authorization: `${types[tokenType]}${token}`, 23 | ...rest.headers, 24 | }, 25 | }; 26 | // Allow `data` for `queryParameters` for requests without bodies. 27 | if (isReadonlyRequest(config.method) && data) { 28 | config.queryParameters = 29 | (_a = config.queryParameters) !== null && _a !== void 0 ? _a : data; 30 | } 31 | else { 32 | config.body = JSON.stringify(data); 33 | } 34 | return apiRequest(url !== null && url !== void 0 ? url : `https://${server}/${endpoint.replace(/^\/+/, '')}`, config); 35 | } 36 | exports.api = api; 37 | function apiRequest(url, options) { 38 | return (0, common_1.request)(url, options).then((response) => { 39 | const apiResponse = response; 40 | apiResponse.response = response; 41 | if (response.status === 204) { 42 | return Promise.resolve(apiResponse); 43 | } 44 | return response 45 | .json() 46 | .then((data) => { 47 | const resource = resourceKey(url, options.method); 48 | apiResponse.next = nextFunc(url, options, data); 49 | apiResponse.data = data; 50 | apiResponse.resource = resource ? data[resource] : null; 51 | return apiResponse; 52 | }) 53 | .catch(() => Promise.reject(apiResponse)); 54 | }); 55 | } 56 | function resourceKey(url, method) { 57 | const resource = url.match(/.+.com\/(?[\w]+)/); 58 | if (resource) { 59 | const resourceName = resource[1]; 60 | if (method && method.toLowerCase() === 'get') { 61 | return resourceName; 62 | } 63 | if (resourceName.endsWith('ies')) { 64 | return resourceName.slice(0, -3) + 'y'; 65 | } 66 | else if (resourceName.endsWith('s')) { 67 | return resourceName.slice(0, -1); 68 | } 69 | return resourceName; 70 | } 71 | return null; 72 | } 73 | function isReadonlyRequest(method) { 74 | var _a; 75 | return !['PUT', 'POST', 'DELETE', 'PATCH'].includes((_a = method.toUpperCase()) !== null && _a !== void 0 ? _a : 'GET'); 76 | } 77 | function isOffsetPagination(data) { 78 | if (data.offset !== undefined) { 79 | return true; 80 | } 81 | return false; 82 | } 83 | function isCursorPagination(data) { 84 | if (data.cursor !== undefined) { 85 | return true; 86 | } 87 | return false; 88 | } 89 | function nextFunc(url, options, data) { 90 | if (isOffsetPagination(data)) { 91 | if ((data === null || data === void 0 ? void 0 : data.more) && typeof data.offset !== undefined && data.limit) { 92 | return () => apiRequest(url, { 93 | ...options, 94 | queryParameters: { 95 | ...options.queryParameters, 96 | limit: data.limit.toString(), 97 | offset: (data.limit + data.offset).toString(), 98 | }, 99 | }); 100 | } 101 | } 102 | else if (isCursorPagination(data)) { 103 | if (data === null || data === void 0 ? void 0 : data.cursor) { 104 | return () => apiRequest(url, { 105 | ...options, 106 | queryParameters: { 107 | ...options.queryParameters, 108 | cursor: data.cursor, 109 | limit: data.limit.toString(), 110 | }, 111 | }); 112 | } 113 | } 114 | return undefined; 115 | } 116 | function partialCall(apiParameters) { 117 | const partialParameters = apiParameters; 118 | const partial = ((apiParameters) => api({ ...partialParameters, ...apiParameters })); 119 | const shorthand = (method) => (endpoint, shorthandParameters) => api({ 120 | endpoint, 121 | method, 122 | ...partialParameters, 123 | ...shorthandParameters, 124 | }); 125 | partial.get = shorthand('get'); 126 | partial.post = shorthand('post'); 127 | partial.put = shorthand('put'); 128 | partial.patch = shorthand('patch'); 129 | partial.delete = shorthand('delete'); 130 | partial.all = (endpoint, shorthandParameters) => { 131 | function allInner(responses) { 132 | const response = responses[responses.length - 1]; 133 | if (!response.next) { 134 | // Base case, resolve and return all responses. 135 | return Promise.resolve(responses); 136 | } 137 | // If there are still more resources to get then concat and repeat. 138 | return response 139 | .next() 140 | .then(response => allInner(responses.concat([response]))); 141 | } 142 | function repackResponses(responses) { 143 | // Repack the responses object to make it more user friendly. 144 | const repackedResponse = responses.shift(); // Use the first response to build the standard response object 145 | repackedResponse.data = [repackedResponse.data]; 146 | responses.forEach(response => { 147 | repackedResponse.data = repackedResponse.data.concat(response.data); 148 | repackedResponse.resource = repackedResponse.resource.concat(response.resource); 149 | }); 150 | return Promise.resolve(repackedResponse); 151 | } 152 | const method = 'get'; 153 | return api({ 154 | endpoint, 155 | method, 156 | ...partialParameters, 157 | ...shorthandParameters, 158 | }) 159 | .then(response => allInner([response])) 160 | .then(responses => repackResponses(responses)); 161 | }; 162 | return partial; 163 | } 164 | //# sourceMappingURL=api.js.map -------------------------------------------------------------------------------- /build/src/api.js.map: -------------------------------------------------------------------------------- 1 | {"version":3,"file":"api.js","sourceRoot":"","sources":["../../src/api.ts"],"names":[],"mappings":";;;AAAA,qCAAiD;AAsCjD,SAAgB,GAAG,CACjB,aAAqC;;IAErC,sEAAsE;IACtE,eAAe;IACf,IAAI,CAAC,aAAa,CAAC,QAAQ,IAAI,CAAC,aAAa,CAAC,GAAG,EAAE;QACjD,OAAO,WAAW,CAAC,aAAa,CAAC,CAAC;KACnC;IAOD,MAAM,KAAK,GAAY;QACrB,MAAM,EAAE,SAAS;QACjB,KAAK,EAAE,cAAc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CAAC,SAAS,CAAC,MAAM,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,CAAC;QAC9D,CAAC;QAED,SAAS,eAAe,CAAC,SAAwB;YAC/C,6DAA6D;YAC7D,MAAM,gBAAgB,GAAG,SAAS,CAAC,KAAK,EAAiB,CAAC,CAAC,+DAA+D;YAC1H,gBAAgB,CAAC,IAAI,GAAG,CAAC,gBAAgB,CAAC,IAAI,CAAC,CAAC;YAChD,SAAS,CAAC,OAAO,CAAC,QAAQ,CAAC,EAAE;gBAC3B,gBAAgB,CAAC,IAAI,GAAG,gBAAgB,CAAC,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC;gBACpE,gBAAgB,CAAC,QAAQ,GAAG,gBAAgB,CAAC,QAAQ,CAAC,MAAM,CAC1D,QAAQ,CAAC,QAAQ,CAClB,CAAC;YACJ,CAAC,CAAC,CAAC;YACH,OAAO,OAAO,CAAC,OAAO,CAAC,gBAAgB,CAAC,CAAC;QAC3C,CAAC;QAED,MAAM,MAAM,GAAG,KAAK,CAAC;QACrB,OAAQ,GAAG,CAAC;YACV,QAAQ;YACR,MAAM;YACN,GAAG,iBAAiB;YACpB,GAAG,mBAAmB;SACvB,CAAgB;aACd,IAAI,CAAC,QAAQ,CAAC,EAAE,CAAC,QAAQ,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC;aACtC,IAAI,CAAC,SAAS,CAAC,EAAE,CAAC,eAAe,CAAC,SAAS,CAAC,CAAC,CAAC;IACnD,CAAC,CAAC;IAEF,OAAO,OAAO,CAAC;AACjB,CAAC"} -------------------------------------------------------------------------------- /build/src/api.test.d.ts: -------------------------------------------------------------------------------- 1 | export {}; 2 | -------------------------------------------------------------------------------- /build/src/api.test.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | Object.defineProperty(exports, "__esModule", { value: true }); 3 | const nock = require("nock"); 4 | const index_1 = require("./index"); 5 | const EMPTY_BODY = { 6 | incidents: [], 7 | limit: 25, 8 | offset: 0, 9 | total: null, 10 | more: false, 11 | }; 12 | test('API calls return JSON for basic API calls with server', async () => { 13 | nock('https://api.pagerduty.com', { 14 | reqheaders: { 15 | Authorization: 'Token token=someToken1234567890', 16 | 'User-Agent': header => header.startsWith('pdjs'), 17 | }, 18 | }) 19 | .get('/incidents') 20 | .reply(200, EMPTY_BODY); 21 | const resp = await (0, index_1.api)({ 22 | token: 'someToken1234567890', 23 | server: 'api.pagerduty.com', 24 | endpoint: 'incidents', 25 | }); 26 | expect(resp.url).toEqual('https://api.pagerduty.com/incidents'); 27 | expect(resp.data).toEqual(EMPTY_BODY); 28 | }); 29 | test('API calls return JSON for basic API calls with url', async () => { 30 | nock('https://api.pagerduty.com', { 31 | reqheaders: { 32 | Authorization: 'Token token=someToken1234567890', 33 | 'User-Agent': header => header.startsWith('pdjs'), 34 | }, 35 | }) 36 | .get('/incidents') 37 | .reply(200, EMPTY_BODY); 38 | const resp = await (0, index_1.api)({ 39 | token: 'someToken1234567890', 40 | url: 'https://api.pagerduty.com/incidents', 41 | }); 42 | expect(resp.url).toEqual('https://api.pagerduty.com/incidents'); 43 | expect(resp.data).toEqual(EMPTY_BODY); 44 | }); 45 | test('API calls return JSON for basic API calls with endpoint', async () => { 46 | nock('https://api.pagerduty.com', { 47 | reqheaders: { 48 | Authorization: 'Token token=someToken1234567890', 49 | 'User-Agent': header => header.startsWith('pdjs'), 50 | }, 51 | }) 52 | .get('/incidents') 53 | .reply(200, EMPTY_BODY); 54 | const resp = await (0, index_1.api)({ 55 | token: 'someToken1234567890', 56 | endpoint: 'incidents', 57 | }); 58 | expect(resp.url).toEqual('https://api.pagerduty.com/incidents'); 59 | expect(resp.data).toEqual(EMPTY_BODY); 60 | }); 61 | test('API calls return successfully on DELETE endpoints', async () => { 62 | nock('https://api.pagerduty.com', { 63 | reqheaders: { 64 | Authorization: 'Token token=someToken1234567890', 65 | 'User-Agent': header => header.startsWith('pdjs'), 66 | }, 67 | }) 68 | .delete('/incidents/delete') 69 | .reply(204); 70 | const pd = (0, index_1.api)({ token: 'someToken1234567890' }); 71 | const response = await pd.delete('/incidents/delete'); 72 | expect(response.url).toEqual('https://api.pagerduty.com/incidents/delete'); 73 | expect(response.data).toEqual(undefined); 74 | }); 75 | test('API calls support partial application with url', async () => { 76 | nock('https://api.pagerduty.com', { 77 | reqheaders: { 78 | Authorization: 'Token token=someToken1234567890', 79 | 'User-Agent': header => header.startsWith('pdjs'), 80 | }, 81 | }) 82 | .get('/incidents') 83 | .reply(200, EMPTY_BODY); 84 | const pd = (0, index_1.api)({ token: 'someToken1234567890' }); 85 | const resp = await pd({ 86 | url: 'https://api.pagerduty.com/incidents', 87 | }); 88 | expect(resp.url).toEqual('https://api.pagerduty.com/incidents'); 89 | expect(resp.data).toEqual(EMPTY_BODY); 90 | }); 91 | test('API calls support partial application with convenience methods', async () => { 92 | nock('https://api.pagerduty.com', { 93 | reqheaders: { 94 | Authorization: 'Token token=someToken1234567890', 95 | 'User-Agent': header => header.startsWith('pdjs'), 96 | }, 97 | }) 98 | .get('/incidents') 99 | .reply(200, EMPTY_BODY); 100 | const resp = await (0, index_1.api)({ token: 'someToken1234567890' }).get('/incidents'); 101 | expect(resp.url).toEqual('https://api.pagerduty.com/incidents'); 102 | expect(resp.data).toEqual(EMPTY_BODY); 103 | }); 104 | test('API calls use data in place of queryParameters when provided on GET requests', async () => { 105 | nock('https://api.pagerduty.com') 106 | .get('/incidents?sort_by=created_at&total=true') 107 | .reply(200, EMPTY_BODY); 108 | const resp = await (0, index_1.api)({ 109 | token: 'someToken1234567890', 110 | endpoint: '/incidents', 111 | data: { sort_by: 'created_at', total: true }, 112 | }); 113 | expect(resp.url).toEqual('https://api.pagerduty.com/incidents?sort_by=created_at&total=true'); 114 | expect(resp.data).toEqual(EMPTY_BODY); 115 | }); 116 | test('API calls populate resource field', async () => { 117 | nock('https://api.pagerduty.com') 118 | .get('/incidents') 119 | .reply(200, { 120 | incidents: ['one', 1, null], 121 | limit: 25, 122 | offset: 0, 123 | total: null, 124 | more: false, 125 | }); 126 | nock('https://api.pagerduty.com') 127 | .post('/incidents') 128 | .reply(201, { 129 | incident: ['some incident'], 130 | }); 131 | const respGet = await (0, index_1.api)({ 132 | token: 'someToken1234567890', 133 | endpoint: '/incidents', 134 | }); 135 | expect(respGet.resource).toEqual(['one', 1, null]); 136 | const respPost = await (0, index_1.api)({ 137 | token: 'someToken1234567890', 138 | endpoint: '/incidents', 139 | method: 'POST', 140 | }); 141 | expect(respPost.resource).toEqual(['some incident']); 142 | }); 143 | test('API explodes list based parameters properly', async () => { 144 | nock('https://api.pagerduty.com') 145 | .get('/incidents?additional_fields[]=one&additional_fields[]=two&additional_fields[]=three') 146 | .reply(200, { 147 | incidents: ['one', 1, null], 148 | limit: 25, 149 | offset: 0, 150 | total: null, 151 | more: false, 152 | }); 153 | const resp = await (0, index_1.api)({ 154 | token: 'someToken1234567890', 155 | endpoint: '/incidents', 156 | queryParameters: { 157 | 'additional_fields[]': ['one', 'two', 'three'], 158 | }, 159 | }); 160 | expect(resp.url).toEqual('https://api.pagerduty.com/incidents?additional_fields%5B%5D=one&additional_fields%5B%5D=two&additional_fields%5B%5D=three'); 161 | }); 162 | test('API `all` calls for offset should generate requests until no more results', async () => { 163 | nock('https://api.pagerduty.com') 164 | .get('/incidents?limit=1') 165 | .reply(200, { 166 | incidents: [{ name: 1 }], 167 | limit: 1, 168 | offset: 0, 169 | more: true, 170 | total: null, 171 | }); 172 | nock('https://api.pagerduty.com') 173 | .get('/incidents?limit=1&offset=1') 174 | .reply(200, { 175 | incidents: [{ name: 2 }], 176 | limit: 1, 177 | offset: 1, 178 | more: true, 179 | total: null, 180 | }); 181 | nock('https://api.pagerduty.com') 182 | .get('/incidents?limit=1&offset=2') 183 | .reply(200, { 184 | incidents: [{ name: 3 }], 185 | limit: 1, 186 | offset: 2, 187 | more: false, 188 | total: null, 189 | }); 190 | const pd = (0, index_1.api)({ token: 'someToken1234567890' }); 191 | const responses = await pd.all('/incidents', { data: { limit: 1 } }); 192 | expect(responses.resource).toEqual([{ name: 1 }, { name: 2 }, { name: 3 }]); 193 | }); 194 | test('API `all` calls for cursor should generate requests until no more results', async () => { 195 | nock('https://api.pagerduty.com') 196 | .get('/incidents?limit=1') 197 | .reply(200, { 198 | incidents: [{ name: 1 }], 199 | limit: 1, 200 | cursor: 'one', 201 | }); 202 | nock('https://api.pagerduty.com') 203 | .get('/incidents?limit=1&cursor=one') 204 | .reply(200, { 205 | incidents: [{ name: 2 }], 206 | limit: 1, 207 | cursor: 'two', 208 | }); 209 | nock('https://api.pagerduty.com') 210 | .get('/incidents?limit=1&cursor=two') 211 | .reply(200, { 212 | incidents: [{ name: 3 }], 213 | limit: 1, 214 | cursor: null, 215 | }); 216 | const pd = (0, index_1.api)({ token: 'someToken1234567890' }); 217 | const responses = await pd.all('/incidents', { 218 | data: { limit: 1 }, 219 | }); 220 | expect(responses.resource).toEqual([{ name: 1 }, { name: 2 }, { name: 3 }]); 221 | }); 222 | test('API `get` calls with shorthand `get` should succeed', async () => { 223 | nock('https://api.pagerduty.com').get('/incidents').reply(200, EMPTY_BODY); 224 | const pd = (0, index_1.api)({ token: 'someToken1234567890' }); 225 | const response = await pd.get('/incidents'); 226 | expect(response.url).toEqual('https://api.pagerduty.com/incidents'); 227 | expect(response.data).toEqual(EMPTY_BODY); 228 | }); 229 | test('API `post` calls with shorthand `get` should succeed', async () => { 230 | nock('https://api.pagerduty.com').post('/incidents').reply(200, EMPTY_BODY); 231 | const pd = (0, index_1.api)({ token: 'someToken1234567890' }); 232 | const response = await pd.post('/incidents'); 233 | expect(response.url).toEqual('https://api.pagerduty.com/incidents'); 234 | expect(response.data).toEqual(EMPTY_BODY); 235 | }); 236 | test('API `put` calls with shorthand `get` should succeed', async () => { 237 | nock('https://api.pagerduty.com').put('/incidents').reply(200, EMPTY_BODY); 238 | const pd = (0, index_1.api)({ token: 'someToken1234567890' }); 239 | const response = await pd.put('/incidents'); 240 | expect(response.url).toEqual('https://api.pagerduty.com/incidents'); 241 | expect(response.data).toEqual(EMPTY_BODY); 242 | }); 243 | test('API `patch` calls with shorthand `get` should succeed', async () => { 244 | nock('https://api.pagerduty.com').patch('/incidents').reply(200, EMPTY_BODY); 245 | const pd = (0, index_1.api)({ token: 'someToken1234567890' }); 246 | const response = await pd.patch('/incidents'); 247 | expect(response.url).toEqual('https://api.pagerduty.com/incidents'); 248 | expect(response.data).toEqual(EMPTY_BODY); 249 | }); 250 | test('API `delete` calls with shorthand `get` should succeed', async () => { 251 | nock('https://api.pagerduty.com').delete('/incidents').reply(200, EMPTY_BODY); 252 | const pd = (0, index_1.api)({ token: 'someToken1234567890' }); 253 | const response = await pd.delete('/incidents'); 254 | expect(response.url).toEqual('https://api.pagerduty.com/incidents'); 255 | expect(response.data).toEqual(EMPTY_BODY); 256 | }); 257 | test('API catches ETIMEDOUT error', async () => { 258 | nock('https://api.pagerduty.com') 259 | .get('/incidents') 260 | .replyWithError({ code: 'ETIMEDOUT' }); 261 | const pd = (0, index_1.api)({ token: 'someToken1234567890' }); 262 | await expect(pd.get('/incidents')).rejects.toThrow('request to https://api.pagerduty.com/incidents failed, reason: undefined'); 263 | }); 264 | //# sourceMappingURL=api.test.js.map -------------------------------------------------------------------------------- /build/src/api.test.js.map: -------------------------------------------------------------------------------- 1 | {"version":3,"file":"api.test.js","sourceRoot":"","sources":["../../src/api.test.ts"],"names":[],"mappings":";;AAAA,6BAA8B;AAC9B,mCAA4B;AAE5B,MAAM,UAAU,GAAG;IACjB,SAAS,EAAE,EAAE;IACb,KAAK,EAAE,EAAE;IACT,MAAM,EAAE,CAAC;IACT,KAAK,EAAE,IAAI;IACX,IAAI,EAAE,KAAK;CACZ,CAAC;AAEF,IAAI,CAAC,uDAAuD,EAAE,KAAK,IAAI,EAAE;IACvE,IAAI,CAAC,2BAA2B,EAAE;QAChC,UAAU,EAAE;YACV,aAAa,EAAE,iCAAiC;YAChD,YAAY,EAAE,MAAM,CAAC,EAAE,CAAC,MAAM,CAAC,UAA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- /build/src/common.d.ts: -------------------------------------------------------------------------------- 1 | declare type QueryParameter = Record>; 2 | export interface RequestOptions extends RequestInit { 3 | queryParameters?: QueryParameter; 4 | retryCount?: number; 5 | requestTimeout?: number; 6 | requestTimer?: any; 7 | retryTimeout?: number; 8 | timeout?: number; 9 | } 10 | export declare function request(url: string | URL, options?: RequestOptions): Promise; 11 | export {}; 12 | -------------------------------------------------------------------------------- /build/src/common.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | Object.defineProperty(exports, "__esModule", { value: true }); 3 | exports.request = void 0; 4 | /* LEGACY-BROWSER-SUPPORT-START */ 5 | const cross_fetch_1 = require("cross-fetch"); 6 | const browser_or_node_1 = require("browser-or-node"); 7 | /* LEGACY-BROWSER-SUPPORT-END */ 8 | const VERSION = '2.0.0'; 9 | function request(url, options = {}) { 10 | const { queryParameters, requestTimeout = 30000 } = options; 11 | url = new URL(url.toString()); 12 | url = applyParameters(url, queryParameters); 13 | options = applyTimeout(options, requestTimeout); 14 | return fetch_retry(url.toString(), 3, { 15 | ...options, 16 | headers: new cross_fetch_1.Headers({ 17 | 'Content-Type': 'application/json; charset=utf-8', 18 | /* LEGACY-BROWSER-SUPPORT-START */ 19 | ...userAgentHeader(), 20 | /* LEGACY-BROWSER-SUPPORT-END */ 21 | ...options.headers, 22 | }), 23 | }); 24 | } 25 | exports.request = request; 26 | function fetch_retry(url, retries, options) { 27 | return new Promise((resolve, reject) => { 28 | (0, cross_fetch_1.default)(url, options) 29 | .then(response => { 30 | // We don't want to `reject` when retries have finished 31 | // Instead simply stop trying and return. 32 | if (retries === 0) 33 | return resolve(response); 34 | if (response.status === 429) { 35 | const { retryTimeout = 20000 } = options; 36 | retryTimeoutPromise(retryTimeout).then(() => { 37 | fetch_retry(url, retries - 1, options) 38 | .then(resolve) 39 | .catch(reject); 40 | }); 41 | } 42 | else { 43 | clearTimeout(options.requestTimer); 44 | resolve(response); 45 | } 46 | }) 47 | .catch(reject); 48 | }); 49 | } 50 | const retryTimeoutPromise = (milliseconds) => { 51 | return new Promise(resolve => setTimeout(resolve, milliseconds)); 52 | }; 53 | function userAgentHeader() { 54 | if (browser_or_node_1.isNode) { 55 | return { 56 | 'User-Agent': `pdjs/${VERSION} (${process.version}/${process.platform})`, 57 | }; 58 | } 59 | else if (browser_or_node_1.isWebWorker) { 60 | return { 61 | 'User-Agent': `pdjs/${VERSION} (WebWorker)`, 62 | }; 63 | } 64 | else if (browser_or_node_1.isJsDom) { 65 | return { 66 | 'User-Agent': `pdjs/${VERSION} (JsDom)`, 67 | }; 68 | } 69 | else if (browser_or_node_1.isDeno) { 70 | return { 71 | 'User-Agent': `pdjs/${VERSION} (Deno)`, 72 | }; 73 | } 74 | else if (browser_or_node_1.isBrowser) { 75 | return { 76 | // Note: This will not work consistently for all browsers as some silently drop the userAgent Header. 77 | 'User-Agent': `pdjs/${VERSION} (${window.navigator.userAgent})`, 78 | }; 79 | } 80 | else { 81 | return {}; 82 | } 83 | } 84 | function applyParameters(url, queryParameters) { 85 | if (!queryParameters) 86 | return url; 87 | const combinedParameters = url.searchParams; 88 | for (const key of Object.keys(queryParameters)) { 89 | const parameter = queryParameters[key]; 90 | if (Array.isArray(parameter)) { 91 | // Support for array based keys like `additional_fields[]` 92 | parameter.forEach(item => { 93 | combinedParameters.append(key, item); 94 | }); 95 | } 96 | else { 97 | combinedParameters.append(key, parameter); 98 | } 99 | } 100 | url.search = combinedParameters.toString(); 101 | return url; 102 | } 103 | function applyTimeout(init, timeout) { 104 | if (!timeout) 105 | return init; 106 | const timer = setTimeout(() => { }, timeout); 107 | return { 108 | ...init, 109 | requestTimer: timer, 110 | }; 111 | } 112 | //# sourceMappingURL=common.js.map -------------------------------------------------------------------------------- /build/src/common.js.map: -------------------------------------------------------------------------------- 1 | {"version":3,"file":"common.js","sourceRoot":"","sources":["../../src/common.ts"],"names":[],"mappings":";;;AAAA,kCAAkC;AAClC,6CAA2C;AAC3C,qDAAgF;AAChF,gCAAgC;AAEhC,MAAM,OAAO,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AE;QAC9C,MAAM,SAAS,GAAG,eAAe,CAAC,GAAG,CAAC,CAAC;QACvC,IAAI,KAAK,CAAC,OAAO,CAAC,SAAS,CAAC,EAAE;YAC5B,0DAA0D;YAC1D,SAAS,CAAC,OAAO,CAAC,IAAI,CAAC,EAAE;gBACvB,kBAAkB,CAAC,MAAM,CAAC,GAAG,EAAE,IAAI,CAAC,CAAC;YACvC,CAAC,CAAC,CAAC;SACJ;aAAM;YACL,kBAAkB,CAAC,MAAM,CAAC,GAAG,EAAE,SAAS,CAAC,CAAC;SAC3C;KACF;IAED,GAAG,CAAC,MAAM,GAAG,kBAAkB,CAAC,QAAQ,EAAE,CAAC;IAC3C,OAAO,GAAG,CAAC;AACb,CAAC;AAED,SAAS,YAAY,CAAC,IAAoB,EAAE,OAAgB;IAC1D,IAAI,CAAC,OAAO;QAAE,OAAO,IAAI,CAAC;IAC1B,MAAM,KAAK,GAAG,UAAU,CAAC,GAAG,EAAE,GAAE,CAAC,EAAE,OAAO,CAAC,CAAC;IAC5C,OAAO;QACL,GAAG,IAAI;QACP,YAAY,EAAE,KAAK;KACpB,CAAC;AACJ,CAAC"} -------------------------------------------------------------------------------- /build/src/events.d.ts: -------------------------------------------------------------------------------- 1 | import { RequestOptions } from './common'; 2 | export declare type Action = 'trigger' | 'acknowledge' | 'resolve'; 3 | export declare type EventPromise = Promise; 4 | export interface EventResponse extends Response { 5 | data: any; 6 | response: Response; 7 | } 8 | export declare type Severity = 'critical' | 'error' | 'warning' | 'info'; 9 | export interface Image { 10 | src: string; 11 | href?: string; 12 | alt?: string; 13 | } 14 | export interface Link { 15 | href: string; 16 | text?: string; 17 | } 18 | export interface EventPayloadV2 { 19 | routing_key: string; 20 | event_action: Action; 21 | dedup_key?: string; 22 | payload: { 23 | summary: string; 24 | source: string; 25 | severity: Severity; 26 | timestamp?: string; 27 | component?: string; 28 | group?: string; 29 | class?: string; 30 | custom_details?: object; 31 | }; 32 | images?: Array; 33 | links?: Array; 34 | } 35 | export interface EventParameters extends RequestOptions { 36 | data: EventPayloadV2; 37 | type?: string; 38 | server?: string; 39 | } 40 | export interface ChangePayload { 41 | routing_key: string; 42 | payload: { 43 | summary: string; 44 | source?: string; 45 | timestamp: string; 46 | custom_details?: object; 47 | }; 48 | images?: Array; 49 | links?: Array; 50 | } 51 | export interface ChangeParameters extends RequestOptions { 52 | data: ChangePayload; 53 | type?: string; 54 | server?: string; 55 | } 56 | export declare function event(eventParameters: EventParameters | ChangeParameters): EventPromise; 57 | export declare const trigger: (eventParameters: EventParameters) => EventPromise; 58 | export declare const acknowledge: (eventParameters: EventParameters) => EventPromise; 59 | export declare const resolve: (eventParameters: EventParameters) => EventPromise; 60 | export declare const change: (changeParameters: ChangeParameters) => EventPromise; 61 | -------------------------------------------------------------------------------- /build/src/events.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | Object.defineProperty(exports, "__esModule", { value: true }); 3 | exports.change = exports.resolve = exports.acknowledge = exports.trigger = exports.event = void 0; 4 | const common_1 = require("./common"); 5 | function event(eventParameters) { 6 | const { server = 'events.pagerduty.com', type = 'event', data, ...config } = eventParameters; 7 | let url = `https://${server}/v2/enqueue`; 8 | if (type === 'change') { 9 | url = `https://${server}/v2/change/enqueue`; 10 | } 11 | return eventFetch(url, { 12 | method: 'POST', 13 | body: JSON.stringify(data), 14 | ...config, 15 | }); 16 | } 17 | exports.event = event; 18 | const shorthand = (action) => (eventParameters) => { 19 | const typeField = 'event_action'; 20 | return event({ 21 | ...eventParameters, 22 | data: { 23 | ...eventParameters.data, 24 | [typeField]: action, 25 | }, 26 | }); 27 | }; 28 | exports.trigger = shorthand('trigger'); 29 | exports.acknowledge = shorthand('acknowledge'); 30 | exports.resolve = shorthand('resolve'); 31 | const change = (changeParameters) => event({ ...changeParameters, type: 'change' }); 32 | exports.change = change; 33 | function eventFetch(url, options) { 34 | return (0, common_1.request)(url, options).then((response) => { 35 | const apiResponse = response; 36 | return response.json().then((data) => { 37 | apiResponse.data = data; 38 | apiResponse.response = response; 39 | return apiResponse; 40 | }); 41 | }); 42 | } 43 | //# sourceMappingURL=events.js.map -------------------------------------------------------------------------------- /build/src/events.js.map: -------------------------------------------------------------------------------- 1 | {"version":3,"file":"events.js","sourceRoot":"","sources":["../../src/events.ts"],"names":[],"mappings":";;;AAAA,qCAAiD;AAiEjD,SAAgB,KAAK,CACnB,eAAmD;IAEnD,MAAM,EACJ,MAAM,GAAG,sBAAsB,EAC/B,IAAI,GAAG,OAAO,EACd,IAAI,EACJ,GAAG,MAAM,EACV,GAAG,eAAe,CAAC;IAEpB,IAAI,GAAG,GAAG,WAAW,MAAM,aAAa,CAAC;IACzC,IAAI,IAAI,KAAK,QAAQ,EAAE;QACrB,GAAG,GAAG,WAAW,MAAM,oBAAoB,CAAC;KAC7C;IAED,OAAO,UAAU,CAAC,GAAG,EAAE;QACrB,MAAM,EAAE,MAAM;QACd,IAAI,EAAE,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC;QAC1B,GAAG,MAAM;KACV,CAAC,CAAC;AACL,CAAC;AApBD,sBAoBC;AAED,MAAM,SAAS,GAAG,CAAC,MAAc,EAAE,EAAE,CAAC,CACpC,eAAgC,EAClB,EAAE;IAChB,MAAM,SAAS,GAAG,cAAc,CAAC;IAEjC,OAAO,KAAK,CAAC;QACX,GAAG,eAAe;QAClB,IAAI,EAAE;YACJ,GAAG,eAAe,CAAC,IAAI;YACvB,CAAC,SAAS,CAAC,EAAE,MAAM;SACpB;KACF,CAAC,CAAC;AACL,CAAC,CAAC;AAEW,QAAA,OAAO,GAAG,SAAS,CAAC,SAAS,CAAC,CAAC;AAC/B,QAAA,WAAW,GAAG,SAAS,CAAC,aAAa,CAAC,CAAC;AACvC,QAAA,OAAO,GAAG,SAAS,CAAC,SAAS,CAAC,CAAC;AACrC,MAAM,MAAM,GAAG,CAAC,gBAAkC,EAAE,EAAE,CAC3D,KAAK,CAAC,EAAC,GAAG,gBAAgB,EAAE,IAAI,EAAE,QAAQ,EAAC,CAAC,CAAC;AADlC,QAAA,MAAM,UAC4B;AAE/C,SAAS,UAAU,CAAC,GAAW,EAAE,OAAuB;IACtD,OAAO,IAAA,gBAAO,EAAC,GAAG,EAAE,OAAO,CAAC,CAAC,IAAI,CAC/B,CAAC,QAAkB,EAAgB,EAAE;QACnC,MAAM,WAAW,GAAG,QAAyB,CAAC;QAC9C,OAAO,QAAQ,CAAC,IAAI,EAAE,CAAC,IAAI,CACzB,CAAC,IAAI,EAAiB,EAAE;YACtB,WAAW,CAAC,IAAI,GAAG,IAAI,CAAC;YACxB,WAAW,CAAC,QAAQ,GAAG,QAAQ,CAAC;YAChC,OAAO,WAAW,CAAC;QACrB,CAAC,CACF,CAAC;IACJ,CAAC,CACF,CAAC;AACJ,CAAC"} -------------------------------------------------------------------------------- /build/src/events.test.d.ts: -------------------------------------------------------------------------------- 1 | export {}; 2 | -------------------------------------------------------------------------------- /build/src/events.test.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | Object.defineProperty(exports, "__esModule", { value: true }); 3 | const nock = require("nock"); 4 | const index_1 = require("./index"); 5 | const eventPayloadV2 = { 6 | data: { 7 | routing_key: 'someRoutingKeybfa2a710673888f520', 8 | event_action: 'trigger', 9 | dedup_key: 'test_incident_2_88f520', 10 | payload: { 11 | summary: 'Test Event V2', 12 | source: 'test-source', 13 | severity: 'error', 14 | }, 15 | }, 16 | }; 17 | const changeParameters = { 18 | data: { 19 | routing_key: 'someRoutingKeybfa2a710673888f520', 20 | payload: { 21 | summary: 'Test change event', 22 | source: 'test-source', 23 | timestamp: new Date().toISOString(), 24 | custom_details: { 25 | test_detail: 'test-value', 26 | }, 27 | }, 28 | }, 29 | }; 30 | test('Events API properly passes Events V2 requests', async () => { 31 | const body = { 32 | data: { 33 | status: 'success', 34 | message: 'Event processed', 35 | dedup_key: 'test_incident_2_88f520', 36 | }, 37 | }; 38 | nock('https://events.pagerduty.com', { 39 | reqheaders: { 40 | 'User-Agent': header => header.startsWith('pdjs'), 41 | }, 42 | }) 43 | .post('/v2/enqueue') 44 | .reply(202, body); 45 | const response = await (0, index_1.event)(eventPayloadV2); 46 | expect(response.url).toEqual('https://events.pagerduty.com/v2/enqueue'); 47 | expect(response.data).toEqual(body); 48 | }); 49 | test('Events API properly passes Change Events requests', async () => { 50 | const body = { 51 | data: { 52 | status: 'success', 53 | message: 'Event processed', 54 | dedup_key: 'test_incident_2_88f520', 55 | }, 56 | }; 57 | nock('https://events.pagerduty.com', { 58 | reqheaders: { 59 | 'User-Agent': header => header.startsWith('pdjs'), 60 | }, 61 | }) 62 | .post('/v2/change/enqueue') 63 | .reply(202, body); 64 | const response = await (0, index_1.change)(changeParameters); 65 | expect(response.url).toEqual('https://events.pagerduty.com/v2/change/enqueue'); 66 | expect(response.data).toEqual(body); 67 | }); 68 | test('Events API properly passes Events V2 requests with images/links/details', async () => { 69 | const body = { 70 | data: { 71 | status: 'success', 72 | message: 'Event processed', 73 | dedup_key: 'test_incident_2_88f520', 74 | }, 75 | }; 76 | nock('https://events.pagerduty.com', { 77 | reqheaders: { 78 | 'User-Agent': header => header.startsWith('pdjs'), 79 | }, 80 | }) 81 | .post('/v2/enqueue') 82 | .reply(202, body); 83 | const response = await (0, index_1.event)({ 84 | data: { 85 | routing_key: 'someRoutingKeybfa2a710673888f520', 86 | event_action: 'trigger', 87 | dedup_key: 'test_incident_3_88f520', 88 | payload: { 89 | summary: 'Test Event V2', 90 | source: 'test-source', 91 | severity: 'error', 92 | custom_details: { 93 | foo: 'bar', 94 | }, 95 | }, 96 | images: [ 97 | { 98 | src: 'foo.jpg', 99 | }, 100 | ], 101 | links: [ 102 | { 103 | href: 'https://www.pagerduty.com', 104 | }, 105 | ], 106 | }, 107 | }); 108 | expect(response.url).toEqual('https://events.pagerduty.com/v2/enqueue'); 109 | expect(response.data).toEqual(body); 110 | }); 111 | test('Events API shorthands should send corresponding events', async () => { 112 | const body = { 113 | data: { 114 | status: 'success', 115 | message: 'Event processed', 116 | dedup_key: 'test_incident_2_88f520', 117 | }, 118 | }; 119 | nock('https://events.pagerduty.com', { 120 | reqheaders: { 121 | 'User-Agent': header => header.startsWith('pdjs'), 122 | }, 123 | }) 124 | .post('/v2/enqueue') 125 | .reply(202, body) 126 | .post('/v2/enqueue') 127 | .reply(202, body) 128 | .post('/v2/enqueue') 129 | .reply(202, body); 130 | let response = await (0, index_1.acknowledge)(eventPayloadV2); 131 | expect(response.url).toEqual('https://events.pagerduty.com/v2/enqueue'); 132 | expect(response.data).toEqual(body); 133 | response = await (0, index_1.resolve)(eventPayloadV2); 134 | expect(response.url).toEqual('https://events.pagerduty.com/v2/enqueue'); 135 | expect(response.data).toEqual(body); 136 | response = await (0, index_1.trigger)(eventPayloadV2); 137 | expect(response.url).toEqual('https://events.pagerduty.com/v2/enqueue'); 138 | expect(response.data).toEqual(body); 139 | }); 140 | //# sourceMappingURL=events.test.js.map -------------------------------------------------------------------------------- /build/src/events.test.js.map: -------------------------------------------------------------------------------- 1 | {"version":3,"file":"events.test.js","sourceRoot":"","sources":["../../src/events.test.ts"],"names":[],"mappings":";;AAAA,6BAA8B;AAE9B,mCAAqE;AAErE,MAAM,cAAc,GAAG;IACrB,IAAI,EAAE;QACJ,WAAW,EAAE,kCAAkC;QAC/C,YAAY,EAAU,SAAS;QAC/B,SAAS,EAAE,wBAAwB;QACnC,OAAO,EAAE;YACP,OAAO,EAAE,eAAe;YACxB,MAAM,EAAE,aAAa;YACrB,QAAQ,EAAY,OAAO;SAC5B;KACF;CACF,CAAC;AAEF,MAAM,gBAAgB,GAAqB;IACzC,IAAI,EAAE;QACJ,WAAW,EAAE,kCAAkC;QAC/C,OAAO,EAAE;YACP,OAAO,EAAE,mBAAmB;YAC5B,MAAM,EAAE,aAAa;YACrB,SAAS,EAAE,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE;YACnC,cAAc,EAAE;gBACd,WAAW,EAAE,YAAY;aAC1B;SACF;KACF;CACF,CAAC;AAEF,IAAI,CAAC,+CAA+C,EAAE,KAAK,IAAI,EAAE;IAC/D,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E,wBAAwB;SACpC;KACF,CAAC;IAEF,IAAI,CAAC,8BAA8B,EAAE;QACnC,UAAU,EAAE;YACV,YAAY,EAAE,MAAM,CAAC,EAAE,CAAC,MAAM,CAAC,UAAU,CAAC,MAAM,CAAC;SAClD;KACF,CAAC;SACC,IAAI,CAAC,aAAa,CAAC;SACnB,KAAK,CAAC,GAAG,EAAE,IAAI,CAAC;SAChB,IAAI,CAAC,aAAa,CAAC;SACnB,KAAK,CAAC,GAAG,EAAE,IAAI,CAAC;SAChB,IAAI,CAAC,aAAa,CAAC;SACnB,KAAK,CAAC,GAAG,EAAE,IAAI,CAAC,CAAC;IAEpB,IAAI,QAAQ,GAAG,MAAM,IAAA,mBAAW,EAAC,cAAc,CAAC,CAAC;IAEjD,MAAM,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,OAAO,CAAC,yCAAyC,CAAC,CAAC;IACxE,MAAM,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;IAEpC,QAAQ,GAAG,MAAM,IAAA,eAAO,EAAC,cAAc,CAAC,CAAC;IAEzC,MAAM,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,OAAO,CAAC,yCAAyC,CAAC,CAAC;IACxE,MAAM,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;IAEpC,QAAQ,GAAG,MAAM,IAAA,eAAO,EAAC,cAAc,CAAC,CAAC;IAEzC,MAAM,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,OAAO,CAAC,yCAAyC,CAAC,CAAC;IACxE,MAAM,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;AACtC,CAAC,CAAC,CAAC"} -------------------------------------------------------------------------------- /build/src/index.d.ts: -------------------------------------------------------------------------------- 1 | export { api } from './api'; 2 | export { event, change, trigger, acknowledge, resolve } from './events'; 3 | -------------------------------------------------------------------------------- /build/src/index.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | Object.defineProperty(exports, "__esModule", { value: true }); 3 | exports.resolve = exports.acknowledge = exports.trigger = exports.change = exports.event = exports.api = void 0; 4 | var api_1 = require("./api"); 5 | Object.defineProperty(exports, "api", { enumerable: true, get: function () { return api_1.api; } }); 6 | var events_1 = require("./events"); 7 | Object.defineProperty(exports, "event", { enumerable: true, get: function () { return events_1.event; } }); 8 | Object.defineProperty(exports, "change", { enumerable: true, get: function () { return events_1.change; } }); 9 | Object.defineProperty(exports, "trigger", { enumerable: true, get: function () { return events_1.trigger; } }); 10 | Object.defineProperty(exports, "acknowledge", { enumerable: true, get: function () { return events_1.acknowledge; } }); 11 | Object.defineProperty(exports, "resolve", { enumerable: true, get: function () { return events_1.resolve; } }); 12 | //# sourceMappingURL=index.js.map -------------------------------------------------------------------------------- /build/src/index.js.map: -------------------------------------------------------------------------------- 1 | {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";;;AAAA,6BAA0B;AAAlB,0FAAA,GAAG,OAAA;AACX,mCAAsE;AAA9D,+FAAA,KAAK,OAAA;AAAE,gGAAA,MAAM,OAAA;AAAE,iGAAA,OAAO,OAAA;AAAE,qGAAA,WAAW,OAAA;AAAE,iGAAA,OAAO,OAAA"} -------------------------------------------------------------------------------- /build/src/retries.test.d.ts: -------------------------------------------------------------------------------- 1 | export {}; 2 | -------------------------------------------------------------------------------- /build/src/retries.test.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | Object.defineProperty(exports, "__esModule", { value: true }); 3 | const nock = require("nock"); 4 | const index_1 = require("./index"); 5 | test('API request should return after 3 rate limited requests', async () => { 6 | const body = { 7 | incidents: [], 8 | limit: 1, 9 | offset: 0, 10 | total: null, 11 | more: true, 12 | }; 13 | nock('https://api.pagerduty.com') 14 | .get('/incidents') 15 | .reply(429, body) 16 | .get('/incidents') 17 | .reply(429, body) 18 | .get('/incidents') 19 | .reply(429, body) 20 | .get('/incidents') 21 | .reply(429, body); 22 | const response = await (0, index_1.api)({ 23 | token: 'someToken1234567890', 24 | endpoint: '/incidents', 25 | retryTimeout: 20, 26 | }); 27 | expect(response.response.status).toEqual(429); 28 | }); 29 | test('API should return data after getting rate limited once.', async () => { 30 | const body = { 31 | incidents: [], 32 | limit: 1, 33 | offset: 0, 34 | total: null, 35 | more: true, 36 | }; 37 | nock('https://api.pagerduty.com') 38 | .get('/incidents') 39 | .reply(429, body) 40 | .get('/incidents') 41 | .reply(200, body); 42 | const response = await (0, index_1.api)({ 43 | token: 'someToken1234567890', 44 | endpoint: '/incidents', 45 | retryTimeout: 20, 46 | }); 47 | expect(response.response.status).toEqual(200); 48 | expect(response.data).toEqual(body); 49 | }); 50 | //# sourceMappingURL=retries.test.js.map -------------------------------------------------------------------------------- /build/src/retries.test.js.map: -------------------------------------------------------------------------------- 1 | {"version":3,"file":"retries.test.js","sourceRoot":"","sources":["../../src/retries.test.ts"],"names":[],"mappings":";;AAAA,6BAA8B;AAC9B,mCAA4B;AAE5B,IAAI,CAAC,yDAAyD,EAAE,KAAK,IAAI,EAAE;IACzE,MAAM,IAAI,GAAG;QACX,SAAS,EAAE,EAAE;QACb,KAAK,EAAE,CAAC;QACR,MAAM,EAAE,CAAC;QACT,KAAK,EAAE,IAAI;QACX,IAAI,EAAE,IAAI;KACX,CAAC;IAEF,IAAI,CAAC,2BAA2B,CAAC;SAC9B,GAAG,CAAC,YAAY,CAAC;SACjB,KAAK,CAAC,GAAG,EAAE,IAAI,CAAC;SAChB,GAAG,CAAC,YAAY,CAAC;SACjB,KAAK,CAAC,GAAG,EAAE,IAAI,CAAC;SAChB,GAAG,CAAC,YAAY,CAAC;SACjB,KAAK,CAAC,GAAG,EAAE,IAAI,CAAC;SAChB,GAAG,CAAC,YAAY,CAAC;SACjB,KAAK,CAAC,GAAG,EAAE,IAAI,CAAC,CAAC;IAEpB,MAAM,QAAQ,GAAG,MAAM,IAAA,WAAG,EAAC;QACzB,KAAK,EAAE,qBAAqB;QAC5B,QAAQ,EAAE,YAAY;QACtB,YAAY,EAAE,EAAE;KACjB,CAAC,CAAC;IAEH,MAAM,CAAC,QAAQ,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC;AAChD,CAAC,CAAC,CAAC;AAEH,IAAI,CAAC,yDAAyD,EAAE,KAAK,IAAI,EAAE;IACzE,MAAM,IAAI,GAAG;QACX,SAAS,EAAE,EAAE;QACb,KAAK,EAAE,CAAC;QACR,MAAM,EAAE,CAAC;QACT,KAAK,EAAE,IAAI;QACX,IAAI,EAAE,IAAI;KACX,CAAC;IAEF,IAAI,CAAC,2BAA2B,CAAC;SAC9B,GAAG,CAAC,YAAY,CAAC;SACjB,KAAK,CAAC,GAAG,EAAE,IAAI,CAAC;SAChB,GAAG,CAAC,YAAY,CAAC;SACjB,KAAK,CAAC,GAAG,EAAE,IAAI,CAAC,CAAC;IAEpB,MAAM,QAAQ,GAAG,MAAM,IAAA,WAAG,EAAC;QACzB,KAAK,EAAE,qBAAqB;QAC5B,QAAQ,EAAE,YAAY;QACtB,YAAY,EAAE,EAAE;KACjB,CAAC,CAAC;IAEH,MAAM,CAAC,QAAQ,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC;IAC9C,MAAM,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;AACtC,CAAC,CAAC,CAAC"} -------------------------------------------------------------------------------- /dist/pdjs-legacy.js: -------------------------------------------------------------------------------- 1 | var PagerDuty;(()=>{var e={818:(e,t)=>{"use strict";var r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},n="undefined"!=typeof window&&void 0!==window.document,o="undefined"!=typeof process&&null!=process.versions&&null!=process.versions.node,i="object"===("undefined"==typeof self?"undefined":r(self))&&self.constructor&&"DedicatedWorkerGlobalScope"===self.constructor.name,s="undefined"!=typeof window&&"nodejs"===window.name||"undefined"!=typeof navigator&&(navigator.userAgent.includes("Node.js")||navigator.userAgent.includes("jsdom")),a="undefined"!=typeof Deno&&void 0!==Deno.core;t.jU=n,t.n2=i,t.UG=o,t.f7=s,t.co=a},98:function(e,t){var r="undefined"!=typeof self?self:this,n=function(){function e(){this.fetch=!1,this.DOMException=r.DOMException}return e.prototype=r,new e}();!function(e){!function(t){var r="URLSearchParams"in e,n="Symbol"in e&&"iterator"in Symbol,o="FileReader"in e&&"Blob"in e&&function(){try{return new Blob,!0}catch(e){return!1}}(),i="FormData"in e,s="ArrayBuffer"in e;if(s)var a=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],u=ArrayBuffer.isView||function(e){return e&&a.indexOf(Object.prototype.toString.call(e))>-1};function c(e){if("string"!=typeof e&&(e=String(e)),/[^a-z0-9\-#$%&'*+.^_`|~]/i.test(e))throw new TypeError("Invalid character in header field name");return e.toLowerCase()}function f(e){return"string"!=typeof e&&(e=String(e)),e}function p(e){var t={next:function(){var t=e.shift();return{done:void 0===t,value:t}}};return n&&(t[Symbol.iterator]=function(){return t}),t}function l(e){this.map={},e instanceof l?e.forEach((function(e,t){this.append(t,e)}),this):Array.isArray(e)?e.forEach((function(e){this.append(e[0],e[1])}),this):e&&Object.getOwnPropertyNames(e).forEach((function(t){this.append(t,e[t])}),this)}function y(e){if(e.bodyUsed)return Promise.reject(new TypeError("Already read"));e.bodyUsed=!0}function d(e){return new Promise((function(t,r){e.onload=function(){t(e.result)},e.onerror=function(){r(e.error)}}))}function h(e){var t=new FileReader,r=d(t);return t.readAsArrayBuffer(e),r}function b(e){if(e.slice)return e.slice(0);var t=new Uint8Array(e.byteLength);return t.set(new Uint8Array(e)),t.buffer}function v(){return this.bodyUsed=!1,this._initBody=function(e){var t;this._bodyInit=e,e?"string"==typeof e?this._bodyText=e:o&&Blob.prototype.isPrototypeOf(e)?this._bodyBlob=e:i&&FormData.prototype.isPrototypeOf(e)?this._bodyFormData=e:r&&URLSearchParams.prototype.isPrototypeOf(e)?this._bodyText=e.toString():s&&o&&(t=e)&&DataView.prototype.isPrototypeOf(t)?(this._bodyArrayBuffer=b(e.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):s&&(ArrayBuffer.prototype.isPrototypeOf(e)||u(e))?this._bodyArrayBuffer=b(e):this._bodyText=e=Object.prototype.toString.call(e):this._bodyText="",this.headers.get("content-type")||("string"==typeof e?this.headers.set("content-type","text/plain;charset=UTF-8"):this._bodyBlob&&this._bodyBlob.type?this.headers.set("content-type",this._bodyBlob.type):r&&URLSearchParams.prototype.isPrototypeOf(e)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},o&&(this.blob=function(){var e=y(this);if(e)return e;if(this._bodyBlob)return Promise.resolve(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(new Blob([this._bodyArrayBuffer]));if(this._bodyFormData)throw new Error("could not read FormData body as blob");return Promise.resolve(new Blob([this._bodyText]))},this.arrayBuffer=function(){return this._bodyArrayBuffer?y(this)||Promise.resolve(this._bodyArrayBuffer):this.blob().then(h)}),this.text=function(){var e,t,r,n=y(this);if(n)return n;if(this._bodyBlob)return e=this._bodyBlob,r=d(t=new FileReader),t.readAsText(e),r;if(this._bodyArrayBuffer)return Promise.resolve(function(e){for(var t=new Uint8Array(e),r=new Array(t.length),n=0;n-1?n:r),this.mode=t.mode||this.mode||null,this.signal=t.signal||this.signal,this.referrer=null,("GET"===this.method||"HEAD"===this.method)&&o)throw new TypeError("Body not allowed for GET or HEAD requests");this._initBody(o)}function O(e){var t=new FormData;return e.trim().split("&").forEach((function(e){if(e){var r=e.split("="),n=r.shift().replace(/\+/g," "),o=r.join("=").replace(/\+/g," ");t.append(decodeURIComponent(n),decodeURIComponent(o))}})),t}function w(e,t){t||(t={}),this.type="default",this.status=void 0===t.status?200:t.status,this.ok=this.status>=200&&this.status<300,this.statusText="statusText"in t?t.statusText:"OK",this.headers=new l(t.headers),this.url=t.url||"",this._initBody(e)}g.prototype.clone=function(){return new g(this,{body:this._bodyInit})},v.call(g.prototype),v.call(w.prototype),w.prototype.clone=function(){return new w(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new l(this.headers),url:this.url})},w.error=function(){var e=new w(null,{status:0,statusText:""});return e.type="error",e};var j=[301,302,303,307,308];w.redirect=function(e,t){if(-1===j.indexOf(t))throw new RangeError("Invalid status code");return new w(null,{status:t,headers:{location:e}})},t.DOMException=e.DOMException;try{new t.DOMException}catch(e){t.DOMException=function(e,t){this.message=e,this.name=t;var r=Error(e);this.stack=r.stack},t.DOMException.prototype=Object.create(Error.prototype),t.DOMException.prototype.constructor=t.DOMException}function P(e,r){return new Promise((function(n,i){var s=new g(e,r);if(s.signal&&s.signal.aborted)return i(new t.DOMException("Aborted","AbortError"));var a=new XMLHttpRequest;function u(){a.abort()}a.onload=function(){var e,t,r={status:a.status,statusText:a.statusText,headers:(e=a.getAllResponseHeaders()||"",t=new l,e.replace(/\r?\n[\t ]+/g," ").split(/\r?\n/).forEach((function(e){var r=e.split(":"),n=r.shift().trim();if(n){var o=r.join(":").trim();t.append(n,o)}})),t)};r.url="responseURL"in a?a.responseURL:r.headers.get("X-Request-URL");var o="response"in a?a.response:a.responseText;n(new w(o,r))},a.onerror=function(){i(new TypeError("Network request failed"))},a.ontimeout=function(){i(new TypeError("Network request failed"))},a.onabort=function(){i(new t.DOMException("Aborted","AbortError"))},a.open(s.method,s.url,!0),"include"===s.credentials?a.withCredentials=!0:"omit"===s.credentials&&(a.withCredentials=!1),"responseType"in a&&o&&(a.responseType="blob"),s.headers.forEach((function(e,t){a.setRequestHeader(t,e)})),s.signal&&(s.signal.addEventListener("abort",u),a.onreadystatechange=function(){4===a.readyState&&s.signal.removeEventListener("abort",u)}),a.send(void 0===s._bodyInit?null:s._bodyInit)}))}P.polyfill=!0,e.fetch||(e.fetch=P,e.Headers=l,e.Request=g,e.Response=w),t.Headers=l,t.Request=g,t.Response=w,t.fetch=P,Object.defineProperty(t,"__esModule",{value:!0})}({})}(n),n.fetch.ponyfill=!0,delete n.fetch.polyfill;var o=n;(t=o.fetch).default=o.fetch,t.fetch=o.fetch,t.Headers=o.Headers,t.Request=o.Request,t.Response=o.Response,e.exports=t}},t={};function r(n){var o=t[n];if(void 0!==o)return o.exports;var i=t[n]={exports:{}};return e[n].call(i.exports,i,i.exports,r),i.exports}r.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return r.d(t,{a:t}),t},r.d=(e,t)=>{for(var n in t)r.o(t,n)&&!r.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},r.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var n={};(()=>{"use strict";r.r(n),r.d(n,{acknowledge:()=>B,api:()=>P,change:()=>k,event:()=>_,resolve:()=>R,trigger:()=>U});var e=r(98),t=r.n(e),o=r(818);function i(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function s(e){for(var t=1;t1&&void 0!==arguments[1]?arguments[1]:{},n=r,o=n.queryParameters,i=n.requestTimeout,a=void 0===i?3e4:i;return t=y(t=new URL(t.toString()),o),r=d(r,a),f(t.toString(),3,s(s({},r),{},{headers:new e.Headers(s(s({"Content-Type":"application/json; charset=utf-8"},l()),r.headers))}))}function f(e,r,n){return new Promise((function(o,i){t()(e,n).then((function(t){if(0===r)return o(t);if(429===t.status){var s=n.retryTimeout;p(void 0===s?2e4:s).then((function(){f(e,r-1,n).then(o).catch(i)}))}else clearTimeout(n.requestTimer),o(t)})).catch(i)}))}var p=function(e){return new Promise((function(t){return setTimeout(t,e)}))};function l(){return o.UG?{"User-Agent":"pdjs/".concat(u," (").concat(process.version,"/").concat(process.platform,")")}:o.n2?{"User-Agent":"pdjs/".concat(u," (WebWorker)")}:o.f7?{"User-Agent":"pdjs/".concat(u," (JsDom)")}:o.co?{"User-Agent":"pdjs/".concat(u," (Deno)")}:o.jU?{"User-Agent":"pdjs/".concat(u," (").concat(window.navigator.userAgent,")")}:{}}function y(e,t){if(!t)return e;for(var r=e.searchParams,n=function(){var e=i[o],n=t[e];Array.isArray(n)?n.forEach((function(t){r.append(e,t)})):r.append(e,n)},o=0,i=Object.keys(t);o]+)>/g,(function(e,t){return"$"+i[t]})))}if("function"==typeof o){var s=this;return e[Symbol.replace].call(this,r,(function(){var e=arguments;return"object"!==b(e[e.length-1])&&(e=[].slice.call(e)).push(n(e,s)),o.apply(this,e)}))}return e[Symbol.replace].call(this,r,o)},v.apply(this,arguments)}function m(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),t&&g(e,t)}function g(e,t){return g=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e},g(e,t)}function O(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function w(e){for(var t=1;t=0||(o[r]=e[r]);return o}(e,t);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(n=0;n=0||Object.prototype.propertyIsEnumerable.call(e,r)&&(o[r]=e[r])}return o}(e,h),b=w(w({method:"GET"},d),{},{headers:w({Accept:"application/vnd.pagerduty+json;version=".concat(l),Authorization:"".concat({bearer:"Bearer ",token:"Token token="}[c]).concat(a)},d.headers)});return r=b.method,!["PUT","POST","DELETE","PATCH"].includes(null!==(n=r.toUpperCase())&&void 0!==n?n:"GET")&&y?b.queryParameters=null!==(t=b.queryParameters)&&void 0!==t?t:y:b.body=JSON.stringify(y),E(null!=f?f:"https://".concat(s,"/").concat(o.replace(/^\/+/,"")),b)}function E(e,t){return c(e,t).then((function(r){var n=r;return n.response=r,204===r.status?Promise.resolve(n):r.json().then((function(r){var o=function(e,t){var r=e.match(v(/.+.com\/([0-9A-Z_a-z]+)/,{resource:1}));if(r){var n=r[1];return t&&"get"===t.toLowerCase()?n:n.endsWith("ies")?n.slice(0,-3)+"y":n.endsWith("s")?n.slice(0,-1):n}return null}(e,t.method);return n.next=function(e,t,r){if(function(e){return void 0!==e.offset}(r)){if(null!=r&&r.more&&void 0!==b(r.offset)&&r.limit)return function(){return E(e,w(w({},t),{},{queryParameters:w(w({},t.queryParameters),{},{limit:r.limit.toString(),offset:(r.limit+r.offset).toString()})}))}}else if(function(e){return void 0!==e.cursor}(r)&&null!=r&&r.cursor)return function(){return E(e,w(w({},t),{},{queryParameters:w(w({},t.queryParameters),{},{cursor:r.cursor,limit:r.limit.toString()})}))}}(e,t,r),n.data=r,n.resource=o?r[o]:null,n})).catch((function(){return Promise.reject(n)}))}))}var S=["server","type","data"];function x(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function T(e){for(var t=1;t=0||(o[r]=e[r]);return o}(e,t);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(n=0;n=0||Object.prototype.propertyIsEnumerable.call(e,r)&&(o[r]=e[r])}return o}(e,S),a="https://".concat(r,"/v2/enqueue");return"change"===o&&(a="https://".concat(r,"/v2/change/enqueue")),function(e,t){return c(e,t).then((function(e){var t=e;return e.json().then((function(r){return t.data=r,t.response=e,t}))}))}(a,T({method:"POST",body:JSON.stringify(i)},s))}var D=function(e){return function(t){return _(T(T({},t),{},{data:T(T({},t.data),{},A({},"event_action",e))}))}},U=D("trigger"),B=D("acknowledge"),R=D("resolve"),k=function(e){return _(T(T({},e),{},{type:"change"}))}})(),PagerDuty=n})(); 2 | //# sourceMappingURL=pdjs-legacy.js.map -------------------------------------------------------------------------------- /dist/pdjs-legacy.js.map: -------------------------------------------------------------------------------- 1 | {"version":3,"file":"pdjs-legacy.js","mappings":"oDAMA,IAAIA,EAA4B,mBAAXC,QAAoD,iBAApBA,OAAOC,SAAwB,SAAUC,GAAO,cAAcA,GAAS,SAAUA,GAAO,OAAOA,GAAyB,mBAAXF,QAAyBE,EAAIC,cAAgBH,QAAUE,IAAQF,OAAOI,UAAY,gBAAkBF,GAElQG,EAA8B,oBAAXC,aAAqD,IAApBA,OAAOC,SAE3DC,EAA4B,oBAAZC,SAA+C,MAApBA,QAAQC,UAA6C,MAAzBD,QAAQC,SAASC,KAExFC,EAA8E,YAA/C,oBAATC,KAAuB,YAAcd,EAAQc,QAAuBA,KAAKV,aAAyC,+BAA1BU,KAAKV,YAAYW,KAM/HC,EAA4B,oBAAXT,QAA0C,WAAhBA,OAAOQ,MAA0C,oBAAdE,YAA8BA,UAAUC,UAAUC,SAAS,YAAcF,UAAUC,UAAUC,SAAS,UAEpLC,EAAyB,oBAATC,WAA6C,IAAdA,KAAKC,KAExDC,EAAQ,GAAYjB,EACpBiB,EAAQ,GAAcV,EACtBU,EAAQ,GAASd,EACjBc,EAAQ,GAAUP,EAClBO,EAAQ,GAASH,G,iBC1BjB,IAAII,EAAyB,oBAATV,KAAuBA,KAAOW,KAC9CC,EAAW,WACf,SAASC,IACTF,KAAKG,OAAQ,EACbH,KAAKI,aAAeL,EAAOK,aAG3B,OADAF,EAAEtB,UAAYmB,EACP,IAAIG,EANI,IAQf,SAAUb,IAEQ,SAAUS,GAE1B,IAAIO,EACY,oBAAqBhB,EADjCgB,EAEQ,WAAYhB,GAAQ,aAAcb,OAF1C6B,EAIA,eAAgBhB,GAChB,SAAUA,GACV,WACE,IAEE,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,EAAd,uBA8BP,SAAoBpH,EAAaH,GAC/B,OAAO+B,EAAQ5B,EAAKH,GAAS1B,MAC3B,SAAC+C,GACC,IAAM4G,EAAc5G,EACpB,OAAOA,EAASpC,OAAOX,MACrB,SAAC6I,GAGC,OAFAc,EAAYd,KAAOA,EACnBc,EAAY5G,SAAWA,EAChB4G,QAnCRc,CAAW5I,EAAD,GACfF,OAAQ,OACRnE,KAAMoD,KAAK6I,UAAUZ,IAClBQ,IAIP,IAAMlB,EAAY,SAACuC,GAAD,OAAoB,SACpCF,GAIA,OAAOD,EAAM,OACRC,GADO,IAEV3B,KAAM,OACD2B,EAAgB3B,MADjB,QAJY,eAMD6B,SAKNC,EAAUxC,EAAU,WACpByC,EAAczC,EAAU,eACxBrK,EAAUqK,EAAU,WACpB0C,EAAS,SAACC,GAAD,OACpBP,EAAM,OAAIO,GAAL,IAAuBlL,KAAM,c","sources":["webpack://PagerDuty/./node_modules/browser-or-node/lib/index.js","webpack://PagerDuty/./node_modules/cross-fetch/dist/browser-ponyfill.js","webpack://PagerDuty/webpack/bootstrap","webpack://PagerDuty/webpack/runtime/compat get default export","webpack://PagerDuty/webpack/runtime/define property getters","webpack://PagerDuty/webpack/runtime/hasOwnProperty shorthand","webpack://PagerDuty/webpack/runtime/make namespace object","webpack://PagerDuty/./src/common.ts","webpack://PagerDuty/./src/api.ts","webpack://PagerDuty/./src/events.ts"],"sourcesContent":["\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\n\nvar _typeof = typeof Symbol === \"function\" && typeof Symbol.iterator === \"symbol\" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === \"function\" && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj; };\n\nvar isBrowser = typeof window !== \"undefined\" && typeof window.document !== \"undefined\";\n\nvar isNode = typeof process !== \"undefined\" && process.versions != null && process.versions.node != null;\n\nvar isWebWorker = (typeof self === \"undefined\" ? \"undefined\" : _typeof(self)) === \"object\" && self.constructor && self.constructor.name === \"DedicatedWorkerGlobalScope\";\n\n/**\n * @see https://github.com/jsdom/jsdom/releases/tag/12.0.0\n * @see https://github.com/jsdom/jsdom/issues/1537\n */\nvar isJsDom = typeof window !== \"undefined\" && window.name === \"nodejs\" || typeof navigator !== \"undefined\" && (navigator.userAgent.includes(\"Node.js\") || navigator.userAgent.includes(\"jsdom\"));\n\nvar isDeno = typeof Deno !== \"undefined\" && typeof Deno.core !== \"undefined\";\n\nexports.isBrowser = isBrowser;\nexports.isWebWorker = isWebWorker;\nexports.isNode = isNode;\nexports.isJsDom = isJsDom;\nexports.isDeno = isDeno;","var global = typeof self !== 'undefined' ? self : this;\nvar __self__ = (function () {\nfunction F() {\nthis.fetch = false;\nthis.DOMException = global.DOMException\n}\nF.prototype = global;\nreturn new F();\n})();\n(function(self) {\n\nvar irrelevant = (function (exports) {\n\n var support = {\n searchParams: 'URLSearchParams' in self,\n iterable: 'Symbol' in self && 'iterator' in Symbol,\n blob:\n 'FileReader' in self &&\n 'Blob' in self &&\n (function() {\n try {\n new Blob();\n return true\n } catch (e) {\n return false\n }\n })(),\n formData: 'FormData' in self,\n arrayBuffer: 'ArrayBuffer' in self\n };\n\n function isDataView(obj) {\n return obj && DataView.prototype.isPrototypeOf(obj)\n }\n\n if (support.arrayBuffer) {\n var viewClasses = [\n '[object Int8Array]',\n '[object Uint8Array]',\n '[object Uint8ClampedArray]',\n '[object Int16Array]',\n '[object Uint16Array]',\n '[object Int32Array]',\n '[object Uint32Array]',\n '[object Float32Array]',\n '[object Float64Array]'\n ];\n\n var isArrayBufferView =\n ArrayBuffer.isView ||\n function(obj) {\n return obj && viewClasses.indexOf(Object.prototype.toString.call(obj)) > -1\n };\n }\n\n function normalizeName(name) {\n if (typeof name !== 'string') {\n name = String(name);\n }\n if (/[^a-z0-9\\-#$%&'*+.^_`|~]/i.test(name)) {\n throw new TypeError('Invalid character in header field name')\n }\n return name.toLowerCase()\n }\n\n function normalizeValue(value) {\n if (typeof value !== 'string') {\n value = String(value);\n }\n return value\n }\n\n // Build a destructive iterator for the value list\n function iteratorFor(items) {\n var iterator = {\n next: function() {\n var value = items.shift();\n return {done: value === undefined, value: value}\n }\n };\n\n if (support.iterable) {\n iterator[Symbol.iterator] = function() {\n return iterator\n };\n }\n\n return iterator\n }\n\n function Headers(headers) {\n this.map = {};\n\n if (headers instanceof Headers) {\n headers.forEach(function(value, name) {\n this.append(name, value);\n }, this);\n } else if (Array.isArray(headers)) {\n headers.forEach(function(header) {\n this.append(header[0], header[1]);\n }, this);\n } else if (headers) {\n Object.getOwnPropertyNames(headers).forEach(function(name) {\n this.append(name, headers[name]);\n }, this);\n }\n }\n\n Headers.prototype.append = function(name, value) {\n name = normalizeName(name);\n value = normalizeValue(value);\n var oldValue = this.map[name];\n this.map[name] = oldValue ? oldValue + ', ' + value : value;\n };\n\n Headers.prototype['delete'] = function(name) {\n delete this.map[normalizeName(name)];\n };\n\n Headers.prototype.get = function(name) {\n name = normalizeName(name);\n return this.has(name) ? this.map[name] : null\n };\n\n Headers.prototype.has = function(name) {\n return this.map.hasOwnProperty(normalizeName(name))\n };\n\n Headers.prototype.set = function(name, value) {\n this.map[normalizeName(name)] = normalizeValue(value);\n };\n\n Headers.prototype.forEach = function(callback, thisArg) {\n for (var name in this.map) {\n if (this.map.hasOwnProperty(name)) {\n callback.call(thisArg, this.map[name], name, this);\n }\n }\n };\n\n Headers.prototype.keys = function() {\n var items = [];\n this.forEach(function(value, name) {\n items.push(name);\n });\n return iteratorFor(items)\n };\n\n Headers.prototype.values = function() {\n var items = [];\n this.forEach(function(value) {\n items.push(value);\n });\n return iteratorFor(items)\n };\n\n Headers.prototype.entries = function() {\n var items = [];\n this.forEach(function(value, name) {\n items.push([name, value]);\n });\n return iteratorFor(items)\n };\n\n if (support.iterable) {\n Headers.prototype[Symbol.iterator] = Headers.prototype.entries;\n }\n\n function consumed(body) {\n if (body.bodyUsed) {\n return Promise.reject(new TypeError('Already read'))\n }\n body.bodyUsed = true;\n }\n\n function fileReaderReady(reader) {\n return new Promise(function(resolve, reject) {\n reader.onload = function() {\n resolve(reader.result);\n };\n reader.onerror = function() {\n reject(reader.error);\n };\n })\n }\n\n function readBlobAsArrayBuffer(blob) {\n var reader = new FileReader();\n var promise = fileReaderReady(reader);\n reader.readAsArrayBuffer(blob);\n return promise\n }\n\n function readBlobAsText(blob) {\n var reader = new FileReader();\n var promise = fileReaderReady(reader);\n reader.readAsText(blob);\n return promise\n }\n\n function readArrayBufferAsText(buf) {\n var view = new Uint8Array(buf);\n var chars = new Array(view.length);\n\n for (var i = 0; i < view.length; i++) {\n chars[i] = String.fromCharCode(view[i]);\n }\n return chars.join('')\n }\n\n function bufferClone(buf) {\n if (buf.slice) {\n return buf.slice(0)\n } else {\n var view = new Uint8Array(buf.byteLength);\n view.set(new Uint8Array(buf));\n return view.buffer\n }\n }\n\n function Body() {\n this.bodyUsed = false;\n\n this._initBody = function(body) {\n this._bodyInit = body;\n if (!body) {\n this._bodyText = '';\n } else if (typeof body === 'string') {\n this._bodyText = body;\n } else if (support.blob && Blob.prototype.isPrototypeOf(body)) {\n this._bodyBlob = body;\n } else if (support.formData && FormData.prototype.isPrototypeOf(body)) {\n this._bodyFormData = body;\n } else if (support.searchParams && URLSearchParams.prototype.isPrototypeOf(body)) {\n this._bodyText = body.toString();\n } else if (support.arrayBuffer && support.blob && isDataView(body)) {\n this._bodyArrayBuffer = bufferClone(body.buffer);\n // IE 10-11 can't handle a DataView body.\n this._bodyInit = new Blob([this._bodyArrayBuffer]);\n } else if (support.arrayBuffer && (ArrayBuffer.prototype.isPrototypeOf(body) || isArrayBufferView(body))) {\n this._bodyArrayBuffer = bufferClone(body);\n } else {\n this._bodyText = body = Object.prototype.toString.call(body);\n }\n\n if (!this.headers.get('content-type')) {\n if (typeof body === 'string') {\n this.headers.set('content-type', 'text/plain;charset=UTF-8');\n } else if (this._bodyBlob && this._bodyBlob.type) {\n this.headers.set('content-type', this._bodyBlob.type);\n } else if (support.searchParams && URLSearchParams.prototype.isPrototypeOf(body)) {\n this.headers.set('content-type', 'application/x-www-form-urlencoded;charset=UTF-8');\n }\n }\n };\n\n if (support.blob) {\n this.blob = function() {\n var rejected = consumed(this);\n if (rejected) {\n return rejected\n }\n\n if (this._bodyBlob) {\n return Promise.resolve(this._bodyBlob)\n } else if (this._bodyArrayBuffer) {\n return Promise.resolve(new Blob([this._bodyArrayBuffer]))\n } else if (this._bodyFormData) {\n throw new Error('could not read FormData body as blob')\n } else {\n return Promise.resolve(new Blob([this._bodyText]))\n }\n };\n\n this.arrayBuffer = function() {\n if (this._bodyArrayBuffer) {\n return consumed(this) || Promise.resolve(this._bodyArrayBuffer)\n } else {\n return this.blob().then(readBlobAsArrayBuffer)\n }\n };\n }\n\n this.text = function() {\n var rejected = consumed(this);\n if (rejected) {\n return rejected\n }\n\n if (this._bodyBlob) {\n return readBlobAsText(this._bodyBlob)\n } else if (this._bodyArrayBuffer) {\n return Promise.resolve(readArrayBufferAsText(this._bodyArrayBuffer))\n } else if (this._bodyFormData) {\n throw new Error('could not read FormData body as text')\n } else {\n return Promise.resolve(this._bodyText)\n }\n };\n\n if (support.formData) {\n this.formData = function() {\n return this.text().then(decode)\n };\n }\n\n this.json = function() {\n return this.text().then(JSON.parse)\n };\n\n return this\n }\n\n // HTTP methods whose capitalization should be normalized\n var methods = ['DELETE', 'GET', 'HEAD', 'OPTIONS', 'POST', 'PUT'];\n\n function normalizeMethod(method) {\n var upcased = method.toUpperCase();\n return methods.indexOf(upcased) > -1 ? upcased : method\n }\n\n function Request(input, options) {\n options = options || {};\n var body = options.body;\n\n if (input instanceof Request) {\n if (input.bodyUsed) {\n throw new TypeError('Already read')\n }\n this.url = input.url;\n this.credentials = input.credentials;\n if (!options.headers) {\n this.headers = new Headers(input.headers);\n }\n this.method = input.method;\n this.mode = input.mode;\n this.signal = input.signal;\n if (!body && input._bodyInit != null) {\n body = input._bodyInit;\n input.bodyUsed = true;\n }\n } else {\n this.url = String(input);\n }\n\n this.credentials = options.credentials || this.credentials || 'same-origin';\n if (options.headers || !this.headers) {\n this.headers = new Headers(options.headers);\n }\n this.method = normalizeMethod(options.method || this.method || 'GET');\n this.mode = options.mode || this.mode || null;\n this.signal = options.signal || this.signal;\n this.referrer = null;\n\n if ((this.method === 'GET' || this.method === 'HEAD') && body) {\n throw new TypeError('Body not allowed for GET or HEAD requests')\n }\n this._initBody(body);\n }\n\n Request.prototype.clone = function() {\n return new Request(this, {body: this._bodyInit})\n };\n\n function decode(body) {\n var form = new FormData();\n body\n .trim()\n .split('&')\n .forEach(function(bytes) {\n if (bytes) {\n var split = bytes.split('=');\n var name = split.shift().replace(/\\+/g, ' ');\n var value = split.join('=').replace(/\\+/g, ' ');\n form.append(decodeURIComponent(name), decodeURIComponent(value));\n }\n });\n return form\n }\n\n function parseHeaders(rawHeaders) {\n var headers = new Headers();\n // Replace instances of \\r\\n and \\n followed by at least one space or horizontal tab with a space\n // https://tools.ietf.org/html/rfc7230#section-3.2\n var preProcessedHeaders = rawHeaders.replace(/\\r?\\n[\\t ]+/g, ' ');\n preProcessedHeaders.split(/\\r?\\n/).forEach(function(line) {\n var parts = line.split(':');\n var key = parts.shift().trim();\n if (key) {\n var value = parts.join(':').trim();\n headers.append(key, value);\n }\n });\n return headers\n }\n\n Body.call(Request.prototype);\n\n function Response(bodyInit, options) {\n if (!options) {\n options = {};\n }\n\n this.type = 'default';\n this.status = options.status === undefined ? 200 : options.status;\n this.ok = this.status >= 200 && this.status < 300;\n this.statusText = 'statusText' in options ? options.statusText : 'OK';\n this.headers = new Headers(options.headers);\n this.url = options.url || '';\n this._initBody(bodyInit);\n }\n\n Body.call(Response.prototype);\n\n Response.prototype.clone = function() {\n return new Response(this._bodyInit, {\n status: this.status,\n statusText: this.statusText,\n headers: new Headers(this.headers),\n url: this.url\n })\n };\n\n Response.error = function() {\n var response = new Response(null, {status: 0, statusText: ''});\n response.type = 'error';\n return response\n };\n\n var redirectStatuses = [301, 302, 303, 307, 308];\n\n Response.redirect = function(url, status) {\n if (redirectStatuses.indexOf(status) === -1) {\n throw new RangeError('Invalid status code')\n }\n\n return new Response(null, {status: status, headers: {location: url}})\n };\n\n exports.DOMException = self.DOMException;\n try {\n new exports.DOMException();\n } catch (err) {\n exports.DOMException = function(message, name) {\n this.message = message;\n this.name = name;\n var error = Error(message);\n this.stack = error.stack;\n };\n exports.DOMException.prototype = Object.create(Error.prototype);\n exports.DOMException.prototype.constructor = exports.DOMException;\n }\n\n function fetch(input, init) {\n return new Promise(function(resolve, reject) {\n var request = new Request(input, init);\n\n if (request.signal && request.signal.aborted) {\n return reject(new exports.DOMException('Aborted', 'AbortError'))\n }\n\n var xhr = new XMLHttpRequest();\n\n function abortXhr() {\n xhr.abort();\n }\n\n xhr.onload = function() {\n var options = {\n status: xhr.status,\n statusText: xhr.statusText,\n headers: parseHeaders(xhr.getAllResponseHeaders() || '')\n };\n options.url = 'responseURL' in xhr ? xhr.responseURL : options.headers.get('X-Request-URL');\n var body = 'response' in xhr ? xhr.response : xhr.responseText;\n resolve(new Response(body, options));\n };\n\n xhr.onerror = function() {\n reject(new TypeError('Network request failed'));\n };\n\n xhr.ontimeout = function() {\n reject(new TypeError('Network request failed'));\n };\n\n xhr.onabort = function() {\n reject(new exports.DOMException('Aborted', 'AbortError'));\n };\n\n xhr.open(request.method, request.url, true);\n\n if (request.credentials === 'include') {\n xhr.withCredentials = true;\n } else if (request.credentials === 'omit') {\n xhr.withCredentials = false;\n }\n\n if ('responseType' in xhr && support.blob) {\n xhr.responseType = 'blob';\n }\n\n request.headers.forEach(function(value, name) {\n xhr.setRequestHeader(name, value);\n });\n\n if (request.signal) {\n request.signal.addEventListener('abort', abortXhr);\n\n xhr.onreadystatechange = function() {\n // DONE (success or failure)\n if (xhr.readyState === 4) {\n request.signal.removeEventListener('abort', abortXhr);\n }\n };\n }\n\n xhr.send(typeof request._bodyInit === 'undefined' ? null : request._bodyInit);\n })\n }\n\n fetch.polyfill = true;\n\n if (!self.fetch) {\n self.fetch = fetch;\n self.Headers = Headers;\n self.Request = Request;\n self.Response = Response;\n }\n\n exports.Headers = Headers;\n exports.Request = Request;\n exports.Response = Response;\n exports.fetch = fetch;\n\n Object.defineProperty(exports, '__esModule', { value: true });\n\n return exports;\n\n}({}));\n})(__self__);\n__self__.fetch.ponyfill = true;\n// Remove \"polyfill\" property added by whatwg-fetch\ndelete __self__.fetch.polyfill;\n// Choose between native implementation (global) or custom implementation (__self__)\n// var ctx = global.fetch ? global : __self__;\nvar ctx = __self__; // this line disable service worker support temporarily\nexports = ctx.fetch // To enable: import fetch from 'cross-fetch'\nexports.default = ctx.fetch // For TypeScript consumers without esModuleInterop.\nexports.fetch = ctx.fetch // To enable: import {fetch} from 'cross-fetch'\nexports.Headers = ctx.Headers\nexports.Request = ctx.Request\nexports.Response = ctx.Response\nmodule.exports = exports\n","// The module cache\nvar __webpack_module_cache__ = {};\n\n// The require function\nfunction __webpack_require__(moduleId) {\n\t// Check if module is in cache\n\tvar cachedModule = __webpack_module_cache__[moduleId];\n\tif (cachedModule !== undefined) {\n\t\treturn cachedModule.exports;\n\t}\n\t// Create a new module (and put it into the cache)\n\tvar module = __webpack_module_cache__[moduleId] = {\n\t\t// no module.id needed\n\t\t// no module.loaded needed\n\t\texports: {}\n\t};\n\n\t// Execute the module function\n\t__webpack_modules__[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n\t// Return the exports of the module\n\treturn module.exports;\n}\n\n","// getDefaultExport function for compatibility with non-harmony modules\n__webpack_require__.n = (module) => {\n\tvar getter = module && module.__esModule ?\n\t\t() => (module['default']) :\n\t\t() => (module);\n\t__webpack_require__.d(getter, { a: getter });\n\treturn getter;\n};","// define getter functions for harmony exports\n__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n\t\tif(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n\t\t\tObject.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n\t\t}\n\t}\n};","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","// define __esModule on exports\n__webpack_require__.r = (exports) => {\n\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n\t}\n\tObject.defineProperty(exports, '__esModule', { value: true });\n};","/* LEGACY-BROWSER-SUPPORT-START */\nimport fetch, {Headers} from 'cross-fetch';\nimport {isBrowser, isNode, isWebWorker, isJsDom, isDeno} from 'browser-or-node';\n/* LEGACY-BROWSER-SUPPORT-END */\n\nconst VERSION = '2.0.0';\n\ntype QueryParameter = Record>;\n\nexport interface RequestOptions extends RequestInit {\n queryParameters?: QueryParameter;\n retryCount?: number;\n requestTimeout?: number;\n requestTimer?: any;\n retryTimeout?: number;\n timeout?: number;\n}\n\nexport function request(\n url: string | URL,\n options: RequestOptions = {}\n): Promise {\n const {queryParameters, requestTimeout = 30000} = options;\n\n url = new URL(url.toString());\n url = applyParameters(url, queryParameters);\n options = applyTimeout(options, requestTimeout);\n\n return fetch_retry(url.toString(), 3, {\n ...options,\n headers: new Headers({\n 'Content-Type': 'application/json; charset=utf-8',\n /* LEGACY-BROWSER-SUPPORT-START */\n ...userAgentHeader(),\n /* LEGACY-BROWSER-SUPPORT-END */\n ...options.headers,\n }),\n });\n}\n\nfunction fetch_retry(\n url: string,\n retries: number,\n options: RequestOptions\n): Promise {\n return new Promise((resolve, reject) => {\n fetch(url, options)\n .then(response => {\n // We don't want to `reject` when retries have finished\n // Instead simply stop trying and return.\n if (retries === 0) return resolve(response);\n if (response.status === 429) {\n const {retryTimeout = 20000} = options;\n retryTimeoutPromise(retryTimeout).then(() => {\n fetch_retry(url, retries - 1, options)\n .then(resolve)\n .catch(reject);\n });\n } else {\n clearTimeout(options.requestTimer);\n resolve(response);\n }\n })\n .catch(reject);\n });\n}\n\nconst retryTimeoutPromise = (milliseconds: number) => {\n return new Promise(resolve => setTimeout(resolve, milliseconds));\n};\n\nfunction userAgentHeader(): object {\n if (isNode) {\n return {\n 'User-Agent': `pdjs/${VERSION} (${process.version}/${process.platform})`,\n };\n } else if (isWebWorker) {\n return {\n 'User-Agent': `pdjs/${VERSION} (WebWorker)`,\n };\n } else if (isJsDom) {\n return {\n 'User-Agent': `pdjs/${VERSION} (JsDom)`,\n };\n } else if (isDeno) {\n return {\n 'User-Agent': `pdjs/${VERSION} (Deno)`,\n };\n } else if (isBrowser) {\n return {\n // Note: This will not work consistently for all browsers as some silently drop the userAgent Header.\n 'User-Agent': `pdjs/${VERSION} (${window.navigator.userAgent})`,\n };\n } else {\n return {};\n }\n}\n\nfunction applyParameters(url: URL, queryParameters?: QueryParameter): URL {\n if (!queryParameters) return url;\n\n const combinedParameters = url.searchParams;\n\n for (const key of Object.keys(queryParameters)) {\n const parameter = queryParameters[key];\n if (Array.isArray(parameter)) {\n // Support for array based keys like `additional_fields[]`\n parameter.forEach(item => {\n combinedParameters.append(key, item);\n });\n } else {\n combinedParameters.append(key, parameter);\n }\n }\n\n url.search = combinedParameters.toString();\n return url;\n}\n\nfunction applyTimeout(init: RequestOptions, timeout?: number): RequestOptions {\n if (!timeout) return init;\n const timer = setTimeout(() => {}, timeout);\n return {\n ...init,\n requestTimer: timer,\n };\n}\n","import {request, RequestOptions} from './common';\n\nexport interface ShorthandCall {\n (res: string, apiParameters?: Partial): APIPromise;\n}\n\nexport interface PartialCall {\n (apiParameters: APIParameters): APIPromise;\n (apiParameters: Partial): PartialCall;\n get: ShorthandCall;\n post: ShorthandCall;\n put: ShorthandCall;\n patch: ShorthandCall;\n delete: ShorthandCall;\n all: ShorthandCall;\n}\n\nexport type APIParameters = RequestOptions & {\n endpoint?: string;\n url?: string;\n data?: object;\n token?: string;\n tokenType?: string;\n server?: string;\n version?: number;\n} & ({endpoint: string} | {url: string});\n\nexport type APIPromise = Promise;\n\nexport interface APIResponse extends Response {\n data: any;\n resource: any;\n response: Response;\n next?: () => APIPromise;\n}\n\nexport function api(apiParameters: APIParameters): APIPromise;\nexport function api(apiParameters: Partial): PartialCall;\nexport function api(\n apiParameters: Partial\n): APIPromise | PartialCall {\n // If the apiParameters don't include `endpoint` treat it as a partial\n // application.\n if (!apiParameters.endpoint && !apiParameters.url) {\n return partialCall(apiParameters);\n }\n\n // allows for Token and Bearer token types to be used in Authorization\n type typeMap = {\n [key: string]: string;\n };\n\n const types: typeMap = {\n bearer: 'Bearer ',\n token: 'Token token=',\n };\n\n const {\n endpoint,\n server = 'api.pagerduty.com',\n token,\n tokenType = apiParameters.tokenType || 'token',\n url,\n version = 2,\n data,\n ...rest\n } = apiParameters;\n\n const config: RequestOptions = {\n method: 'GET',\n ...rest,\n headers: {\n Accept: `application/vnd.pagerduty+json;version=${version}`,\n Authorization: `${types[tokenType]}${token!}`,\n ...rest.headers,\n },\n };\n\n // Allow `data` for `queryParameters` for requests without bodies.\n if (isReadonlyRequest(config.method!) && data) {\n config.queryParameters =\n config.queryParameters ?? (data as Record);\n } else {\n config.body = JSON.stringify(data);\n }\n\n return apiRequest(\n url ?? `https://${server}/${endpoint!.replace(/^\\/+/, '')}`,\n config\n );\n}\n\nfunction apiRequest(url: string, options: RequestOptions): APIPromise {\n return request(url, options).then(\n (response: Response): APIPromise => {\n const apiResponse = response as APIResponse;\n apiResponse.response = response;\n\n if (response.status === 204) {\n return Promise.resolve(apiResponse);\n }\n\n return response\n .json()\n .then(\n (data): APIResponse => {\n const resource = resourceKey(url, options.method);\n apiResponse.next = nextFunc(url, options, data);\n apiResponse.data = data;\n apiResponse.resource = resource ? data[resource] : null;\n return apiResponse;\n }\n )\n .catch(() => Promise.reject(apiResponse));\n }\n );\n}\n\nfunction resourceKey(url: string, method?: string) {\n const resource = url.match(/.+.com\\/(?[\\w]+)/);\n if (resource) {\n const resourceName = resource[1];\n if (method && method.toLowerCase() === 'get') {\n return resourceName;\n }\n if (resourceName.endsWith('ies')) {\n return resourceName.slice(0, -3) + 'y';\n } else if (resourceName.endsWith('s')) {\n return resourceName.slice(0, -1);\n }\n return resourceName;\n }\n return null;\n}\n\nfunction isReadonlyRequest(method: string) {\n return !['PUT', 'POST', 'DELETE', 'PATCH'].includes(\n method.toUpperCase() ?? 'GET'\n );\n}\n\ninterface OffsetPagination {\n type: 'offset';\n more?: boolean;\n offset?: number;\n limit?: number;\n}\n\ninterface CursorPagination {\n type: 'cursor';\n cursor?: string;\n limit?: number;\n}\n\nfunction isOffsetPagination(\n data: OffsetPagination | CursorPagination\n): data is OffsetPagination {\n if ((data as OffsetPagination).offset !== undefined) {\n return true;\n }\n return false;\n}\n\nfunction isCursorPagination(\n data: OffsetPagination | CursorPagination\n): data is CursorPagination {\n if ((data as CursorPagination).cursor !== undefined) {\n return true;\n }\n return false;\n}\n\nfunction nextFunc(\n url: string,\n options: RequestOptions,\n data: OffsetPagination | CursorPagination\n) {\n if (isOffsetPagination(data)) {\n if (data?.more && typeof data.offset !== undefined && data.limit) {\n return () =>\n apiRequest(url, {\n ...options,\n queryParameters: {\n ...options.queryParameters,\n limit: data.limit!.toString(),\n offset: (data.limit! + data.offset!).toString(),\n },\n });\n }\n } else if (isCursorPagination(data)) {\n if (data?.cursor) {\n return () =>\n apiRequest(url, {\n ...options,\n queryParameters: {\n ...options.queryParameters,\n cursor: data.cursor!,\n limit: data.limit!.toString(),\n },\n });\n }\n }\n\n return undefined;\n}\n\nfunction partialCall(apiParameters: Partial) {\n const partialParameters = apiParameters;\n const partial = ((apiParameters: Partial) =>\n api({...partialParameters, ...apiParameters})) as PartialCall;\n\n const shorthand = (method: string) => (\n endpoint: string,\n shorthandParameters?: Partial\n ): APIPromise =>\n api({\n endpoint,\n method,\n ...partialParameters,\n ...shorthandParameters,\n }) as APIPromise;\n\n partial.get = shorthand('get');\n partial.post = shorthand('post');\n partial.put = shorthand('put');\n partial.patch = shorthand('patch');\n partial.delete = shorthand('delete');\n\n partial.all = (\n endpoint: string,\n shorthandParameters?: Partial\n ): APIPromise => {\n function allInner(responses: APIResponse[]): Promise {\n const response = responses[responses.length - 1];\n if (!response.next) {\n // Base case, resolve and return all responses.\n return Promise.resolve(responses);\n }\n // If there are still more resources to get then concat and repeat.\n return response\n .next()\n .then(response => allInner(responses.concat([response])));\n }\n\n function repackResponses(responses: APIResponse[]): APIPromise {\n // Repack the responses object to make it more user friendly.\n const repackedResponse = responses.shift() as APIResponse; // Use the first response to build the standard response object\n repackedResponse.data = [repackedResponse.data];\n responses.forEach(response => {\n repackedResponse.data = repackedResponse.data.concat(response.data);\n repackedResponse.resource = repackedResponse.resource.concat(\n response.resource\n );\n });\n return Promise.resolve(repackedResponse);\n }\n\n const method = 'get';\n return (api({\n endpoint,\n method,\n ...partialParameters,\n ...shorthandParameters,\n }) as APIPromise)\n .then(response => allInner([response]))\n .then(responses => repackResponses(responses));\n };\n\n return partial;\n}\n","import {request, RequestOptions} from './common';\n\nexport type Action = 'trigger' | 'acknowledge' | 'resolve';\n\nexport type EventPromise = Promise;\n\nexport interface EventResponse extends Response {\n data: any;\n response: Response;\n}\n\nexport type Severity = 'critical' | 'error' | 'warning' | 'info';\n\nexport interface Image {\n src: string;\n href?: string;\n alt?: string;\n}\n\nexport interface Link {\n href: string;\n text?: string;\n}\n\nexport interface EventPayloadV2 {\n routing_key: string;\n event_action: Action;\n dedup_key?: string;\n payload: {\n summary: string;\n source: string;\n severity: Severity;\n timestamp?: string;\n component?: string;\n group?: string;\n class?: string;\n custom_details?: object;\n };\n images?: Array;\n links?: Array;\n}\n\nexport interface EventParameters extends RequestOptions {\n data: EventPayloadV2;\n type?: string;\n server?: string;\n}\n\nexport interface ChangePayload {\n routing_key: string;\n payload: {\n summary: string;\n source?: string;\n timestamp: string;\n custom_details?: object;\n };\n images?: Array;\n links?: Array;\n}\nexport interface ChangeParameters extends RequestOptions {\n data: ChangePayload;\n type?: string;\n server?: string;\n}\n\nexport function event(\n eventParameters: EventParameters | ChangeParameters\n): EventPromise {\n const {\n server = 'events.pagerduty.com',\n type = 'event',\n data,\n ...config\n } = eventParameters;\n\n let url = `https://${server}/v2/enqueue`;\n if (type === 'change') {\n url = `https://${server}/v2/change/enqueue`;\n }\n\n return eventFetch(url, {\n method: 'POST',\n body: JSON.stringify(data),\n ...config,\n });\n}\n\nconst shorthand = (action: Action) => (\n eventParameters: EventParameters\n): EventPromise => {\n const typeField = 'event_action';\n\n return event({\n ...eventParameters,\n data: {\n ...eventParameters.data,\n [typeField]: action,\n },\n });\n};\n\nexport const trigger = shorthand('trigger');\nexport const acknowledge = shorthand('acknowledge');\nexport const resolve = shorthand('resolve');\nexport const change = (changeParameters: ChangeParameters) =>\n event({...changeParameters, type: 'change'});\n\nfunction eventFetch(url: string, options: RequestOptions): EventPromise {\n return request(url, options).then(\n (response: Response): EventPromise => {\n const apiResponse = response as EventResponse;\n return response.json().then(\n (data): EventResponse => {\n apiResponse.data = data;\n apiResponse.response = response;\n return apiResponse;\n }\n );\n }\n );\n}\n"],"names":["_typeof","Symbol","iterator","obj","constructor","prototype","isBrowser","window","document","isNode","process","versions","node","isWebWorker","self","name","isJsDom","navigator","userAgent","includes","isDeno","Deno","core","exports","global","this","__self__","F","fetch","DOMException","support","Blob","e","viewClasses","isArrayBufferView","ArrayBuffer","isView","indexOf","Object","toString","call","normalizeName","String","test","TypeError","toLowerCase","normalizeValue","value","iteratorFor","items","next","shift","done","undefined","Headers","headers","map","forEach","append","Array","isArray","header","getOwnPropertyNames","consumed","body","bodyUsed","Promise","reject","fileReaderReady","reader","resolve","onload","result","onerror","error","readBlobAsArrayBuffer","blob","FileReader","promise","readAsArrayBuffer","bufferClone","buf","slice","view","Uint8Array","byteLength","set","buffer","Body","_initBody","_bodyInit","_bodyText","isPrototypeOf","_bodyBlob","FormData","_bodyFormData","URLSearchParams","DataView","_bodyArrayBuffer","get","type","rejected","Error","arrayBuffer","then","text","readAsText","chars","length","i","fromCharCode","join","readArrayBufferAsText","formData","decode","json","JSON","parse","oldValue","has","hasOwnProperty","callback","thisArg","keys","push","values","entries","methods","Request","input","options","method","upcased","url","credentials","mode","signal","toUpperCase","referrer","form","trim","split","bytes","replace","decodeURIComponent","Response","bodyInit","status","ok","statusText","clone","response","redirectStatuses","redirect","RangeError","location","err","message","stack","create","init","request","aborted","xhr","XMLHttpRequest","abortXhr","abort","rawHeaders","getAllResponseHeaders","line","parts","key","responseURL","responseText","ontimeout","onabort","open","withCredentials","responseType","setRequestHeader","addEventListener","onreadystatechange","readyState","removeEventListener","send","polyfill","defineProperty","ponyfill","ctx","module","__webpack_module_cache__","__webpack_require__","moduleId","cachedModule","__webpack_modules__","n","getter","__esModule","d","a","definition","o","enumerable","prop","r","toStringTag","VERSION","queryParameters","requestTimeout","applyParameters","URL","applyTimeout","fetch_retry","userAgentHeader","retries","retryTimeout","retryTimeoutPromise","clearTimeout","requestTimer","milliseconds","setTimeout","version","platform","combinedParameters","searchParams","parameter","item","search","timeout","timer","api","apiParameters","endpoint","partialParameters","partial","shorthand","shorthandParameters","post","put","patch","all","allInner","responses","concat","repackedResponse","data","resource","repackResponses","partialCall","server","token","tokenType","rest","config","Accept","Authorization","bearer","stringify","apiRequest","apiResponse","match","resourceName","endsWith","resourceKey","offset","isOffsetPagination","more","limit","cursor","isCursorPagination","nextFunc","event","eventParameters","eventFetch","action","trigger","acknowledge","change","changeParameters"],"sourceRoot":""} -------------------------------------------------------------------------------- /dist/pdjs.js: -------------------------------------------------------------------------------- 1 | var PagerDuty;(()=>{"use strict";var e={d:(t,r)=>{for(var n in r)e.o(r,n)&&!e.o(t,n)&&Object.defineProperty(t,n,{enumerable:!0,get:r[n]})},o:(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r:e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})}},t={};function r(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function n(e){for(var t=1;t1&&void 0!==arguments[1]?arguments[1]:{},r=t,o=r.queryParameters,u=r.requestTimeout,i=void 0===u?3e4:u;return e=a(e=new URL(e.toString()),o),t=f(t,i),c(e.toString(),3,n(n({},t),{},{headers:new Headers(n({"Content-Type":"application/json; charset=utf-8"},t.headers))}))}function c(e,t,r){return new Promise((function(n,o){fetch(e,r).then((function(u){if(0===t)return n(u);if(429===u.status){var a=r.retryTimeout;i(void 0===a?2e4:a).then((function(){c(e,t-1,r).then(n).catch(o)}))}else clearTimeout(r.requestTimer),n(u)})).catch(o)}))}e.r(t),e.d(t,{acknowledge:()=>E,api:()=>g,change:()=>x,event:()=>S,resolve:()=>D,trigger:()=>k});var i=function(e){return new Promise((function(t){return setTimeout(t,e)}))};function a(e,t){if(!t)return e;for(var r=e.searchParams,n=function(){var e=u[o],n=t[e];Array.isArray(n)?n.forEach((function(t){r.append(e,t)})):r.append(e,n)},o=0,u=Object.keys(t);o]+)>/g,(function(e,t){return"$"+u[t]})))}if("function"==typeof o){var c=this;return e[Symbol.replace].call(this,r,(function(){var e=arguments;return"object"!==l(e[e.length-1])&&(e=[].slice.call(e)).push(n(e,c)),o.apply(this,e)}))}return e[Symbol.replace].call(this,r,o)},p.apply(this,arguments)}function y(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),t&&b(e,t)}function b(e,t){return b=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e},b(e,t)}function v(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function O(e){for(var t=1;t=0||(o[r]=e[r]);return o}(e,t);if(Object.getOwnPropertySymbols){var u=Object.getOwnPropertySymbols(e);for(n=0;n=0||Object.prototype.propertyIsEnumerable.call(e,r)&&(o[r]=e[r])}return o}(e,s),d=O(O({method:"GET"},v),{},{headers:O({Accept:"application/vnd.pagerduty+json;version=".concat(y),Authorization:"".concat({bearer:"Bearer ",token:"Token token="}[f]).concat(i)},v.headers)});return r=d.method,!["PUT","POST","DELETE","PATCH"].includes(null!==(n=r.toUpperCase())&&void 0!==n?n:"GET")&&b?d.queryParameters=null!==(t=d.queryParameters)&&void 0!==t?t:b:d.body=JSON.stringify(b),h(null!=l?l:"https://".concat(c,"/").concat(o.replace(/^\/+/,"")),d)}function h(e,t){return u(e,t).then((function(r){var n=r;return n.response=r,204===r.status?Promise.resolve(n):r.json().then((function(r){var o=function(e,t){var r=e.match(p(/.+.com\/([0-9A-Z_a-z]+)/,{resource:1}));if(r){var n=r[1];return t&&"get"===t.toLowerCase()?n:n.endsWith("ies")?n.slice(0,-3)+"y":n.endsWith("s")?n.slice(0,-1):n}return null}(e,t.method);return n.next=function(e,t,r){if(function(e){return void 0!==e.offset}(r)){if(null!=r&&r.more&&void 0!==l(r.offset)&&r.limit)return function(){return h(e,O(O({},t),{},{queryParameters:O(O({},t.queryParameters),{},{limit:r.limit.toString(),offset:(r.limit+r.offset).toString()})}))}}else if(function(e){return void 0!==e.cursor}(r)&&null!=r&&r.cursor)return function(){return h(e,O(O({},t),{},{queryParameters:O(O({},t.queryParameters),{},{cursor:r.cursor,limit:r.limit.toString()})}))}}(e,t,r),n.data=r,n.resource=o?r[o]:null,n})).catch((function(){return Promise.reject(n)}))}))}var m=["server","type","data"];function j(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function P(e){for(var t=1;t=0||(o[r]=e[r]);return o}(e,t);if(Object.getOwnPropertySymbols){var u=Object.getOwnPropertySymbols(e);for(n=0;n=0||Object.prototype.propertyIsEnumerable.call(e,r)&&(o[r]=e[r])}return o}(e,m),a="https://".concat(r,"/v2/enqueue");return"change"===o&&(a="https://".concat(r,"/v2/change/enqueue")),function(e,t){return u(e,t).then((function(e){var t=e;return e.json().then((function(r){return t.data=r,t.response=e,t}))}))}(a,P({method:"POST",body:JSON.stringify(c)},i))}var T=function(e){return function(t){return S(P(P({},t),{},{data:P(P({},t.data),{},w({},"event_action",e))}))}},k=T("trigger"),E=T("acknowledge"),D=T("resolve"),x=function(e){return S(P(P({},e),{},{type:"change"}))};PagerDuty=t})(); 2 | //# sourceMappingURL=pdjs.js.map -------------------------------------------------------------------------------- /dist/pdjs.js.map: -------------------------------------------------------------------------------- 1 | {"version":3,"file":"pdjs.js","mappings":"iCACA,IAAIA,EAAsB,CCA1BA,EAAwB,CAACC,EAASC,KACjC,IAAI,IAAIC,KAAOD,EACXF,EAAoBI,EAAEF,EAAYC,KAASH,EAAoBI,EAAEH,EAASE,IAC5EE,OAAOC,eAAeL,EAASE,EAAK,CAAEI,YAAY,EAAMC,IAAKN,EAAWC,MCJ3EH,EAAwB,CAACS,EAAKC,IAAUL,OAAOM,UAAUC,eAAeC,KAAKJ,EAAKC,GCClFV,EAAyBC,IACH,oBAAXa,QAA0BA,OAAOC,aAC1CV,OAAOC,eAAeL,EAASa,OAAOC,YAAa,CAAEC,MAAO,WAE7DX,OAAOC,eAAeL,EAAS,aAAc,CAAEe,OAAO,M,4rBCUhD,SAASC,EACdC,GAEmB,IADnBC,EACmB,uDADO,GAE1B,EAAkDA,EAA3CC,EAAP,EAAOA,gBAAP,IAAwBC,eAAAA,OAAxB,MAAyC,IAAzC,EAMA,OAHAH,EAAMI,EADNJ,EAAM,IAAIK,IAAIL,EAAIM,YACSJ,GAC3BD,EAAUM,EAAaN,EAASE,GAEzBK,EAAYR,EAAIM,WAAY,EAAjB,OACbL,GADa,IAEhBQ,QAAS,IAAIC,QAAJ,GACP,eAAgB,mCAEbT,EAAQQ,aAKjB,SAASD,EACPR,EACAW,EACAV,GAEA,OAAO,IAAIW,SAAQ,SAACC,EAASC,GAC3BC,MAAMf,EAAKC,GACRe,MAAK,SAAAC,GAGJ,GAAgB,IAAZN,EA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ACR,OAAO,kBACLf,EAAW3E,EAAD,EAAC,KACNC,GADK,IAERC,gBAAiB,OACZD,EAAQC,iBADE,IAEbwF,OAAQjC,EAAKiC,OACbD,MAAOhC,EAAKgC,MAAOnF,iBA1FAsF,CAAS5F,EAAKC,EAASwD,GAC1CoB,EAAYpB,KAAOA,EACnBoB,EAAYnB,SAAWA,EAAWD,EAAKC,GAAY,KAC5CmB,KARN,OAWE,kBAAMjE,QAAQE,OAAO+D,S,stBChD7B,SAASgB,EACdC,GAEA,MAKIA,EAJFjC,OAAAA,OADF,MACW,uBADX,IAKIiC,EAHFC,KAAAA,OAFF,MAES,QAFT,EAGEtC,EAEEqC,EAFFrC,KACGS,E,kXAJL,CAKI4B,EALJ,GAOI9F,EAAM,WAAH,OAAc6D,EAAd,eAKP,MAJa,WAATkC,IACF/F,EAAM,WAAH,OAAc6D,EAAd,uBA8BP,SAAoB7D,EAAaC,GAC/B,OAAOF,EAAQC,EAAKC,GAASe,MAC3B,SAACC,GACC,IAAM4D,EAAc5D,EACpB,OAAOA,EAAS6D,OAAO9D,MACrB,SAACyC,GAGC,OAFAoB,EAAYpB,KAAOA,EACnBoB,EAAY5D,SAAWA,EAChB4D,QAnCRmB,CAAWhG,EAAD,GACf4C,OAAQ,OACR4B,KAAMC,KAAKC,UAAUjB,IAClBS,IAIP,IAAMvB,EAAY,SAACsD,GAAD,OAAoB,SACpCH,GAIA,OAAOD,EAAM,OACRC,GADO,IAEVrC,KAAM,OACDqC,EAAgBrC,MADjB,QAJY,eAMDwC,SAKNC,EAAUvD,EAAU,WACpBwD,EAAcxD,EAAU,eACxB9B,EAAU8B,EAAU,WACpByD,EAAS,SAACC,GAAD,OACpBR,EAAM,OAAIQ,GAAL,IAAuBN,KAAM,a","sources":["webpack://PagerDuty/webpack/bootstrap","webpack://PagerDuty/webpack/runtime/define property getters","webpack://PagerDuty/webpack/runtime/hasOwnProperty shorthand","webpack://PagerDuty/webpack/runtime/make namespace object","webpack://PagerDuty/./src/common.ts","webpack://PagerDuty/./src/api.ts","webpack://PagerDuty/./src/events.ts"],"sourcesContent":["// The require scope\nvar __webpack_require__ = {};\n\n","// define getter functions for harmony exports\n__webpack_require__.d = (exports, definition) => {\n\tfor(var key in definition) {\n\t\tif(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n\t\t\tObject.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n\t\t}\n\t}\n};","__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))","// define __esModule on exports\n__webpack_require__.r = (exports) => {\n\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n\t}\n\tObject.defineProperty(exports, '__esModule', { value: true });\n};","/* webpack-strip-block:removed */\n\nconst VERSION = '2.0.0';\n\ntype QueryParameter = Record>;\n\nexport interface RequestOptions extends RequestInit {\n queryParameters?: QueryParameter;\n retryCount?: number;\n requestTimeout?: number;\n requestTimer?: any;\n retryTimeout?: number;\n timeout?: number;\n}\n\nexport function request(\n url: string | URL,\n options: RequestOptions = {}\n): Promise {\n const {queryParameters, requestTimeout = 30000} = options;\n\n url = new URL(url.toString());\n url = applyParameters(url, queryParameters);\n options = applyTimeout(options, requestTimeout);\n\n return fetch_retry(url.toString(), 3, {\n ...options,\n headers: new Headers({\n 'Content-Type': 'application/json; charset=utf-8',\n /* webpack-strip-block:removed */\n ...options.headers,\n }),\n });\n}\n\nfunction fetch_retry(\n url: string,\n retries: number,\n options: RequestOptions\n): Promise {\n return new Promise((resolve, reject) => {\n fetch(url, options)\n .then(response => {\n // We don't want to `reject` when retries have finished\n // Instead simply stop trying and return.\n if (retries === 0) return resolve(response);\n if (response.status === 429) {\n const {retryTimeout = 20000} = options;\n retryTimeoutPromise(retryTimeout).then(() => {\n fetch_retry(url, retries - 1, options)\n .then(resolve)\n .catch(reject);\n });\n } else {\n clearTimeout(options.requestTimer);\n resolve(response);\n }\n })\n .catch(reject);\n });\n}\n\nconst retryTimeoutPromise = (milliseconds: number) => {\n return new Promise(resolve => setTimeout(resolve, milliseconds));\n};\n\nfunction userAgentHeader(): object {\n if (isNode) {\n return {\n 'User-Agent': `pdjs/${VERSION} (${process.version}/${process.platform})`,\n };\n } else if (isWebWorker) {\n return {\n 'User-Agent': `pdjs/${VERSION} (WebWorker)`,\n };\n } else if (isJsDom) {\n return {\n 'User-Agent': `pdjs/${VERSION} (JsDom)`,\n };\n } else if (isDeno) {\n return {\n 'User-Agent': `pdjs/${VERSION} (Deno)`,\n };\n } else if (isBrowser) {\n return {\n // Note: This will not work consistently for all browsers as some silently drop the userAgent Header.\n 'User-Agent': `pdjs/${VERSION} (${window.navigator.userAgent})`,\n };\n } else {\n return {};\n }\n}\n\nfunction applyParameters(url: URL, queryParameters?: QueryParameter): URL {\n if (!queryParameters) return url;\n\n const combinedParameters = url.searchParams;\n\n for (const key of Object.keys(queryParameters)) {\n const parameter = queryParameters[key];\n if (Array.isArray(parameter)) {\n // Support for array based keys like `additional_fields[]`\n parameter.forEach(item => {\n combinedParameters.append(key, item);\n });\n } else {\n combinedParameters.append(key, parameter);\n }\n }\n\n url.search = combinedParameters.toString();\n return url;\n}\n\nfunction applyTimeout(init: RequestOptions, timeout?: number): RequestOptions {\n if (!timeout) return init;\n const timer = setTimeout(() => {}, timeout);\n return {\n ...init,\n requestTimer: timer,\n };\n}\n","import {request, RequestOptions} from './common';\n\nexport interface ShorthandCall {\n (res: string, apiParameters?: Partial): APIPromise;\n}\n\nexport interface PartialCall {\n (apiParameters: APIParameters): APIPromise;\n (apiParameters: Partial): PartialCall;\n get: ShorthandCall;\n post: ShorthandCall;\n put: ShorthandCall;\n patch: ShorthandCall;\n delete: ShorthandCall;\n all: ShorthandCall;\n}\n\nexport type APIParameters = RequestOptions & {\n endpoint?: string;\n url?: string;\n data?: object;\n token?: string;\n tokenType?: string;\n server?: string;\n version?: number;\n} & ({endpoint: string} | {url: string});\n\nexport type APIPromise = Promise;\n\nexport interface APIResponse extends Response {\n data: any;\n resource: any;\n response: Response;\n next?: () => APIPromise;\n}\n\nexport function api(apiParameters: APIParameters): APIPromise;\nexport function api(apiParameters: Partial): PartialCall;\nexport function api(\n apiParameters: Partial\n): APIPromise | PartialCall {\n // If the apiParameters don't include `endpoint` treat it as a partial\n // application.\n if (!apiParameters.endpoint && !apiParameters.url) {\n return partialCall(apiParameters);\n }\n\n // allows for Token and Bearer token types to be used in Authorization\n type typeMap = {\n [key: string]: string;\n };\n\n const types: typeMap = {\n bearer: 'Bearer ',\n token: 'Token token=',\n };\n\n const {\n endpoint,\n server = 'api.pagerduty.com',\n token,\n tokenType = apiParameters.tokenType || 'token',\n url,\n version = 2,\n data,\n ...rest\n } = apiParameters;\n\n const config: RequestOptions = {\n method: 'GET',\n ...rest,\n headers: {\n Accept: `application/vnd.pagerduty+json;version=${version}`,\n Authorization: `${types[tokenType]}${token!}`,\n ...rest.headers,\n },\n };\n\n // Allow `data` for `queryParameters` for requests without bodies.\n if (isReadonlyRequest(config.method!) && data) {\n config.queryParameters =\n config.queryParameters ?? (data as Record);\n } else {\n config.body = JSON.stringify(data);\n }\n\n return apiRequest(\n url ?? `https://${server}/${endpoint!.replace(/^\\/+/, '')}`,\n config\n );\n}\n\nfunction apiRequest(url: string, options: RequestOptions): APIPromise {\n return request(url, options).then(\n (response: Response): APIPromise => {\n const apiResponse = response as APIResponse;\n apiResponse.response = response;\n\n if (response.status === 204) {\n return Promise.resolve(apiResponse);\n }\n\n return response\n .json()\n .then(\n (data): APIResponse => {\n const resource = resourceKey(url, options.method);\n apiResponse.next = nextFunc(url, options, data);\n apiResponse.data = data;\n apiResponse.resource = resource ? data[resource] : null;\n return apiResponse;\n }\n )\n .catch(() => Promise.reject(apiResponse));\n }\n );\n}\n\nfunction resourceKey(url: string, method?: string) {\n const resource = url.match(/.+.com\\/(?[\\w]+)/);\n if (resource) {\n const resourceName = resource[1];\n if (method && method.toLowerCase() === 'get') {\n return resourceName;\n }\n if (resourceName.endsWith('ies')) {\n return resourceName.slice(0, -3) + 'y';\n } else if (resourceName.endsWith('s')) {\n return resourceName.slice(0, -1);\n }\n return resourceName;\n }\n return null;\n}\n\nfunction isReadonlyRequest(method: string) {\n return !['PUT', 'POST', 'DELETE', 'PATCH'].includes(\n method.toUpperCase() ?? 'GET'\n );\n}\n\ninterface OffsetPagination {\n type: 'offset';\n more?: boolean;\n offset?: number;\n limit?: number;\n}\n\ninterface CursorPagination {\n type: 'cursor';\n cursor?: string;\n limit?: number;\n}\n\nfunction isOffsetPagination(\n data: OffsetPagination | CursorPagination\n): data is OffsetPagination {\n if ((data as OffsetPagination).offset !== undefined) {\n return true;\n }\n return false;\n}\n\nfunction isCursorPagination(\n data: OffsetPagination | CursorPagination\n): data is CursorPagination {\n if ((data as CursorPagination).cursor !== undefined) {\n return true;\n }\n return false;\n}\n\nfunction nextFunc(\n url: string,\n options: RequestOptions,\n data: OffsetPagination | CursorPagination\n) {\n if (isOffsetPagination(data)) {\n if (data?.more && typeof data.offset !== undefined && data.limit) {\n return () =>\n apiRequest(url, {\n ...options,\n queryParameters: {\n ...options.queryParameters,\n limit: data.limit!.toString(),\n offset: (data.limit! + data.offset!).toString(),\n },\n });\n }\n } else if (isCursorPagination(data)) {\n if (data?.cursor) {\n return () =>\n apiRequest(url, {\n ...options,\n queryParameters: {\n ...options.queryParameters,\n cursor: data.cursor!,\n limit: data.limit!.toString(),\n },\n });\n }\n }\n\n return undefined;\n}\n\nfunction partialCall(apiParameters: Partial) {\n const partialParameters = apiParameters;\n const partial = ((apiParameters: Partial) =>\n api({...partialParameters, ...apiParameters})) as PartialCall;\n\n const shorthand = (method: string) => (\n endpoint: string,\n shorthandParameters?: Partial\n ): APIPromise =>\n api({\n endpoint,\n method,\n ...partialParameters,\n ...shorthandParameters,\n }) as APIPromise;\n\n partial.get = shorthand('get');\n partial.post = shorthand('post');\n partial.put = shorthand('put');\n partial.patch = shorthand('patch');\n partial.delete = shorthand('delete');\n\n partial.all = (\n endpoint: string,\n shorthandParameters?: Partial\n ): APIPromise => {\n function allInner(responses: APIResponse[]): Promise {\n const response = responses[responses.length - 1];\n if (!response.next) {\n // Base case, resolve and return all responses.\n return Promise.resolve(responses);\n }\n // If there are still more resources to get then concat and repeat.\n return response\n .next()\n .then(response => allInner(responses.concat([response])));\n }\n\n function repackResponses(responses: APIResponse[]): APIPromise {\n // Repack the responses object to make it more user friendly.\n const repackedResponse = responses.shift() as APIResponse; // Use the first response to build the standard response object\n repackedResponse.data = [repackedResponse.data];\n responses.forEach(response => {\n repackedResponse.data = repackedResponse.data.concat(response.data);\n repackedResponse.resource = repackedResponse.resource.concat(\n response.resource\n );\n });\n return Promise.resolve(repackedResponse);\n }\n\n const method = 'get';\n return (api({\n endpoint,\n method,\n ...partialParameters,\n ...shorthandParameters,\n }) as APIPromise)\n .then(response => allInner([response]))\n .then(responses => repackResponses(responses));\n };\n\n return partial;\n}\n","import {request, RequestOptions} from './common';\n\nexport type Action = 'trigger' | 'acknowledge' | 'resolve';\n\nexport type EventPromise = Promise;\n\nexport interface EventResponse extends Response {\n data: any;\n response: Response;\n}\n\nexport type Severity = 'critical' | 'error' | 'warning' | 'info';\n\nexport interface Image {\n src: string;\n href?: string;\n alt?: string;\n}\n\nexport interface Link {\n href: string;\n text?: string;\n}\n\nexport interface EventPayloadV2 {\n routing_key: string;\n event_action: Action;\n dedup_key?: string;\n payload: {\n summary: string;\n source: string;\n severity: Severity;\n timestamp?: string;\n component?: string;\n group?: string;\n class?: string;\n custom_details?: object;\n };\n images?: Array;\n links?: Array;\n}\n\nexport interface EventParameters extends RequestOptions {\n data: EventPayloadV2;\n type?: string;\n server?: string;\n}\n\nexport interface ChangePayload {\n routing_key: string;\n payload: {\n summary: string;\n source?: string;\n timestamp: string;\n custom_details?: object;\n };\n images?: Array;\n links?: Array;\n}\nexport interface ChangeParameters extends RequestOptions {\n data: ChangePayload;\n type?: string;\n server?: string;\n}\n\nexport function event(\n eventParameters: EventParameters | ChangeParameters\n): EventPromise {\n const {\n server = 'events.pagerduty.com',\n type = 'event',\n data,\n ...config\n } = eventParameters;\n\n let url = `https://${server}/v2/enqueue`;\n if (type === 'change') {\n url = `https://${server}/v2/change/enqueue`;\n }\n\n return eventFetch(url, {\n method: 'POST',\n body: JSON.stringify(data),\n ...config,\n });\n}\n\nconst shorthand = (action: Action) => (\n eventParameters: EventParameters\n): EventPromise => {\n const typeField = 'event_action';\n\n return event({\n ...eventParameters,\n data: {\n ...eventParameters.data,\n [typeField]: action,\n },\n });\n};\n\nexport const trigger = shorthand('trigger');\nexport const acknowledge = shorthand('acknowledge');\nexport const resolve = shorthand('resolve');\nexport const change = (changeParameters: ChangeParameters) =>\n event({...changeParameters, type: 'change'});\n\nfunction eventFetch(url: string, options: RequestOptions): EventPromise {\n return request(url, options).then(\n (response: Response): EventPromise => {\n const apiResponse = response as EventResponse;\n return response.json().then(\n (data): EventResponse => {\n apiResponse.data = data;\n apiResponse.response = response;\n return apiResponse;\n }\n );\n }\n );\n}\n"],"names":["__webpack_require__","exports","definition","key","o","Object","defineProperty","enumerable","get","obj","prop","prototype","hasOwnProperty","call","Symbol","toStringTag","value","request","url","options","queryParameters","requestTimeout","applyParameters","URL","toString","applyTimeout","fetch_retry","headers","Headers","retries","Promise","resolve","reject","fetch","then","response","status","retryTimeout","retryTimeoutPromise","clearTimeout","requestTimer","milliseconds","setTimeout","combinedParameters","searchParams","parameter","Array","isArray","forEach","item","append","keys","search","init","timeout","timer","api","apiParameters","endpoint","partialParameters","partial","shorthand","method","shorthandParameters","post","put","patch","all","allInner","responses","length","next","concat","repackedResponse","shift","data","resource","repackResponses","partialCall","server","token","tokenType","version","rest","config","Accept","Authorization","bearer","includes","toUpperCase","body","JSON","stringify","apiRequest","replace","apiResponse","json","match","resourceName","toLowerCase","endsWith","slice","resourceKey","undefined","offset","isOffsetPagination","more","limit","cursor","isCursorPagination","nextFunc","event","eventParameters","type","eventFetch","action","trigger","acknowledge","change","changeParameters"],"sourceRoot":""} -------------------------------------------------------------------------------- /examples/browser.html: -------------------------------------------------------------------------------- 1 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 35 | 36 | 37 |
    38 | 39 | 40 | -------------------------------------------------------------------------------- /examples/node.js: -------------------------------------------------------------------------------- 1 | // How to use pdjs in a node environment 2 | // This example will list users contact info. 3 | const PagerDuty = require('../build/src/index.js'); 4 | 5 | const pd = PagerDuty.api({token: 'y_NbAkKc66ryYTWUXYEu', tokenType: 'token'}); 6 | pd.get('/users', {params: {'include[]': 'contact_methods'}}) 7 | .then(({resource}) => { 8 | // The Users are returned in the `resource` key. 9 | resource.forEach(user => { 10 | console.log(`${user['name']}: ${user['email']}`); 11 | }); 12 | }) 13 | .catch(console.error); 14 | -------------------------------------------------------------------------------- /jest.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | preset: 'ts-jest', 3 | testEnvironment: 'node', 4 | testPathIgnorePatterns: ['/node_modules/', 'build'], 5 | }; 6 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "@pagerduty/pdjs", 3 | "version": "2.2.4", 4 | "description": "A new simple JavaScript wrapper for the PagerDuty API", 5 | "main": "build/src/index.js", 6 | "types": "build/src/index.d.ts", 7 | "files": [ 8 | "build/src" 9 | ], 10 | "license": "Apache-2.0", 11 | "keywords": [ 12 | "pagerduty" 13 | ], 14 | "scripts": { 15 | "build": "tsc && webpack", 16 | "test": "jest", 17 | "compile": "tsc", 18 | "lint": "gts lint", 19 | "clean": "gts clean", 20 | "fix": "gts fix" 21 | }, 22 | "devDependencies": { 23 | "@babel/core": "^7.15.5", 24 | "@babel/preset-env": "^7.15.6", 25 | "@babel/preset-typescript": "^7.15.0", 26 | "@types/browser-or-node": "^1.2.0", 27 | "@types/jest": "^27.0.2", 28 | "@types/node": "^16.9.1", 29 | "babel-loader": "^8.1.0", 30 | "gts": "^3.0.0", 31 | "jest": "^27.2.1", 32 | "nock": "^13.1.3", 33 | "ts-jest": "^27.0.5", 34 | "ts-loader": "^9.2.6", 35 | "typescript": "^4.4.3", 36 | "webpack": "^5.53.0", 37 | "webpack-cli": "^4.8.0", 38 | "webpack-strip-block": "^0.3.0" 39 | }, 40 | "dependencies": { 41 | "browser-or-node": "^2.0.0", 42 | "cross-fetch": "^3.0.6" 43 | }, 44 | "engines": { 45 | "node": ">=10.0.0" 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/api.test.ts: -------------------------------------------------------------------------------- 1 | import nock = require('nock'); 2 | import {api} from './index'; 3 | 4 | const EMPTY_BODY = { 5 | incidents: [], 6 | limit: 25, 7 | offset: 0, 8 | total: null, 9 | more: false, 10 | }; 11 | 12 | test('API calls return JSON for basic API calls with server', async () => { 13 | nock('https://api.pagerduty.com', { 14 | reqheaders: { 15 | Authorization: 'Token token=someToken1234567890', 16 | 'User-Agent': header => header.startsWith('pdjs'), 17 | }, 18 | }) 19 | .get('/incidents') 20 | .reply(200, EMPTY_BODY); 21 | 22 | const resp = await api({ 23 | token: 'someToken1234567890', 24 | server: 'api.pagerduty.com', 25 | endpoint: 'incidents', 26 | }); 27 | 28 | expect(resp.url).toEqual('https://api.pagerduty.com/incidents'); 29 | expect(resp.data).toEqual(EMPTY_BODY); 30 | }); 31 | 32 | test('API calls return JSON for basic API calls with url', async () => { 33 | nock('https://api.pagerduty.com', { 34 | reqheaders: { 35 | Authorization: 'Token token=someToken1234567890', 36 | 'User-Agent': header => header.startsWith('pdjs'), 37 | }, 38 | }) 39 | .get('/incidents') 40 | .reply(200, EMPTY_BODY); 41 | 42 | const resp = await api({ 43 | token: 'someToken1234567890', 44 | url: 'https://api.pagerduty.com/incidents', 45 | }); 46 | 47 | expect(resp.url).toEqual('https://api.pagerduty.com/incidents'); 48 | expect(resp.data).toEqual(EMPTY_BODY); 49 | }); 50 | 51 | test('API calls return JSON for basic API calls with endpoint', async () => { 52 | nock('https://api.pagerduty.com', { 53 | reqheaders: { 54 | Authorization: 'Token token=someToken1234567890', 55 | 'User-Agent': header => header.startsWith('pdjs'), 56 | }, 57 | }) 58 | .get('/incidents') 59 | .reply(200, EMPTY_BODY); 60 | 61 | const resp = await api({ 62 | token: 'someToken1234567890', 63 | endpoint: 'incidents', 64 | }); 65 | 66 | expect(resp.url).toEqual('https://api.pagerduty.com/incidents'); 67 | expect(resp.data).toEqual(EMPTY_BODY); 68 | }); 69 | 70 | test('API calls return successfully on DELETE endpoints', async () => { 71 | nock('https://api.pagerduty.com', { 72 | reqheaders: { 73 | Authorization: 'Token token=someToken1234567890', 74 | 'User-Agent': header => header.startsWith('pdjs'), 75 | }, 76 | }) 77 | .delete('/incidents/delete') 78 | .reply(204); 79 | 80 | const pd = api({token: 'someToken1234567890'}); 81 | 82 | const response = await pd.delete('/incidents/delete'); 83 | 84 | expect(response.url).toEqual('https://api.pagerduty.com/incidents/delete'); 85 | expect(response.data).toEqual(undefined); 86 | }); 87 | 88 | test('API calls support partial application with url', async () => { 89 | nock('https://api.pagerduty.com', { 90 | reqheaders: { 91 | Authorization: 'Token token=someToken1234567890', 92 | 'User-Agent': header => header.startsWith('pdjs'), 93 | }, 94 | }) 95 | .get('/incidents') 96 | .reply(200, EMPTY_BODY); 97 | 98 | const pd = api({token: 'someToken1234567890'}); 99 | const resp = await pd({ 100 | url: 'https://api.pagerduty.com/incidents', 101 | }); 102 | 103 | expect(resp.url).toEqual('https://api.pagerduty.com/incidents'); 104 | expect(resp.data).toEqual(EMPTY_BODY); 105 | }); 106 | 107 | test('API calls support partial application with convenience methods', async () => { 108 | nock('https://api.pagerduty.com', { 109 | reqheaders: { 110 | Authorization: 'Token token=someToken1234567890', 111 | 'User-Agent': header => header.startsWith('pdjs'), 112 | }, 113 | }) 114 | .get('/incidents') 115 | .reply(200, EMPTY_BODY); 116 | 117 | const resp = await api({token: 'someToken1234567890'}).get('/incidents'); 118 | 119 | expect(resp.url).toEqual('https://api.pagerduty.com/incidents'); 120 | expect(resp.data).toEqual(EMPTY_BODY); 121 | }); 122 | 123 | test('API calls use data in place of queryParameters when provided on GET requests', async () => { 124 | nock('https://api.pagerduty.com') 125 | .get('/incidents?sort_by=created_at&total=true') 126 | .reply(200, EMPTY_BODY); 127 | 128 | const resp = await api({ 129 | token: 'someToken1234567890', 130 | endpoint: '/incidents', 131 | data: {sort_by: 'created_at', total: true}, 132 | }); 133 | 134 | expect(resp.url).toEqual( 135 | 'https://api.pagerduty.com/incidents?sort_by=created_at&total=true' 136 | ); 137 | expect(resp.data).toEqual(EMPTY_BODY); 138 | }); 139 | 140 | test('API calls populate resource field', async () => { 141 | nock('https://api.pagerduty.com') 142 | .get('/incidents') 143 | .reply(200, { 144 | incidents: ['one', 1, null], 145 | limit: 25, 146 | offset: 0, 147 | total: null, 148 | more: false, 149 | }); 150 | nock('https://api.pagerduty.com') 151 | .post('/incidents') 152 | .reply(201, { 153 | incident: ['some incident'], 154 | }); 155 | 156 | const respGet = await api({ 157 | token: 'someToken1234567890', 158 | endpoint: '/incidents', 159 | }); 160 | expect(respGet.resource).toEqual(['one', 1, null]); 161 | const respPost = await api({ 162 | token: 'someToken1234567890', 163 | endpoint: '/incidents', 164 | method: 'POST', 165 | }); 166 | expect(respPost.resource).toEqual(['some incident']); 167 | }); 168 | 169 | test('API explodes list based parameters properly', async () => { 170 | nock('https://api.pagerduty.com') 171 | .get( 172 | '/incidents?additional_fields[]=one&additional_fields[]=two&additional_fields[]=three' 173 | ) 174 | .reply(200, { 175 | incidents: ['one', 1, null], 176 | limit: 25, 177 | offset: 0, 178 | total: null, 179 | more: false, 180 | }); 181 | 182 | const resp = await api({ 183 | token: 'someToken1234567890', 184 | endpoint: '/incidents', 185 | queryParameters: { 186 | 'additional_fields[]': ['one', 'two', 'three'], 187 | }, 188 | }); 189 | 190 | expect(resp.url).toEqual( 191 | 'https://api.pagerduty.com/incidents?additional_fields%5B%5D=one&additional_fields%5B%5D=two&additional_fields%5B%5D=three' 192 | ); 193 | }); 194 | 195 | test('API `all` calls for offset should generate requests until no more results', async () => { 196 | nock('https://api.pagerduty.com') 197 | .get('/incidents?limit=1') 198 | .reply(200, { 199 | incidents: [{name: 1}], 200 | limit: 1, 201 | offset: 0, 202 | more: true, 203 | total: null, 204 | }); 205 | 206 | nock('https://api.pagerduty.com') 207 | .get('/incidents?limit=1&offset=1') 208 | .reply(200, { 209 | incidents: [{name: 2}], 210 | limit: 1, 211 | offset: 1, 212 | more: true, 213 | total: null, 214 | }); 215 | 216 | nock('https://api.pagerduty.com') 217 | .get('/incidents?limit=1&offset=2') 218 | .reply(200, { 219 | incidents: [{name: 3}], 220 | limit: 1, 221 | offset: 2, 222 | more: false, 223 | total: null, 224 | }); 225 | 226 | const pd = api({token: 'someToken1234567890'}); 227 | 228 | const responses = await pd.all('/incidents', {data: {limit: 1}}); 229 | 230 | expect(responses.resource).toEqual([{name: 1}, {name: 2}, {name: 3}]); 231 | }); 232 | 233 | test('API `all` calls for cursor should generate requests until no more results', async () => { 234 | nock('https://api.pagerduty.com') 235 | .get('/incidents?limit=1') 236 | .reply(200, { 237 | incidents: [{name: 1}], 238 | limit: 1, 239 | cursor: 'one', 240 | }); 241 | 242 | nock('https://api.pagerduty.com') 243 | .get('/incidents?limit=1&cursor=one') 244 | .reply(200, { 245 | incidents: [{name: 2}], 246 | limit: 1, 247 | cursor: 'two', 248 | }); 249 | 250 | nock('https://api.pagerduty.com') 251 | .get('/incidents?limit=1&cursor=two') 252 | .reply(200, { 253 | incidents: [{name: 3}], 254 | limit: 1, 255 | cursor: null, 256 | }); 257 | 258 | const pd = api({token: 'someToken1234567890'}); 259 | 260 | const responses = await pd.all('/incidents', { 261 | data: {limit: 1}, 262 | }); 263 | 264 | expect(responses.resource).toEqual([{name: 1}, {name: 2}, {name: 3}]); 265 | }); 266 | 267 | test('API `get` calls with shorthand `get` should succeed', async () => { 268 | nock('https://api.pagerduty.com').get('/incidents').reply(200, EMPTY_BODY); 269 | 270 | const pd = api({token: 'someToken1234567890'}); 271 | 272 | const response = await pd.get('/incidents'); 273 | 274 | expect(response.url).toEqual('https://api.pagerduty.com/incidents'); 275 | expect(response.data).toEqual(EMPTY_BODY); 276 | }); 277 | 278 | test('API `post` calls with shorthand `get` should succeed', async () => { 279 | nock('https://api.pagerduty.com').post('/incidents').reply(200, EMPTY_BODY); 280 | 281 | const pd = api({token: 'someToken1234567890'}); 282 | 283 | const response = await pd.post('/incidents'); 284 | 285 | expect(response.url).toEqual('https://api.pagerduty.com/incidents'); 286 | expect(response.data).toEqual(EMPTY_BODY); 287 | }); 288 | 289 | test('API `put` calls with shorthand `get` should succeed', async () => { 290 | nock('https://api.pagerduty.com').put('/incidents').reply(200, EMPTY_BODY); 291 | 292 | const pd = api({token: 'someToken1234567890'}); 293 | 294 | const response = await pd.put('/incidents'); 295 | 296 | expect(response.url).toEqual('https://api.pagerduty.com/incidents'); 297 | expect(response.data).toEqual(EMPTY_BODY); 298 | }); 299 | 300 | test('API `patch` calls with shorthand `get` should succeed', async () => { 301 | nock('https://api.pagerduty.com').patch('/incidents').reply(200, EMPTY_BODY); 302 | 303 | const pd = api({token: 'someToken1234567890'}); 304 | 305 | const response = await pd.patch('/incidents'); 306 | 307 | expect(response.url).toEqual('https://api.pagerduty.com/incidents'); 308 | expect(response.data).toEqual(EMPTY_BODY); 309 | }); 310 | 311 | test('API `delete` calls with shorthand `get` should succeed', async () => { 312 | nock('https://api.pagerduty.com').delete('/incidents').reply(200, EMPTY_BODY); 313 | 314 | const pd = api({token: 'someToken1234567890'}); 315 | 316 | const response = await pd.delete('/incidents'); 317 | 318 | expect(response.url).toEqual('https://api.pagerduty.com/incidents'); 319 | expect(response.data).toEqual(EMPTY_BODY); 320 | }); 321 | 322 | test('API catches ETIMEDOUT error', async () => { 323 | nock('https://api.pagerduty.com') 324 | .get('/incidents') 325 | .replyWithError({code: 'ETIMEDOUT'}); 326 | 327 | const pd = api({token: 'someToken1234567890'}); 328 | 329 | await expect(pd.get('/incidents')).rejects.toThrow( 330 | 'request to https://api.pagerduty.com/incidents failed, reason: undefined' 331 | ); 332 | }); 333 | -------------------------------------------------------------------------------- /src/api.ts: -------------------------------------------------------------------------------- 1 | import {request, RequestOptions} from './common'; 2 | 3 | export interface ShorthandCall { 4 | (res: string, apiParameters?: Partial): APIPromise; 5 | } 6 | 7 | export interface PartialCall { 8 | (apiParameters: APIParameters): APIPromise; 9 | (apiParameters: Partial): PartialCall; 10 | get: ShorthandCall; 11 | post: ShorthandCall; 12 | put: ShorthandCall; 13 | patch: ShorthandCall; 14 | delete: ShorthandCall; 15 | all: ShorthandCall; 16 | } 17 | 18 | export type APIParameters = RequestOptions & { 19 | endpoint?: string; 20 | url?: string; 21 | data?: object; 22 | token?: string; 23 | tokenType?: string; 24 | server?: string; 25 | version?: number; 26 | } & ({endpoint: string} | {url: string}); 27 | 28 | export type APIPromise = Promise; 29 | 30 | export interface APIResponse extends Response { 31 | data: any; 32 | resource: any; 33 | response: Response; 34 | next?: () => APIPromise; 35 | } 36 | 37 | export function api(apiParameters: APIParameters): APIPromise; 38 | export function api(apiParameters: Partial): PartialCall; 39 | export function api( 40 | apiParameters: Partial 41 | ): APIPromise | PartialCall { 42 | // If the apiParameters don't include `endpoint` treat it as a partial 43 | // application. 44 | if (!apiParameters.endpoint && !apiParameters.url) { 45 | return partialCall(apiParameters); 46 | } 47 | 48 | // allows for Token and Bearer token types to be used in Authorization 49 | type typeMap = { 50 | [key: string]: string; 51 | }; 52 | 53 | const types: typeMap = { 54 | bearer: 'Bearer ', 55 | token: 'Token token=', 56 | }; 57 | 58 | const { 59 | endpoint, 60 | server = 'api.pagerduty.com', 61 | token, 62 | tokenType = apiParameters.tokenType || 'token', 63 | url, 64 | version = 2, 65 | data, 66 | ...rest 67 | } = apiParameters; 68 | 69 | const config: RequestOptions = { 70 | method: 'GET', 71 | ...rest, 72 | headers: { 73 | Accept: `application/vnd.pagerduty+json;version=${version}`, 74 | Authorization: `${types[tokenType]}${token!}`, 75 | ...rest.headers, 76 | }, 77 | }; 78 | 79 | // Allow `data` for `queryParameters` for requests without bodies. 80 | if (isReadonlyRequest(config.method!) && data) { 81 | config.queryParameters = 82 | config.queryParameters ?? (data as Record); 83 | } else { 84 | config.body = JSON.stringify(data); 85 | } 86 | 87 | return apiRequest( 88 | url ?? `https://${server}/${endpoint!.replace(/^\/+/, '')}`, 89 | config 90 | ); 91 | } 92 | 93 | function apiRequest(url: string, options: RequestOptions): APIPromise { 94 | return request(url, options).then( 95 | (response: Response): APIPromise => { 96 | const apiResponse = response as APIResponse; 97 | apiResponse.response = response; 98 | 99 | if (response.status === 204) { 100 | return Promise.resolve(apiResponse); 101 | } 102 | 103 | return response 104 | .json() 105 | .then( 106 | (data): APIResponse => { 107 | const resource = resourceKey(url, options.method); 108 | apiResponse.next = nextFunc(url, options, data); 109 | apiResponse.data = data; 110 | apiResponse.resource = resource ? data[resource] : null; 111 | return apiResponse; 112 | } 113 | ) 114 | .catch(() => Promise.reject(apiResponse)); 115 | } 116 | ); 117 | } 118 | 119 | function resourceKey(url: string, method?: string) { 120 | const resource = url.match(/.+.com\/(?[\w]+)/); 121 | if (resource) { 122 | const resourceName = resource[1]; 123 | if (method && method.toLowerCase() === 'get') { 124 | return resourceName; 125 | } 126 | if (resourceName.endsWith('ies')) { 127 | return resourceName.slice(0, -3) + 'y'; 128 | } else if (resourceName.endsWith('s')) { 129 | return resourceName.slice(0, -1); 130 | } 131 | return resourceName; 132 | } 133 | return null; 134 | } 135 | 136 | function isReadonlyRequest(method: string) { 137 | return !['PUT', 'POST', 'DELETE', 'PATCH'].includes( 138 | method.toUpperCase() ?? 'GET' 139 | ); 140 | } 141 | 142 | interface OffsetPagination { 143 | type: 'offset'; 144 | more?: boolean; 145 | offset?: number; 146 | limit?: number; 147 | } 148 | 149 | interface CursorPagination { 150 | type: 'cursor'; 151 | cursor?: string; 152 | limit?: number; 153 | } 154 | 155 | function isOffsetPagination( 156 | data: OffsetPagination | CursorPagination 157 | ): data is OffsetPagination { 158 | if ((data as OffsetPagination).offset !== undefined) { 159 | return true; 160 | } 161 | return false; 162 | } 163 | 164 | function isCursorPagination( 165 | data: OffsetPagination | CursorPagination 166 | ): data is CursorPagination { 167 | if ((data as CursorPagination).cursor !== undefined) { 168 | return true; 169 | } 170 | return false; 171 | } 172 | 173 | function nextFunc( 174 | url: string, 175 | options: RequestOptions, 176 | data: OffsetPagination | CursorPagination 177 | ) { 178 | if (isOffsetPagination(data)) { 179 | if (data?.more && typeof data.offset !== undefined && data.limit) { 180 | return () => 181 | apiRequest(url, { 182 | ...options, 183 | queryParameters: { 184 | ...options.queryParameters, 185 | limit: data.limit!.toString(), 186 | offset: (data.limit! + data.offset!).toString(), 187 | }, 188 | }); 189 | } 190 | } else if (isCursorPagination(data)) { 191 | if (data?.cursor) { 192 | return () => 193 | apiRequest(url, { 194 | ...options, 195 | queryParameters: { 196 | ...options.queryParameters, 197 | cursor: data.cursor!, 198 | limit: data.limit!.toString(), 199 | }, 200 | }); 201 | } 202 | } 203 | 204 | return undefined; 205 | } 206 | 207 | function partialCall(apiParameters: Partial) { 208 | const partialParameters = apiParameters; 209 | const partial = ((apiParameters: Partial) => 210 | api({...partialParameters, ...apiParameters})) as PartialCall; 211 | 212 | const shorthand = (method: string) => ( 213 | endpoint: string, 214 | shorthandParameters?: Partial 215 | ): APIPromise => 216 | api({ 217 | endpoint, 218 | method, 219 | ...partialParameters, 220 | ...shorthandParameters, 221 | }) as APIPromise; 222 | 223 | partial.get = shorthand('get'); 224 | partial.post = shorthand('post'); 225 | partial.put = shorthand('put'); 226 | partial.patch = shorthand('patch'); 227 | partial.delete = shorthand('delete'); 228 | 229 | partial.all = ( 230 | endpoint: string, 231 | shorthandParameters?: Partial 232 | ): APIPromise => { 233 | function allInner(responses: APIResponse[]): Promise { 234 | const response = responses[responses.length - 1]; 235 | if (!response.next) { 236 | // Base case, resolve and return all responses. 237 | return Promise.resolve(responses); 238 | } 239 | // If there are still more resources to get then concat and repeat. 240 | return response 241 | .next() 242 | .then(response => allInner(responses.concat([response]))); 243 | } 244 | 245 | function repackResponses(responses: APIResponse[]): APIPromise { 246 | // Repack the responses object to make it more user friendly. 247 | const repackedResponse = responses.shift() as APIResponse; // Use the first response to build the standard response object 248 | repackedResponse.data = [repackedResponse.data]; 249 | responses.forEach(response => { 250 | repackedResponse.data = repackedResponse.data.concat(response.data); 251 | repackedResponse.resource = repackedResponse.resource.concat( 252 | response.resource 253 | ); 254 | }); 255 | return Promise.resolve(repackedResponse); 256 | } 257 | 258 | const method = 'get'; 259 | return (api({ 260 | endpoint, 261 | method, 262 | ...partialParameters, 263 | ...shorthandParameters, 264 | }) as APIPromise) 265 | .then(response => allInner([response])) 266 | .then(responses => repackResponses(responses)); 267 | }; 268 | 269 | return partial; 270 | } 271 | -------------------------------------------------------------------------------- /src/common.ts: -------------------------------------------------------------------------------- 1 | /* LEGACY-BROWSER-SUPPORT-START */ 2 | import fetch, {Headers} from 'cross-fetch'; 3 | import {isBrowser, isNode, isWebWorker, isJsDom, isDeno} from 'browser-or-node'; 4 | /* LEGACY-BROWSER-SUPPORT-END */ 5 | 6 | const VERSION = '2.0.0'; 7 | 8 | type QueryParameter = Record>; 9 | 10 | export interface RequestOptions extends RequestInit { 11 | queryParameters?: QueryParameter; 12 | retryCount?: number; 13 | requestTimeout?: number; 14 | requestTimer?: any; 15 | retryTimeout?: number; 16 | timeout?: number; 17 | } 18 | 19 | export function request( 20 | url: string | URL, 21 | options: RequestOptions = {} 22 | ): Promise { 23 | const {queryParameters, requestTimeout = 30000} = options; 24 | 25 | url = new URL(url.toString()); 26 | url = applyParameters(url, queryParameters); 27 | options = applyTimeout(options, requestTimeout); 28 | 29 | return fetch_retry(url.toString(), 3, { 30 | ...options, 31 | headers: new Headers({ 32 | 'Content-Type': 'application/json; charset=utf-8', 33 | /* LEGACY-BROWSER-SUPPORT-START */ 34 | ...userAgentHeader(), 35 | /* LEGACY-BROWSER-SUPPORT-END */ 36 | ...options.headers, 37 | }), 38 | }); 39 | } 40 | 41 | function fetch_retry( 42 | url: string, 43 | retries: number, 44 | options: RequestOptions 45 | ): Promise { 46 | return new Promise((resolve, reject) => { 47 | fetch(url, options) 48 | .then(response => { 49 | // We don't want to `reject` when retries have finished 50 | // Instead simply stop trying and return. 51 | if (retries === 0) return resolve(response); 52 | if (response.status === 429) { 53 | const {retryTimeout = 20000} = options; 54 | retryTimeoutPromise(retryTimeout).then(() => { 55 | fetch_retry(url, retries - 1, options) 56 | .then(resolve) 57 | .catch(reject); 58 | }); 59 | } else { 60 | clearTimeout(options.requestTimer); 61 | resolve(response); 62 | } 63 | }) 64 | .catch(reject); 65 | }); 66 | } 67 | 68 | const retryTimeoutPromise = (milliseconds: number) => { 69 | return new Promise(resolve => setTimeout(resolve, milliseconds)); 70 | }; 71 | 72 | function userAgentHeader(): object { 73 | if (isNode) { 74 | return { 75 | 'User-Agent': `pdjs/${VERSION} (${process.version}/${process.platform})`, 76 | }; 77 | } else if (isWebWorker) { 78 | return { 79 | 'User-Agent': `pdjs/${VERSION} (WebWorker)`, 80 | }; 81 | } else if (isJsDom) { 82 | return { 83 | 'User-Agent': `pdjs/${VERSION} (JsDom)`, 84 | }; 85 | } else if (isDeno) { 86 | return { 87 | 'User-Agent': `pdjs/${VERSION} (Deno)`, 88 | }; 89 | } else if (isBrowser) { 90 | return { 91 | // Note: This will not work consistently for all browsers as some silently drop the userAgent Header. 92 | 'User-Agent': `pdjs/${VERSION} (${window.navigator.userAgent})`, 93 | }; 94 | } else { 95 | return {}; 96 | } 97 | } 98 | 99 | function applyParameters(url: URL, queryParameters?: QueryParameter): URL { 100 | if (!queryParameters) return url; 101 | 102 | const combinedParameters = url.searchParams; 103 | 104 | for (const key of Object.keys(queryParameters)) { 105 | const parameter = queryParameters[key]; 106 | if (Array.isArray(parameter)) { 107 | // Support for array based keys like `additional_fields[]` 108 | parameter.forEach(item => { 109 | combinedParameters.append(key, item); 110 | }); 111 | } else { 112 | combinedParameters.append(key, parameter); 113 | } 114 | } 115 | 116 | url.search = combinedParameters.toString(); 117 | return url; 118 | } 119 | 120 | function applyTimeout(init: RequestOptions, timeout?: number): RequestOptions { 121 | if (!timeout) return init; 122 | const timer = setTimeout(() => {}, timeout); 123 | return { 124 | ...init, 125 | requestTimer: timer, 126 | }; 127 | } 128 | -------------------------------------------------------------------------------- /src/decs.d.ts: -------------------------------------------------------------------------------- 1 | // TODO: Proper type support for abortcontroller-polyfill 2 | declare module 'abortcontroller-polyfill/dist/cjs-ponyfill'; 3 | -------------------------------------------------------------------------------- /src/events.test.ts: -------------------------------------------------------------------------------- 1 | import nock = require('nock'); 2 | import {Action, ChangeParameters, Severity} from './events'; 3 | import {event, change, trigger, resolve, acknowledge} from './index'; 4 | 5 | const eventPayloadV2 = { 6 | data: { 7 | routing_key: 'someRoutingKeybfa2a710673888f520', 8 | event_action: 'trigger', 9 | dedup_key: 'test_incident_2_88f520', 10 | payload: { 11 | summary: 'Test Event V2', 12 | source: 'test-source', 13 | severity: 'error', 14 | }, 15 | }, 16 | }; 17 | 18 | const changeParameters: ChangeParameters = { 19 | data: { 20 | routing_key: 'someRoutingKeybfa2a710673888f520', 21 | payload: { 22 | summary: 'Test change event', 23 | source: 'test-source', 24 | timestamp: new Date().toISOString(), 25 | custom_details: { 26 | test_detail: 'test-value', 27 | }, 28 | }, 29 | }, 30 | }; 31 | 32 | test('Events API properly passes Events V2 requests', async () => { 33 | const body = { 34 | data: { 35 | status: 'success', 36 | message: 'Event processed', 37 | dedup_key: 'test_incident_2_88f520', 38 | }, 39 | }; 40 | 41 | nock('https://events.pagerduty.com', { 42 | reqheaders: { 43 | 'User-Agent': header => header.startsWith('pdjs'), 44 | }, 45 | }) 46 | .post('/v2/enqueue') 47 | .reply(202, body); 48 | 49 | const response = await event(eventPayloadV2); 50 | 51 | expect(response.url).toEqual('https://events.pagerduty.com/v2/enqueue'); 52 | expect(response.data).toEqual(body); 53 | }); 54 | 55 | test('Events API properly passes Change Events requests', async () => { 56 | const body = { 57 | data: { 58 | status: 'success', 59 | message: 'Event processed', 60 | dedup_key: 'test_incident_2_88f520', 61 | }, 62 | }; 63 | 64 | nock('https://events.pagerduty.com', { 65 | reqheaders: { 66 | 'User-Agent': header => header.startsWith('pdjs'), 67 | }, 68 | }) 69 | .post('/v2/change/enqueue') 70 | .reply(202, body); 71 | 72 | const response = await change(changeParameters); 73 | 74 | expect(response.url).toEqual( 75 | 'https://events.pagerduty.com/v2/change/enqueue' 76 | ); 77 | expect(response.data).toEqual(body); 78 | }); 79 | 80 | test('Events API properly passes Events V2 requests with images/links/details', async () => { 81 | const body = { 82 | data: { 83 | status: 'success', 84 | message: 'Event processed', 85 | dedup_key: 'test_incident_2_88f520', 86 | }, 87 | }; 88 | 89 | nock('https://events.pagerduty.com', { 90 | reqheaders: { 91 | 'User-Agent': header => header.startsWith('pdjs'), 92 | }, 93 | }) 94 | .post('/v2/enqueue') 95 | .reply(202, body); 96 | 97 | const response = await event({ 98 | data: { 99 | routing_key: 'someRoutingKeybfa2a710673888f520', 100 | event_action: 'trigger', 101 | dedup_key: 'test_incident_3_88f520', 102 | payload: { 103 | summary: 'Test Event V2', 104 | source: 'test-source', 105 | severity: 'error', 106 | custom_details: { 107 | foo: 'bar', 108 | }, 109 | }, 110 | images: [ 111 | { 112 | src: 'foo.jpg', 113 | }, 114 | ], 115 | links: [ 116 | { 117 | href: 'https://www.pagerduty.com', 118 | }, 119 | ], 120 | }, 121 | }); 122 | 123 | expect(response.url).toEqual('https://events.pagerduty.com/v2/enqueue'); 124 | expect(response.data).toEqual(body); 125 | }); 126 | 127 | test('Events API shorthands should send corresponding events', async () => { 128 | const body = { 129 | data: { 130 | status: 'success', 131 | message: 'Event processed', 132 | dedup_key: 'test_incident_2_88f520', 133 | }, 134 | }; 135 | 136 | nock('https://events.pagerduty.com', { 137 | reqheaders: { 138 | 'User-Agent': header => header.startsWith('pdjs'), 139 | }, 140 | }) 141 | .post('/v2/enqueue') 142 | .reply(202, body) 143 | .post('/v2/enqueue') 144 | .reply(202, body) 145 | .post('/v2/enqueue') 146 | .reply(202, body); 147 | 148 | let response = await acknowledge(eventPayloadV2); 149 | 150 | expect(response.url).toEqual('https://events.pagerduty.com/v2/enqueue'); 151 | expect(response.data).toEqual(body); 152 | 153 | response = await resolve(eventPayloadV2); 154 | 155 | expect(response.url).toEqual('https://events.pagerduty.com/v2/enqueue'); 156 | expect(response.data).toEqual(body); 157 | 158 | response = await trigger(eventPayloadV2); 159 | 160 | expect(response.url).toEqual('https://events.pagerduty.com/v2/enqueue'); 161 | expect(response.data).toEqual(body); 162 | }); 163 | -------------------------------------------------------------------------------- /src/events.ts: -------------------------------------------------------------------------------- 1 | import {request, RequestOptions} from './common'; 2 | 3 | export type Action = 'trigger' | 'acknowledge' | 'resolve'; 4 | 5 | export type EventPromise = Promise; 6 | 7 | export interface EventResponse extends Response { 8 | data: any; 9 | response: Response; 10 | } 11 | 12 | export type Severity = 'critical' | 'error' | 'warning' | 'info'; 13 | 14 | export interface Image { 15 | src: string; 16 | href?: string; 17 | alt?: string; 18 | } 19 | 20 | export interface Link { 21 | href: string; 22 | text?: string; 23 | } 24 | 25 | export interface EventPayloadV2 { 26 | routing_key: string; 27 | event_action: Action; 28 | dedup_key?: string; 29 | payload: { 30 | summary: string; 31 | source: string; 32 | severity: Severity; 33 | timestamp?: string; 34 | component?: string; 35 | group?: string; 36 | class?: string; 37 | custom_details?: object; 38 | }; 39 | images?: Array; 40 | links?: Array; 41 | } 42 | 43 | export interface EventParameters extends RequestOptions { 44 | data: EventPayloadV2; 45 | type?: string; 46 | server?: string; 47 | } 48 | 49 | export interface ChangePayload { 50 | routing_key: string; 51 | payload: { 52 | summary: string; 53 | source?: string; 54 | timestamp: string; 55 | custom_details?: object; 56 | }; 57 | images?: Array; 58 | links?: Array; 59 | } 60 | export interface ChangeParameters extends RequestOptions { 61 | data: ChangePayload; 62 | type?: string; 63 | server?: string; 64 | } 65 | 66 | export function event( 67 | eventParameters: EventParameters | ChangeParameters 68 | ): EventPromise { 69 | const { 70 | server = 'events.pagerduty.com', 71 | type = 'event', 72 | data, 73 | ...config 74 | } = eventParameters; 75 | 76 | let url = `https://${server}/v2/enqueue`; 77 | if (type === 'change') { 78 | url = `https://${server}/v2/change/enqueue`; 79 | } 80 | 81 | return eventFetch(url, { 82 | method: 'POST', 83 | body: JSON.stringify(data), 84 | ...config, 85 | }); 86 | } 87 | 88 | const shorthand = (action: Action) => ( 89 | eventParameters: EventParameters 90 | ): EventPromise => { 91 | const typeField = 'event_action'; 92 | 93 | return event({ 94 | ...eventParameters, 95 | data: { 96 | ...eventParameters.data, 97 | [typeField]: action, 98 | }, 99 | }); 100 | }; 101 | 102 | export const trigger = shorthand('trigger'); 103 | export const acknowledge = shorthand('acknowledge'); 104 | export const resolve = shorthand('resolve'); 105 | export const change = (changeParameters: ChangeParameters) => 106 | event({...changeParameters, type: 'change'}); 107 | 108 | function eventFetch(url: string, options: RequestOptions): EventPromise { 109 | return request(url, options).then( 110 | (response: Response): EventPromise => { 111 | const apiResponse = response as EventResponse; 112 | return response.json().then( 113 | (data): EventResponse => { 114 | apiResponse.data = data; 115 | apiResponse.response = response; 116 | return apiResponse; 117 | } 118 | ); 119 | } 120 | ); 121 | } 122 | -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | export {api} from './api'; 2 | export {event, change, trigger, acknowledge, resolve} from './events'; 3 | -------------------------------------------------------------------------------- /src/retries.test.ts: -------------------------------------------------------------------------------- 1 | import nock = require('nock'); 2 | import {api} from './index'; 3 | 4 | test('API request should return after 3 rate limited requests', async () => { 5 | const body = { 6 | incidents: [], 7 | limit: 1, 8 | offset: 0, 9 | total: null, 10 | more: true, 11 | }; 12 | 13 | nock('https://api.pagerduty.com') 14 | .get('/incidents') 15 | .reply(429, body) 16 | .get('/incidents') 17 | .reply(429, body) 18 | .get('/incidents') 19 | .reply(429, body) 20 | .get('/incidents') 21 | .reply(429, body); 22 | 23 | const response = await api({ 24 | token: 'someToken1234567890', 25 | endpoint: '/incidents', 26 | retryTimeout: 20, 27 | }); 28 | 29 | expect(response.response.status).toEqual(429); 30 | }); 31 | 32 | test('API should return data after getting rate limited once.', async () => { 33 | const body = { 34 | incidents: [], 35 | limit: 1, 36 | offset: 0, 37 | total: null, 38 | more: true, 39 | }; 40 | 41 | nock('https://api.pagerduty.com') 42 | .get('/incidents') 43 | .reply(429, body) 44 | .get('/incidents') 45 | .reply(200, body); 46 | 47 | const response = await api({ 48 | token: 'someToken1234567890', 49 | endpoint: '/incidents', 50 | retryTimeout: 20, 51 | }); 52 | 53 | expect(response.response.status).toEqual(200); 54 | expect(response.data).toEqual(body); 55 | }); 56 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "./node_modules/gts/tsconfig-google.json", 3 | "compilerOptions": { 4 | "lib": ["DOM"], 5 | "rootDir": ".", 6 | "outDir": "build", 7 | "sourceMap": true 8 | }, 9 | "include": ["src/**/*.ts", "test/**/*.ts"] 10 | } 11 | -------------------------------------------------------------------------------- /tslint.json: -------------------------------------------------------------------------------- 1 | { 2 | "defaultSeverity": "error", 3 | "extends": ["tslint:recommended"], 4 | "jsRules": {}, 5 | "rules": {}, 6 | "rulesDirectory": [] 7 | } 8 | -------------------------------------------------------------------------------- /webpack.config.js: -------------------------------------------------------------------------------- 1 | const path = require('path'); 2 | 3 | const baseConfig = { 4 | entry: './src/index.ts', 5 | devtool: 'source-map', 6 | output: { 7 | filename: 'pdjs.js', 8 | library: 'PagerDuty', 9 | path: path.resolve(__dirname, 'dist'), 10 | }, 11 | module: { 12 | rules: [ 13 | { 14 | test: /\.tsx?$/, 15 | exclude: /node_modules/, 16 | loader: 'babel-loader', 17 | }, 18 | ], 19 | }, 20 | resolve: { 21 | extensions: ['.tsx', '.ts', '.js'], 22 | }, 23 | }; 24 | 25 | module.exports = [ 26 | { 27 | ...baseConfig, 28 | output: { 29 | ...baseConfig.output, 30 | filename: 'pdjs-legacy.js', 31 | }, 32 | }, 33 | { 34 | ...baseConfig, 35 | module: { 36 | ...baseConfig.module, 37 | rules: [ 38 | ...baseConfig.module.rules, 39 | { 40 | test: /\.[jt]sx?$/, 41 | enforce: 'pre', 42 | exclude: /(node_modules|\.spec\.js)/, 43 | use: [ 44 | { 45 | loader: 'webpack-strip-block', 46 | options: { 47 | start: 'LEGACY-BROWSER-SUPPORT-START', 48 | end: 'LEGACY-BROWSER-SUPPORT-END', 49 | }, 50 | }, 51 | ], 52 | }, 53 | ], 54 | }, 55 | }, 56 | ]; 57 | --------------------------------------------------------------------------------